From e0b032a911c86dc14a0547f3da74c0a52d1bceed Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Tue, 3 Nov 2026 22:20:26 +0100 Subject: [PATCH 01/77] feat(benchmarks): add the agentic spend ledger and price snapshot MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Design §8 usage buckets per provider, the researched price snapshot with its 2026-12-31 expiry, bound and actual pricing, and the persistent per-provider ledger: one unit in flight, cap and overrun stops, an exclusive flock that dies with its holder, and 2x booking of units left unsettled. LedgerService is the host's async arbiter. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/__init__.py | 7 + benchmarks/agentic/ledger.py | 471 ++++++++++++++++++++++ benchmarks/agentic/types.py | 20 + benchmarks/agentic/usage.py | 63 +++ docs/benchmarks/price-snapshot.yml | 65 +++ tests/benchmarks/test_agentic_ledger.py | 501 ++++++++++++++++++++++++ 6 files changed, 1127 insertions(+) create mode 100644 benchmarks/agentic/__init__.py create mode 100644 benchmarks/agentic/ledger.py create mode 100644 benchmarks/agentic/types.py create mode 100644 benchmarks/agentic/usage.py create mode 100644 docs/benchmarks/price-snapshot.yml create mode 100644 tests/benchmarks/test_agentic_ledger.py diff --git a/benchmarks/agentic/__init__.py b/benchmarks/agentic/__init__.py new file mode 100644 index 00000000..b07ca831 --- /dev/null +++ b/benchmarks/agentic/__init__.py @@ -0,0 +1,7 @@ +"""Agentic benchmark harness (docs/benchmarks/AGENTIC-BENCHMARK-DESIGN.md). + +Real models choose tools in a loop over the systems under test. A host +orchestrator holds the spend ledger and never a provider key; it runs one +worker process per (model, system) pair. ``python -m benchmarks agentic-run`` +is the entry point. +""" diff --git a/benchmarks/agentic/ledger.py b/benchmarks/agentic/ledger.py new file mode 100644 index 00000000..f930cf6a --- /dev/null +++ b/benchmarks/agentic/ledger.py @@ -0,0 +1,471 @@ +"""Price snapshot, bound pricing, the persistent spend ledger and its async arbiter. + +Design §12: each provider has one billable unit in flight at a time, and a +unit starts only when the provider's recorded spend plus the unit's bound is +at or under the provider's cap. Spend is the design §8 buckets priced from the +committed snapshot; a unit that may have been billed without reporting usage +is booked at twice its bound. +""" + +from __future__ import annotations + +import asyncio +import fcntl +import json +import os +import uuid +from collections.abc import Mapping +from dataclasses import asdict, dataclass +from datetime import UTC, date, datetime +from decimal import Decimal, InvalidOperation +from pathlib import Path +from typing import Any, Literal + +from benchmarks.agentic.types import Buckets +from benchmarks.model_matrix import ModelFamily +from benchmarks.runner import BenchmarkValidationError, _load_yaml_mapping + +#: Hard caps, a margin below each provider's budget (design §12). +PROVIDER_CAPS: dict[str, Decimal] = { + "anthropic": Decimal(180), + "openai": Decimal(65), + "google": Decimal(180), +} +PROVIDER_MARGINS: dict[str, Decimal] = { + "anthropic": Decimal(20), + "openai": Decimal(10), + "google": Decimal(20), +} + +Outcome = Literal[ + "ok", + "rejected", + "rate_limited", + "server", + "timeout", + "connection", + "no_usage", + "worker_lost", + "unsettled_at_load", +] + +_MILLION = Decimal(1_000_000) +_RATE_FIELDS = ("input", "cache_write", "cached_input", "output") + + +@dataclass(frozen=True) +class Rates: + """USD per million tokens.""" + + input: Decimal + cache_write: Decimal + cached_input: Decimal + output: Decimal + + +@dataclass(frozen=True) +class Tier: + up_to_input_tokens: int | None # None = no upper limit (last tier) + rates: Rates + + +@dataclass(frozen=True) +class ModelPrice: + model_id: str + provider: str + tiers: tuple[Tier, ...] + source_url: str + + +@dataclass(frozen=True) +class PriceSnapshot: + captured_on: date + expires_on: date | None + models: dict[str, ModelPrice] # keyed by model_id + + +def load_price_snapshot(path: Path) -> PriceSnapshot: + data = _load_yaml_mapping(path, "price snapshot") + captured_on = _date(data.get("captured_on"), "captured_on") + if captured_on is None: + raise BenchmarkValidationError("price snapshot must set 'captured_on'") + expires_on = _date(data.get("expires_on"), "expires_on") + items = data.get("models") + if not isinstance(items, list) or not items: + raise BenchmarkValidationError("price snapshot must contain a non-empty 'models' list") + models: dict[str, ModelPrice] = {} + for index, item in enumerate(items): + price = _model_price(item, f"price snapshot model at index {index}") + if price.model_id in models: + raise BenchmarkValidationError( + f"price snapshot has a duplicate model_id {price.model_id!r}" + ) + models[price.model_id] = price + return PriceSnapshot(captured_on=captured_on, expires_on=expires_on, models=models) + + +def _date(value: Any, field: str) -> date | None: + if value is None or isinstance(value, date): + return value + try: + return date.fromisoformat(str(value)) + except ValueError as exc: + raise BenchmarkValidationError(f"price snapshot {field!r} is not an ISO date") from exc + + +def _model_price(item: Any, label: str) -> ModelPrice: + if not isinstance(item, Mapping): + raise BenchmarkValidationError(f"{label} must be a mapping") + model_id, provider, source_url = ( + item.get("model_id"), + item.get("provider"), + item.get("source_url"), + ) + if not isinstance(model_id, str) or not model_id.strip(): + raise BenchmarkValidationError(f"{label} is missing 'model_id'") + if provider not in PROVIDER_CAPS: + raise BenchmarkValidationError( + f"price for {model_id!r} has provider {provider!r}; " + f"expected one of {sorted(PROVIDER_CAPS)}" + ) + if not isinstance(source_url, str) or not source_url.startswith("https://"): + raise BenchmarkValidationError(f"price for {model_id!r} must cite an https 'source_url'") + raw_tiers = item.get("tiers") + if not isinstance(raw_tiers, list) or not raw_tiers: + raise BenchmarkValidationError(f"price for {model_id!r} must have a non-empty 'tiers' list") + tiers: list[Tier] = [] + for position, raw in enumerate(raw_tiers): + if not isinstance(raw, Mapping): + raise BenchmarkValidationError(f"price for {model_id!r}: each tier must be a mapping") + limit = raw.get("up_to_input_tokens") + last = position == len(raw_tiers) - 1 + if last and limit is not None: + raise BenchmarkValidationError( + f"price for {model_id!r}: the last tier must have no up_to_input_tokens limit" + ) + if not last: + if isinstance(limit, bool) or not isinstance(limit, int) or limit <= 0: + raise BenchmarkValidationError( + f"price for {model_id!r}: only the last tier may omit a positive " + "up_to_input_tokens" + ) + previous = tiers[-1].up_to_input_tokens if tiers else None + if previous is not None and limit <= previous: + raise BenchmarkValidationError( + f"price for {model_id!r}: tiers must be in ascending up_to_input_tokens order" + ) + tiers.append(Tier(limit, Rates(*(_rate(raw.get(f), model_id, f) for f in _RATE_FIELDS)))) + return ModelPrice( + model_id=model_id, provider=provider, tiers=tuple(tiers), source_url=source_url + ) + + +def _rate(value: Any, model_id: str, field: str) -> Decimal: + if isinstance(value, bool) or not isinstance(value, (str, int)): + raise BenchmarkValidationError( + f"price for {model_id!r}: {field!r} must be a decimal string" + ) + try: + rate = Decimal(str(value)) + except InvalidOperation as exc: + raise BenchmarkValidationError( + f"price for {model_id!r}: {field!r} is not a number" + ) from exc + if not rate.is_finite() or rate < 0: + raise BenchmarkValidationError( + f"price for {model_id!r}: {field!r} is negative or not finite" + ) + return rate + + +def refuse_stale_snapshot(snapshot: PriceSnapshot, *, today: date) -> None: + if snapshot.expires_on is not None and today >= snapshot.expires_on: + raise BenchmarkValidationError( + f"price snapshot expires on {snapshot.expires_on.isoformat()} and today is " + f"{today.isoformat()}: refresh docs/benchmarks/price-snapshot.yml before a live run" + ) + + +def _tier(price: ModelPrice, input_tokens: int) -> Rates: + for tier in price.tiers: + if tier.up_to_input_tokens is None or input_tokens <= tier.up_to_input_tokens: + return tier.rates + return price.tiers[-1].rates + + +def actual_cost(price: ModelPrice, buckets: Buckets) -> Decimal: + """Each bucket at its own rate, in the tier the total reported input reached.""" + rates = _tier(price, buckets.total_input) + return ( + buckets.uncached_input * rates.input + + buckets.cache_write_input * rates.cache_write + + buckets.cached_input * rates.cached_input + + buckets.output * rates.output + ) / _MILLION + + +def bound_cost(price: ModelPrice, *, input_bound: int, output_bound: int) -> Decimal: + """Input at the highest rate a harness request can incur, in the tier the bound reaches.""" + rates = _tier(price, input_bound) + input_rate = rates.cache_write if price.provider == "openai" else rates.input + return (input_bound * input_rate + output_bound * rates.output) / _MILLION + + +def clamp_input_bound(bound: int, max_input_tokens: int) -> int: + return min(bound, max_input_tokens) + + +def booked_cost(outcome: Outcome, *, bound: Decimal, actual: Decimal | None) -> Decimal: + if outcome == "ok": + if actual is None: + raise ValueError("an 'ok' unit needs its actual cost") + return actual + if outcome in ("rejected", "rate_limited"): + return Decimal(0) # a 4xx is not billed + return 2 * bound # may have been billed without usage: booked at twice its bound + + +def _utc_now() -> str: + return datetime.now(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z") + + +class Ledger: + """One JSONL file per provider under ``ledger_dir``, held under an exclusive lock.""" + + def __init__(self, ledger_dir: Path, run_id: str, caps: dict[str, Decimal], lock_fd: int): + self._dir = ledger_dir + self._run_id = run_id + self._caps = caps + self._lock_fd: int | None = lock_fd + self._events: list[dict[str, Any]] = [] + self._spent: dict[str, Decimal] = {} + self._stops: dict[str, str] = {} + self._units: dict[str, tuple[str, Decimal]] = {} # unit id -> (provider, bound) + self._in_flight: dict[str, str] = {} # provider -> unit id + + @classmethod + def open( + cls, ledger_dir: Path, *, run_id: str, caps: Mapping[str, Decimal] = PROVIDER_CAPS + ) -> Ledger: + ledger_dir.mkdir(parents=True, exist_ok=True) + lock_path = ledger_dir / ".lock" + fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o644) + 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: + ledger._load() + except BaseException: + ledger.close() + 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 + + def _load(self) -> None: + pending: dict[str, None] = {} # ordered set of reserves without a settle + for path in sorted(self._dir.glob("*.jsonl")): + for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): + if not line.strip(): + continue + try: + event = json.loads(line) + except json.JSONDecodeError as exc: + raise BenchmarkValidationError( + f"spend ledger {path}:{number} is corrupt" + ) from exc + self._apply(event) + if event["event"] == "reserve": + pending[event["unit_id"]] = None + elif event["event"] == "settle": + pending.pop(event["unit_id"], None) + for unit_id in pending: + provider, _ = self._units[unit_id] + self._in_flight[provider] = unit_id + self.settle(unit_id, outcome="unsettled_at_load", actual=None, buckets=None) + + def _apply(self, event: dict[str, Any]) -> None: + self._events.append(event) + provider = event["provider"] + kind = event["event"] + if kind == "reserve": + self._units[event["unit_id"]] = (provider, Decimal(event["bound"])) + elif kind == "settle": + self._spent[provider] = self.spent(provider) + Decimal(event["booked"]) + elif kind == "stop" and event["reason"] == "overrun": + # Only an overrun stop survives a reopen: a cap stop is re-checked against the + # caps of the new run, so a raised cap lets the provider run again. + self._stops[provider] = "overrun" + elif kind == "resume": + self._stops.pop(provider, 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") + self._events.append(event) + + def spent(self, provider: str) -> Decimal: + return self._spent.get(provider, Decimal(0)) + + def stopped(self, provider: str) -> str | None: + return self._stops.get(provider) + + def _stop(self, provider: str, reason: str) -> None: + self._stops[provider] = reason + self._append(provider, {"event": "stop", "reason": reason}) + + def reserve( + self, + provider: str, + *, + model_id: str, + kind: str, + bound: Decimal, + input_bound: int, + output_bound: int, + ) -> str | None: + cap = self._caps.get(provider) + if cap is None: + raise BenchmarkValidationError(f"provider {provider!r} has no spend cap in the ledger") + if provider in self._in_flight: + raise RuntimeError( + f"a {provider} unit is already in flight: {self._in_flight[provider]}" + ) + if provider in self._stops: + return None + if self.spent(provider) + bound > cap: + self._stop(provider, "cap") + return None + unit_id = f"{provider}-{uuid.uuid4().hex}" + self._append( + provider, + { + "event": "reserve", + "unit_id": unit_id, + "model_id": model_id, + "kind": kind, + "bound": str(bound), + "input_bound": input_bound, + "output_bound": output_bound, + }, + ) + self._units[unit_id] = (provider, bound) + self._in_flight[provider] = unit_id + return unit_id + + def settle( + self, + unit_id: str, + *, + outcome: Outcome, + actual: Decimal | None, + buckets: Buckets | None, + input_bound_exceeded: bool = False, + ) -> Decimal: + provider, bound = self._units[unit_id] + if self._in_flight.get(provider) != unit_id: + raise RuntimeError(f"unit {unit_id} is not in flight") + booked = booked_cost(outcome, bound=bound, actual=actual) + self._append( + provider, + { + "event": "settle", + "unit_id": unit_id, + "outcome": outcome, + "actual": None if actual is None else str(actual), + "booked": str(booked), + "buckets": None if buckets is None else asdict(buckets), + "input_bound_exceeded": input_bound_exceeded, + }, + ) + self._spent[provider] = self.spent(provider) + booked + del self._in_flight[provider] + if outcome == "ok" and booked > bound: + self._stop(provider, "overrun") + return booked + + def acknowledge_overrun(self, provider: str) -> None: + if self._stops.get(provider) == "overrun": + del self._stops[provider] + self._append(provider, {"event": "resume"}) + + def events(self, run_id: str) -> list[dict[str, Any]]: + return [dict(event) for event in self._events if event["run_id"] == run_id] + + +class LedgerService: + """The host's async arbiter: one unit in flight per provider, providers in parallel.""" + + def __init__( + self, + ledger: Ledger, + prices: Mapping[str, ModelPrice], + families: Mapping[str, ModelFamily], + ) -> None: # both keyed by model_id + self._ledger = ledger + self._prices = dict(prices) + self._families = dict(families) + self._locks: dict[str, asyncio.Lock] = {} + self._units: dict[str, tuple[str, ModelPrice, int]] = {} + + async def reserve( + self, + *, + provider: str, + model_id: str, + input_bound: int, + output_bound: int, + kind: str = "model_call", + ) -> str | None: + price = self._prices.get(model_id) + if price is None: + raise BenchmarkValidationError(f"no price snapshot entry for model {model_id!r}") + family = self._families.get(model_id) + if family is not None and family.max_input_tokens is not None: + input_bound = clamp_input_bound(input_bound, family.max_input_tokens) + 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 + try: + unit_id = self._ledger.reserve( + provider, + model_id=model_id, + kind=kind, + bound=bound, + input_bound=input_bound, + output_bound=output_bound, + ) + except BaseException: + lock.release() + raise + if unit_id is None: + lock.release() + return None + self._units[unit_id] = (provider, price, input_bound) + return unit_id + + async def settle(self, unit_id: str, *, outcome: Outcome, buckets: Buckets | None) -> None: + provider, price, input_bound = self._units.pop(unit_id) + try: + if outcome == "ok" and buckets is None: + outcome = "no_usage" + self._ledger.settle( + unit_id, + outcome=outcome, + actual=actual_cost(price, buckets) if outcome == "ok" and buckets else None, + buckets=buckets, + input_bound_exceeded=buckets is not None and buckets.total_input > input_bound, + ) + finally: + self._locks[provider].release() diff --git a/benchmarks/agentic/types.py b/benchmarks/agentic/types.py new file mode 100644 index 00000000..6b082702 --- /dev/null +++ b/benchmarks/agentic/types.py @@ -0,0 +1,20 @@ +"""Neutral value types shared by every agentic module.""" + +from __future__ import annotations + +from dataclasses import dataclass + + +@dataclass(frozen=True) +class Buckets: + """Provider usage in the four disjoint design §8 buckets.""" + + uncached_input: int + cache_write_input: int + cached_input: int + output: int # includes thinking/reasoning + reasoning: int = 0 # information only, already inside `output` + + @property + def total_input(self) -> int: + return self.uncached_input + self.cache_write_input + self.cached_input diff --git a/benchmarks/agentic/usage.py b/benchmarks/agentic/usage.py new file mode 100644 index 00000000..82b4368e --- /dev/null +++ b/benchmarks/agentic/usage.py @@ -0,0 +1,63 @@ +"""Design §8 usage buckets per hosted provider. + +Each function takes the SDK usage object's ``model_dump()`` (snake_case keys). +A missing or ``None`` count is 0. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from benchmarks.agentic.types import Buckets +from benchmarks.runner import BenchmarkValidationError + + +def _count(usage: Mapping[str, Any] | None, key: str) -> int: + value = (usage or {}).get(key) + return int(value) if value is not None else 0 + + +def _buckets(uncached: int, cache_write: int, cached: int, output: int, reasoning: int) -> Buckets: + if uncached < 0: + raise BenchmarkValidationError( + f"provider usage gives a negative uncached input ({uncached}); the usage object " + "does not match the design section 8 bucket rules" + ) + return Buckets(uncached, cache_write, cached, output, reasoning) + + +def anthropic_buckets(usage: Mapping[str, Any]) -> Buckets: + return _buckets( + _count(usage, "input_tokens"), + _count(usage, "cache_creation_input_tokens"), + _count(usage, "cache_read_input_tokens"), + _count(usage, "output_tokens"), + 0, + ) + + +def openai_buckets(usage: Mapping[str, Any]) -> Buckets: + """Responses API usage: cached and cache-write tokens are nested inside input.""" + details = usage.get("input_tokens_details") + cached = _count(details, "cached_tokens") + cache_write = _count(details, "cache_write_tokens") + return _buckets( + _count(usage, "input_tokens") - cached - cache_write, + cache_write, + cached, + _count(usage, "output_tokens"), + _count(usage.get("output_tokens_details"), "reasoning_tokens"), + ) + + +def gemini_buckets(usage: Mapping[str, Any]) -> Buckets: + cached = _count(usage, "cached_content_token_count") + thoughts = _count(usage, "thoughts_token_count") + return _buckets( + _count(usage, "prompt_token_count") - cached + _count(usage, "tool_use_prompt_token_count"), + 0, + cached, + _count(usage, "candidates_token_count") + thoughts, + thoughts, + ) diff --git a/docs/benchmarks/price-snapshot.yml b/docs/benchmarks/price-snapshot.yml new file mode 100644 index 00000000..3032071e --- /dev/null +++ b/docs/benchmarks/price-snapshot.yml @@ -0,0 +1,65 @@ +# Price snapshot for the agentic benchmark's spend ledger. +# +# Context: docs/benchmarks/AGENTIC-BENCHMARK-DESIGN.md sections 8 and 12. +# Every value comes from the research note named in `source`, which quotes +# the vendor page each `source_url` points at. Rates are USD per million +# tokens, written as strings so they load as exact decimals. +# +# Each tier applies up to `up_to_input_tokens` total input tokens; the last +# tier has no limit (null). A call's tier is picked from its total reported +# input (actual cost) or from its input bound (reservation), and applies to +# input and output both. +# +# Loaded and validated by benchmarks.agentic.ledger.load_price_snapshot(). +schema_version: 1 +currency: USD +unit: per_million_tokens +captured_on: "2026-10-31" +# Gemini 3.8 Flash's prices double on 2027-01-01. A live run refuses this +# snapshot from 2026-12-31 UTC, a one-day margin across time zones, until the +# snapshot is refreshed. +expires_on: "2026-12-31" +source: docs/research/2026-10-31-benchmark-provider-limits.md + +models: + - model_id: claude-sonnet-5-5 + provider: anthropic + source_url: https://platform.claude.com/docs/en/about-claude/pricing + tiers: + - up_to_input_tokens: null + input: "2" + # $4, the higher of the 5-minute and 1-hour write rates: the harness + # sends no cache_control, so a write is unexpected and priced high. + cache_write: "4" + cached_input: "0.10" + output: "10" + + - model_id: gpt-6.1-sol + provider: openai + source_url: https://developers.openai.com/api/docs/pricing + tiers: + - up_to_input_tokens: 272000 + input: "2" + # $2.50, the 30-minute rate: the harness never requests 12-hour + # retention (tests/benchmarks/test_agentic_clients.py pins that). + cache_write: "2.50" + cached_input: "0.10" + output: "10" + - up_to_input_tokens: null + input: "4" + # $5.00, the 30-minute rate above 272K input tokens. + cache_write: "5" + cached_input: "0.20" + output: "15" + + - model_id: gemini-3.8-flash + provider: google + source_url: https://ai.google.dev/gemini-api/docs/pricing + tiers: + - up_to_input_tokens: null + input: "0.75" + # 0: Gemini has no cache-write bucket, and the harness creates no + # cached content. + cache_write: "0" + cached_input: "0.075" + output: "3.75" diff --git a/tests/benchmarks/test_agentic_ledger.py b/tests/benchmarks/test_agentic_ledger.py new file mode 100644 index 00000000..08e05b16 --- /dev/null +++ b/tests/benchmarks/test_agentic_ledger.py @@ -0,0 +1,501 @@ +"""Usage buckets, the price snapshot and the spend ledger (design §8, §12).""" + +from __future__ import annotations + +import asyncio +import subprocess +import sys +from datetime import date +from decimal import Decimal +from pathlib import Path +from typing import Any + +import pytest + +from benchmarks.agentic.ledger import ( + PROVIDER_CAPS, + PROVIDER_MARGINS, + Ledger, + LedgerService, + ModelPrice, + Rates, + Tier, + actual_cost, + booked_cost, + bound_cost, + clamp_input_bound, + load_price_snapshot, + refuse_stale_snapshot, +) +from benchmarks.agentic.types import Buckets +from benchmarks.agentic.usage import anthropic_buckets, gemini_buckets, openai_buckets +from benchmarks.model_matrix import ModelFamily, load_model_matrix, model_family_from_raw +from benchmarks.runner import BenchmarkValidationError + +REPO_ROOT = Path(__file__).resolve().parents[2] +MODEL_MATRIX_PATH = REPO_ROOT / "docs" / "benchmarks" / "model-matrix.yml" +PRICE_SNAPSHOT_PATH = REPO_ROOT / "docs" / "benchmarks" / "price-snapshot.yml" +RUN_ID = "run-1" +D = Decimal + + +def _rates(input_: str, cache_write: str, cached: str, output: str) -> Rates: + return Rates(D(input_), D(cache_write), D(cached), D(output)) + + +def _flat( + input_: str, cache_write: str, cached: str, output: str, *, provider: str = "anthropic" +) -> ModelPrice: + return ModelPrice( + model_id="m", + provider=provider, + tiers=(Tier(None, _rates(input_, cache_write, cached, output)),), + source_url="https://example.invalid/pricing", + ) + + +def _tiered( + *, up_to: int, low: tuple[str, str], high: tuple[str, str], provider: str = "anthropic" +) -> ModelPrice: + return ModelPrice( + model_id="m", + provider=provider, + tiers=( + Tier(up_to, _rates(low[0], low[0], "0", low[1])), + Tier(None, _rates(high[0], high[0], "0", high[1])), + ), + source_url="https://example.invalid/pricing", + ) + + +def _event(ledger: Ledger, kind: str, unit_id: str) -> dict[str, Any]: + (found,) = [ + e for e in ledger.events(RUN_ID) if e["event"] == kind and e.get("unit_id") == unit_id + ] + return found + + +def _open(tmp_path: Path, **caps: str) -> Ledger: + return Ledger.open(tmp_path, run_id=RUN_ID, caps={p: D(c) for p, c in caps.items()}) + + +def _reserve(ledger: Ledger, provider: str, bound: str) -> str | None: + return ledger.reserve( + provider, model_id="m", kind="model_call", bound=D(bound), input_bound=1, output_bound=1 + ) + + +def _family(model_id: str, provider: str, max_input: int) -> ModelFamily: + return model_family_from_raw( + { + "id": f"{provider}-test", + "provider": provider, + "model_id": model_id, + "client": "test", + "token_count_method": "claude_normalized_payload", + "latency_scope": "request_dispatch_to_final_answer", + "headline_eligible": False, + "headline_ineligibility_reason": "test", + "api": "scripted", + "arm": "hosted", + "max_input_tokens": max_input, + "max_output_tokens": 32_768, + "output_cap_includes_reasoning": True, + "framing_allowance_tokens": 256, + } + ) + + +# --- usage buckets --------------------------------------------------------------------------- + + +def test_anthropic_buckets() -> None: + assert anthropic_buckets( + { + "input_tokens": 100, + "cache_creation_input_tokens": None, + "cache_read_input_tokens": 20, + "output_tokens": 30, + } + ) == Buckets(100, 0, 20, 30, 0) + + +def test_openai_buckets_subtract_cached_and_cache_write_from_input() -> None: + assert openai_buckets( + { + "input_tokens": 1000, + "input_tokens_details": {"cached_tokens": 200, "cache_write_tokens": 300}, + "output_tokens": 50, + "output_tokens_details": {"reasoning_tokens": 40}, + } + ) == Buckets(500, 300, 200, 50, 40) + + +def test_gemini_buckets_add_tool_use_prompt_and_thoughts() -> None: + assert gemini_buckets( + { + "prompt_token_count": 1000, + "cached_content_token_count": 100, + "tool_use_prompt_token_count": 50, + "candidates_token_count": 30, + "thoughts_token_count": 20, + } + ) == Buckets(950, 0, 100, 50, 20) + + +def test_buckets_refuse_a_negative_uncached_input() -> None: + with pytest.raises(BenchmarkValidationError, match="negative"): + openai_buckets( + { + "input_tokens": 100, + "input_tokens_details": {"cached_tokens": 200}, + "output_tokens": 1, + } + ) + + +# --- price snapshot -------------------------------------------------------------------------- + + +def test_committed_snapshot_has_the_researched_prices() -> None: + snap = load_price_snapshot(PRICE_SNAPSHOT_PATH) # values: research note §§A-C + + def tiers(model_id: str) -> list[tuple[int | None, Rates]]: + return [(t.up_to_input_tokens, t.rates) for t in snap.models[model_id].tiers] + + assert tiers("claude-sonnet-5-5") == [(None, Rates(D("2"), D("4"), D("0.10"), D("10")))] + assert tiers("gpt-6.1-sol") == [ + (272_000, Rates(D("2"), D("2.50"), D("0.10"), D("10"))), + (None, Rates(D("4"), D("5"), D("0.20"), D("15"))), + ] + assert tiers("gemini-3.8-flash") == [(None, Rates(D("0.75"), D("0"), D("0.075"), D("3.75")))] + assert snap.expires_on == date(2026, 12, 31) + assert all(p.source_url.startswith("https://") for p in snap.models.values()) + + +def test_stale_snapshot_is_refused_from_its_expiry_day() -> None: + snap = load_price_snapshot(PRICE_SNAPSHOT_PATH) + refuse_stale_snapshot(snap, today=date(2026, 12, 30)) # no error + with pytest.raises(BenchmarkValidationError, match="2026-12-31"): + refuse_stale_snapshot(snap, today=date(2026, 12, 31)) + + +_GOOD_MODEL = ( + " - model_id: m\n" + " provider: anthropic\n" + " source_url: https://example.invalid\n" + " tiers:\n" + " - up_to_input_tokens: null\n" + " input: '1'\n" + " cache_write: '1'\n" + " cached_input: '1'\n" + " output: '1'\n" +) + + +@pytest.mark.parametrize( + "models,match", + [ + ( + _GOOD_MODEL.replace("up_to_input_tokens: null", "up_to_input_tokens: 10"), + "last tier", + ), + (_GOOD_MODEL.replace("output: '1'", "output: '-1'"), "negative"), + (_GOOD_MODEL.replace("provider: anthropic", "provider: mistral"), "mistral"), + (_GOOD_MODEL + _GOOD_MODEL, "duplicate"), + ( + _GOOD_MODEL.replace( + " tiers:\n", + " tiers:\n - up_to_input_tokens: 20\n input: '1'\n" + " cache_write: '1'\n cached_input: '1'\n output: '1'\n" + " - up_to_input_tokens: 10\n input: '1'\n" + " cache_write: '1'\n cached_input: '1'\n output: '1'\n", + ), + "ascending", + ), + ], +) +def test_load_price_snapshot_refuses_a_bad_entry(tmp_path: Path, models: str, match: str) -> None: + path = tmp_path / "prices.yml" + path.write_text( + "schema_version: 1\ncurrency: USD\nunit: per_million_tokens\n" + f"captured_on: '2026-10-31'\nexpires_on: null\nmodels:\n{models}", + encoding="utf-8", + ) + with pytest.raises(BenchmarkValidationError, match=match): + load_price_snapshot(path) + + +# --- pricing --------------------------------------------------------------------------------- + + +def test_actual_cost_prices_each_bucket_at_its_own_rate() -> None: + price = _flat("2", "2.5", "0.2", "10") # input, cache_write, cached, output + assert actual_cost(price, Buckets(1_000_000, 1_000_000, 1_000_000, 1_000_000, 500_000)) == D( + "14.7" + ) + + +def test_tier_is_chosen_by_total_input_and_applies_to_output_too() -> None: + price = _tiered(up_to=200_000, low=("2", "10"), high=("4", "15")) + assert actual_cost(price, Buckets(200_000, 0, 0, 1_000_000)) == D("10.4") + assert actual_cost(price, Buckets(200_001, 0, 0, 1_000_000)) == D("15.800004") + + +def test_bound_cost_uses_openai_cache_write_rate_and_uncached_rate_elsewhere() -> None: + openai = _flat("2", "2.5", "0.2", "10", provider="openai") + anthropic = _flat("2", "2.5", "0.2", "10", provider="anthropic") + assert bound_cost(openai, input_bound=1_000_000, output_bound=0) == D("2.5") + assert bound_cost(anthropic, input_bound=1_000_000, output_bound=0) == D("2") + + +def test_input_bound_is_clamped_to_the_model_maximum() -> None: + assert clamp_input_bound(2_000_000, 1_048_576) == 1_048_576 + assert clamp_input_bound(10, 1_048_576) == 10 + + +@pytest.mark.parametrize( + "outcome,expected", + [ + ("ok", "1.2"), + ("rejected", "0"), + ("rate_limited", "0"), + ("server", "4"), + ("timeout", "4"), + ("connection", "4"), + ("no_usage", "4"), + ("worker_lost", "4"), + ("unsettled_at_load", "4"), + ], +) +def test_booked_cost_by_outcome(outcome: Any, expected: str) -> None: + actual = D("1.2") if outcome == "ok" else None + assert booked_cost(outcome, bound=D("2"), actual=actual) == D(expected) + + +# --- ledger ---------------------------------------------------------------------------------- + + +def test_reserve_refuses_when_spend_plus_bound_exceeds_cap_and_stops_provider( + tmp_path: Path, +) -> None: + ledger = _open(tmp_path, anthropic="10") + unit = _reserve(ledger, "anthropic", "6") + assert unit is not None + ledger.settle(unit, outcome="ok", actual=D("5"), buckets=Buckets(1, 0, 0, 1)) + unit = _reserve(ledger, "anthropic", "5") # 5 + 5 == 10: at the cap is allowed + assert unit is not None + ledger.settle(unit, outcome="ok", actual=D("5"), buckets=Buckets(1, 0, 0, 1)) + assert _reserve(ledger, "anthropic", "0.01") is None + assert ledger.stopped("anthropic") == "cap" + assert _reserve(ledger, "anthropic", "0") is None # sticky + assert [e["event"] for e in ledger.events(RUN_ID)].count("stop") == 1 + ledger.close() + + +def test_reserve_raises_when_a_unit_is_already_in_flight(tmp_path: Path) -> None: + ledger = _open(tmp_path, anthropic="10") + assert _reserve(ledger, "anthropic", "1") is not None + with pytest.raises(RuntimeError, match="in flight"): + _reserve(ledger, "anthropic", "1") + ledger.close() + + +def test_actual_above_bound_stops_the_provider_until_acknowledged(tmp_path: Path) -> None: + ledger = _open(tmp_path, anthropic="10") + unit = _reserve(ledger, "anthropic", "2") + assert unit is not None + booked = ledger.settle(unit, outcome="ok", actual=D("3"), buckets=Buckets(1, 0, 0, 1)) + assert booked == D("3") and ledger.stopped("anthropic") == "overrun" + assert _reserve(ledger, "anthropic", "0") is None + ledger.close() + ledger = _open(tmp_path, anthropic="10") + assert ledger.stopped("anthropic") == "overrun" + ledger.acknowledge_overrun("anthropic") + assert ledger.stopped("anthropic") is None + assert [e["event"] for e in ledger.events(RUN_ID)][-1] == "resume" + assert _reserve(ledger, "anthropic", "1") is not None + 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") + assert unit is not None + ledger.settle( + unit, outcome="ok", actual=D("1.5"), buckets=Buckets(1, 0, 0, 1), input_bound_exceeded=True + ) + reserve, settle = _event(ledger, "reserve", unit), _event(ledger, "settle", unit) + assert reserve["bound"] == "2" and settle["booked"] == "1.5" and settle["actual"] == "1.5" + assert settle["input_bound_exceeded"] is True + assert (tmp_path / "anthropic.jsonl").read_text(encoding="utf-8").count("\n") == 2 + ledger.close() + + +def test_reopening_books_an_unsettled_unit_at_twice_its_bound(tmp_path: Path) -> None: + ledger = _open(tmp_path, anthropic="10") + assert _reserve(ledger, "anthropic", "3") is not None + ledger.close() + ledger = _open(tmp_path, anthropic="10") + assert ledger.spent("anthropic") == D("6") + assert [e["outcome"] for e in ledger.events(RUN_ID) if e["event"] == "settle"] == [ + "unsettled_at_load" + ] + ledger.close() + + +def test_a_second_open_on_the_same_directory_is_refused(tmp_path: Path) -> None: + ledger = _open(tmp_path, anthropic="10") + with pytest.raises(BenchmarkValidationError, match=r"\.lock"): + _open(tmp_path, anthropic="10") + ledger.close() + _open(tmp_path, anthropic="10").close() # released by close() + + +def test_a_killed_ledger_holder_releases_the_lock_and_its_unit_is_booked_at_twice_its_bound( + tmp_path: Path, +) -> None: + script = ( + "import sys, time\n" + "from decimal import Decimal\n" + "from pathlib import Path\n" + "from benchmarks.agentic.ledger import Ledger\n" + "ledger = Ledger.open(Path(sys.argv[1]), run_id='holder'," + " caps={'anthropic': Decimal(10)})\n" + "ledger.reserve('anthropic', model_id='m', kind='model_call', bound=Decimal(3)," + " input_bound=1, output_bound=1)\n" + "print('reserved', flush=True)\n" + "time.sleep(60)\n" + ) + proc = subprocess.Popen( + [sys.executable, "-c", script, str(tmp_path)], + cwd=REPO_ROOT, + stdout=subprocess.PIPE, + text=True, + ) + try: + assert proc.stdout is not None + assert proc.stdout.readline().strip() == "reserved" + with pytest.raises(BenchmarkValidationError, match=r"\.lock"): + _open(tmp_path, anthropic="10") + finally: + proc.kill() # SIGKILL: no cleanup runs in the holder + proc.wait() + ledger = _open(tmp_path, anthropic="10") + assert ledger.spent("anthropic") == D("6") + ledger.close() + + +@pytest.mark.parametrize("provider", ["ollama", "mistral"]) +def test_provider_without_a_cap_is_refused(tmp_path: Path, provider: str) -> None: + ledger = _open(tmp_path, anthropic="10") + with pytest.raises(BenchmarkValidationError, match=provider): + _reserve(ledger, provider, "1") + ledger.close() + + +# --- service --------------------------------------------------------------------------------- + + +def _service(tmp_path: Path, **caps: str) -> tuple[Ledger, LedgerService]: + ledger = _open(tmp_path, **caps) + prices = { + "a": _flat("1", "1", "0", "1", provider="anthropic"), + "o": _flat("1", "1", "0", "1", provider="openai"), + } + families = {"a": _family("a", "anthropic", 1_000_000), "o": _family("o", "openai", 1_000_000)} + return ledger, LedgerService(ledger, prices, families) + + +async def test_service_allows_one_unit_in_flight_per_provider_and_runs_providers_in_parallel( + tmp_path: Path, +) -> None: + ledger, service = _service(tmp_path, anthropic="10", openai="10") + first = await service.reserve(provider="anthropic", model_id="a", input_bound=1, output_bound=1) + assert first is not None + second = asyncio.ensure_future( + service.reserve(provider="anthropic", model_id="a", input_bound=1, output_bound=1) + ) + with pytest.raises(TimeoutError): + await asyncio.wait_for(asyncio.shield(second), timeout=0.1) + other = await asyncio.wait_for( + service.reserve(provider="openai", model_id="o", input_bound=1, output_bound=1), + timeout=0.5, + ) + assert other is not None + await service.settle(first, outcome="ok", buckets=Buckets(1, 0, 0, 1)) + assert await asyncio.wait_for(second, timeout=0.5) is not None + ledger.close() + + +async def test_service_releases_the_provider_when_a_reserve_is_refused(tmp_path: Path) -> None: + ledger, service = _service(tmp_path, anthropic="0", openai="10") + for _ in range(2): + unit = await asyncio.wait_for( + service.reserve(provider="anthropic", model_id="a", input_bound=1, output_bound=1), + timeout=0.5, + ) + assert unit is None + ledger.close() + + +async def test_service_prices_a_bound_above_the_tier_threshold_at_the_high_tier( + tmp_path: Path, +) -> None: + ledger = _open(tmp_path, openai="65") + price = ModelPrice( + model_id="m", + provider="openai", + tiers=( + Tier(272_000, _rates("2", "2.5", "0.1", "10")), + Tier(None, _rates("4", "5", "0.2", "15")), + ), + source_url="https://example.invalid/pricing", + ) + service = LedgerService(ledger, {"m": price}, {"m": _family("m", "openai", 1_017_232)}) + unit = await service.reserve( + provider="openai", model_id="m", input_bound=300_000, output_bound=1_000 + ) + assert unit is not None + assert _event(ledger, "reserve", unit)["bound"] == "1.515" # 300_000*5 + 1_000*15, per 1M + await service.settle(unit, outcome="ok", buckets=Buckets(310_000, 0, 0, 10)) + assert _event(ledger, "settle", unit)["input_bound_exceeded"] is True + assert ledger.spent("openai") == D("1.24015") # actual, at the high tier + ledger.close() + + +async def test_service_clamps_the_input_bound_to_the_family_maximum(tmp_path: Path) -> None: + ledger = _open(tmp_path, openai="65") + service = LedgerService( + ledger, + {"m": _flat("1", "1", "0", "0", provider="openai")}, + {"m": _family("m", "openai", 1_000)}, + ) + unit = await service.reserve(provider="openai", model_id="m", input_bound=5_000, output_bound=0) + assert unit is not None + assert _event(ledger, "reserve", unit)["input_bound"] == 1_000 + await service.settle(unit, outcome="server", buckets=None) + assert ledger.spent("openai") == D("0.002") # 2x the clamped bound + ledger.close() + + +def test_committed_matrix_largest_single_call_bound_is_below_every_margin() -> None: + matrix, snap = load_model_matrix(MODEL_MATRIX_PATH), load_price_snapshot(PRICE_SNAPSHOT_PATH) + hosted = [f for f in matrix.model_families if f.arm == "hosted"] + assert len(hosted) == 3 + for f in hosted: + assert f.max_input_tokens is not None and f.max_output_tokens is not None + cost = bound_cost( + snap.models[f.model_id], + input_bound=f.max_input_tokens, + output_bound=f.max_output_tokens, + ) + assert cost < PROVIDER_MARGINS[f.provider] # about $2.33, $5.58 and $0.91 + + +def test_caps_and_margins_add_up_to_the_budget() -> None: + assert {p: PROVIDER_CAPS[p] + PROVIDER_MARGINS[p] for p in PROVIDER_CAPS} == { + "anthropic": D(200), + "openai": D(75), + "google": D(200), + } From 01378e2f04cf6931c17177145c073fe5bc792934 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Tue, 3 Nov 2026 22:24:59 +0100 Subject: [PATCH 02/77] feat(benchmarks): add the agentic MCP bridge and systems manifest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One stdio bridge for every MCP system: the full tools/list (all pages, unfiltered), the design §6 canonical result text and its sha256, UTF-8 truncation at 100,000 bytes on a character boundary, error results kept as results, and BridgeCrash when the transport dies. The server gets only its manifest env and pass_env names. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/bridge.py | 188 ++++++++++++++++++ benchmarks/agentic/types.py | 10 + docs/benchmarks/agentic-manifest.yml | 40 ++++ .../fixtures/agentic/fake_fetch_server.py | 39 ++++ tests/benchmarks/test_agentic_bridge.py | 152 ++++++++++++++ 5 files changed, 429 insertions(+) create mode 100644 benchmarks/agentic/bridge.py create mode 100644 docs/benchmarks/agentic-manifest.yml create mode 100644 tests/benchmarks/fixtures/agentic/fake_fetch_server.py create mode 100644 tests/benchmarks/test_agentic_bridge.py diff --git a/benchmarks/agentic/bridge.py b/benchmarks/agentic/bridge.py new file mode 100644 index 00000000..854283a5 --- /dev/null +++ b/benchmarks/agentic/bridge.py @@ -0,0 +1,188 @@ +"""Systems manifest, the generic MCP stdio bridge, canonical results and truncation. + +Design §5 and §6: every MCP system goes through this one bridge, exposes its +full tool list unfiltered, and has each ``CallToolResult`` turned into one +canonical text string by the same rule. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import sys +import time +from collections.abc import AsyncIterator, 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.types import CONNECTION_CLOSED, CallToolResult, PaginatedRequestParams, TextContent + +from benchmarks.agentic.types import ToolSpec +from benchmarks.runner import ( + _SAFE_ID, + BenchmarkValidationError, + _load_competitors, + _load_yaml_mapping, + _validate_manifest_eligibility, + cell_failure_from, +) + +RESULT_CAP_BYTES = 100_000 +TRUNCATION_MARKER = "\n[benchmark harness: tool result truncated at 100000 UTF-8 bytes]" + +_TRANSPORTS: dict[str, Literal["stdio", "none"]] = {"mcp-stdio": "stdio", "none": "none"} + + +@dataclass(frozen=True) +class SystemSpec: + id: str + transport: Literal["stdio", "none"] # manifest `adapter`: "mcp-stdio" | "none" + command: tuple[str, ...] # "{python}" is replaced by sys.executable at spawn + env: dict[str, str] + pass_env: tuple[str, ...] + raw: dict[str, Any] + + +@dataclass(frozen=True) +class ToolOutcome: + text: str # full canonical text, before truncation + sha256: str # sha256 of `text` as UTF-8 + is_error: bool + wall_ms: float + + +class BridgeCrash(Exception): + """The MCP transport or session failed; the server is gone.""" + + +class ToolBridge(Protocol): + tools: list[ToolSpec] + + async def call(self, name: str, arguments: dict[str, Any]) -> ToolOutcome: ... + + +def _strings(value: Any, label: str) -> tuple[str, ...]: + if not isinstance(value, list) or not all(isinstance(item, str) for item in value): + raise BenchmarkValidationError(f"{label} must be a list of strings") + return tuple(value) + + +def system_spec_from_raw(raw: Mapping[str, Any]) -> SystemSpec: + """Validate one manifest entry; the worker rebuilds its system with this.""" + system_id = raw.get("id") + if not isinstance(system_id, str) or not _SAFE_ID.fullmatch(system_id): + raise BenchmarkValidationError(f"system id {system_id!r} must match {_SAFE_ID.pattern}") + transport = _TRANSPORTS.get(str(raw.get("adapter"))) + if transport is None: + raise BenchmarkValidationError( + f"system {system_id!r} has adapter {raw.get('adapter')!r}; " + f"expected one of {sorted(_TRANSPORTS)}" + ) + if transport == "none": + return SystemSpec(system_id, transport, (), {}, (), dict(raw)) + command = _strings(raw.get("command"), f"system {system_id!r} 'command'") + if not command: + raise BenchmarkValidationError(f"system {system_id!r} 'command' must not be empty") + env = raw.get("env") or {} + if not isinstance(env, Mapping) or not all( + isinstance(k, str) and isinstance(v, str) for k, v in env.items() + ): + raise BenchmarkValidationError(f"system {system_id!r} 'env' must map strings to strings") + pass_env = _strings(raw.get("pass_env") or [], f"system {system_id!r} 'pass_env'") + return SystemSpec(system_id, transport, command, dict(env), pass_env, dict(raw)) + + +def load_systems(manifest_path: Path) -> list[SystemSpec]: + data = _load_yaml_mapping(manifest_path, "manifest") + _validate_manifest_eligibility(data) + return [system_spec_from_raw(competitor.raw) for competitor in _load_competitors(data)] + + +def canonical_text(result: CallToolResult) -> str: + """Compact JSON of ``structured_content`` when present, else the joined text blocks.""" + if result.structured_content is not None: + return json.dumps(result.structured_content, ensure_ascii=False, separators=(",", ":")) + return "\n".join( + block.text if isinstance(block, TextContent) else f"[{block.type} content omitted]" + for block in result.content + ) + + +def truncate_utf8(text: str, limit: int = RESULT_CAP_BYTES) -> tuple[str, bool]: + """Cut to the longest prefix whose UTF-8 fits ``limit``, plus the marker.""" + data = text.encode("utf-8") + if len(data) <= limit: + return text, False + # The prefix is valid UTF-8 except for a character the cut split; "ignore" drops it. + return data[:limit].decode("utf-8", errors="ignore") + TRUNCATION_MARKER, True + + +class Bridge: + """One live MCP session; implements :class:`ToolBridge`.""" + + def __init__( + self, + session: ClientSession, + server_info: dict[str, Any], + tools_raw: list[dict[str, Any]], + ) -> None: + self._session = session + self.server_info = server_info + self.tools_raw = tools_raw + self.tools = [ + ToolSpec(t["name"], t.get("description") or "", t["inputSchema"]) for t in tools_raw + ] + + async def call(self, name: str, arguments: dict[str, Any]) -> ToolOutcome: + started = time.perf_counter() + 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 + text, is_error = str(exc.message), True + except Exception as exc: # noqa: BLE001 - any other failure means the session is gone + failure = cell_failure_from(exc, timeout_seconds=0.0, label=f"MCP tool {name}") + raise BridgeCrash(str(failure)) from exc + else: + text, is_error = canonical_text(result), bool(result.is_error) + return ToolOutcome( + text=text, + sha256=hashlib.sha256(text.encode("utf-8")).hexdigest(), + is_error=is_error, + wall_ms=(time.perf_counter() - started) * 1000, + ) + + +@asynccontextmanager +async def open_bridge(system: SystemSpec) -> 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) + # 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): + async with ClientSession(read, write) as session: + initialized = await session.initialize() + tools_raw: list[dict[str, Any]] = [] + cursor: str | None = None + while True: + page = await session.list_tools( + params=None if cursor is None else PaginatedRequestParams(cursor=cursor) + ) + tools_raw += [ + t.model_dump(mode="json", by_alias=True, exclude_unset=True) for t in page.tools + ] + cursor = page.next_cursor + if not cursor: + break + server_info = initialized.server_info.model_dump( + mode="json", by_alias=True, exclude_unset=True + ) + yield Bridge(session, server_info, tools_raw) diff --git a/benchmarks/agentic/types.py b/benchmarks/agentic/types.py index 6b082702..c3c0b02f 100644 --- a/benchmarks/agentic/types.py +++ b/benchmarks/agentic/types.py @@ -3,6 +3,16 @@ from __future__ import annotations from dataclasses import dataclass +from typing import Any + + +@dataclass(frozen=True) +class ToolSpec: + """One tool as an MCP server advertises it.""" + + name: str + description: str + input_schema: dict[str, Any] @dataclass(frozen=True) diff --git a/docs/benchmarks/agentic-manifest.yml b/docs/benchmarks/agentic-manifest.yml new file mode 100644 index 00000000..eb7d41e6 --- /dev/null +++ b/docs/benchmarks/agentic-manifest.yml @@ -0,0 +1,40 @@ +# Systems under test for the agentic benchmark, round 1. +# +# Context: docs/benchmarks/AGENTIC-BENCHMARK-DESIGN.md section 5. Every MCP +# system exposes its full tool list exactly as the server advertises it, +# unfiltered, through the one generic stdio bridge +# (benchmarks/agentic/bridge.py). Round 2 adds Context7, GitMCP, DeepWiki and +# Ref.tools behind the terms gates recorded in competitor-manifest.template.yml. +# +# Same `competitors:` format as the fixed-flow manifest, so the runner's loaders +# and the report read it. Agentic fields: +# - 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. +# - 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 + +competitors: + - id: python-docs + name: python-docs-mcp-server + adapter: mcp-stdio + command: ["{python}", "-m", "mcp_server_python_docs", "serve"] + env: + # Never let a missing index trigger the server's network auto-build. + PYTHON_DOCS_MCP_DISABLE_AUTO_INDEX: "1" + 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. + command: [mcp-server-fetch] + env: {} + pass_env: [HOME, HTTPS_PROXY, HTTP_PROXY, NO_PROXY] + + - id: no-docs + name: No documentation tools (correctness floor) + adapter: none diff --git a/tests/benchmarks/fixtures/agentic/fake_fetch_server.py b/tests/benchmarks/fixtures/agentic/fake_fetch_server.py new file mode 100644 index 00000000..9c9442da --- /dev/null +++ b/tests/benchmarks/fixtures/agentic/fake_fetch_server.py @@ -0,0 +1,39 @@ +"""A stand-in for ``mcp-server-fetch`` in the agentic tests: stdio MCP, no network. + +``--edge`` adds tools the bridge and host tests use to observe the server. +""" + +import os +import sys + +from mcp.server import MCPServer + +server = MCPServer("fake-fetch") + + +@server.tool() +def fetch(url: str, max_length: int = 5000, start_index: int = 0, raw: bool = False) -> str: + """Fetch a URL and return its contents (fixed text here).""" + return f"Contents of {url}: the json module encodes and decodes JSON." + + +if "--edge" in sys.argv: + + @server.tool() + def env_names() -> list[str]: + """The sorted names in this process's environment.""" + return sorted(os.environ) + + @server.tool() + def die() -> str: + """Exit at once, mid-request.""" + os._exit(1) + + @server.tool() + def pid() -> int: + """This server's process id.""" + return os.getpid() + + +if __name__ == "__main__": + server.run() diff --git a/tests/benchmarks/test_agentic_bridge.py b/tests/benchmarks/test_agentic_bridge.py new file mode 100644 index 00000000..57adba9a --- /dev/null +++ b/tests/benchmarks/test_agentic_bridge.py @@ -0,0 +1,152 @@ +"""Systems manifest and MCP stdio bridge (design §5, §6).""" + +from __future__ import annotations + +import hashlib +from pathlib import Path + +import pytest +from mcp.types import CallToolResult, ImageContent, TextContent + +from benchmarks.agentic.bridge import ( + TRUNCATION_MARKER, + BridgeCrash, + SystemSpec, + canonical_text, + load_systems, + open_bridge, + system_spec_from_raw, + truncate_utf8, +) +from tests.test_mcp_get_docs_cache_smoke import _create_contentful_json_index +from tests.test_stdio_smoke import _isolated_cache_env + +REPO_ROOT = Path(__file__).resolve().parents[2] +AGENTIC_MANIFEST_PATH = REPO_ROOT / "docs" / "benchmarks" / "agentic-manifest.yml" +FAKE_SERVER = Path(__file__).parent / "fixtures" / "agentic" / "fake_fetch_server.py" + + +def _fake(env: dict[str, str] | None = None, pass_env: list[str] | None = None) -> SystemSpec: + return system_spec_from_raw( + { + "id": "fake-fetch", + "adapter": "mcp-stdio", + "command": ["{python}", str(FAKE_SERVER), "--edge"], + "env": env or {}, + "pass_env": pass_env or [], + } + ) + + +@pytest.fixture +def python_docs(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> SystemSpec: + env, cache_dir = _isolated_cache_env(tmp_path) + _create_contentful_json_index(cache_dir) + monkeypatch.setenv("XDG_CACHE_HOME", env["XDG_CACHE_HOME"]) + monkeypatch.setenv("HOME", env["HOME"]) + return {s.id: s for s in load_systems(AGENTIC_MANIFEST_PATH)}["python-docs"] + + +def test_canonical_text_prefers_compact_structured_content() -> None: + r = CallToolResult( + content=[TextContent(type="text", text="ignored")], + structured_content={"a": "é", "b": [1, 2]}, + is_error=False, + ) + assert canonical_text(r) == '{"a":"é","b":[1,2]}' + + +def test_canonical_text_joins_text_blocks_and_marks_other_blocks() -> None: + r = CallToolResult( + content=[ + TextContent(type="text", text="one"), + ImageContent(type="image", data="aGk=", mime_type="image/png"), + TextContent(type="text", text="two"), + ], + structured_content=None, + is_error=False, + ) + assert canonical_text(r) == "one\n[image content omitted]\ntwo" + + +def test_truncate_utf8_cuts_on_a_character_boundary_and_marks_it() -> None: + text = "a" * 99_999 + "é" + "tail" # "é" is 2 bytes and straddles byte 100,000 + assert truncate_utf8(text, 100_000) == ("a" * 99_999 + TRUNCATION_MARKER, True) + + +def test_truncate_utf8_leaves_a_result_at_the_limit_untouched() -> None: + assert truncate_utf8("a" * 100_000, 100_000) == ("a" * 100_000, False) + + +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"].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["no-docs"].transport == "none" + assert all(system_spec_from_raw(s.raw) == s for s in systems.values()) + + +@pytest.mark.parametrize( + "raw", + [ + {"id": "x", "adapter": "mcp-http"}, + {"id": "x", "adapter": "mcp-stdio", "command": []}, + {"id": "x", "adapter": "mcp-stdio", "command": ["a"], "env": {"A": 1}}, + {"id": "x/y", "adapter": "none"}, + ], +) +def test_system_spec_from_raw_refuses_a_bad_entry(raw: dict) -> None: + from benchmarks.runner import BenchmarkValidationError + + with pytest.raises(BenchmarkValidationError): + system_spec_from_raw(raw) + + +async def test_bridge_lists_the_real_server_tools_unfiltered(python_docs: SystemSpec) -> None: + async with open_bridge(python_docs) as bridge: + assert {t.name for t in bridge.tools} == { + "search_docs", + "get_docs", + "lookup_package_docs", + "list_versions", + "detect_python_version", + "compare_versions", + "whatsnew_for_version", + } + assert len(bridge.tools_raw) == 7 and "name" in bridge.server_info + assert all("inputSchema" in t for t in bridge.tools_raw) + outcome = await bridge.call("get_docs", {"slug": "library/json.html", "version": "3.13"}) + assert outcome.is_error is False and "json module" in outcome.text + assert outcome.sha256 == hashlib.sha256(outcome.text.encode()).hexdigest() + assert outcome.wall_ms > 0 + + +async def test_bridge_returns_an_unknown_tool_as_an_error_result(python_docs: SystemSpec) -> None: + async with open_bridge(python_docs) as bridge: + outcome = await bridge.call("no_such_tool", {}) + assert outcome.is_error is True and "no_such_tool" in outcome.text + + +async def test_bridge_returns_invalid_arguments_as_an_error_result( + python_docs: SystemSpec, +) -> None: + async with open_bridge(python_docs) as bridge: + assert (await bridge.call("search_docs", {"query": 5})).is_error is True + + +async def test_bridge_raises_bridge_crash_when_the_server_dies() -> None: + async with open_bridge(_fake()) as bridge: + with pytest.raises(BridgeCrash): + await bridge.call("die", {}) + + +async def test_server_env_holds_only_the_listed_variables(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-not-a-real-key") + async with open_bridge(_fake(env={"MARKER": "1"}, pass_env=["HOME"])) as bridge: + text = (await bridge.call("env_names", {})).text + assert '"MARKER"' in text and '"HOME"' in text + assert "ANTHROPIC_API_KEY" not in text From 510aa5b185b326fbfe92631c04fd7fe465ddfaa9 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Tue, 3 Nov 2026 22:27:29 +0100 Subject: [PATCH 03/77] feat(benchmarks): add the provider SDKs and tool schema conversion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dev group, exact pins approved by design §13: anthropic 1.15.0, openai 3.32.0, google-genai 2.31.0. Transitive packages younger than 14 days are locked one release back: jiter 0.17.0, google-auth 2.62.0. pyasn1 0.6.5 is the one security exception: it fixes GHSA-fm9c-5rcf-2q5p, GHSA-9m75-vc3g-4x39, GHSA-2qm8-x737-gmw5 and GHSA-mm57-4v3p-rchx, which OSV lists against 0.6.4. No existing locked package changes version and aiohttp stays out of the lock. Tool conversion: Anthropic and OpenAI Responses (strict false) take the MCP schema verbatim; Gemini schemas are reduced to the pinned SDK's Schema keys with every dropped key recorded. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/schemas.py | 87 ++++ pyproject.toml | 3 + tests/benchmarks/test_agentic_schemas.py | 108 +++++ uv.lock | 493 +++++++++++++++++++++++ 4 files changed, 691 insertions(+) create mode 100644 benchmarks/agentic/schemas.py create mode 100644 tests/benchmarks/test_agentic_schemas.py diff --git a/benchmarks/agentic/schemas.py b/benchmarks/agentic/schemas.py new file mode 100644 index 00000000..1c439cd0 --- /dev/null +++ b/benchmarks/agentic/schemas.py @@ -0,0 +1,87 @@ +"""MCP tool -> provider tool conversion (design §6, "Tool schemas"). + +Anthropic and OpenAI take the MCP input schema verbatim (OpenAI with +``strict`` explicitly false). Gemini accepts an OpenAPI subset, so its +schemas are reduced to the keys the pinned SDK's ``Schema`` model knows, and +every dropped key is recorded. +""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Sequence +from typing import Any + +from google.genai import types as genai_types + +from benchmarks.agentic.types import ToolSpec + +#: JSON names (pydantic aliases) of google.genai.types.Schema fields. +GEMINI_SCHEMA_KEYS: frozenset[str] = frozenset( + field.alias or name for name, field in genai_types.Schema.model_fields.items() +) + + +def to_anthropic(tools: Sequence[ToolSpec]) -> list[dict[str, Any]]: + return [ + {"name": t.name, "description": t.description, "input_schema": t.input_schema} + for t in tools + ] + + +def to_openai_responses(tools: Sequence[ToolSpec]) -> list[dict[str, Any]]: + return [ + { + "type": "function", + "name": t.name, + "description": t.description, + "parameters": t.input_schema, + "strict": False, # MCP schemas do not meet strict-mode rules + } + for t in tools + ] + + +def _reduce(schema: Any, path: str, dropped: list[str]) -> Any: + if not isinstance(schema, dict): + return schema + reduced: dict[str, Any] = {} + for key, value in schema.items(): + if key not in GEMINI_SCHEMA_KEYS: + dropped.append(f"{path}.{key}") + elif key == "properties" and isinstance(value, dict): + # Property names are data, not keywords: keep every one, reduce its schema. + reduced[key] = { + name: _reduce(sub, f"{path}.properties.{name}", dropped) + for name, sub in value.items() + } + elif key == "items": + reduced[key] = _reduce(value, f"{path}.items", dropped) + elif key == "anyOf" and isinstance(value, list): + reduced[key] = [ + _reduce(member, f"{path}.anyOf.{index}", dropped) + for index, member in enumerate(value) + ] + else: + reduced[key] = value + return reduced + + +def to_gemini(tools: Sequence[ToolSpec]) -> tuple[list[dict[str, Any]], list[str]]: + """Function declarations, and the dotted paths of every key dropped.""" + dropped: list[str] = [] + declarations = [ + { + "name": t.name, + "description": t.description, + "parameters": _reduce(t.input_schema, t.name, dropped), + } + for t in tools + ] + return declarations, dropped + + +def schemas_sha256(converted: Any) -> str: + canonical = json.dumps(converted, sort_keys=True, ensure_ascii=False, separators=(",", ":")) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest() diff --git a/pyproject.toml b/pyproject.toml index 5abe6f38..10808202 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -40,6 +40,9 @@ dev = [ "pytest-asyncio>=0.23", "ruff>=0.4", "pyright>=1.1", + "anthropic==1.15.0", + "openai==3.32.0", + "google-genai==2.31.0", ] [project.scripts] diff --git a/tests/benchmarks/test_agentic_schemas.py b/tests/benchmarks/test_agentic_schemas.py new file mode 100644 index 00000000..067107f5 --- /dev/null +++ b/tests/benchmarks/test_agentic_schemas.py @@ -0,0 +1,108 @@ +"""MCP tool -> provider tool conversion (design §6, "Tool schemas").""" + +from __future__ import annotations + +import json +from pathlib import Path + +from benchmarks.agentic.schemas import ( + GEMINI_SCHEMA_KEYS, + schemas_sha256, + to_anthropic, + to_gemini, + to_openai_responses, +) +from benchmarks.agentic.types import ToolSpec + +REPO_ROOT = Path(__file__).resolve().parents[2] +TOOLS = [ + ToolSpec(t["name"], t["description"], t["inputSchema"]) + for t in json.loads((REPO_ROOT / "tests/fixtures/tools-list.json").read_text()) +] + + +def test_anthropic_tools_keep_name_description_and_input_schema_verbatim() -> None: + assert to_anthropic(TOOLS)[0] == { + "name": TOOLS[0].name, + "description": TOOLS[0].description, + "input_schema": TOOLS[0].input_schema, + } + assert len(to_anthropic(TOOLS)) == 7 + + +def test_openai_tools_set_strict_false_explicitly() -> None: + converted = to_openai_responses(TOOLS) + assert all(t["type"] == "function" and t["strict"] is False for t in converted) + assert converted[0]["parameters"] == TOOLS[0].input_schema + assert converted[0]["name"] == TOOLS[0].name + + +def test_gemini_reduction_drops_unsupported_keywords_and_records_them() -> None: + spec = ToolSpec( + "fetch", + "d", + { + "type": "object", + "properties": { + "max_length": { + "type": "integer", + "exclusiveMaximum": 1000000, + "exclusiveMinimum": 0, + "default": 5000, + } + }, + "required": [], + }, + ) + decls, dropped = to_gemini([spec]) + assert decls[0]["parameters"]["properties"]["max_length"] == { + "type": "integer", + "default": 5000, + } + assert dropped == [ + "fetch.properties.max_length.exclusiveMaximum", + "fetch.properties.max_length.exclusiveMinimum", + ] + assert decls[0]["name"] == "fetch" and decls[0]["description"] == "d" + + +def test_gemini_reduction_walks_items_and_any_of() -> None: + spec = ToolSpec( + "t", + "d", + { + "type": "object", + "properties": { + "a": {"type": "array", "items": {"type": "string", "const": "x"}}, + "b": {"anyOf": [{"type": "string", "$comment": "c"}, {"type": "null"}]}, + }, + }, + ) + decls, dropped = to_gemini([spec]) + assert decls[0]["parameters"]["properties"]["a"]["items"] == {"type": "string"} + assert dropped == ["t.properties.a.items.const", "t.properties.b.anyOf.0.$comment"] + + +def test_gemini_reduction_keeps_a_property_named_like_a_keyword() -> None: + props = { + "format": {"type": "string"}, + "pattern": {"type": "string"}, + "const": {"type": "string"}, + } + decls, dropped = to_gemini([ToolSpec("t", "d", {"type": "object", "properties": props})]) + assert decls[0]["parameters"]["properties"] == props and dropped == [] + + +def test_gemini_reduction_of_the_real_tool_list_drops_nothing() -> None: + assert to_gemini(TOOLS)[1] == [] + + +def test_gemini_schema_keys_come_from_the_pinned_sdk() -> None: + assert {"anyOf", "enum", "minimum", "maxLength", "description", "default"} <= GEMINI_SCHEMA_KEYS + assert "exclusiveMinimum" not in GEMINI_SCHEMA_KEYS + assert "max_length" not in GEMINI_SCHEMA_KEYS # aliases, not Python field names + + +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}]) diff --git a/uv.lock b/uv.lock index 6fe56837..086fbdde 100644 --- a/uv.lock +++ b/uv.lock @@ -17,6 +17,25 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl", hash = "sha256:1f02e8b43a8fbbc3f3e0d4f0f4bfc8131bcb4eebe8849b8e5c773f3a1c582a53", size = 13643, upload-time = "2024-05-20T21:33:24.1Z" }, ] +[[package]] +name = "anthropic" +version = "1.15.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "docstring-parser" }, + { name = "httpx2" }, + { name = "jiter" }, + { name = "opentelemetry-api" }, + { name = "pydantic" }, + { name = "sniffio" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/10/37/5a2a4316df8babd28f096477a707cd75f240b4264c97fb128c32375105d6/anthropic-1.15.0.tar.gz", hash = "sha256:90caa9df83e2fc8bddb4ddeb83b7191bce255f635c03eae055deec521741df08", size = 1726101, upload-time = "2026-10-15T19:45:34.635Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/65/54437e7edea49a3be9ef56f6b5965999bfdc52b9dadc9b448124ca51a594/anthropic-1.15.0-py3-none-any.whl", hash = "sha256:10189a7993c5c71a0a2d4bb80020ca6a2fd27679f51e627405da37251d15ff49", size = 2047755, upload-time = "2026-10-15T19:45:32.951Z" }, +] + [[package]] name = "anyio" version = "4.14.2" @@ -118,6 +137,137 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ae/3a/dbeec9d1ee0844c679f6bb5d6ad4e9f198b1224f4e7a32825f47f6192b0c/cffi-2.0.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0a1527a803f0a659de1af2e1fd700213caba79377e27e4693648c2923da066f9", size = 184195, upload-time = "2025-09-08T23:23:43.004Z" }, ] +[[package]] +name = "charset-normalizer" +version = "3.5.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/33/1c/f41d4e74c28ab327ff3acd36053f7ea506c55872d7a90b0fa71aa3ab0c89/charset_normalizer-3.5.2.tar.gz", hash = "sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef", size = 172659, upload-time = "2026-09-30T04:39:23.398Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/c8/693809898870237d82785a03f3b2b58fe4c9f14669f84a7d4e623c92a59e/charset_normalizer-3.5.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:ed2a239c0ea213acc1908150a3037257083c7c083128f1a4cec2ec4b97dca491", size = 367780, upload-time = "2026-09-30T04:35:30.888Z" }, + { url = "https://files.pythonhosted.org/packages/c9/87/2fea8c13dc24b3ca9c6f803a5b2dfdeae73eb4f9e12c7885ed908ff0433c/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b91363207bd9dc966a691e959bb47f64b30f7ac4b072be9968b366982f7db77c", size = 246730, upload-time = "2026-09-30T04:35:32.286Z" }, + { url = "https://files.pythonhosted.org/packages/a8/9e/09efac30b937722f46d3110ba30b875b24b2e3a266ed746cc4e376a94d80/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:38a873987f3be698494da8b2e3085e29da02da7b633dce73e79c699a113d7bf0", size = 237707, upload-time = "2026-09-30T04:35:33.709Z" }, + { url = "https://files.pythonhosted.org/packages/9e/18/70d76670b13686237863a379928d60bd10e021f17d243ab3d7014c4a5f4e/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:355ad8011081dec5412240c087a9a0c9d4d5039f3ed11a3f13e18c2b29b56c51", size = 273050, upload-time = "2026-09-30T04:35:35.138Z" }, + { url = "https://files.pythonhosted.org/packages/54/e2/77a8b09d5adc013ed07b95b01b8b8fa5441c4e810e83ee7e4aae2fa4d91a/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ee21e28f0430bd6dc9086c6e525d5e818a44a5ad19720c8a0ef766792f3eb5e5", size = 270345, upload-time = "2026-09-30T04:35:36.502Z" }, + { url = "https://files.pythonhosted.org/packages/7f/c5/38806a25ab5e65fc178f39affeda20858efafede2fce1ffc2556cfc9fe73/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3d31298449090ab8d47b7b1b2a555ff73cac7ed438a08b7ac160980c7ebed649", size = 257601, upload-time = "2026-09-30T04:35:37.919Z" }, + { url = "https://files.pythonhosted.org/packages/ae/8d/213565184708fdb263ae55e2c04ee1ff748129dd65d48ed0e3502da9c85a/charset_normalizer-3.5.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5cde776b7cc66e4f6c99612cea4aa7269aa65863f7a15841b2c264f103822f4e", size = 252222, upload-time = "2026-09-30T04:35:39.544Z" }, + { url = "https://files.pythonhosted.org/packages/7e/24/76d2cefc25472531e4c5c7dfff68865eb1c39b78482f0fdc15b46f047830/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ae4f5fea5b8b8ccff88238cc8569303e5ee95efae67fa62922a311397a71f346", size = 248482, upload-time = "2026-09-30T04:35:41.088Z" }, + { url = "https://files.pythonhosted.org/packages/7d/dc/65a801b66ab4c197e22c433ab25e7ac24324ac6f45a2269aca42cce309bf/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:f7d486c83842422badd511868fd8a9a20e9407ace71564b6af47ce7e60a336c1", size = 241206, upload-time = "2026-09-30T04:35:42.59Z" }, + { url = "https://files.pythonhosted.org/packages/a7/95/ca9b5eabde673002c6f1e7ada1b223916fe18f6d661da7aabd4d643718f1/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:11a4d68a6ecda3292cb1e50239e111543ba5d709bb62a6b4ea1afcfa729d8875", size = 273190, upload-time = "2026-09-30T04:35:44.347Z" }, + { url = "https://files.pythonhosted.org/packages/2d/8b/803b4d2a3f6e1740f63f1e87b04d14b42f3d4fdfe6ed7d4db2d34102b14f/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:d6734d2ef8a50fbf8445c139477da401f50d62a0606bf00e20ec6d87773fefb1", size = 253527, upload-time = "2026-09-30T04:35:45.915Z" }, + { url = "https://files.pythonhosted.org/packages/a9/55/93c0e5dbd085ae0471346026abbe7e0db9ea2d6fea74e51f0b5a46f233a7/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:a815775b6c38d4e0ff7bcffbeba67feded90202bb6a226b8dd35f1c855217413", size = 271285, upload-time = "2026-09-30T04:35:47.49Z" }, + { url = "https://files.pythonhosted.org/packages/95/69/0dbd0e0b9b16cfa816cdfcb3e2e3854a1f680dc07fb1245ea125e7448060/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:23851fb4e1b85ed3f6c2a27b777cdfe2e19fb5b38429a8faf38c7542b7665869", size = 260010, upload-time = "2026-09-30T04:35:48.996Z" }, + { url = "https://files.pythonhosted.org/packages/58/9d/e7b88e7b1bf403590c3b573277b5e1e488c68c7a6fbacca310a2c324e90c/charset_normalizer-3.5.2-cp312-cp312-win32.whl", hash = "sha256:db19d07e2e0129e974a0e65d0064fc222a446cd5122c2fd4184d2af9fc734a9e", size = 184125, upload-time = "2026-09-30T04:35:50.777Z" }, + { url = "https://files.pythonhosted.org/packages/eb/e6/e6e083884cbcfd49c64865af05027fe7011be7b2d9179524f099a1b611f3/charset_normalizer-3.5.2-cp312-cp312-win_amd64.whl", hash = "sha256:780fbe7cab297b81dad9fb8dc5eb003c0468ffb0d9e5f65068c53a34661a96bc", size = 207486, upload-time = "2026-09-30T04:35:52.194Z" }, + { url = "https://files.pythonhosted.org/packages/c4/e3/017aea0911ada7405a825c7d937eb3a13009664e2f5b38e8c4bbf2abf894/charset_normalizer-3.5.2-cp312-cp312-win_arm64.whl", hash = "sha256:e2af3aad578aa6bd1384bcf4750fc285e5a9de53f40b7d41e5a0bf748edeb2b3", size = 196734, upload-time = "2026-09-30T04:35:53.636Z" }, + { url = "https://files.pythonhosted.org/packages/c5/34/68292d68512768591aaff07c59bb53ee31341c87759433a859c4641a50c2/charset_normalizer-3.5.2-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:ed905975ab14056a2e5eb1c376cb2e1ebc5396baf84163939c518556fccde9f5", size = 225946, upload-time = "2026-09-30T04:35:55.313Z" }, + { url = "https://files.pythonhosted.org/packages/e3/80/bee0b01b90ccd5322ae1d0abb33fab1bd95b7c2eadaf02aeccf22e04ee83/charset_normalizer-3.5.2-cp313-cp313-android_24_x86_64.whl", hash = "sha256:a66c3bc5ab1f0ff2164fc9965ddd611ff0802173f4b9d24554c563f6ab7e1d6e", size = 238619, upload-time = "2026-09-30T04:35:56.863Z" }, + { url = "https://files.pythonhosted.org/packages/78/6e/60ce52a85a7fd631ae8482ae6d74521014ca2f255892679484dc04d7ef56/charset_normalizer-3.5.2-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:d2374b62878abb00cd8309b32af6c0b715cd02dec0ca74ef12e5069bdc64144a", size = 206701, upload-time = "2026-09-30T04:35:58.639Z" }, + { url = "https://files.pythonhosted.org/packages/36/8c/71aafad23f971afc84c2b295bc0c560739ce1dac558aad9fec22e39f3639/charset_normalizer-3.5.2-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:d376bbd28b3a8999db1a103b3b388aee6f1ddeb3e51bc2172993efdcd86e064d", size = 210506, upload-time = "2026-09-30T04:36:00.147Z" }, + { url = "https://files.pythonhosted.org/packages/91/da/3c5a7798c046df7d2d68ad653cf5b6c5a8bfee225055a843c6f2f42aac1a/charset_normalizer-3.5.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:6045373d5a89a5ec71afde535db987ca28e76dfa276c2d4c818265b375d4b055", size = 366626, upload-time = "2026-09-30T04:36:01.77Z" }, + { url = "https://files.pythonhosted.org/packages/e1/16/710ac3de2ee354e2bd1a9c94efe45a2d27b5c6ad39b2d6a905be2c094b6c/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:849df64e889b2e17230d58410a03dba311a65b163508fd33679b2b737d4b7858", size = 244624, upload-time = "2026-09-30T04:36:03.389Z" }, + { url = "https://files.pythonhosted.org/packages/d6/39/45c7439f5b63d24f7d5b2a1d760f34af7628782d7144b4cc8ded45c2d4bc/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:15c44f7edfd477b06f517a5cc317fc1707edb9de2c865f43d4b6513907473234", size = 235731, upload-time = "2026-09-30T04:36:04.987Z" }, + { url = "https://files.pythonhosted.org/packages/4d/34/38f3154785ce92e9f56eb226f4d35bdfae6b008480dd055f58837a89c810/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a89012d6d5476ee112d20d998570ed58df2260a852afb1758809cd6900411d21", size = 270352, upload-time = "2026-09-30T04:36:06.412Z" }, + { url = "https://files.pythonhosted.org/packages/04/f3/859f74e7babc977705026b30593b3be04049632a522fb7000f83c033d747/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0c951d5e6dd9c2ff60609476752bee49da4206adde960ebc247766937f72e718", size = 267393, upload-time = "2026-09-30T04:36:07.865Z" }, + { url = "https://files.pythonhosted.org/packages/4b/85/41d27f234b82e47c167a5f6c0f62501dc0c640585ff4aba79e08a390336a/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7218e8f32b0956cfcd048fd42d9d5779809745ca1d86113ca56f66e7ae1549c4", size = 254660, upload-time = "2026-09-30T04:36:09.248Z" }, + { url = "https://files.pythonhosted.org/packages/58/ca/5d1a997587febe5b26d8daffe363b5c1a091cece19828eec6502fd09c5ef/charset_normalizer-3.5.2-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a19a731138fc27d5682277d3b9df22855cea1239bce7fcec5f78f42ef2d1f3c3", size = 249996, upload-time = "2026-09-30T04:36:10.73Z" }, + { url = "https://files.pythonhosted.org/packages/b3/1f/d1e78246f7ed60c8c8d606b4ac27f66ce49cc3e95f24893ccbeba9f77302/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:62603db9a7caa0802eaa28c1c46fecd7b3a263a774069c24c3c28c302448721c", size = 247028, upload-time = "2026-09-30T04:36:12.294Z" }, + { url = "https://files.pythonhosted.org/packages/8e/37/eba316edd4f0c4d3a5d945924c4eeeae59abac4056aa815d8a4268f863a2/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:b6856554c4f44d79fc2307d5768854310a8f0096e501c75637542c82292b0429", size = 240562, upload-time = "2026-09-30T04:36:13.887Z" }, + { url = "https://files.pythonhosted.org/packages/c8/8e/aaa037d40ca9ef045977f1a661048b1aa33f223adfce3452fe9be9f79d14/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:1bc0baf5ef96b6ede57d47f4b8fe4d9d84019c3bfcbeb20a41edc6a6ee341f1f", size = 271699, upload-time = "2026-09-30T04:36:15.41Z" }, + { url = "https://files.pythonhosted.org/packages/26/19/1c1c9f75974adf523b87f34b8a2adc5a435cd65916812bcbd0dfa45f9a29/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:56bc200a365efb37383b7852e4cc5898d3b2da5987289b543956cf8cad71018a", size = 252030, upload-time = "2026-09-30T04:36:16.839Z" }, + { url = "https://files.pythonhosted.org/packages/bc/90/0660ef18e18df0a4d2a1a0edff7dfbba42d4e50ef2425557a5bb7051f77b/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:2c9ad19a6cfcd5ea5c0d41161d22f9df1dcc277e9bef2751391334546a314c00", size = 268565, upload-time = "2026-09-30T04:36:18.468Z" }, + { url = "https://files.pythonhosted.org/packages/79/ba/57adc269824e8658f1a0f97a9e514c247445a9632b3419b97e0ba37f16dc/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e243bd13217235fc7290c621941c3f5cc8b66e4872495be821d7436ba2fb838d", size = 257627, upload-time = "2026-09-30T04:36:19.938Z" }, + { url = "https://files.pythonhosted.org/packages/9a/85/33abd4315c052d3d4f54c92b1ee49bfbc0dc7115a981e462a793b6d2ab87/charset_normalizer-3.5.2-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:a090bb2c68df85450502e3e20d665e3a5af9c65a84d6508ed477badd49166fd3", size = 143407, upload-time = "2026-09-30T04:36:21.376Z" }, + { url = "https://files.pythonhosted.org/packages/4f/de/6435e18d1aaa5d910b896d551411c96af1f42a0c56c29afc2016c61ccc2e/charset_normalizer-3.5.2-cp313-cp313-win32.whl", hash = "sha256:2b7b3bbfb4fe8ef40600792d762fbaa9057559f9d3fad209525b7a22b99e91fd", size = 183207, upload-time = "2026-09-30T04:36:22.776Z" }, + { url = "https://files.pythonhosted.org/packages/9c/76/b8ec57f4e9ee3253541abf95e4a462c0175fe8032dcd070f1f2421240942/charset_normalizer-3.5.2-cp313-cp313-win_amd64.whl", hash = "sha256:78456a747de8dc58360ffa581f30a002baf5aa28cb262536545e91f113ed7639", size = 206489, upload-time = "2026-09-30T04:36:24.306Z" }, + { url = "https://files.pythonhosted.org/packages/3e/60/c647c6ae47480221e875ea5d743ff94946f7416e3c69415ab772928e8d32/charset_normalizer-3.5.2-cp313-cp313-win_arm64.whl", hash = "sha256:11912e4bb14baae7c5d8791aa55ba0a3a03ec6729073307b0f57270abaa713d3", size = 195501, upload-time = "2026-09-30T04:36:25.846Z" }, + { url = "https://files.pythonhosted.org/packages/58/ca/7aa91362a2f77ac8e9e28a9b902a74f7d0e11a851ef0d27a74308da8cd90/charset_normalizer-3.5.2-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:1afb975bd5d68d5ce9f6b6d44fdf2f7e34b895a35e95708a7a91b20a3b51d187", size = 226010, upload-time = "2026-09-30T04:36:27.669Z" }, + { url = "https://files.pythonhosted.org/packages/a8/cf/ac8878d0322cf88a1aad4c7b147db32ca0bd806eb0060957b2e31486dbe6/charset_normalizer-3.5.2-cp314-cp314-android_24_x86_64.whl", hash = "sha256:bbbfc8e28816f19d7c0f1816664980c0a9875d01b27cdf8eedddb639d9e108ad", size = 239266, upload-time = "2026-09-30T04:36:29.434Z" }, + { url = "https://files.pythonhosted.org/packages/c9/6d/9a08d7e0b29b7208e2c6c01dc56c8e0520e7c7beadbbfb024b58fd69c8a5/charset_normalizer-3.5.2-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7967d08cf06dee78443b874f98c98036f624f3a4e73e11f9f64f5be4d25393cf", size = 206783, upload-time = "2026-09-30T04:36:30.872Z" }, + { url = "https://files.pythonhosted.org/packages/82/44/b0aa350280e6ff5a5492d17cf10460dd39d5ee848f872f7ba2df10607f60/charset_normalizer-3.5.2-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:4c2b5031f63e331e3839b40aed2dd6f191e9c07edbde303e7876846ea1946995", size = 210449, upload-time = "2026-09-30T04:36:32.625Z" }, + { url = "https://files.pythonhosted.org/packages/7c/8a/40db9aa9f5907bb0e6f8b6d64064bf8852fb33d4b813ff9414911df7647c/charset_normalizer-3.5.2-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:fcff63213e8e6e47770541a4607175404f47cbb3ebea7b6058cc82d524a0e424", size = 367815, upload-time = "2026-09-30T04:36:34.197Z" }, + { url = "https://files.pythonhosted.org/packages/7f/72/9c5e7707b57c8ddfa9ddf7b0b1d009d7fbab9e9e887d5b721060f37e307d/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8d86d6fc60743dc916eb79e2eb1ec4818e21e427731543af40a3021851174a13", size = 247095, upload-time = "2026-09-30T04:36:35.803Z" }, + { url = "https://files.pythonhosted.org/packages/83/09/71e453691e927de4ddf792770cfaab3f49d494e222f66ea5e404bbd5e39c/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:7a881931aa470808df94a8c380eed2bbbc76cd9dc622310f99665658c821eb6d", size = 233942, upload-time = "2026-09-30T04:36:37.407Z" }, + { url = "https://files.pythonhosted.org/packages/9f/86/85c84e4da8b27dd409577d9437926ff581c5f9d3c66038dc68c1a526de51/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8024d00c3faf3fc0c16e07a69f4405e8eac7cc0ab15f65fe6cf43827c4cf72b4", size = 273762, upload-time = "2026-09-30T04:36:38.904Z" }, + { url = "https://files.pythonhosted.org/packages/92/08/564955a4b5f2ccb410ab480bbe8c6a18063ff27f2d35458731c4a5335df9/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4d48f2d08b9de5864e2c8744d4461b862fb149a18274abc8b698c45975573438", size = 269514, upload-time = "2026-09-30T04:36:40.469Z" }, + { url = "https://files.pythonhosted.org/packages/18/24/bad3ac4271589df29cf5ce2f5ae490518a5739358052bd0d61209e6fea54/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:34276fd796040bf0993ab33a369aa572e6979c7aab225a88893667ad8eac8f7a", size = 255056, upload-time = "2026-09-30T04:36:42.02Z" }, + { url = "https://files.pythonhosted.org/packages/d6/3e/350d89ad49916b86554d6f5f2d03ec1152148f87e5ff735106c6a03b1a36/charset_normalizer-3.5.2-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0521c5665880b33d603717defa76c094048900010897909952397feb3039da56", size = 251311, upload-time = "2026-09-30T04:36:43.577Z" }, + { url = "https://files.pythonhosted.org/packages/56/5b/4970a2d154df502e133402906dd04e3ae7cada7b3011283c88d0479a2585/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:eff0ac9dbe711a4aee69bf04a83896aa9b85f19641264053a9f6d48573abb7dd", size = 250190, upload-time = "2026-09-30T04:36:45.185Z" }, + { url = "https://files.pythonhosted.org/packages/88/8c/f1a91bddc8fb47c2889e29ea7ea49a194eb0d9868675d786806519c00d76/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:1503bccbeb36d5527790c3930327704c39af22de3112f1b1666a9f3ce15ee204", size = 237098, upload-time = "2026-09-30T04:36:46.689Z" }, + { url = "https://files.pythonhosted.org/packages/24/0e/bb5dace3cc7e79068425386a6589c19b5a2ab5fefc2a46abea6919683332/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:52aa6992700996af31f375de0c6bacd402b0097fe40b53c426b9f51a90ebabc7", size = 274228, upload-time = "2026-09-30T04:36:48.31Z" }, + { url = "https://files.pythonhosted.org/packages/9d/79/b849ad523017ea9f5a45581bbebed91439e0cf42fd2860a6f64e358eb5a6/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:e09a3942ecbdee5cce73ea9d42da82b81b72ac1bf031ce069b93b5adf4eac8cd", size = 252401, upload-time = "2026-09-30T04:36:50.091Z" }, + { url = "https://files.pythonhosted.org/packages/89/8c/75469d690cf47200bce8f6cad7655724fc23148e147abfc5ce78b5f65863/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:c7c9ab723cde841fefb34efbad91e87f00a674b1fe1cd0784fde742bf2c154dc", size = 271846, upload-time = "2026-09-30T04:36:51.719Z" }, + { url = "https://files.pythonhosted.org/packages/26/cd/6d52d3c7437cdcf2e310ce9f28f282e733d4ef60ed19105d1819c356255f/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ddc7dacc8ece3a182e7f15cb862d1fd616b46d076cb1ae9dd232b2c38b655874", size = 258151, upload-time = "2026-09-30T04:36:53.234Z" }, + { url = "https://files.pythonhosted.org/packages/f7/4c/070b38bdb5f49a70199fce923ec0726a49536a63ab262abbfcaaf351110b/charset_normalizer-3.5.2-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:ee43c17b173d46a3212baa6ead3ae258eeabdae48c263a01ccf0218c366dd655", size = 143570, upload-time = "2026-09-30T04:36:54.816Z" }, + { url = "https://files.pythonhosted.org/packages/81/84/9ebfc8ed6c8c4fcd8e726ff6bf220cc8deb3966e31dce9be8dd8aa017e64/charset_normalizer-3.5.2-cp314-cp314-win32.whl", hash = "sha256:4f87960d57feabfb618e4e0af6e7371645fa26a277860739d6e5d6e0012c92f0", size = 186412, upload-time = "2026-09-30T04:36:56.643Z" }, + { url = "https://files.pythonhosted.org/packages/d1/78/5ed86f743d4bc350db307e7636419a0a5ee1d91806d30c7f667bd5c80dae/charset_normalizer-3.5.2-cp314-cp314-win_amd64.whl", hash = "sha256:e4e81e09c1578b8df602e3db08b0b3ea0a6947ad612f52bf8dc5ea8d47691f0c", size = 210965, upload-time = "2026-09-30T04:36:58.205Z" }, + { url = "https://files.pythonhosted.org/packages/53/94/a3a7698e9b1a395e1eb99ccd9a324be9347973bff4e72db2a06496d7cd27/charset_normalizer-3.5.2-cp314-cp314-win_arm64.whl", hash = "sha256:80d02b6f04e92601a081dd97b23d3128033098bff5d35d392ddcc0476ea11253", size = 200406, upload-time = "2026-09-30T04:36:59.764Z" }, + { url = "https://files.pythonhosted.org/packages/c1/48/c5dd00d5ef7791f02666de250a5bb6071e29b7e133cf4b835800b6d3bc27/charset_normalizer-3.5.2-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:dca9ab98072a5a54ebacebdc45f53e645336b320c667410b061be1ca588ae709", size = 396871, upload-time = "2026-09-30T04:37:01.543Z" }, + { url = "https://files.pythonhosted.org/packages/12/c8/8379554b42e8368161d898476686947a0fdbd3e8865170d7909dcabfdee8/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f0aa869112ef88429ae17820d99c3dd9504c9e9c671d3c246f3d7442cb051084", size = 249711, upload-time = "2026-09-30T04:37:03.111Z" }, + { url = "https://files.pythonhosted.org/packages/4a/eb/2ddb1035d17320caa9f41682935123a9a250277b261c3efc86b2d2a21343/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c0afc6800ba57ccc350374c5bd6150419915d95ce93cdbab2d783d75eaf30ecb", size = 231146, upload-time = "2026-09-30T04:37:04.721Z" }, + { url = "https://files.pythonhosted.org/packages/4a/24/2ecb4bde104322cd7859d6594fcfa74649f8d90b3221c9feecbef149875b/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7dcd882da75ef9adf94903b1e3b9419e8aa8fb4c7396822b834b9ef7fb96954f", size = 271552, upload-time = "2026-09-30T04:37:06.295Z" }, + { url = "https://files.pythonhosted.org/packages/3f/98/9d5f6ebc3aee9fef5d30b4aff11fb2ab7a1222b4064f8ef2c7c87cde217a/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2e06a3a98f916dd41d27f3105e02e7a40181c98c94b9158733d03a6f80506c09", size = 269810, upload-time = "2026-09-30T04:37:07.905Z" }, + { url = "https://files.pythonhosted.org/packages/09/e1/a3b06a10461b1b7628853c934c644e03bc28e42767116afb52f19a56519b/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6bd128f206a7752ae1f2ab6c61bf8a24ba28913a10df8b14c2637b973ff97a80", size = 259845, upload-time = "2026-09-30T04:37:09.554Z" }, + { url = "https://files.pythonhosted.org/packages/fd/d3/6f561f74a296cf27d61775a1dc665ad13f3bff6a798810ca05907f37a7c4/charset_normalizer-3.5.2-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c8f3d67aeaf55f017982b73683f0e7342ba2f6635a78f69ce89ebb26aa411e5c", size = 252825, upload-time = "2026-09-30T04:37:11.274Z" }, + { url = "https://files.pythonhosted.org/packages/26/9f/69e13ca3b18f43e0eafcd34c04a45b732ae22a43b54a5fc9e119103356eb/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:fe9753dfee015c570d73df76f899f18444d41388bffcde097deba51c4fadbb9f", size = 252659, upload-time = "2026-09-30T04:37:12.941Z" }, + { url = "https://files.pythonhosted.org/packages/73/a9/ace29806a0dae18939919c76ba526472d83214afa101105fabff2cf30625/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:92888bb3187c5ba50500b00b3b310c9f2c651709d28036077680cb5255450a03", size = 238819, upload-time = "2026-09-30T04:37:14.659Z" }, + { url = "https://files.pythonhosted.org/packages/f8/c1/6116d52a2e3311ec80f21f5fb5e17b27405f10b9608af8f6e69516841a1b/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:d008d90a7f2471519aef0c90dfbe73b3e6e4d5e66ac48e19154c17e89e98b604", size = 272973, upload-time = "2026-09-30T04:37:16.346Z" }, + { url = "https://files.pythonhosted.org/packages/19/aa/9955c7e93bba10a9c7e8f7a5031b7ced66f3a1883a55c00712b8d5850ff3/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:31f3930700408d211f13378ccbe1c40845d8da54bd0681fac3a9b5aae81c7aa8", size = 253692, upload-time = "2026-09-30T04:37:18.212Z" }, + { url = "https://files.pythonhosted.org/packages/bb/33/2a6ae7fdc1b10cb581cef91addd8cdfc5f40d50abb5702309369d5834579/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:2a925889534b3748302dae5dead07cc13480de1dac3aea80a941b729b471ef93", size = 268757, upload-time = "2026-09-30T04:37:19.877Z" }, + { url = "https://files.pythonhosted.org/packages/a2/22/80992720a0282cd39bba1db35868e6b9c22f41281160143a836544bc1d8a/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f5ec61164adcec446f8969a3358ec3f9b26bbda3b9213e5586d219afa8df2915", size = 262220, upload-time = "2026-09-30T04:37:21.583Z" }, + { url = "https://files.pythonhosted.org/packages/92/9f/181fd07e1bffea1d95cd80c84ac537354f50699c22cfc4d3c02b6fc16208/charset_normalizer-3.5.2-cp314-cp314t-win32.whl", hash = "sha256:598a11a2c7ebaa5334bf698bf29568c9c390abac6a154d8170fedecd1cea38c5", size = 197797, upload-time = "2026-09-30T04:37:23.235Z" }, + { url = "https://files.pythonhosted.org/packages/49/1c/25d8415ec1c4f2f41f1680435e4c87cfb378ff2f677d950946f2a45d0632/charset_normalizer-3.5.2-cp314-cp314t-win_amd64.whl", hash = "sha256:7fdde2c9fd9e3eca40631e024664cf2584272cc8f96308cbe5fdfc930f51d8bc", size = 222765, upload-time = "2026-09-30T04:37:24.891Z" }, + { url = "https://files.pythonhosted.org/packages/3e/b4/46b48f013dadfc0d0d33b375438e31bdf5a989dc68389c6bf627054d4df9/charset_normalizer-3.5.2-cp314-cp314t-win_arm64.whl", hash = "sha256:d1befeed746d247c81127bb14de9dc3d30edb6e5976d34f83f86ed262b1d9105", size = 210985, upload-time = "2026-09-30T04:37:26.634Z" }, + { url = "https://files.pythonhosted.org/packages/ca/e9/34e597dee616d0b8ee4b34d29399e85c2204ade174157a48505d42baa4ff/charset_normalizer-3.5.2-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:87475fabc8d9996fd9c27debb395e642e8c838d78a00b6e932227a0e06b81e26", size = 367676, upload-time = "2026-09-30T04:37:28.329Z" }, + { url = "https://files.pythonhosted.org/packages/60/9f/a5d1c91c0263745e2cd344c5a4415d787c575501ab1d449f1148ac6b495d/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9409a8bf35cf78353942504b24a57de3d75b708997a1e4bd8db71ac8633ce364", size = 248414, upload-time = "2026-09-30T04:37:30.167Z" }, + { url = "https://files.pythonhosted.org/packages/26/79/e697f77464748a3ee3cf490c83d592459400d4898380d66c38366b03080c/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:498dc3188ca05a68231ac3fdbfc7f57eb67e1343c30e0fea17f8218c1599b253", size = 244775, upload-time = "2026-09-30T04:37:31.964Z" }, + { url = "https://files.pythonhosted.org/packages/ca/87/3d42a42e18ea066e2513936fd678a00696e77878b5ae04528976abdbcb83/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e242bb1c5e76e97dfa9e7f209a71e93a01d7f19ffdd5cfbb2e2d55b4f08f8ab0", size = 273877, upload-time = "2026-09-30T04:37:33.661Z" }, + { url = "https://files.pythonhosted.org/packages/c3/76/8a28136f3938ba9836f84280ce0c4d61ed1cf15a036b2034900c62634162/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:def79fa35ef0cef8d2accec024f4fdc7ead3012ff02f5215c783f39f03ef8cfc", size = 269455, upload-time = "2026-09-30T04:37:35.573Z" }, + { url = "https://files.pythonhosted.org/packages/a0/a1/4fbf5d0f0f1b2a080474c1cf9a2f12c4c6531bb0e8ba591055e846d2b4e9/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3df041de8887954562c9b261cba85ca0e9ded74048daf125f45edcfaa4832229", size = 257336, upload-time = "2026-09-30T04:37:37.397Z" }, + { url = "https://files.pythonhosted.org/packages/ba/a2/8b50aa320adb880ad579518e6f718f24944804b42a88b83d267d5d444125/charset_normalizer-3.5.2-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:04851f73ae72b8413dddadb16a49dfee95263553741fd42d546f7d66907e6be5", size = 257584, upload-time = "2026-09-30T04:37:39.522Z" }, + { url = "https://files.pythonhosted.org/packages/a5/57/50e3fed84e175f40349bd0da7a4fce94c87f0378f52d74f511d89e0bdc20/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:183b88127acdb4fabe59d951ab424faf1af7b63cdbb5f776186c1ea2ffcaed98", size = 251854, upload-time = "2026-09-30T04:37:41.23Z" }, + { url = "https://files.pythonhosted.org/packages/d6/54/f7fbb3493c9f49091213b9c2d6dd65800696f1ce1a3f196a4205f50417b1/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:16fa0eccf81304b79c5cd87f9271c3b85dd9dd99245e4422ae9c0dd45e0f99d3", size = 248767, upload-time = "2026-09-30T04:37:42.883Z" }, + { url = "https://files.pythonhosted.org/packages/d9/37/b3a6385acc5a1e45b39ae9c90bfb9cf838a09b9dd37ef2740ab4c6b4a2eb/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:7441d755b7ab94f8d4eb3e43ec05482d760842fd263d003a99102d742cd835e2", size = 274479, upload-time = "2026-09-30T04:37:44.658Z" }, + { url = "https://files.pythonhosted.org/packages/89/44/809913e2cfd279e635a9294fdbbfb1b1dc62a8189d473d561f649fce98d8/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:ca403d7e4798f525fdfc78e258820419cbbd0f0ecbab9de7840e3c017cf6b8cf", size = 258310, upload-time = "2026-09-30T04:37:46.529Z" }, + { url = "https://files.pythonhosted.org/packages/af/a2/f28400ab13359d91bd39179df8e149376b9bf36588e739a3a4f9de2b84b2/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:df29a0a7107f7011e77f4eebdddec4c7331e24d787a0b21a46d63bdf7445da95", size = 271100, upload-time = "2026-09-30T04:37:48.399Z" }, + { url = "https://files.pythonhosted.org/packages/e9/89/9bab37955edf0adb3b66f8a3a6617d9f2f487e0d56f295a6a286cb640aa6/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:f3c96f633825733f735c5a9cf21d21a257d8e1edf0b1cee0a064b9c424ca0f7d", size = 259936, upload-time = "2026-09-30T04:37:50.023Z" }, + { url = "https://files.pythonhosted.org/packages/23/b5/4459e08d45a679f903d50fea08bc52cfa728cca4d7bd02c757b5e5abda2e/charset_normalizer-3.5.2-cp315-cp315-win32.whl", hash = "sha256:281cb91036248400f4cc957495cccd44c275c2e0c5854f7e45ac5cf7dc193847", size = 186301, upload-time = "2026-09-30T04:37:51.722Z" }, + { url = "https://files.pythonhosted.org/packages/98/e8/55d5fd3935b4bce6da4fe0df61898e8c82653e317e677bd58aceb9c60f13/charset_normalizer-3.5.2-cp315-cp315-win_amd64.whl", hash = "sha256:89b53f3cda69831909888e0494f4fa0bcd3537e3e138dabeb620bd6ad946bae8", size = 210858, upload-time = "2026-09-30T04:37:53.427Z" }, + { url = "https://files.pythonhosted.org/packages/a9/5b/974423c2fd8e524c7a7f64318c1e02240ef954912fa2b4d70344107b9c68/charset_normalizer-3.5.2-cp315-cp315-win_arm64.whl", hash = "sha256:6be488a102b8cf28d0391d8c4ba7748938ae28b78ad901f8585520fca33ead1a", size = 200309, upload-time = "2026-09-30T04:37:55.015Z" }, + { url = "https://files.pythonhosted.org/packages/ee/f9/00ee0195db1013d8f7c416fd770fbeb560bb46eb2e36b054d05cb56f6cfa/charset_normalizer-3.5.2-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:915563965d418f986e7e145accc592eae9e1a1be3566ff98a05d7a9ec42a76e1", size = 395343, upload-time = "2026-09-30T04:37:56.743Z" }, + { url = "https://files.pythonhosted.org/packages/04/3a/c00b50e94c964cf934c7899cd47c97952fc11dad71cc5884b3c61795b09b/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:65cd72beeeca9d3aaea1201e5923859f308f952f9c71de93f06063c79f0f7a3b", size = 250114, upload-time = "2026-09-30T04:37:58.607Z" }, + { url = "https://files.pythonhosted.org/packages/50/27/d102dc880bbcffd0479ab64dfc1fb96777a854355a55e2bda72a71efadcb/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b7fd005a73d9e657273b7a10dc71a9e03c8fb9ee6999798d6918ce095b81ac7f", size = 239997, upload-time = "2026-09-30T04:38:00.511Z" }, + { url = "https://files.pythonhosted.org/packages/a5/4a/bf7ef45794dd293fab5f98a9309817977fbb845b9998f171b8cc5d8437a3/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e54da4baf05720032d527874d40b65fa4d7e5c6c6a43d0c3adbeffcaf275a2b3", size = 272313, upload-time = "2026-09-30T04:38:02.509Z" }, + { url = "https://files.pythonhosted.org/packages/e8/ee/008a2837737991474c5754bb3191010007663860979701990982a502cbaf/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:124fbf1a8ff966d87ae05bb8bd45a71f966055ed8bba320d0c7cf450bc5f4d0e", size = 269986, upload-time = "2026-09-30T04:38:04.435Z" }, + { url = "https://files.pythonhosted.org/packages/93/ad/bd74a283940dc910c5b14f8e4f80a248082bc9c0fcbe1f54530cb6d9cc5e/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:28b4f0d66fb834ff90f28209ac7bce77868c45d8c93e26f906709d9b7c2e1af9", size = 260202, upload-time = "2026-09-30T04:38:06.549Z" }, + { url = "https://files.pythonhosted.org/packages/8a/7b/ed341c66f69f688723501fac752be3d63c7159ca0d0d4174fc611e5710bb/charset_normalizer-3.5.2-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:58ca3755ee7ff7f59b57789ec9833c9de9ea275405cdd240eda1f193112e398a", size = 259083, upload-time = "2026-09-30T04:38:08.311Z" }, + { url = "https://files.pythonhosted.org/packages/cc/9d/e41588b777965e5031a43128a1e96173ebb35ac75fc53ec3b517e7c21cd4/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:443eae2bf318abeaf6f15d785138f71fd6de770e99a92158b8b814265e079115", size = 253081, upload-time = "2026-09-30T04:38:10.402Z" }, + { url = "https://files.pythonhosted.org/packages/81/35/b761eb6d8c1eb218b9b42b9b4d5ac902afdc399fb6dac6f9a9aac7bda589/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:58f361dcbab699cf8f42db3f47c8e7fd1036f138c23a5d08de9fde5f425a730c", size = 248712, upload-time = "2026-09-30T04:38:12.317Z" }, + { url = "https://files.pythonhosted.org/packages/4d/2c/147169a041b747759f37405c0a97157e8e92de967968373101ff14915cba/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:1b4cbc7c3491ccb4aa17fcd8165649d01cf39f76de1696da8631b5f71b85401d", size = 274176, upload-time = "2026-09-30T04:38:14.138Z" }, + { url = "https://files.pythonhosted.org/packages/f0/2d/0ff8db0d373ba8538db686db11cd7e8912031490b9e4f383b41912e8d594/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:ba0b1d2620edf869789c3879223f52bf2afc5d31b3cb47cc57b3a12c05e2aa9d", size = 259413, upload-time = "2026-09-30T04:38:15.841Z" }, + { url = "https://files.pythonhosted.org/packages/8a/8e/b4a085fb47c9d3a7e43576a4784fdd8fe23f907514a972de8086edaf7a48/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:5e2b6b57e9733d39f0c9fd3185efa6b8e29652c4cd8fe94180272cf6ed9a78c4", size = 269434, upload-time = "2026-09-30T04:38:17.626Z" }, + { url = "https://files.pythonhosted.org/packages/83/1c/d8d8d7322a7c3eecdf3237a4a419cf41d2eaad8e006ce7dfdd9d4c8fa2eb/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:51cf45226a9b588d0d2b4880c62d686934b63ab0bd79ca23ab0e9762eb27441b", size = 262716, upload-time = "2026-09-30T04:38:19.214Z" }, + { url = "https://files.pythonhosted.org/packages/a0/16/0e4c6ba9b44e97a2da150e52d331e8f9c968b21b358fbffa6c856cebcd89/charset_normalizer-3.5.2-cp315-cp315t-win32.whl", hash = "sha256:5fb29fb8cd1a46c27a1bf9613ad5ec2599310d46b4025d9556404a6b6a292800", size = 197159, upload-time = "2026-09-30T04:38:21.037Z" }, + { url = "https://files.pythonhosted.org/packages/be/33/e90bc2b1374f7f36ef106f56620de5a783907e19ca857efe2277e31cac3e/charset_normalizer-3.5.2-cp315-cp315t-win_amd64.whl", hash = "sha256:a192e2c40070d92c3ccf777e3a5c4ff515573cd2bb7ed0c537fdadbbec5bbf21", size = 221322, upload-time = "2026-09-30T04:38:22.886Z" }, + { url = "https://files.pythonhosted.org/packages/66/89/dfa6dcb08c200b7830ab56439e8c1890f2971d51aafbb3937894a2e7fcfc/charset_normalizer-3.5.2-cp315-cp315t-win_arm64.whl", hash = "sha256:749e97e1b32313717a565abbe321bc2190bc8b35f1a67e4cdbc7c56c8d8ffe58", size = 209192, upload-time = "2026-09-30T04:38:24.648Z" }, + { url = "https://files.pythonhosted.org/packages/8c/ab/176fbfd5b64939c55d652366aa5b9ef1d767af207a3aa6ebeb0d226c484d/charset_normalizer-3.5.2-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:4275811936e2f06feff5e598fb42a1b7ae852da8e39605211892b56b81a34efd", size = 331815, upload-time = "2026-09-30T04:38:26.216Z" }, + { url = "https://files.pythonhosted.org/packages/7e/84/371eac6b30bdbcbf2d632a1a01809103459216fcaae61b8b8d922c1bfb8a/charset_normalizer-3.5.2-cp37-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7", size = 253276, upload-time = "2026-09-30T04:38:28.032Z" }, + { url = "https://files.pythonhosted.org/packages/43/6f/c4fbae58febff71709c51bc7e18fdfa55341dc382704740f9f0cbf03817b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d19fbd981a488e22cd04883659ca6b08f50b5974f9fd7c95655ef6a043e5893f", size = 241239, upload-time = "2026-09-30T04:38:29.732Z" }, + { url = "https://files.pythonhosted.org/packages/61/71/458c3f42164a07d0c5210798e9e704b39e540a6793b05aba67f3a35243a9/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93", size = 231121, upload-time = "2026-09-30T04:38:31.462Z" }, + { url = "https://files.pythonhosted.org/packages/09/54/ab9e89367076f6331bb6c65c4bf14a5361fa5191cb6561bf534f18504e1b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade", size = 260350, upload-time = "2026-09-30T04:38:33.239Z" }, + { url = "https://files.pythonhosted.org/packages/7c/c1/061431ecc688d9d76602502cb57cc01e691e682c18f1beb45f9673b5bbd2/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0", size = 255430, upload-time = "2026-09-30T04:38:34.865Z" }, + { url = "https://files.pythonhosted.org/packages/8d/1f/20c8949f0676f7ab811abdeb7f4d7f1cbc6e61ff20bef08b44edeb092bc8/charset_normalizer-3.5.2-cp37-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26", size = 250612, upload-time = "2026-09-30T04:38:36.649Z" }, + { url = "https://files.pythonhosted.org/packages/2b/9e/46f2fa4c431fc98c4ae76a8cb5bdca54e0341e3cfc3fcfd8e82740250818/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1db38f4c5496827c1a501846d64d14c3b80c7e6714e406cd7dc36a9899fa1011", size = 242083, upload-time = "2026-09-30T04:38:38.26Z" }, + { url = "https://files.pythonhosted.org/packages/bd/39/559be29a0c0f086e0bba6922babd38916cc5e0b58ced4de13ee01ea05508/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621", size = 232738, upload-time = "2026-09-30T04:38:39.81Z" }, + { url = "https://files.pythonhosted.org/packages/ff/6c/387b0e4f756a282831c1d9fc6aeb6c51ca4507ca202767c8de15ce9b12e2/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4", size = 260703, upload-time = "2026-09-30T04:38:41.346Z" }, + { url = "https://files.pythonhosted.org/packages/96/92/1fdf015f09ef449f50d3ac4b67c90887c9c318b727daa95cc4f866e6521d/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e", size = 247622, upload-time = "2026-09-30T04:38:42.937Z" }, + { url = "https://files.pythonhosted.org/packages/dc/3c/8e7b8a5671ad5d433669fb2a76f1a0164df2d9b1718b0206bc2a16d840cc/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_s390x.whl", hash = "sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c", size = 257500, upload-time = "2026-09-30T04:38:44.604Z" }, + { url = "https://files.pythonhosted.org/packages/b4/f0/45b579df5cabc1d5d53ea1cc35e8437d3ca768c0acccc7041517cb6fbb32/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0", size = 255100, upload-time = "2026-09-30T04:38:46.289Z" }, + { url = "https://files.pythonhosted.org/packages/31/68/fdec18a343f5fb3f310588dd478b09ac4799e0b187dbade3a8cd776f03ef/charset_normalizer-3.5.2-cp37-abi3-win32.whl", hash = "sha256:01b0c0d2262a9e28e8484a278c7e1b5d650e3ac8cf2683d2967e25899f208bdf", size = 174499, upload-time = "2026-09-30T04:38:47.999Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8a/b618149cc5207943a0242068d7a27897f56a62947b5a039085f2a22029f8/charset_normalizer-3.5.2-cp37-abi3-win_amd64.whl", hash = "sha256:9f56f72050826f63dcee7a7f55b0a77168cb3bfc553fd405e7f8f9ece75a4036", size = 200092, upload-time = "2026-09-30T04:38:49.707Z" }, + { url = "https://files.pythonhosted.org/packages/03/cf/4c66866fa9e2b1c78e3c911516d1de497a677b7ac60f1eceda74ce777ca3/charset_normalizer-3.5.2-cp37-abi3-win_arm64.whl", hash = "sha256:40ab6bffa02ae10a0581e6c198be7d2d8ca5c2a0c64e4ed3465d766df457573e", size = 294363, upload-time = "2026-09-30T04:38:51.312Z" }, + { url = "https://files.pythonhosted.org/packages/fc/ad/d07d7862a62ffa6d79d68074d14823243dd235a77c45262acbf6adeb28bf/charset_normalizer-3.5.2-py3-none-any.whl", hash = "sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685", size = 68872, upload-time = "2026-09-30T04:39:21.828Z" }, +] + [[package]] name = "click" version = "8.5.0" @@ -186,6 +336,63 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/99/89/87ef49ffe383ef4e147d27b7bf2088fb0b54ea409dd87b5a89442e5828a5/cryptography-50.0.1-cp39-abi3-win_amd64.whl", hash = "sha256:55d16b1ef3ee0958d893a977b19777887e546c9954ea81b200c3301a864013f2", size = 3875429, upload-time = "2026-08-25T19:45:24.418Z" }, ] +[[package]] +name = "distro" +version = "1.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fc/f8/98eea607f65de6527f8a2e8885fc8015d3e6f5775df186e443e0964a11c3/distro-1.9.0.tar.gz", hash = "sha256:2fa77c6fd8940f116ee1d6b94a2f90b13b5ea8d019b98bc8bafdcabcdd9bdbed", size = 60722, upload-time = "2023-12-24T09:54:32.31Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/b3/231ffd4ab1fc9d679809f356cebee130ac7daa00d6d6f3206dd4fd137e9e/distro-1.9.0-py3-none-any.whl", hash = "sha256:7bffd925d65168f85027d8da9af6bddab658135b840670a223589bc0c8ef02b2", size = 20277, upload-time = "2023-12-24T09:54:30.421Z" }, +] + +[[package]] +name = "docstring-parser" +version = "0.18.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e0/4d/f332313098c1de1b2d2ff91cf2674415cc7cddab2ca1b01ae29774bd5fdf/docstring_parser-0.18.0.tar.gz", hash = "sha256:292510982205c12b1248696f44959db3cdd1740237a968ea1e2e7a900eeb2015", size = 29341, upload-time = "2026-04-14T04:09:19.867Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a7/5f/ed01f9a3cdffbd5a008556fc7b2a08ddb1cc6ace7effa7340604b1d16699/docstring_parser-0.18.0-py3-none-any.whl", hash = "sha256:b3fcbed555c47d8479be0796ef7e19c2670d428d72e96da63f3a40122860374b", size = 22484, upload-time = "2026-04-14T04:09:18.638Z" }, +] + +[[package]] +name = "google-auth" +version = "2.62.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cryptography" }, + { name = "pyasn1-modules" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f5/b9/4b2528f30114b106e3c3a7298ba38d85e682fd1f83fe7c4a5b77c7677082/google_auth-2.62.0.tar.gz", hash = "sha256:0bef0ce54bdf9ce226c5d66e4264413bd918141c31bbe49fb52eac882f513d69", size = 398180, upload-time = "2026-10-12T19:20:48.328Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/eb/a3/87fe9b7203ec2e56ea6a57c75e6d632eaf9487c7f7978cdad1d801bee0af/google_auth-2.62.0-py3-none-any.whl", hash = "sha256:4ff4319aeb4ad128409759d397a9fcafad126d0031d241cc0dd6b9a00b43e3f3", size = 267911, upload-time = "2026-10-12T19:20:46.355Z" }, +] + +[package.optional-dependencies] +requests = [ + { name = "requests" }, +] + +[[package]] +name = "google-genai" +version = "2.31.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "distro" }, + { name = "google-auth", extra = ["requests"] }, + { name = "httpx" }, + { name = "pydantic" }, + { name = "requests" }, + { name = "sniffio" }, + { name = "tenacity" }, + { name = "typing-extensions" }, + { name = "websockets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/34/69/6a3d3839ab56ec17d7923c8679b38955e286e0a9793df10ce6d13bc5f122/google_genai-2.31.0.tar.gz", hash = "sha256:71518537de2ba967a61960cba844691dca3dd4ff07726c01a6917d132213541e", size = 745679, upload-time = "2026-10-14T23:52:24.836Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1c/64/1e9ab799830101ccbdcb67376a3f12b59e51f57643862999fd31af6938a1/google_genai-2.31.0-py3-none-any.whl", hash = "sha256:c87b9d495a24b09dedb29b852a201bea69ecd0b3f6c2561dc68f4055451b1b90", size = 1208245, upload-time = "2026-10-14T23:52:22.766Z" }, +] + [[package]] name = "h11" version = "0.16.0" @@ -195,6 +402,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, ] +[[package]] +name = "httpcore" +version = "1.0.9" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, +] + [[package]] name = "httpcore2" version = "2.16.0" @@ -208,6 +428,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/af/c2/ce417c397afa5181f0e3c6ff01a4d01639414e1adef08730d97571297151/httpcore2-2.16.0-py3-none-any.whl", hash = "sha256:5c4358319f2602d984ad93182c9fee5160f22e9da7babdda870a5e7c4e2dc34f", size = 85070, upload-time = "2026-10-21T07:09:42.802Z" }, ] +[[package]] +name = "httpx" +version = "0.28.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "certifi" }, + { name = "httpcore" }, + { name = "idna" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, +] + [[package]] name = "httpx2" version = "2.16.0" @@ -252,6 +487,101 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, ] +[[package]] +name = "jiter" +version = "0.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9c/1f/8176d92e001f86505424b41664032ae26a882bc9ca41a32c803f373f9195/jiter-0.17.0.tar.gz", hash = "sha256:03e432f226a453851079fb84cd17c6da9991eab723e28d716f14ae3d906e0c12", size = 229037, upload-time = "2026-09-12T15:14:14.253Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/aa/f8/07bd8c3a23f7a8a6875e6a820bbffe1483a18f18f9398a91b5495123176e/jiter-0.17.0-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:ebf918dfd6a74adc1b9ad71f63c4ab00902fcd3b7fd39f2e24d871db8d713b91", size = 291633, upload-time = "2026-09-12T15:11:49.431Z" }, + { url = "https://files.pythonhosted.org/packages/0e/5e/0de4c6f84ffefa6809ffc2d550b9a314365acf7e7ec9b6c7375d49047900/jiter-0.17.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:61aed66ee042b3b49ef85fdf75714234d055d89d8496ac1c6e47f89e7a30d5e4", size = 321695, upload-time = "2026-09-12T15:11:52.727Z" }, + { url = "https://files.pythonhosted.org/packages/20/ac/befe2e82065bee37a0252081666ed2f48c1ac5f5c6c318c2de8168ba393d/jiter-0.17.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:76eb4a5c20e86f9f848286f167024890f2862258a965d254774deb7fc1545ca1", size = 341967, upload-time = "2026-09-12T15:11:54.231Z" }, + { url = "https://files.pythonhosted.org/packages/9f/cd/9797c1e529746750ae589da7c1a8c24373f00d88e11a989f9e5eb1959079/jiter-0.17.0-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:bcc064f99183a9cbe7f26ed648c352031a74145cd61ed75d34632c73eb46a5a8", size = 326546, upload-time = "2026-09-12T15:11:55.41Z" }, + { url = "https://files.pythonhosted.org/packages/d9/fd/e6914c38d6347bab4ebff2b1f0c0f191db276e7a1d5c376176757da42fe3/jiter-0.17.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:73b64e69c4150748e020356d958af94bec33c70a0a93d665cfa8f6d580fe1a63", size = 340995, upload-time = "2026-09-12T15:11:58.211Z" }, + { url = "https://files.pythonhosted.org/packages/9d/7d/611b3abf6f88945b5474da5cdc6d1a185e805ac9bf446bb7766dcda6ea87/jiter-0.17.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f0bc7f684b65bcda9c20434267577db71bf9905ceddd32b60d1d93278d8c8d3a", size = 352188, upload-time = "2026-09-12T15:11:59.414Z" }, + { url = "https://files.pythonhosted.org/packages/52/f8/b6e513ecbdf3b3cebe587c2279281ecf775b729a58cf4cc7bdf898ded029/jiter-0.17.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8c21265b251d99bbb40080d178a8953e35601d3a1564e05c4de4c0d2ca616797", size = 345025, upload-time = "2026-09-12T15:12:00.697Z" }, + { url = "https://files.pythonhosted.org/packages/28/a8/fe26d06c5a6c5a4cfe703c5154c8a140da1305671eb3681aba9422d4f393/jiter-0.17.0-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:f3d7f7b34114f7ddc6d72a8e882d49de636b35d9fd12b4d420d3c5729f6c9812", size = 329180, upload-time = "2026-09-12T15:12:01.831Z" }, + { url = "https://files.pythonhosted.org/packages/e1/58/e6d66a26af40a20e62486feb7e222fd50f6e7aaa4f107abd89675dcc835b/jiter-0.17.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:5078ab00664307fab2019b522a93aeb191122789f085daf5fd9e362154021d4a", size = 335805, upload-time = "2026-09-12T15:12:03.056Z" }, + { url = "https://files.pythonhosted.org/packages/ef/3e/96520aa2fef5ef831d95483a902140bfab83dcac9eaa74f7df61b5e50a1b/jiter-0.17.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:470e1b1e4c42f1ead2189166a299691871a2df5056c976e7fb96feafaf5f9d44", size = 484121, upload-time = "2026-09-12T15:12:04.414Z" }, + { url = "https://files.pythonhosted.org/packages/6a/8f/5d9d92fe538bf36ff481a2278c48147e59c1cf8eb2f7be665260665febe5/jiter-0.17.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:6eb6aedeb7352b8f3b6af9cbd67983840165c00428e63f1b420a85885128ea31", size = 521310, upload-time = "2026-09-12T15:12:05.612Z" }, + { url = "https://files.pythonhosted.org/packages/50/06/a09f979b22e652afbc3de66c709b2ba92edcef555f7535ab937c86b4f21a/jiter-0.17.0-cp312-cp312-win32.whl", hash = "sha256:362bb47423886d45a9f705d2d9d4008c6eedd4e41eb1bab4e96fb6daa06b33fd", size = 185029, upload-time = "2026-09-12T15:12:06.994Z" }, + { url = "https://files.pythonhosted.org/packages/6c/d9/98265a005b2473ec2be5a84e2b64c2f65382c673879f1574845cd4bcd77c/jiter-0.17.0-cp312-cp312-win_amd64.whl", hash = "sha256:9bd3caac219df476dd0cc3fe01d2f1581ed588906feac767abd9614c1c12f8b3", size = 227381, upload-time = "2026-09-12T15:12:08.823Z" }, + { url = "https://files.pythonhosted.org/packages/a8/11/2e05bf5a56e57a543ebb8f585074adf09383e99d7b062dac92eab1f4d57f/jiter-0.17.0-cp312-cp312-win_arm64.whl", hash = "sha256:36ee6e69027396664e59995b9a635a947a5304ee9837279584a0bb8145c8f6b8", size = 183610, upload-time = "2026-09-12T15:12:10.374Z" }, + { url = "https://files.pythonhosted.org/packages/40/eb/2c4a8075ed5ea02b56911e9375d4c8d7784572ff4af32e5a99ae0d071044/jiter-0.17.0-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:1b18434638228c0c184281609bf3d9459026a0f1ea48fb76c205e3ef72069caa", size = 290991, upload-time = "2026-09-12T15:12:11.641Z" }, + { url = "https://files.pythonhosted.org/packages/ca/b1/34bfa29599d420423baac6ff7cada6674fe63d5a7a2ccb3900b904678783/jiter-0.17.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:ec89771f4272b989487a6364e519db6bbaba323e8bbf949ac89a45ea9c18b7a3", size = 321425, upload-time = "2026-09-12T15:12:13.855Z" }, + { url = "https://files.pythonhosted.org/packages/11/71/a5ac64a62a04aebd556afadab14a6b730001e16df87266ded943a100a1d9/jiter-0.17.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4e3f052c671d5f425cca5ea5901cf11a831369fba4a55a3862cab93c323b4c3b", size = 343138, upload-time = "2026-09-12T15:12:15.046Z" }, + { url = "https://files.pythonhosted.org/packages/01/dd/f761e320ea473314cb68612bc6a435393464dbd198051399b36848b4ebf3/jiter-0.17.0-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:785a216bbaf8f15fc974e964ced7322cd3d774bb0e86949edd78c6bffd6ba35b", size = 325805, upload-time = "2026-09-12T15:12:16.506Z" }, + { url = "https://files.pythonhosted.org/packages/19/1a/27d8e40f0fb29bbc7a5adf30907144396a115dbe93d5d8976c054a6dfe96/jiter-0.17.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d85c558c9f8532bba287a990ac63767c7daf756f0d8c030219f62499b1fa228a", size = 340230, upload-time = "2026-09-12T15:12:17.682Z" }, + { url = "https://files.pythonhosted.org/packages/ac/c0/30bcde78a28155461f965d16b7aca4ffca6d17494d905f7a0bb072e6c64e/jiter-0.17.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5c23849235d2142ce444b2b8c6eceee9f82f4cc0bd5c9081602e4155c6197807", size = 351343, upload-time = "2026-09-12T15:12:19.337Z" }, + { url = "https://files.pythonhosted.org/packages/27/17/91420b156315ae22732f5ee1a7b5725a030aab9dc8fd7dcdacfb4aa588d3/jiter-0.17.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:58df29268a95e910f17db7ec9178eb7f15aa8619aaca3575275c4e6b3f4fe4c5", size = 344990, upload-time = "2026-09-12T15:12:20.705Z" }, + { url = "https://files.pythonhosted.org/packages/6d/a2/ae6d5672644cc11127970277c9aeb0fa6fae376845587f5b0a8e8828167c/jiter-0.17.0-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:a277f97eba7d66b1ee27eb5dab5b774ff46a10c78d89a1d3dcce04ce1357c8ca", size = 328624, upload-time = "2026-09-12T15:12:23.859Z" }, + { url = "https://files.pythonhosted.org/packages/04/62/45cb1162f6aa586536e4a973fc339d72dc6b08cca030d70a838a307aa778/jiter-0.17.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:fe15ddf316f1f1f643347d3a474e74ce61880c79a11ec5dca53df20c071bd3e8", size = 334731, upload-time = "2026-09-12T15:12:25.229Z" }, + { url = "https://files.pythonhosted.org/packages/d9/5f/45c1574b644da7deda0b7591c349520dcf83ce45b24d7ca19922dab1fc27/jiter-0.17.0-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:02adebb7ce6413c44d40af9ad59d1c1cd79630ccdcb6f7bdd2d461e48c03d8f9", size = 483649, upload-time = "2026-09-12T15:12:27.557Z" }, + { url = "https://files.pythonhosted.org/packages/c1/d3/ebea1ecb5b241c519f192b30215c79a8e47f42f1621acbcd6f8830728416/jiter-0.17.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:55d0e0e613a3f9ad600cf436e0e2b8057d1b52bcf1d91b2d36ac53451231e6a8", size = 520758, upload-time = "2026-09-12T15:12:28.99Z" }, + { url = "https://files.pythonhosted.org/packages/64/e6/682b641ff0765ea9bdc349dbc7d223de5c8af8ec1abda0db3406992f92fe/jiter-0.17.0-cp313-cp313-win32.whl", hash = "sha256:2c45ad7c973ef33fe5114a953377b35a95240f4542c0724d9f781e47dc24bac7", size = 184334, upload-time = "2026-09-12T15:12:30.813Z" }, + { url = "https://files.pythonhosted.org/packages/b8/d2/9a49aac2b27af4cc5015e368c0cc3588491a532f717a668ffce1f1ac57da/jiter-0.17.0-cp313-cp313-win_amd64.whl", hash = "sha256:a3cebb1fe4a1abb00465f3f8a17e09112603e8b7c59e5c3adbcd9f7815a64acd", size = 226601, upload-time = "2026-09-12T15:12:32.096Z" }, + { url = "https://files.pythonhosted.org/packages/b4/ce/9a43e9f614608eafa78de22aedcff54cd21324467b5d442d5c9b00244145/jiter-0.17.0-cp313-cp313-win_arm64.whl", hash = "sha256:96b8b0c6dc5d78682f54a450785e075aa929cde768304cad363cd4efba5a82ac", size = 183103, upload-time = "2026-09-12T15:12:34.396Z" }, + { url = "https://files.pythonhosted.org/packages/01/9e/23065f8e2c7a4c372c1b6f6622e4cfab4dc786cb5150052b1527e6a6a840/jiter-0.17.0-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:00d783a779c5664e16dbad5e3a3c3a75e128b07dd5f4765159658d9210a50ca5", size = 292210, upload-time = "2026-09-12T15:12:35.613Z" }, + { url = "https://files.pythonhosted.org/packages/ea/81/67b58647560bc82a4490d722caa8561d7a86a9f45d4fa620b7e5fe282c7a/jiter-0.17.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:0619d806e260ecf0c2a64521942c94af5d547c9ec99b55ae4f51b538b5576a76", size = 321512, upload-time = "2026-09-12T15:12:36.907Z" }, + { url = "https://files.pythonhosted.org/packages/c7/07/6658359a25f55927f7f8bf0e16465dee2ccd0b2a1a5208acc0df8972e074/jiter-0.17.0-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dc0288ce39190ee33fe6e4ec73161eed34e7e2da509b525546ca061778d62b64", size = 343897, upload-time = "2026-09-12T15:12:38.189Z" }, + { url = "https://files.pythonhosted.org/packages/46/04/5d50a9f0319cbdc37fd53c27f8c313d46afc34f1b048219ae6d8ea068da4/jiter-0.17.0-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:5a52a430d04225ffde633e6840bf2381d34c019ff98526b5929755b9052fb199", size = 326519, upload-time = "2026-09-12T15:12:39.532Z" }, + { url = "https://files.pythonhosted.org/packages/bb/c7/d02517832b29eb8275fdd0f4ce0f17b80f58cc4c3ebecd4d9ace990d633d/jiter-0.17.0-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:37f33d327900bf2879613b3363fd48df97b4232d0c41f54bcf2e790c2fc40a71", size = 341369, upload-time = "2026-09-12T15:12:41.486Z" }, + { url = "https://files.pythonhosted.org/packages/3b/07/499b5f5603501cdd93a73a6a176dfad9c96555a3ae58ca9f8e3acba63dc9/jiter-0.17.0-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6cf564d43c4388149ca58ee571d0f5ccf875e20d1fd4662fd94cc0d1ea3b10ef", size = 352160, upload-time = "2026-09-12T15:12:42.721Z" }, + { url = "https://files.pythonhosted.org/packages/f5/75/b04013c7743269d4533ef4e746fc0ed678a143968dd7448658e3f51daad2/jiter-0.17.0-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:523c499235fb65add25d4bb01b1c4709ce695efdc7deb6c0a7bc515b5c44e0fb", size = 345018, upload-time = "2026-09-12T15:12:44.192Z" }, + { url = "https://files.pythonhosted.org/packages/1d/96/cbb6fd1e42a77c8412ec4643db95059b30cdfc635e387cc9193e098ce268/jiter-0.17.0-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:455e4ab35cb2a4a91a8404e08fd3c621bae433922e59bf1c494fe20a426b013b", size = 329244, upload-time = "2026-09-12T15:12:45.491Z" }, + { url = "https://files.pythonhosted.org/packages/15/67/d3be402f398566a379bf40ae65be5c3505b14d9e95e0802a597ddde7ddee/jiter-0.17.0-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:6871973bfbd4408f7f1c632b30bbb5bbd9671c1bc8650af6823e24b7be13709b", size = 335693, upload-time = "2026-09-12T15:12:46.935Z" }, + { url = "https://files.pythonhosted.org/packages/7f/8d/98e2c4130b93d64f1d67c89060b928d04102549bf05e64451c9e6024f9ca/jiter-0.17.0-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:77f6aac0137309b31448c1bdcda4c6c77077664a6d018ece8d94019c68a5a5b9", size = 484329, upload-time = "2026-09-12T15:12:48.361Z" }, + { url = "https://files.pythonhosted.org/packages/78/5e/8da91e49f0fbca37c3489fb4cf3ad6676d4965f00ae5468bca3a2513737a/jiter-0.17.0-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:93946d89fa04d5ba64dd323a8dd8d901676cb8a3c81d99ae4f6c051a9b4c3f2f", size = 521358, upload-time = "2026-09-12T15:12:49.856Z" }, + { url = "https://files.pythonhosted.org/packages/be/21/5388684a5a38af3557cd9c2424b9827c71809cff24373c75ef9d0d3dfba9/jiter-0.17.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:70f19a2ca8429f91e82eeffb2f51cb87bc2d6e953b009b91a92d29c3a16ccb03", size = 110459, upload-time = "2026-09-12T15:12:51.747Z" }, + { url = "https://files.pythonhosted.org/packages/b1/ad/58b3a93525d2ffca7f54d9dee441381990082bd1172fbeb8d6a3f72a4dc3/jiter-0.17.0-cp314-cp314-win32.whl", hash = "sha256:71dbd74314c5df52a1bccf7b8bca46d14e943af7a2012e73b23f49977ef194c8", size = 185043, upload-time = "2026-09-12T15:12:54.477Z" }, + { url = "https://files.pythonhosted.org/packages/7a/4a/1aa520eb6c359b262c14ff995ca7283837208ddfb1202082ce9d73cf214d/jiter-0.17.0-cp314-cp314-win_amd64.whl", hash = "sha256:ac3c6ee3264d6f5c44c617f90bc7e8b9e1587e7d6708c9d8f811cb65582ee312", size = 227163, upload-time = "2026-09-12T15:12:55.931Z" }, + { url = "https://files.pythonhosted.org/packages/cf/e4/5997f648794bd9b499491d0ff480b096cc9a9c65bdba29f57568e6aa1705/jiter-0.17.0-cp314-cp314-win_arm64.whl", hash = "sha256:6219adaf59711ba7063a52496e8ec6d3fa3e209d7827d83eee3b2abc780a1744", size = 183505, upload-time = "2026-09-12T15:12:58.196Z" }, + { url = "https://files.pythonhosted.org/packages/ac/4a/84a5ec271d09f7590b6073af5ee4abb44eab4ccace453b7e2c5ce45234ca/jiter-0.17.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:59bddbe6f9ffecc68d641e1e2d619ce64cf8a9e9eeb74e5c518f74fc87abf1b0", size = 321527, upload-time = "2026-09-12T15:12:59.394Z" }, + { url = "https://files.pythonhosted.org/packages/39/71/9e1fd0045f5920b4c36be35c3f0f0dfd123668684f8ad352619d7aa44183/jiter-0.17.0-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6cb41cd1432f1dc19a231cf70b54d42b2c9f05085155859263fce06fa4d41388", size = 340865, upload-time = "2026-09-12T15:13:00.756Z" }, + { url = "https://files.pythonhosted.org/packages/b7/2b/14627fd2bc377f3dd09491bcace6b90e34b4d7fea2f1f3295031ff91f528/jiter-0.17.0-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:fd7790aa79c8b518e512ebcdfce9f11d8ef5f30efd43720c8a19a548b39fa489", size = 325412, upload-time = "2026-09-12T15:13:02.152Z" }, + { url = "https://files.pythonhosted.org/packages/4c/f3/8d5808f7bf0f456bde79e6393587183a0cee5f83d179fe1f7f1eff2ba067/jiter-0.17.0-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:dbbfe4e3c21c8166980cddc5bee1a315df082454f007947dfb6fb73800768165", size = 340473, upload-time = "2026-09-12T15:13:03.485Z" }, + { url = "https://files.pythonhosted.org/packages/4f/da/1d8c7c6c4ae6b2423b94a81b6b907d37b28f87664e077427b531bf1b5313/jiter-0.17.0-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8c286860abfe8b100cac1c02e225e5776eb9216edd71ba17cdb237da4af32bc9", size = 350757, upload-time = "2026-09-12T15:13:04.828Z" }, + { url = "https://files.pythonhosted.org/packages/eb/96/c1813dcca15c5a370145a448aaea7d1f83f6f0228a5f1130e79340ee385f/jiter-0.17.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f753eb70b1474a29e635e7542ff7312e6d6b951e0b25e8a2e8c34eeb1ddcd478", size = 345203, upload-time = "2026-09-12T15:13:06.131Z" }, + { url = "https://files.pythonhosted.org/packages/d7/f7/fc61cbcf2992d169ede13648fc3fd8e2d3171a3669dde43cd4db556549ac/jiter-0.17.0-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:eae86b1f027031e39db2e0e9c4842221edb7b8cd474d23f87a79b3bd4b651768", size = 328322, upload-time = "2026-09-12T15:13:07.392Z" }, + { url = "https://files.pythonhosted.org/packages/8f/88/46418a3abbdffb7dc41b314200360f24f75faaeb35573e81c92de322cce9/jiter-0.17.0-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:5bf350452a43173e69e1fc74847c57a60e3d7515807287f29849baa2a85d8718", size = 336570, upload-time = "2026-09-12T15:13:08.666Z" }, + { url = "https://files.pythonhosted.org/packages/f0/28/b8a55b949be6306df8888e365a8df05441de8a7b11289f6957004302e41e/jiter-0.17.0-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:da139721f4b7cafdbff580a4f511ea24cb91f4909330c6b926a1ca53836c0a59", size = 482879, upload-time = "2026-09-12T15:13:10.037Z" }, + { url = "https://files.pythonhosted.org/packages/75/3b/21d0afa53ba0680962c39f3eb95ed2946f8793369ed44b0c82b490723081/jiter-0.17.0-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:8079849db9a1371bfd90bad088458a8fb836261879df2233cc9632464ecf64e1", size = 520406, upload-time = "2026-09-12T15:13:11.456Z" }, + { url = "https://files.pythonhosted.org/packages/ef/03/bcbaf8b6b9ea23c2c074411f8ecfbb02d820abac5d0cb8f4e280209174a2/jiter-0.17.0-cp314-cp314t-win32.whl", hash = "sha256:8f770b0c77e5fac482e1ba03ca1a7e18286bfb213d749932a00a7e4cd5de5e06", size = 184434, upload-time = "2026-09-12T15:13:13.037Z" }, + { url = "https://files.pythonhosted.org/packages/7a/b5/5d6ce2c93ef6fe1241b37a9005547f9b6d58db1f07f39fe95807d4b98f51/jiter-0.17.0-cp314-cp314t-win_amd64.whl", hash = "sha256:c4289293e5278d9314b00f15c37f2120fa51d3d68565292e715524c750e775a9", size = 227392, upload-time = "2026-09-12T15:13:14.933Z" }, + { url = "https://files.pythonhosted.org/packages/f5/4b/1e52baf90187606e33a7b8cfa8f96f5829acd7f01870077eb01059ab76d0/jiter-0.17.0-cp314-cp314t-win_arm64.whl", hash = "sha256:4dfbfe5a6e1e80a7082af559f66386405025ec278833e0c649f69cbc6e1004cc", size = 182776, upload-time = "2026-09-12T15:13:16.239Z" }, + { url = "https://files.pythonhosted.org/packages/05/fc/efe3ac75564ab10f53517958f5ccdc231fc7334af66c76776cb554a88967/jiter-0.17.0-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:84963d3f395ef5e9a32ce47155e08a7962fa292c159a10cb98b931cef1416925", size = 292143, upload-time = "2026-09-12T15:13:17.502Z" }, + { url = "https://files.pythonhosted.org/packages/d1/4c/46982118d91f9ffe9714319d21ec4f98d9b7e0cfd9062826c524a54de24e/jiter-0.17.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:ffa0380ad091de7d3fc33e17a97ff479851ee18a0a2a3ee56ff3215cdc886656", size = 321341, upload-time = "2026-09-12T15:13:19.133Z" }, + { url = "https://files.pythonhosted.org/packages/e7/12/9b1ac6ecc6307049913db54839ddba1c11c1ef72c5a8bbb5514bc3b50d1b/jiter-0.17.0-cp315-cp315-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:755079792868ce5d4938e83b91a0939b34fb858a1ca65a104f2d771bea57faa1", size = 344383, upload-time = "2026-09-12T15:13:20.508Z" }, + { url = "https://files.pythonhosted.org/packages/a9/b6/527cc72af836d824e9d4d666e64f0a1ca7eafd662a8da9657b78592172ba/jiter-0.17.0-cp315-cp315-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:3bf4dc2b84a464117fb097d15a25c58d100d2692888e3b0d92df5b48ed16b7c0", size = 326841, upload-time = "2026-09-12T15:13:21.83Z" }, + { url = "https://files.pythonhosted.org/packages/d1/41/567f98617e88005b249503b933803f633ec6ba2d427cf4cc35e5c832125c/jiter-0.17.0-cp315-cp315-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:02a360707033d8cef53f7f3480817a1489177a259ec6ec01e98c37e0b922ddca", size = 341354, upload-time = "2026-09-12T15:13:23.323Z" }, + { url = "https://files.pythonhosted.org/packages/40/da/b29cda895b785f7d426e224638a885b6145a08ce853b381f34afe3e88c5d/jiter-0.17.0-cp315-cp315-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:300ce01ab0215e3dea4d00090143c909aedc65c0f809b3c07983e1d038f291b9", size = 351985, upload-time = "2026-09-12T15:13:26.526Z" }, + { url = "https://files.pythonhosted.org/packages/f7/5c/8a73829e7389e72ea298a450f2b3cb58e71a3e464b45f6d8753740f1c4f5/jiter-0.17.0-cp315-cp315-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:746243a080b4ca790b8499af3d7cf9825d5f5987933950cd818e767ee353d826", size = 346052, upload-time = "2026-09-12T15:13:27.887Z" }, + { url = "https://files.pythonhosted.org/packages/1d/2f/98d6001026932c095ba440925570123043bed29f5ff56158dfe729a9e81b/jiter-0.17.0-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:b550585523339b71cb852b811aae49d08d7601ad8ffe9f5dc1562f4c3d22fd87", size = 329159, upload-time = "2026-09-12T15:13:31.569Z" }, + { url = "https://files.pythonhosted.org/packages/94/2e/708dc1d2678f092c31c12754e860cd8353e6a85ecbdb1010157edca0da9e/jiter-0.17.0-cp315-cp315-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:0239520085cac678e77a606fd7e3f1c60c371d719790c5e3807388d3da4354c2", size = 336001, upload-time = "2026-09-12T15:13:32.846Z" }, + { url = "https://files.pythonhosted.org/packages/f4/f0/75a5ae38862f4eaf0fe2f8a9fbf6484c4890df04c06dcdffc45e36bca61a/jiter-0.17.0-cp315-cp315-musllinux_1_1_aarch64.whl", hash = "sha256:eb2295da7c3769f6719b227a237aa6a5cfa6550e478bc838001b592c57e16575", size = 484281, upload-time = "2026-09-12T15:13:35.333Z" }, + { url = "https://files.pythonhosted.org/packages/a0/32/6636fae811c27c7f93e1b11fb5800de6a5c9e4269a27cf718e0b31218ad1/jiter-0.17.0-cp315-cp315-musllinux_1_1_x86_64.whl", hash = "sha256:e088612ff90ebc9247e1a43074b72835804261c47e6a6c01cb3ddcb55360d688", size = 521300, upload-time = "2026-09-12T15:13:37.101Z" }, + { url = "https://files.pythonhosted.org/packages/61/aa/12df7e0b0b1a2602e3d5a5a7104d7d9700f254b400f134a9b50955c4d231/jiter-0.17.0-cp315-cp315-win32.whl", hash = "sha256:0b52d52035b3907c5b1f6277857b29c1cbfc965e24e0f27330dbed83edb591ec", size = 185138, upload-time = "2026-09-12T15:13:38.901Z" }, + { url = "https://files.pythonhosted.org/packages/ba/ec/3dd2e495032cddde05723c1f4c743b67a23e55d2af244692a7f58f0cdae3/jiter-0.17.0-cp315-cp315-win_amd64.whl", hash = "sha256:10f5558eed511b830488003449d942bd75829ad6257dc58cb9a03e596a7777b1", size = 226950, upload-time = "2026-09-12T15:13:40.17Z" }, + { url = "https://files.pythonhosted.org/packages/c3/c7/ef85704e0a57e9cadb2babc05f6d7c5df4a1c75da1a6ee31e1986b0099a5/jiter-0.17.0-cp315-cp315-win_arm64.whl", hash = "sha256:fa13acf1046f95df808c64b1310705e143fab87aee73ae00cc42d640867fd2c1", size = 183618, upload-time = "2026-09-12T15:13:41.432Z" }, + { url = "https://files.pythonhosted.org/packages/0e/9a/a4b348349de68762b58d6713973d363ad80a1c741d0bf8def7975f0ecb26/jiter-0.17.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:af2f7501580f274b63c4b2283bc425f5df7edf06ae5b171e5f87d912ff359a20", size = 321155, upload-time = "2026-09-12T15:13:42.716Z" }, + { url = "https://files.pythonhosted.org/packages/c1/70/aebd6d0b5f0677de3a3d0bdc4a05fac949b97c4ede454c8809f180ac7b17/jiter-0.17.0-cp315-cp315t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:10c5349312e5cb02b7a21e123a57665afa895953f05bf252a9dd4c13a572b7ab", size = 340985, upload-time = "2026-09-12T15:13:44.115Z" }, + { url = "https://files.pythonhosted.org/packages/a7/82/4c3b49796b5eb62f3f5046f957683f4ba0135fe1a60957c11180512460df/jiter-0.17.0-cp315-cp315t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:86f3f9343a288eb85a81ef20a752b2f84564296636db54a9fff0b5c8deaf1df2", size = 325670, upload-time = "2026-09-12T15:13:45.901Z" }, + { url = "https://files.pythonhosted.org/packages/bc/43/f6341ecb4872202a4ef150486fcee0e1ace4aa3da39b71b82061452cdd3a/jiter-0.17.0-cp315-cp315t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4607ec7d93355fbc25b8dc5189153cf21d66063b9f9cd04dd2774e6e783f9b6a", size = 340339, upload-time = "2026-09-12T15:13:47.442Z" }, + { url = "https://files.pythonhosted.org/packages/f9/c4/bc2c86e08fa065e03cb2fbc53b367c3640a7d257ef9d877b29118ea636b7/jiter-0.17.0-cp315-cp315t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:10cd64a5720ad7f809ac5466ff1705813f1b6b510f195a73acafba0ac0e1f675", size = 350705, upload-time = "2026-09-12T15:13:48.848Z" }, + { url = "https://files.pythonhosted.org/packages/9d/67/91f12aa111cca6e3a197c3e36bf60a034bf9f122f6d41112a639e44217d8/jiter-0.17.0-cp315-cp315t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:efe9f61bb30174d2f5c8396445c360c96c44e78164d0815dfe627ccf57849574", size = 345011, upload-time = "2026-09-12T15:13:50.215Z" }, + { url = "https://files.pythonhosted.org/packages/f5/cb/9f5556e8f6ec89755fb5a709d8eb8270c9a324e31079eda0dfbeca451b6e/jiter-0.17.0-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:370d8fe5bf201dc6925e8a84c81ac7291f74d9fd1778234fc79d517064a5c76b", size = 328268, upload-time = "2026-09-12T15:13:51.809Z" }, + { url = "https://files.pythonhosted.org/packages/22/98/153f20680fb75781a490fb849940e2b00f95035c7aa054df592f36ed33fc/jiter-0.17.0-cp315-cp315t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:6b303d88e6a0bda789ec4b7801c7bad68e27230ba1fe4baffc756d1fbd32dc9d", size = 337024, upload-time = "2026-09-12T15:13:53.095Z" }, + { url = "https://files.pythonhosted.org/packages/af/59/b16c9be3a5035df4466cc72e888188c027562de90a723d290ab6814cb9d4/jiter-0.17.0-cp315-cp315t-musllinux_1_1_aarch64.whl", hash = "sha256:30793a24a31e968969757c9e08d830cbb15a2cd3c4959b4498b38f4b1c2258eb", size = 482766, upload-time = "2026-09-12T15:13:55.713Z" }, + { url = "https://files.pythonhosted.org/packages/d0/55/667dea313094024bef082175d6bfe8976f90d1c00c926af9df1d8e0eab48/jiter-0.17.0-cp315-cp315t-musllinux_1_1_x86_64.whl", hash = "sha256:686c93d86f2b426c803024b805bd161a6cd10e9627c23e901640eab646c0ad8a", size = 520367, upload-time = "2026-09-12T15:13:57.674Z" }, + { url = "https://files.pythonhosted.org/packages/21/e3/4b1a43501fb9ed17b01d137e380cb0e8fdcb39a254ce31aa2ab95bc861ac/jiter-0.17.0-cp315-cp315t-win32.whl", hash = "sha256:86d703d9faa1ffc8ae4e9de0fa007712ed2171b5c0d93811a8e2e105ac729b0d", size = 184603, upload-time = "2026-09-12T15:13:59.27Z" }, + { url = "https://files.pythonhosted.org/packages/f9/f2/b8ee0372b6ebdf1bde5cc44495d5291d17f961065f5b48f8616cc67cac2e/jiter-0.17.0-cp315-cp315t-win_amd64.whl", hash = "sha256:42b0260445251b1bc520a63baa94a32d88e0f931fba234f1764db7feb7c72174", size = 227936, upload-time = "2026-09-12T15:14:00.472Z" }, + { url = "https://files.pythonhosted.org/packages/a4/b4/923a1215daba959aed8355973315cb3f81f53e0d01c5b211870a27b41f45/jiter-0.17.0-cp315-cp315t-win_arm64.whl", hash = "sha256:d47687806f9c54c84ea38733507081337922beca90ce819c7d852dd485bc0f23", size = 182977, upload-time = "2026-09-12T15:14:01.799Z" }, + { url = "https://files.pythonhosted.org/packages/17/31/4bb27f54333d3b9ef1e5bd3312dc0b4bbe59c68bb0885fdb40583a6b1567/jiter-0.17.0-graalpy312-graalpy250_312_native-macosx_10_12_x86_64.whl", hash = "sha256:454c4997d73cc466c71fd565d91e603b0274e48ea0c6b0b7a7aee6967e4ceb7c", size = 288415, upload-time = "2026-09-12T15:14:08.455Z" }, + { url = "https://files.pythonhosted.org/packages/28/30/879570ecf82574eaea77c5eb10309f4b630dece5f2a556e9814a90ba3f2d/jiter-0.17.0-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:40d2c240f8f80b5b0f201b29f0ae129c81448c60c772227a41747b5e0026f6a2", size = 279113, upload-time = "2026-09-12T15:14:10.117Z" }, + { url = "https://files.pythonhosted.org/packages/77/7a/1f0b8a35fbd079a4f1752c31a15dc99cf277f863747c459be0af39e900e5/jiter-0.17.0-graalpy312-graalpy250_312_native-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3e05f5adbf68c4bd11e1610f394034d984152988e84be6f8314235ce6f2139e5", size = 303708, upload-time = "2026-09-12T15:14:11.445Z" }, + { url = "https://files.pythonhosted.org/packages/e1/8b/d76219ebdbcf3d4209d9d21a0810db4c8d0a6f88e3ee87d30bdea4e90d30/jiter-0.17.0-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d2c0bf24c72fd0491405dce5d40194f2070e9021ce648c1a1d46234b93d848ff", size = 307147, upload-time = "2026-09-12T15:14:12.897Z" }, +] + [[package]] name = "jsonschema" version = "4.26.0" @@ -339,6 +669,23 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/88/b2/d0896bdcdc8d28a7fc5717c305f1a861c26e18c05047949fb371034d98bd/nodeenv-1.10.0-py2.py3-none-any.whl", hash = "sha256:5bb13e3eed2923615535339b3c620e76779af4cb4c6a90deccc9e36b274d3827", size = 23438, upload-time = "2025-12-20T14:08:52.782Z" }, ] +[[package]] +name = "openai" +version = "3.32.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "httpx2" }, + { name = "jiter" }, + { name = "pydantic" }, + { name = "sniffio" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/01/f7/17bcb5033c79721d11b8815a7822575e6dedb5af65149575b56c21eb43ae/openai-3.32.0.tar.gz", hash = "sha256:6feb4a50aa653df6d2cd5e9118d5f079a51cb653d652746d344164a3e8419c89", size = 2227852, upload-time = "2026-10-16T20:18:14.688Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9d/2d/3acb5ea3c158ecb205d73d951d8b3df263bc7c927c25a687e06918fd8c07/openai-3.32.0-py3-none-any.whl", hash = "sha256:dac6033390174ee85a3115e312a3a4fabc71824711ded5b3a79d5b670dd6b562", size = 2256256, upload-time = "2026-10-16T20:18:12.544Z" }, +] + [[package]] name = "opentelemetry-api" version = "1.45.2" @@ -378,6 +725,27 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, ] +[[package]] +name = "pyasn1" +version = "0.6.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/88/7e/3c0da41061a2021cac7cd524fd57092adbe5b515e8bf9005702e366802e2/pyasn1-0.6.5.tar.gz", hash = "sha256:6b11616a6bcf3a40e635f082bb232fa57b5e0dd7f517bd7ddd69ec3794508a47", size = 155152, upload-time = "2026-10-27T06:32:49.125Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/19/1f/3eefd5c84c35cae44549ce1c7f7e58f7945b34f5a6bce07a135438522073/pyasn1-0.6.5-py3-none-any.whl", hash = "sha256:4017b0fce125096b8573b39c989fdb1a4b19cf761e683398184550fea0e66587", size = 84807, upload-time = "2026-10-27T06:32:48.045Z" }, +] + +[[package]] +name = "pyasn1-modules" +version = "0.4.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyasn1" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e9/e6/78ebbb10a8c8e4b61a59249394a4a594c1a7af95593dc933a349c8d00964/pyasn1_modules-0.4.2.tar.gz", hash = "sha256:677091de870a80aae844b1ca6134f54652fa2c8c5a52aa396440ac3106e941e6", size = 307892, upload-time = "2025-03-28T02:41:22.17Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/47/8d/d529b5d697919ba8c11ad626e835d4039be708a35b0d22de83a269a6682c/pyasn1_modules-0.4.2-py3-none-any.whl", hash = "sha256:29253a9207ce32b64c3ac6600edc75368f98473906e8fd1043bd6b5b1de2c14a", size = 181259, upload-time = "2025-03-28T02:41:19.028Z" }, +] + [[package]] name = "pycparser" version = "3.0" @@ -591,6 +959,9 @@ dependencies = [ [package.dev-dependencies] dev = [ + { name = "anthropic" }, + { name = "google-genai" }, + { name = "openai" }, { name = "pyright" }, { name = "pytest" }, { name = "pytest-asyncio" }, @@ -612,6 +983,9 @@ requires-dist = [ [package.metadata.requires-dev] dev = [ + { name = "anthropic", specifier = "==1.15.0" }, + { name = "google-genai", specifier = "==2.31.0" }, + { name = "openai", specifier = "==3.32.0" }, { name = "pyright", specifier = ">=1.1" }, { name = "pytest", specifier = ">=8.0" }, { name = "pytest-asyncio", specifier = ">=0.23" }, @@ -703,6 +1077,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/2c/58/ca301544e1fa93ed4f80d724bf5b194f6e4b945841c5bfd555878eea9fcb/referencing-0.37.0-py3-none-any.whl", hash = "sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231", size = 26766, upload-time = "2025-10-13T15:30:47.625Z" }, ] +[[package]] +name = "requests" +version = "2.34.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "charset-normalizer" }, + { name = "idna" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, +] + [[package]] name = "rpds-py" version = "0.30.0" @@ -818,6 +1207,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, ] +[[package]] +name = "sniffio" +version = "1.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a2/87/a6771e1546d97e7e041b6ae58d80074f81b7d5121207425c964ddf5cfdbd/sniffio-1.3.1.tar.gz", hash = "sha256:f4324edc670a0f49750a81b895f35c3adb843cca46f0530f79fc1babb23789dc", size = 20372, upload-time = "2024-02-25T23:20:04.057Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e9/44/75a9c9421471a6c4805dbf2356f7c181a29c1879239abab1ea2cc8f38b40/sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2", size = 10235, upload-time = "2024-02-25T23:20:01.196Z" }, +] + [[package]] name = "soupsieve" version = "2.10" @@ -867,6 +1265,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ec/bb/2799cc2ede3ed41131f8975621e7213dfc7ef4acbbaadfa440f32500c370/starlette-1.3.1-py3-none-any.whl", hash = "sha256:c7372aae11c3c3f26a42df7bd626cec2f47d03483d261d369516a615a53714c6", size = 73632, upload-time = "2026-06-12T09:23:10.017Z" }, ] +[[package]] +name = "tenacity" +version = "9.1.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/47/c6/ee486fd809e357697ee8a44d3d69222b344920433d3b6666ccd9b374630c/tenacity-9.1.4.tar.gz", hash = "sha256:adb31d4c263f2bd041081ab33b498309a57c77f9acf2db65aadf0898179cf93a", size = 49413, upload-time = "2026-02-07T10:45:33.841Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d7/c1/eb8f9debc45d3b7918a32ab756658a0904732f75e555402972246b0b8e71/tenacity-9.1.4-py3-none-any.whl", hash = "sha256:6095a360c919085f28c6527de529e76a06ad89b23659fa881ae0649b867a9d55", size = 28926, upload-time = "2026-02-07T10:45:32.24Z" }, +] + [[package]] name = "truststore" version = "0.10.5" @@ -897,6 +1304,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/67/81/4add07e5172b7ac40d8ed5ff580409a7801a4fe26d529bdd915401dabfbe/typing_inspection-0.4.4-py3-none-any.whl", hash = "sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147", size = 14750, upload-time = "2026-08-12T12:37:24.648Z" }, ] +[[package]] +name = "urllib3" +version = "2.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, +] + [[package]] name = "uvicorn" version = "0.46.0" @@ -910,6 +1326,83 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/31/a3/5b1562db76a5a488274b2332a97199b32d0442aca0ed193697fd47786316/uvicorn-0.46.0-py3-none-any.whl", hash = "sha256:bbebbcbed972d162afca128605223022bedd345b7bc7855ce66deb31487a9048", size = 70926, upload-time = "2026-04-23T07:15:58.355Z" }, ] +[[package]] +name = "websockets" +version = "16.1.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/21/f7/bc3a25c5ec26ce62ce487690becc2f3710bbc7b33338f005ad390db0b986/websockets-16.1.1.tar.gz", hash = "sha256:db234eda965dcce15df96bb9709f587cd87d4d52aaf0e80e2f34ec04c7670c57", size = 182204, upload-time = "2026-07-17T22:51:05.858Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/17/9d/681cda21c9eee743203a6cb79b9d3d05adad9aa60ec660c6c9bf4dd619ca/websockets-16.1.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:cc97814dfb786a83b6e2dc2e79351e1b83e6d715647d6887fcabd83026417a00", size = 179600, upload-time = "2026-07-17T22:49:13.92Z" }, + { url = "https://files.pythonhosted.org/packages/fb/8d/6195a88b45e8d2a8f745fc2046e36f885a3c9763e6767d2c46229bf9510c/websockets-16.1.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:e047dc87ef7ca50f4d309bf775ad4a71711c58556d75d7bd0604b2317f43e94b", size = 177272, upload-time = "2026-07-17T22:49:15.453Z" }, + { url = "https://files.pythonhosted.org/packages/73/e3/fe2d498c64dea0095c9a9f9a351af4cd6eef31b618395582bc1f38ba45ff/websockets-16.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:01fbdcbac298efe19360b94bc0039c8f746f0220ba570f327577bfee81059175", size = 177542, upload-time = "2026-07-17T22:49:16.875Z" }, + { url = "https://files.pythonhosted.org/packages/fe/ed/f1831681fce0e3242346e5458486003c5f124ed69e5e0b847fd029db4973/websockets-16.1.1-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:0f62863e8a00a6d33c3d6566ec0b89f23787b747ffe0c3bc71ec0e76b82c94b1", size = 187137, upload-time = "2026-07-17T22:49:18.323Z" }, + { url = "https://files.pythonhosted.org/packages/6f/79/4ff9dcc1bb46f6b4c536936dde1fd60f9b564f3304307274db97f4c9496d/websockets-16.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8087e82f842609734c9b5a1330464f8e94e346ba0e18c832c08bafa4b0d63c15", size = 188374, upload-time = "2026-07-17T22:49:19.65Z" }, + { url = "https://files.pythonhosted.org/packages/62/c3/5c49b6efb36cab733d23773f6de575e1dba65736ead17d5d2b2a1daef779/websockets-16.1.1-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:2bb5d041a8307d2e18782e7ce777f6fdb1e8c2f5d09291484b18c294b789d9aa", size = 191155, upload-time = "2026-07-17T22:49:21.331Z" }, + { url = "https://files.pythonhosted.org/packages/6e/f6/56ccceda3a4838d18f1d40821480da4775397e8b1eecf4031e20c50e2e90/websockets-16.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1db4de4a0e95673f7545d393c49eeb0c2f18ac1ef93073218c79d5cdb2ee75ab", size = 189011, upload-time = "2026-07-17T22:49:22.889Z" }, + { url = "https://files.pythonhosted.org/packages/86/d6/ad5286241a2bce1107e2798d3bfbd62cf79aee167bdb654f8cb1e9dbf949/websockets-16.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f17dbe07eb3ea7f99e4df9b7e0efefe80fbf30d37a8cc4d561a0aed310bc8847", size = 187766, upload-time = "2026-07-17T22:49:24.339Z" }, + { url = "https://files.pythonhosted.org/packages/bc/67/d65c970b7e347fdca69479beb7811c2060529956730a7a4e3ae7c66b0e31/websockets-16.1.1-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4b57693728576d84ede0a77987ab16881b783d2cd9f1dc180a8fbbc3f79c4428", size = 185173, upload-time = "2026-07-17T22:49:25.743Z" }, + { url = "https://files.pythonhosted.org/packages/1d/5b/14af3cd4ee69d8ea9baca58f3dc3cfb1ba78332a347fd478cb096549d60e/websockets-16.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2a636ff1e7a5c4edf71ef0e79adae7f25dba93b4fcbe3dc958733477ffeb0eaf", size = 187809, upload-time = "2026-07-17T22:49:27.147Z" }, + { url = "https://files.pythonhosted.org/packages/7b/11/be301710d70de97e3e7b3586e6d492c9c06d6a61bf1c2202c36cf0c75607/websockets-16.1.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:d6bec75c290fe484a8ba4cacdf838501e17c06ecfbbf31eede81a9e431bd7751", size = 186412, upload-time = "2026-07-17T22:49:28.611Z" }, + { url = "https://files.pythonhosted.org/packages/db/07/fe1435bf6fe738a3d3b54dbe0c18dabf12cba4d909ac8b58b539ce27c1f4/websockets-16.1.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:54509b8e92fee4453e152b7558ddef37ce9705a044922f2095a6105e3f80c96f", size = 188290, upload-time = "2026-07-17T22:49:29.965Z" }, + { url = "https://files.pythonhosted.org/packages/8a/0a/81f394aff8efcbb01208c1ced77df0a3c7fcce584a88c7273663697946c2/websockets-16.1.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:f0aa4aad3b1b69ad3fd85a0fd0952ec64331c762bd77ec51cc814170873890b2", size = 185844, upload-time = "2026-07-17T22:49:31.447Z" }, + { url = "https://files.pythonhosted.org/packages/39/5c/dd485b995473f415510251fe9bd708f2d24458f439fce958daf8d66dc7c6/websockets-16.1.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:42290eb6db4ccaca7012656738214f8514082fb6fa40cdeb61bb9a471b52e383", size = 186823, upload-time = "2026-07-17T22:49:33.104Z" }, + { url = "https://files.pythonhosted.org/packages/9d/0b/f78de76ff446f1e66af12b43c48a35f31744de93cfdec2f4ea67d5d7bbf1/websockets-16.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:53260c8930da5771cec89439bff99c20c8cb03ddb9588b980697355a83cd4bd3", size = 187102, upload-time = "2026-07-17T22:49:34.616Z" }, + { url = "https://files.pythonhosted.org/packages/37/a1/4cf892007778eaf84ad162bfc98046e0ed89b63ac55949e3236626b2a23f/websockets-16.1.1-cp312-cp312-win32.whl", hash = "sha256:1d27fa8462ad6a1cb36206a3d0640b2333340def181fae11ed7f9adeaa5c0747", size = 179943, upload-time = "2026-07-17T22:49:36.213Z" }, + { url = "https://files.pythonhosted.org/packages/d9/de/6abe251d28c3a3f217096575400b27750b18e0b1d2fff3a2a239960fea07/websockets-16.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:b436f6ec4fc3a6b4237c84d3f83170ed2b40bb584222f0ac47a0c8a5921980c7", size = 180243, upload-time = "2026-07-17T22:49:37.626Z" }, + { url = "https://files.pythonhosted.org/packages/ce/fd/6ec6c6d2850aea25b1b2aa9901a016980bb87d01e89b3eb00470b1b5d471/websockets-16.1.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:ab59169ace05dcb49a1d4118f0bde139557adf45091bd85747e36bf5de984dd1", size = 179587, upload-time = "2026-07-17T22:49:38.959Z" }, + { url = "https://files.pythonhosted.org/packages/5f/d8/1d299d2dd34087db39831a34cc645ef8a6f89d78efada6983093513cd81c/websockets-16.1.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:5e3b7d601f6f84156b08cc4a5e541c2b50ad7b36cfc302b657a12477c904a5df", size = 177272, upload-time = "2026-07-17T22:49:40.293Z" }, + { url = "https://files.pythonhosted.org/packages/3d/86/0a70d3ae2f0f2256bb41302d9804dbca65d4360281e7feb3e1f94102ac46/websockets-16.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:cd2ca96a082a36964aca83e992f72abeb61b7306c1a6cba4c7d06a7b93750cac", size = 177530, upload-time = "2026-07-17T22:49:41.786Z" }, + { url = "https://files.pythonhosted.org/packages/b5/c2/c676c69444d9db448b3f0a55a98dcc534affce0bce961d9d2f0b8499b10a/websockets-16.1.1-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:f5d497865f05bb222cab7016c6034542e84e5f29f49c6fd3f4939cda7197b5b8", size = 187197, upload-time = "2026-07-17T22:49:43.658Z" }, + { url = "https://files.pythonhosted.org/packages/0b/13/88137fbaf726ebe29d62c1117fa11fa2bbb6209dc79d4ad738efbe36a2aa/websockets-16.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bae954c382e013d5ea5b190d2830526bfa45ad121c326da0049b8c769f185db6", size = 188433, upload-time = "2026-07-17T22:49:45.147Z" }, + { url = "https://files.pythonhosted.org/packages/01/6d/46c2f2ce6751cb26f39293e1ecbf8544cb01321397cd476c2756b98c216d/websockets-16.1.1-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e09f753a169951eb4f28c2c774f71069304f66e7277e0f5a2892423599cfa854", size = 189868, upload-time = "2026-07-17T22:49:46.581Z" }, + { url = "https://files.pythonhosted.org/packages/29/2b/170a9e8097636cfde4dc3c592b6e00b18a44a2f5407606d96ca542dd5838/websockets-16.1.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:024193f8551a2b0eafbdd160911012c4e6c228c28430c84433253299a9e42d6a", size = 189059, upload-time = "2026-07-17T22:49:47.972Z" }, + { url = "https://files.pythonhosted.org/packages/a7/48/f0d4ebc9ab4b473b8861b9e20fdb663d515d42f7befdf62cdb60fee7a1ec/websockets-16.1.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:aabe464bfd13bd25f4821faf111da6fefdc389f870265a53105580e45b0a2e49", size = 187814, upload-time = "2026-07-17T22:49:49.344Z" }, + { url = "https://files.pythonhosted.org/packages/d5/ba/39a41d3ae8e72696a9492581900611c5a91e2b07563b0bcd2523adea9854/websockets-16.1.1-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a28fcbc9b6baf54a2e23f8655f308e4ccc6afdd7266f8fe7954f320dcda0f785", size = 185229, upload-time = "2026-07-17T22:49:50.787Z" }, + { url = "https://files.pythonhosted.org/packages/3c/36/ac15b604f850d1907f0a85ed721cefe47cd45034b3620069b829746cccbe/websockets-16.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:79eace538c6a97e96d0d03d4f9d314f9677f5ed85a8a984992ffd90b13cb8a56", size = 187874, upload-time = "2026-07-17T22:49:52.228Z" }, + { url = "https://files.pythonhosted.org/packages/a8/f3/3fbd5d71d59299c3770faa5884d4f45070236ca5a35ab3a61830812c409a/websockets-16.1.1-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:496af849a472b531f758dbd4d61338f5000538cb1a7b3d20d9d32a264517f509", size = 186469, upload-time = "2026-07-17T22:49:53.776Z" }, + { url = "https://files.pythonhosted.org/packages/b4/fc/dd90349bba58af2a53ef2ddd9c32716c81eb6d59a0687939fff561860878/websockets-16.1.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:5283810d2646741a0d8da2aa733d6aefa0545809afccb2a5d105a26bc45125f1", size = 188347, upload-time = "2026-07-17T22:49:55.202Z" }, + { url = "https://files.pythonhosted.org/packages/4c/f3/f73ba86427682da59b78c11d77ba56d5b801c32e84afe79b274bbd6a9bb2/websockets-16.1.1-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:4e3b680b1e0a27457e727a0d572fd81dffa87b6dbf8b228ab57da64f7d85aead", size = 185903, upload-time = "2026-07-17T22:49:56.75Z" }, + { url = "https://files.pythonhosted.org/packages/34/7c/f95eb20e80104173b3a0a092291f89ea4047ef6e608e0a57ca06eb14eecb/websockets-16.1.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:69159730a823dde3ea8d08783e8d47ef135a6d7e8d44eb127e32b321c9db8e3e", size = 186855, upload-time = "2026-07-17T22:49:58.467Z" }, + { url = "https://files.pythonhosted.org/packages/b0/35/dd875b3e050ff232d60fa377707f890e369f74d134f1be32e8f68879747c/websockets-16.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:ed5bb271084b46530ee2ddc0410537a9961152c5ccba2fc98c5276d992ccba87", size = 187140, upload-time = "2026-07-17T22:50:00.016Z" }, + { url = "https://files.pythonhosted.org/packages/e8/dc/5cbfcb41824502f6af93b8f3943a4d06c67c23c7d2e31eb18748c4a5b2a7/websockets-16.1.1-cp313-cp313-win32.whl", hash = "sha256:cfb70b4eb56cac4da0a83588f3ad50d46beb0690391082f3d4e2d488c70b68ea", size = 179928, upload-time = "2026-07-17T22:50:01.685Z" }, + { url = "https://files.pythonhosted.org/packages/b0/c1/71e5deb5b7f8f226997ab64908c184ac3105c0155ce2d486f318e5dd08a8/websockets-16.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:d9531d9cbeac99af6f038fb1bc351403531f7d634a2c2e10e2f7c854c6ed5b68", size = 180242, upload-time = "2026-07-17T22:50:03.117Z" }, + { url = "https://files.pythonhosted.org/packages/73/a2/ba78a164eeea4620df4a4df4bd2ed6017438c4655cc0f36f2c0bc0432355/websockets-16.1.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:443aefe96b7fdb132e2a70806cca1f2af49bb3f28e47abcd7c2e9dcf4d8fa1b8", size = 179635, upload-time = "2026-07-17T22:50:05.001Z" }, + { url = "https://files.pythonhosted.org/packages/b9/08/d26d7a7628cd4ac34cbbdb63ac80914ca842ed8e42938c40a53567806df3/websockets-16.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:6456ff333092d509127d75a638cb411afae8ff17f092635015d1902efec8a293", size = 177320, upload-time = "2026-07-17T22:50:06.427Z" }, + { url = "https://files.pythonhosted.org/packages/0f/45/ebec83e6269536aa5932533c67b0af5c781f3e73fdbcd68672dcf43f4f44/websockets-16.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:fce6c48559c86d1ac3632ccb1bebc7d5442fbe79bd9bb0e40379ee54be2a4051", size = 177544, upload-time = "2026-07-17T22:50:07.834Z" }, + { url = "https://files.pythonhosted.org/packages/c9/d5/abc614d2297f6c1c3e01e61260364457a47c25cc1cf6a879038902bc6aa8/websockets-16.1.1-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:92b820d345f7a3fc7b8163949ee92df910f290c3fc517b3d5301c78065adafe1", size = 187270, upload-time = "2026-07-17T22:50:09.275Z" }, + { url = "https://files.pythonhosted.org/packages/52/71/4c99af3b87dff1b2927981f6876607d4acb45338c665242168d3982f7758/websockets-16.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2a606d9c24035242a3e256e9d5b77ed9cd6bccfcb7cf993e5ca3c0f6f68fb6a7", size = 188509, upload-time = "2026-07-17T22:50:10.722Z" }, + { url = "https://files.pythonhosted.org/packages/9b/b4/5c8ca14b0df7eb84ed0524165c5359150210140817a3312aee57bf62a1cf/websockets-16.1.1-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:414e596c75f74e0994084694189d7dc9229fb278e33064d6784b73ffbba3ca31", size = 189882, upload-time = "2026-07-17T22:50:12.293Z" }, + { url = "https://files.pythonhosted.org/packages/25/c1/bedfba9e70557129cb8083748d167bdcc01483dedf0f0df143676df05cbe/websockets-16.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:536676848fc5961aca9d20389951f59169508f765637a172403dc5434d722fa0", size = 189114, upload-time = "2026-07-17T22:50:13.789Z" }, + { url = "https://files.pythonhosted.org/packages/df/09/aa835b2787835aebd839114be5de51b797cb480b63ba42b26d34dfe147cb/websockets-16.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:97fd3a0e8b53efa41970ac1dff3d8cf0d2884cadeb4caaf95db7ad1526926ee3", size = 187861, upload-time = "2026-07-17T22:50:15.179Z" }, + { url = "https://files.pythonhosted.org/packages/20/26/f6408330694dbc9830857d9d23bc14ac4f6875127a480cfdda8d5ca21198/websockets-16.1.1-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:7b1b19636af86a3c7995d4d028dbe376f39b4bf31541146f9c123582a6c94562", size = 185286, upload-time = "2026-07-17T22:50:16.741Z" }, + { url = "https://files.pythonhosted.org/packages/17/9a/e0675e70dd8a80762cf35bb18799d3f290a4890ffe6439bc51d222796083/websockets-16.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:41c8e77f17294c0ac18008a7309b99b34ee72247ef10b6dff4c3f8b5ac29896b", size = 187935, upload-time = "2026-07-17T22:50:18.213Z" }, + { url = "https://files.pythonhosted.org/packages/33/c1/3234cfb86afde01b81e9bddcc6e534c440975d60a13991259e833069ab3e/websockets-16.1.1-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:9f63bcef7f4b02b06b35fc01c93b96c43b5e88e1e8868676caacf493d5a31f3a", size = 186444, upload-time = "2026-07-17T22:50:19.67Z" }, + { url = "https://files.pythonhosted.org/packages/89/87/9c15206e1d778923d8daa9657de07aa62ea815e13448319c98458c37b281/websockets-16.1.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:dab9eb87869da2d6ed3af3f3adf28414baae6ec9d4df355ffc18889132f3436c", size = 188409, upload-time = "2026-07-17T22:50:21.28Z" }, + { url = "https://files.pythonhosted.org/packages/f2/00/cf5de5c67676de2d3eef8b2a518f168f6796595447a5b7161ba0d012915c/websockets-16.1.1-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:43e3a9fdd7cbf7ba6040c31fae0faf84ca1474fef777c4e37912f1540f854499", size = 185958, upload-time = "2026-07-17T22:50:22.719Z" }, + { url = "https://files.pythonhosted.org/packages/62/c0/731b6ddede2e4136912ec4cff2cffbda35af73546be4762c3d7bd3bd79af/websockets-16.1.1-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:056ae37939ed7e9974f364f5864e76e49182622d8f9751ac1903c0d09b013985", size = 186911, upload-time = "2026-07-17T22:50:24.108Z" }, + { url = "https://files.pythonhosted.org/packages/8c/7f/39c634472c4469a24a7c09cecddffb08fac6d0e74f73881a94ee8a40a196/websockets-16.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:a0eadbbf2c30f01efa58e1f110eb6fa293261f6b0b1aa38f7f48707107690af9", size = 187204, upload-time = "2026-07-17T22:50:25.548Z" }, + { url = "https://files.pythonhosted.org/packages/26/89/9667c256c256dafcc62d21328ce7a40067da857969b68ee9af375b0aaf72/websockets-16.1.1-cp314-cp314-win32.whl", hash = "sha256:195c978b065fa40910582464f99d6b15c8b314c68e0546549a55ed83f4735328", size = 179603, upload-time = "2026-07-17T22:50:27.086Z" }, + { url = "https://files.pythonhosted.org/packages/bd/dd/1c099d6c0fc5deb6b46ccdbb6981fdb4b12c917869cb3952408409dc18db/websockets-16.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:4e8d01cc3bcae7bbf8167f944aeafefed590fae5693552bba9794a9df68371cc", size = 179948, upload-time = "2026-07-17T22:50:28.521Z" }, + { url = "https://files.pythonhosted.org/packages/35/25/9956b2d5e0529d5d23924f21bba1440d4c5c88a562e4f08550871ffa97a7/websockets-16.1.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:0ffd3031ea8bda8d61762e84220186105ba3b748b3c8da2ae4f7816fac03e573", size = 179963, upload-time = "2026-07-17T22:50:29.982Z" }, + { url = "https://files.pythonhosted.org/packages/17/06/55ffc976c488b6aee9ea05761ff7c4e88e7c1fd82818c8ca7b556ad2f90c/websockets-16.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:84a2cef8deffbd9ab8ee0ea546a2a6a7030c28f44e6cdd4547dbfeb489eb8999", size = 177497, upload-time = "2026-07-17T22:50:31.396Z" }, + { url = "https://files.pythonhosted.org/packages/0c/e8/f7dac2e980bacc92bdc26cebae4ae4d50cae5380732c50980598fc0bbae4/websockets-16.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:3df13f73af9b3b38ab1195eb299ecb67a4330c911c97ae04043ff74085728abe", size = 177698, upload-time = "2026-07-17T22:50:32.829Z" }, + { url = "https://files.pythonhosted.org/packages/b2/39/26762f734113e22da2b942c3aca85798e0c0405d64c256549540ff31e5a1/websockets-16.1.1-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:23253dd5bcae3f9aaee0a1d30967a8dbd52e5d3cff93a2e5b84df57b77d4750d", size = 187561, upload-time = "2026-07-17T22:50:34.24Z" }, + { url = "https://files.pythonhosted.org/packages/11/94/c3f330851806b9b02138b774d593478323e73c99238681b4b93efe64e02d/websockets-16.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9c1c5705e314449e3308872fe084b8571ce078ee4fc55a98a769bdefe5917392", size = 188732, upload-time = "2026-07-17T22:50:36.088Z" }, + { url = "https://files.pythonhosted.org/packages/d1/f2/eb2c450f052de334ae33cf200ece6e87b0e14d186807074e4eb1cd2cdea2/websockets-16.1.1-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:69e52d175a0a7d1e13b4b67ad41c560b7d98e8c6f6126eb0bda496c784faf8c7", size = 190872, upload-time = "2026-07-17T22:50:38.008Z" }, + { url = "https://files.pythonhosted.org/packages/70/31/2ac8cecf3a74f7fed9132129fc3d90b3998a1554570c11a69b2a8c20332d/websockets-16.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1f79c89b5eb034d1722938a891916582f8f7f503f58ca22518a63c3f2cd18499", size = 189305, upload-time = "2026-07-17T22:50:39.53Z" }, + { url = "https://files.pythonhosted.org/packages/6a/cf/8ab19650d3c0d4562c92e70ab47c257c4aa5c6a713ed87fe63766b31fefc/websockets-16.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:39f2a024af5c345ffe8fcf1ee18c049c024c94df393bb09b044a6917c77bde43", size = 188033, upload-time = "2026-07-17T22:50:40.912Z" }, + { url = "https://files.pythonhosted.org/packages/66/d7/a49a38a6127a4acb134fb1912b215d900cc657605cff32445bf519f3acc4/websockets-16.1.1-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:952303a7318d4cbe1011400839bb2051c9f84fa0a35923267f5daba34b15d458", size = 185748, upload-time = "2026-07-17T22:50:42.559Z" }, + { url = "https://files.pythonhosted.org/packages/95/3e/ad1fa40388c7f2e0bb2c7930d0090b6c5498594bd1cdaec18864df3d9e97/websockets-16.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:249116b4a76063d930a46391ad56e135c286e4562a18309029fc2c73f4ed4c62", size = 188285, upload-time = "2026-07-17T22:50:43.974Z" }, + { url = "https://files.pythonhosted.org/packages/35/b8/d5db28ca264b9104f82196f92dc8843e35fd391f763d42e4ad358f5bc97e/websockets-16.1.1-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:61922544a0587a13fd3f53e4c0e5e606510c7b0d9d22c8444e5fae22a06b38cb", size = 186777, upload-time = "2026-07-17T22:50:45.474Z" }, + { url = "https://files.pythonhosted.org/packages/42/9c/726cb39d0cc43ae848dce4aa2acb04eecc6738b1264ec6d700bf6bcfb9f8/websockets-16.1.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:46dcaa042cd1de6c59e7d9269fa63ff7572b6df40510600b678f0826b3c7af51", size = 188682, upload-time = "2026-07-17T22:50:46.973Z" }, + { url = "https://files.pythonhosted.org/packages/be/c7/1168704de8c2dd483edabe4a22cbe4465dd8be8dd95561d214f9fe092871/websockets-16.1.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:38565aca3e01ea8734e578fb2118dade0ecb0250533f29e22b8d1a7a196cf4d0", size = 186377, upload-time = "2026-07-17T22:50:48.413Z" }, + { url = "https://files.pythonhosted.org/packages/ca/40/f9ff2d630ffce4e7dfea0b2288e1caf9ebbf9ff8a9ec9396136ce8b94935/websockets-16.1.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:42f599f4d48c7e1a3338fdaac3acd075be3b3cf02d4b274f3bf2767aedd3d217", size = 187148, upload-time = "2026-07-17T22:50:49.845Z" }, + { url = "https://files.pythonhosted.org/packages/b5/71/e177c8299f78d7cbe2d14df228643c10c70c0e86e108e092056bbcc16e46/websockets-16.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:dcc04fedf83effaeb9cce98abc9469bb1b42ef85f03e01c8c1f4438ef7555737", size = 187578, upload-time = "2026-07-17T22:50:51.619Z" }, + { url = "https://files.pythonhosted.org/packages/49/b2/b6987faf330f5af5c787a2610124c2e8403d51724f9001ec4fff6311fe7a/websockets-16.1.1-cp314-cp314t-win32.whl", hash = "sha256:8483c2096363120eea8b07c06ae7304d520f686665fffd4811fad423930a65d7", size = 179729, upload-time = "2026-07-17T22:50:53.269Z" }, + { url = "https://files.pythonhosted.org/packages/a2/6e/fbac6ed878dd362fbad7d415fa4f84d38e3e33fed8cde45c64e783acf826/websockets-16.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:bcce07e23e5769375158f5efdcdafa8d5cd014b93c6683865b840ed65b96f231", size = 180072, upload-time = "2026-07-17T22:50:54.969Z" }, + { url = "https://files.pythonhosted.org/packages/be/4d/2d0d67834092e354d2b0498f014a41249a89556bc406cf86f3e1557bb463/websockets-16.1.1-py3-none-any.whl", hash = "sha256:6abbd3e82c731c8e531714466acd5d87b5e88ac3243465337ba71d68e23ae7e3", size = 173814, upload-time = "2026-07-17T22:51:04.184Z" }, +] + [[package]] name = "zstandard" version = "0.25.0" From fdb0b88fb794c24070e3351e175442459d9bf989 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Tue, 3 Nov 2026 22:31:18 +0100 Subject: [PATCH 04/77] feat(benchmarks): add Anthropic and OpenAI agentic clients The neutral turn types, and one client per API that sends exactly one HTTP request per call (SDK retries off). Anthropic: auto tool choice, no sampling parameters, no cache_control, thinking blocks replayed as received. OpenAI Responses: store false, encrypted reasoning included and replayed, strict false, no prompt-cache option. Status, timeout and connection errors are classified for the ledger; retry-after is parsed in milliseconds, seconds or as an HTTP date. Non-object tool arguments are kept raw. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/clients.py | 259 ++++++++++++++++ benchmarks/agentic/types.py | 87 +++++- tests/benchmarks/test_agentic_clients.py | 379 +++++++++++++++++++++++ 3 files changed, 724 insertions(+), 1 deletion(-) create mode 100644 benchmarks/agentic/clients.py create mode 100644 tests/benchmarks/test_agentic_clients.py diff --git a/benchmarks/agentic/clients.py b/benchmarks/agentic/clients.py new file mode 100644 index 00000000..d9f30ed8 --- /dev/null +++ b/benchmarks/agentic/clients.py @@ -0,0 +1,259 @@ +"""Provider clients for the agentic loop: SDK construction, calls and error classes. + +Every client sends exactly one HTTP request per ``call`` (#177 item 1): SDK +retries are off, and the loop retries by itself, one ledger unit per attempt. +A conversation without tools sends neither tools nor ``tool_choice``. +""" + +from __future__ import annotations + +import json +from collections.abc import Mapping, Sequence +from datetime import UTC, datetime +from email.utils import parsedate_to_datetime +from typing import Any + +import anthropic +import httpx2 +import openai +from anthropic.types import TextBlock, ToolUseBlock + +from benchmarks.agentic.schemas import to_anthropic, to_openai_responses +from benchmarks.agentic.types import ( + Conversation, + ModelTurn, + ProviderCallError, + ToolCall, + ToolResults, + UserText, +) +from benchmarks.agentic.usage import anthropic_buckets, openai_buckets + + +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 + if isinstance(value, str): + try: + parsed = json.loads(value) + except json.JSONDecodeError: + return {}, value + if isinstance(parsed, dict): + return parsed, None + return {}, value if isinstance(value, str) else json.dumps(value) + + +def parse_retry_after(headers: Mapping[str, str]) -> float | None: + """Seconds to wait from ``retry-after-ms`` or ``retry-after`` (seconds or an HTTP date).""" + try: + if (ms := headers.get("retry-after-ms")) is not None: + return float(ms) / 1000 + value = headers.get("retry-after") + if value is None: + return None + try: + return float(value) + except ValueError: + when = parsedate_to_datetime(value) + return max(0.0, (when - datetime.now(UTC)).total_seconds()) + except (TypeError, ValueError): + return None + + +def _status_error(status: int, headers: Mapping[str, str], message: str) -> ProviderCallError: + if status == 429: + return ProviderCallError( + "rate_limited", message, status=status, retry_after_s=parse_retry_after(headers) + ) + kind = "server" if status >= 500 else "rejected" + return ProviderCallError(kind, message, status=status) + + +def _utf8_len(payload: Any) -> int: + return len(json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")) + + +def anthropic_sdk( + api_key: str, timeout_s: float, *, http_client: httpx2.AsyncClient | None = None +) -> anthropic.AsyncAnthropic: + return anthropic.AsyncAnthropic( + api_key=api_key, max_retries=0, timeout=timeout_s, http_client=http_client + ) + + +def openai_sdk( + api_key: str, + timeout_s: float, + *, + base_url: str | None = None, + http_client: httpx2.AsyncClient | None = None, +) -> openai.AsyncOpenAI: + return openai.AsyncOpenAI( + api_key=api_key, + base_url=base_url, + max_retries=0, + timeout=timeout_s, + http_client=http_client, + ) + + +class AnthropicClient: + """Anthropic Messages: no sampling parameters, no ``cache_control``.""" + + provider = "anthropic" + + def __init__(self, sdk: anthropic.AsyncAnthropic, model_id: str, max_output_tokens: int): + self._sdk = sdk + self.model_id = model_id + self._max_output_tokens = max_output_tokens + + def request_params(self) -> dict[str, Any]: + return { + "model": self.model_id, + "max_tokens": self._max_output_tokens, + "tool_choice": {"type": "auto"}, # sent only with tools + } + + 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): + content = [ + { + "type": "tool_result", + "tool_use_id": r.call_id, + "content": r.text, + "is_error": r.is_error, + } + for r in entry.results + ] + messages.append({"role": "user", "content": content}) + else: + messages.append({"role": "assistant", "content": entry.replay}) + return messages + + def rendered_bytes(self, conv: Conversation, start: int) -> int: + messages = self._messages(conv.entries[start:]) + if start: + return _utf8_len(messages) + tools = to_anthropic(conv.tools) + return _utf8_len({"system": conv.system, "tools": tools, "messages": messages}) + + async def call(self, conv: Conversation) -> ModelTurn: + kwargs: dict[str, Any] = { + "model": self.model_id, + "max_tokens": self._max_output_tokens, + "system": conv.system, + "messages": self._messages(conv.entries), + } + if conv.tools: + kwargs |= {"tools": to_anthropic(conv.tools), "tool_choice": {"type": "auto"}} + try: + response = await self._sdk.messages.create(**kwargs) + except anthropic.APIStatusError as exc: + raise _status_error(exc.status_code, exc.response.headers, str(exc)) from exc + except anthropic.APITimeoutError as exc: + raise ProviderCallError("timeout", str(exc)) from exc + except anthropic.APIConnectionError as exc: + raise ProviderCallError("connection", str(exc)) from exc + calls = [] + for block in response.content: + if isinstance(block, ToolUseBlock): + arguments, raw = 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( + text="".join(b.text for b in response.content if isinstance(b, TextBlock)), + tool_calls=tuple(calls), + # Thinking blocks and their signatures go back exactly as received. + replay=[block.to_dict(mode="json") for block in response.content], + raw_response=response.model_dump(mode="json"), + raw_usage=usage, + buckets=None if usage is None else anthropic_buckets(usage), + reported_model=response.model, + stop_reason=response.stop_reason, + ) + + +class OpenAIResponsesClient: + """OpenAI Responses: ``store=False``, encrypted reasoning replayed, no prompt-cache option.""" + + provider = "openai" + + def __init__(self, sdk: openai.AsyncOpenAI, model_id: str, max_output_tokens: int): + self._sdk = sdk + self.model_id = model_id + self._max_output_tokens = max_output_tokens + + def request_params(self) -> dict[str, Any]: + return { + "model": self.model_id, + "max_output_tokens": self._max_output_tokens, + "store": False, + "include": ["reasoning.encrypted_content"], + "tool_choice": "auto", # sent only with tools + } + + def _input(self, entries: Sequence[Any]) -> list[dict[str, Any]]: + items: list[dict[str, Any]] = [] + for entry in entries: + if isinstance(entry, UserText): + items.append({"role": "user", "content": entry.text}) + elif isinstance(entry, ToolResults): + items += [ + {"type": "function_call_output", "call_id": r.call_id, "output": r.text} + for r in entry.results + ] + else: + items += entry.replay + return items + + def rendered_bytes(self, conv: Conversation, start: int) -> int: + items = self._input(conv.entries[start:]) + if start: + return _utf8_len(items) + tools = to_openai_responses(conv.tools) + return _utf8_len({"instructions": conv.system, "tools": tools, "input": items}) + + async def call(self, conv: Conversation) -> ModelTurn: + kwargs: dict[str, Any] = { + "model": self.model_id, + "instructions": conv.system, + "input": self._input(conv.entries), + "max_output_tokens": self._max_output_tokens, + "store": False, + "include": ["reasoning.encrypted_content"], + } + if conv.tools: + kwargs |= {"tools": to_openai_responses(conv.tools), "tool_choice": "auto"} + try: + response = await self._sdk.responses.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 + calls, texts = [], [] + for item in response.output: + if item.type == "function_call": + arguments, raw = 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"] + usage = response.usage.model_dump(mode="json") if response.usage else None + details = response.incomplete_details + return ModelTurn( + text="".join(texts), + tool_calls=tuple(calls), + replay=[item.to_dict(mode="json") for item in response.output], + raw_response=response.model_dump(mode="json"), + raw_usage=usage, + buckets=None if usage is None else openai_buckets(usage), + reported_model=response.model, + stop_reason=details.reason + if response.status == "incomplete" and details is not None + else response.status, + ) diff --git a/benchmarks/agentic/types.py b/benchmarks/agentic/types.py index c3c0b02f..2684ef16 100644 --- a/benchmarks/agentic/types.py +++ b/benchmarks/agentic/types.py @@ -3,7 +3,7 @@ from __future__ import annotations from dataclasses import dataclass -from typing import Any +from typing import Any, Literal, Protocol @dataclass(frozen=True) @@ -28,3 +28,88 @@ class Buckets: @property def total_input(self) -> int: return self.uncached_input + self.cache_write_input + self.cached_input + + +@dataclass(frozen=True) +class ToolCall: + id: str # provider id, or "call_" (1-based within the turn) when missing + name: str + arguments: dict[str, Any] + raw_arguments: str | None = None # set only when the arguments were not a JSON object + + +@dataclass(frozen=True) +class ToolResult: + call_id: str + name: str + text: str # as sent, after truncation + is_error: bool + + +@dataclass(frozen=True) +class UserText: + text: str + + +@dataclass(frozen=True) +class ToolResults: + results: tuple[ToolResult, ...] + + +@dataclass(frozen=True) +class ModelTurn: + text: str # visible text blocks joined with "" + tool_calls: tuple[ToolCall, ...] + replay: Any # provider-native assistant content, appended back unchanged + raw_response: dict[str, Any] # SDK response model_dump(mode="json") + raw_usage: dict[str, Any] | None + buckets: Buckets | None + reported_model: str | None + stop_reason: str | None # normalized per provider + + +@dataclass(eq=False) # identity equality: a conversation is one object, never compared by value +class Conversation: + system: str + tools: list[ToolSpec] + entries: list[UserText | ModelTurn | ToolResults] + + +ErrorKind = Literal["rejected", "rate_limited", "server", "timeout", "connection"] + + +class ProviderCallError(Exception): + """One failed provider request, classified for the ledger and the retry policy.""" + + def __init__( + self, + kind: ErrorKind, + message: str, + *, + status: int | None = None, + retry_after_s: float | None = None, + ) -> None: + super().__init__(message) + self.kind: ErrorKind = kind + self.status = status + self.retry_after_s = retry_after_s + + +class ModelClient(Protocol): + provider: str + model_id: str + + def request_params(self) -> dict[str, Any]: + """Every setting sent except system, tools and messages.""" + ... + + def rendered_bytes(self, conv: Conversation, start: int) -> int: + """UTF-8 bytes of the provider-rendered request. + + System, tools and ``entries[start:]`` when ``start == 0``, else ``entries[start:]`` only. + """ + ... + + async def call(self, conv: Conversation) -> ModelTurn: + """One HTTP request; raises :class:`ProviderCallError`.""" + ... diff --git a/tests/benchmarks/test_agentic_clients.py b/tests/benchmarks/test_agentic_clients.py new file mode 100644 index 00000000..d3acacf3 --- /dev/null +++ b/tests/benchmarks/test_agentic_clients.py @@ -0,0 +1,379 @@ +"""Provider clients for the agentic loop (design §6, §8, §12; #177 item 1). + +Every HTTP exchange goes through a mock transport; no test reaches a network host. +""" + +from __future__ import annotations + +import json +from collections.abc import Callable +from datetime import UTC, datetime, timedelta +from email.utils import format_datetime +from typing import Any + +import httpx2 +import pytest + +from benchmarks.agentic.clients import ( + AnthropicClient, + OpenAIResponsesClient, + anthropic_sdk, + openai_sdk, + parse_retry_after, + tool_arguments, +) +from benchmarks.agentic.types import ( + Buckets, + Conversation, + ModelTurn, + ProviderCallError, + ToolCall, + ToolResult, + ToolResults, + ToolSpec, + UserText, +) + +TOOLS = [ + ToolSpec( + "search_docs", + "Search Python documentation.", + {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}, + ) +] + +ANTHROPIC_TOOL_TURN = { + "id": "msg_1", + "type": "message", + "role": "assistant", + "model": "claude-sonnet-5-5", + "content": [ + {"type": "thinking", "thinking": "t", "signature": "sig"}, + {"type": "tool_use", "id": "toolu_1", "name": "search_docs", "input": {"query": "json"}}, + ], + "stop_reason": "tool_use", + "stop_sequence": None, + "usage": { + "input_tokens": 100, + "cache_creation_input_tokens": None, + "cache_read_input_tokens": 20, + "output_tokens": 30, + }, +} +ANTHROPIC_ANSWER = { + **ANTHROPIC_TOOL_TURN, + "id": "msg_2", + "content": [{"type": "text", "text": "The answer."}], + "stop_reason": "end_turn", +} + + +def _openai_response( + output: list[dict[str, Any]], *, status: str = "completed", details: Any = None +) -> dict[str, Any]: + return { + "id": "resp_1", + "object": "response", + "created_at": 0, + "status": status, + "incomplete_details": details, + "model": "gpt-6.1-sol", + "output": output, + "parallel_tool_calls": True, + "tool_choice": "auto", + "tools": [], + "usage": { + "input_tokens": 1000, + "input_tokens_details": {"cached_tokens": 200, "cache_write_tokens": 300}, + "output_tokens": 50, + "output_tokens_details": {"reasoning_tokens": 40}, + "total_tokens": 1050, + }, + } + + +OPENAI_CALL = { + "type": "function_call", + "id": "fc_1", + "call_id": "call_abc", + "name": "search_docs", + "arguments": '{"query": "json"}', + "status": "completed", +} +OPENAI_REASONING = { + "type": "reasoning", + "id": "rs_1", + "summary": [], + "encrypted_content": "opaque", +} +OPENAI_MESSAGE = { + "type": "message", + "id": "msg_1", + "role": "assistant", + "status": "completed", + "content": [{"type": "output_text", "text": "The answer.", "annotations": []}], +} +ERROR_BODY = {"type": "error", "error": {"type": "api_error", "message": "boom"}} + + +class Recorder: + """A mock transport handler that records each request and plays canned responses.""" + + def __init__(self, *responses: httpx2.Response | Callable[[httpx2.Request], Any]) -> None: + self.responses = list(responses) + self.seen: list[httpx2.Request] = [] + + def __call__(self, request: httpx2.Request) -> httpx2.Response: + self.seen.append(request) + response = self.responses.pop(0) + if callable(response): + return response(request) + return response + + def client(self) -> httpx2.AsyncClient: + return httpx2.AsyncClient(transport=httpx2.MockTransport(self)) + + def body(self, index: int) -> dict[str, Any]: + return json.loads(self.seen[index].content) + + +def _ok(body: dict[str, Any], status: int = 200, headers: dict[str, str] | None = None): + return httpx2.Response(status, json=body, headers=headers or {}) + + +def _anthropic(recorder: Recorder) -> AnthropicClient: + sdk = anthropic_sdk("test-key", 30, http_client=recorder.client()) + return AnthropicClient(sdk, "claude-sonnet-5-5", 32_768) + + +def _openai(recorder: Recorder) -> OpenAIResponsesClient: + sdk = openai_sdk("test-key", 30, http_client=recorder.client()) + return OpenAIResponsesClient(sdk, "gpt-6.1-sol", 32_768) + + +def _conv(tools: list[ToolSpec] | None = None) -> Conversation: + return Conversation("system prompt", TOOLS if tools is None else tools, [UserText("q?")]) + + +def test_sdk_clients_have_their_retries_off() -> None: + assert anthropic_sdk("test-key", 30).max_retries == 0 + assert openai_sdk("test-key", 30).max_retries == 0 + assert anthropic_sdk("test-key", 30).timeout == 30 + + +@pytest.mark.parametrize("provider", ["anthropic", "openai"]) +@pytest.mark.parametrize("status", [200, 500, 529]) +async def test_each_client_sends_one_request_per_call(provider: str, status: int) -> None: + good = ANTHROPIC_ANSWER if provider == "anthropic" else _openai_response([OPENAI_MESSAGE]) + recorder = Recorder(_ok(good if status == 200 else ERROR_BODY, status)) + client = _anthropic(recorder) if provider == "anthropic" else _openai(recorder) + if status == 200: + await client.call(_conv()) + else: + with pytest.raises(ProviderCallError) as caught: + await client.call(_conv()) + assert caught.value.kind == "server" and caught.value.status == status + assert len(recorder.seen) == 1 + + +async def test_anthropic_request_has_auto_tool_choice_and_no_sampling_parameters() -> None: + recorder = Recorder(_ok(ANTHROPIC_TOOL_TURN)) + turn = await _anthropic(recorder).call(_conv()) + body = recorder.body(0) + assert body["tool_choice"] == {"type": "auto"} and body["max_tokens"] == 32768 + assert body["model"] == "claude-sonnet-5-5" and body["system"] == "system prompt" + assert body["tools"] == [ + {"name": t.name, "description": t.description, "input_schema": t.input_schema} + for t in TOOLS + ] + assert body["messages"] == [{"role": "user", "content": "q?"}] + assert not {"temperature", "top_p", "top_k", "cache_control"} & set(body) + assert turn.tool_calls == (ToolCall("toolu_1", "search_docs", {"query": "json"}),) + assert turn.buckets == Buckets(100, 0, 20, 30, 0) and turn.reported_model == "claude-sonnet-5-5" + assert turn.stop_reason == "tool_use" and turn.raw_usage is not None + assert turn.raw_response["id"] == "msg_1" + + +async def test_anthropic_replays_the_assistant_content_unchanged() -> None: + recorder = Recorder(_ok(ANTHROPIC_TOOL_TURN), _ok(ANTHROPIC_ANSWER)) + client = _anthropic(recorder) + conv = _conv() + turn = await client.call(conv) + conv.entries += [turn, ToolResults((ToolResult("toolu_1", "search_docs", "found", False),))] + answer = await client.call(conv) + messages = recorder.body(1)["messages"] + assert messages[1] == {"role": "assistant", "content": ANTHROPIC_TOOL_TURN["content"]} + assert messages[2] == { + "role": "user", + "content": [ + {"type": "tool_result", "tool_use_id": "toolu_1", "content": "found", "is_error": False} + ], + } + assert answer.text == "The answer." and answer.tool_calls == () + + +async def test_a_conversation_without_tools_sends_neither_tools_nor_tool_choice() -> None: + recorder = Recorder(_ok(ANTHROPIC_ANSWER), _ok(_openai_response([OPENAI_MESSAGE]))) + await _anthropic(recorder).call(_conv(tools=[])) + await _openai(recorder).call(_conv(tools=[])) + for index in (0, 1): + assert not {"tools", "tool_choice"} & set(recorder.body(index)) + + +@pytest.mark.parametrize( + "status,headers,kind,retry_after", + [ + (429, {"retry-after": "7"}, "rate_limited", 7.0), + (429, {"retry-after-ms": "1500"}, "rate_limited", 1.5), + (400, {}, "rejected", None), + (500, {}, "server", None), + (529, {}, "server", None), + ], +) +async def test_anthropic_status_errors_are_classified( + status: int, headers: dict[str, str], kind: str, retry_after: float | None +) -> None: + recorder = Recorder(_ok(ERROR_BODY, status, headers)) + with pytest.raises(ProviderCallError) as caught: + await _anthropic(recorder).call(_conv()) + assert (caught.value.kind, caught.value.status, caught.value.retry_after_s) == ( + kind, + status, + retry_after, + ) + + +@pytest.mark.parametrize("provider", ["anthropic", "openai"]) +async def test_timeout_and_connection_errors_are_classified(provider: str) -> None: + def raise_(error: type[Exception]): + def handler(request: httpx2.Request) -> httpx2.Response: + raise error("simulated", request=request) + + return handler + + recorder = Recorder(raise_(httpx2.ReadTimeout), raise_(httpx2.ConnectError)) + client = _anthropic(recorder) if provider == "anthropic" else _openai(recorder) + kinds = [] + for _ in range(2): + with pytest.raises(ProviderCallError) as caught: + await client.call(_conv()) + kinds.append(caught.value.kind) + assert kinds == ["timeout", "connection"] and len(recorder.seen) == 2 + + +async def test_openai_responses_request_and_usage() -> None: + recorder = Recorder(_ok(_openai_response([OPENAI_REASONING, OPENAI_CALL]))) + client = _openai(recorder) + turn = await client.call(_conv()) + body = recorder.body(0) + assert body["tool_choice"] == "auto" and body["store"] is False + assert body["include"] == ["reasoning.encrypted_content"] and body["max_output_tokens"] == 32768 + assert body["instructions"] == "system prompt" and body["model"] == "gpt-6.1-sol" + assert body["input"] == [{"role": "user", "content": "q?"}] + assert all(t["strict"] is False for t in body["tools"]) and "temperature" not in body + assert turn.buckets == Buckets(500, 300, 200, 50, 40) + assert turn.tool_calls == (ToolCall("call_abc", "search_docs", {"query": "json"}),) + assert turn.reported_model == "gpt-6.1-sol" + + +@pytest.mark.parametrize( + "status,details,expected", + [ + ("incomplete", {"reason": "max_output_tokens"}, "max_output_tokens"), + ("completed", None, "completed"), + ], +) +async def test_openai_stop_reason_is_normalized(status: str, details: Any, expected: str) -> None: + recorder = Recorder(_ok(_openai_response([OPENAI_MESSAGE], status=status, details=details))) + turn = await _openai(recorder).call(_conv()) + assert turn.stop_reason == expected + + +async def test_openai_request_never_asks_for_extended_cache_retention() -> None: + recorder = Recorder( + _ok(_openai_response([OPENAI_CALL])), _ok(_openai_response([OPENAI_MESSAGE])) + ) + client = _openai(recorder) + conv = _conv() + turn = await client.call(conv) + conv.entries += [turn, ToolResults((ToolResult("call_abc", "search_docs", "found", False),))] + await client.call(conv) + for body in (recorder.body(0), recorder.body(1), client.request_params()): + assert not {"prompt_cache_options", "prompt_cache_retention"} & set(body) + + +async def test_openai_replays_output_items_and_sends_function_call_output() -> None: + recorder = Recorder( + _ok(_openai_response([OPENAI_REASONING, OPENAI_CALL])), + _ok(_openai_response([OPENAI_MESSAGE])), + ) + client = _openai(recorder) + conv = _conv() + turn = await client.call(conv) + conv.entries += [turn, ToolResults((ToolResult("call_abc", "search_docs", "found", False),))] + answer = await client.call(conv) + assert recorder.body(1)["input"] == [ + {"role": "user", "content": "q?"}, + OPENAI_REASONING, + OPENAI_CALL, + {"type": "function_call_output", "call_id": "call_abc", "output": "found"}, + ] + assert answer.text == "The answer." and answer.tool_calls == () + + +@pytest.mark.parametrize("raw", ["{not json", "[1, 2]", "3", '"x"', "null", "true"]) +async def test_openai_non_object_arguments_are_kept_raw(raw: str) -> None: + recorder = Recorder(_ok(_openai_response([{**OPENAI_CALL, "arguments": raw}]))) + turn = await _openai(recorder).call(_conv()) + assert turn.tool_calls[0].arguments == {} and turn.tool_calls[0].raw_arguments == raw + + +@pytest.mark.parametrize( + "value,expected", + [ + ('{"a": 1}', ({"a": 1}, None)), + ({"a": 1}, ({"a": 1}, None)), + ([1], ({}, "[1]")), + (None, ({}, "null")), + ("[1]", ({}, "[1]")), + ], +) +def test_tool_arguments(value: Any, expected: tuple[dict[str, Any], str | None]) -> 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) + assert parse_retry_after({"retry-after": past}) == 0 + assert parse_retry_after({"retry-after": "soon"}) is None + assert parse_retry_after({}) is None + + +@pytest.mark.parametrize("provider", ["anthropic", "openai"]) +def test_rendered_bytes_grows_with_each_entry(provider: str) -> None: + client = _anthropic(Recorder()) if provider == "anthropic" else _openai(Recorder()) + conv = _conv() + first = client.rendered_bytes(conv, 0) + assert first > len("system prompt") + len("q?") + turn = ModelTurn( + text="", + tool_calls=(), + replay=ANTHROPIC_TOOL_TURN["content"] + if provider == "anthropic" + else [OPENAI_REASONING, OPENAI_CALL], + raw_response={}, + raw_usage=None, + buckets=None, + reported_model=None, + stop_reason=None, + ) + conv.entries += [turn] + second = client.rendered_bytes(conv, 0) + conv.entries += [ToolResults((ToolResult("call_abc", "search_docs", "é" * 10, False),))] + third = client.rendered_bytes(conv, 0) + assert first < second < third + assert client.rendered_bytes(conv, 2) < third - second + 100 # only the added entry + assert client.rendered_bytes(conv, 2) >= 20 # "é" is two UTF-8 bytes From 1f03bfae3eeaddb19d17def817de7c9d05d125a7 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Tue, 3 Nov 2026 22:37:30 +0100 Subject: [PATCH 05/77] feat(benchmarks): add the Gemini and scripted clients and the client factory Gemini: AUTO function calling, automatic calling and automatic continuation off, one attempt, thought signatures replayed, calls without ids paired with their results by position. A CONTINUATION stop comes back as a turn and is never followed. ScriptedClient plays a YAML script of tool turns, answers and errors, counting steps per Conversation object held strongly (owner amendment on #184: never by a reusable id()). make_client is the only builder: a scripted family needs no key; a live API passes the guard, refuses a second paid key and a provider that does not match its API. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/clients.py | 302 +++++++++++++++- .../fixtures/agentic/script-anthropic.yml | 11 + .../fixtures/agentic/script-google.yml | 11 + .../fixtures/agentic/script-openai.yml | 23 ++ tests/benchmarks/test_agentic_clients.py | 331 ++++++++++++++++++ 5 files changed, 676 insertions(+), 2 deletions(-) create mode 100644 tests/benchmarks/fixtures/agentic/script-anthropic.yml create mode 100644 tests/benchmarks/fixtures/agentic/script-google.yml create mode 100644 tests/benchmarks/fixtures/agentic/script-openai.yml diff --git a/benchmarks/agentic/clients.py b/benchmarks/agentic/clients.py index d9f30ed8..3c9c286f 100644 --- a/benchmarks/agentic/clients.py +++ b/benchmarks/agentic/clients.py @@ -7,27 +7,47 @@ from __future__ import annotations +import asyncio import json +import os from collections.abc import Mapping, Sequence from datetime import UTC, datetime from email.utils import parsedate_to_datetime +from pathlib import Path from typing import Any import anthropic +import httpx import httpx2 import openai from anthropic.types import TextBlock, ToolUseBlock +from google import genai +from google.genai import errors as genai_errors +from google.genai import types as genai_types -from benchmarks.agentic.schemas import to_anthropic, to_openai_responses +from benchmarks.adapters.guard import PROVIDER_API_KEY_ENV, require_live_environment +from benchmarks.agentic.schemas import to_anthropic, to_gemini, to_openai_responses from benchmarks.agentic.types import ( Conversation, + ModelClient, ModelTurn, ProviderCallError, ToolCall, ToolResults, UserText, ) -from benchmarks.agentic.usage import anthropic_buckets, openai_buckets +from benchmarks.agentic.usage import anthropic_buckets, gemini_buckets, openai_buckets +from benchmarks.model_matrix import ModelFamily +from benchmarks.runner import BenchmarkValidationError, _load_yaml_mapping + +PAID_KEY_ENVS = ("ANTHROPIC_API_KEY", "OPENAI_API_KEY", "GOOGLE_API_KEY") + +#: Live API -> the one provider whose key it may carry. +_LIVE_APIS = { + "anthropic-messages": "anthropic", + "openai-responses": "openai", + "gemini-generate-content": "google", +} def tool_arguments(value: Any) -> tuple[dict[str, Any], str | None]: @@ -257,3 +277,281 @@ async def call(self, conv: Conversation) -> ModelTurn: if response.status == "incomplete" and details is not None else response.status, ) + + +def gemini_sdk( + api_key: str, timeout_s: float, *, http_client: httpx.AsyncClient | None = None +) -> genai.Client: + return genai.Client( + api_key=api_key, + vertexai=False, + http_options=genai_types.HttpOptions( + timeout=int(timeout_s * 1000), + retry_options=genai_types.HttpRetryOptions(attempts=1), + httpx_async_client=http_client, + ), + ) + + +class GeminiClient: + """Gemini ``generate_content``: AUTO mode, no automatic calling, no continuation.""" + + provider = "google" + + def __init__(self, sdk: genai.Client, model_id: str, max_output_tokens: int): + self._sdk = sdk + self.model_id = model_id + self._max_output_tokens = max_output_tokens + + def request_params(self) -> dict[str, Any]: + return { + "model": self.model_id, + "max_output_tokens": self._max_output_tokens, + "function_calling_mode": "AUTO", # sent only with tools + "automatic_function_calling": {"disable": True}, + "automatic_continuation": False, + } + + def _contents(self, entries: Sequence[Any]) -> list[genai_types.Content]: + contents: list[genai_types.Content] = [] + provider_ids: set[str] = set() + for entry in entries: + if isinstance(entry, UserText): + contents.append( + genai_types.Content(role="user", parts=[genai_types.Part(text=entry.text)]) + ) + elif isinstance(entry, ToolResults): + # A call without a provider id pairs with its result by position: no id. + parts = [ + genai_types.Part( + function_response=genai_types.FunctionResponse( + id=r.call_id if r.call_id in provider_ids else None, + name=r.name, + response={"error": r.text} if r.is_error else {"output": r.text}, + ) + ) + for r in entry.results + ] + contents.append(genai_types.Content(role="user", parts=parts)) + elif entry.replay is not None: + contents.append(entry.replay) + provider_ids = { + p.function_call.id + for p in entry.replay.parts or [] + if p.function_call and p.function_call.id + } + return contents + + def _config(self, conv: Conversation) -> genai_types.GenerateContentConfig: + tools: genai_types.ToolListUnion | None = None + tool_config: genai_types.ToolConfig | None = None + if conv.tools: + declarations = [ + genai_types.FunctionDeclaration.model_validate(d) for d in to_gemini(conv.tools)[0] + ] + tools = [genai_types.Tool(function_declarations=declarations)] + mode = genai_types.FunctionCallingConfigMode.AUTO + tool_config = genai_types.ToolConfig( + function_calling_config=genai_types.FunctionCallingConfig(mode=mode) + ) + return genai_types.GenerateContentConfig( + system_instruction=conv.system, + tools=tools, + tool_config=tool_config, + automatic_function_calling=genai_types.AutomaticFunctionCallingConfig(disable=True), + # google-genai follows a CONTINUATION stop with extra requests by default. + automatic_continuation=False, + max_output_tokens=self._max_output_tokens, + ) + + def rendered_bytes(self, conv: Conversation, start: int) -> int: + contents = [ + c.model_dump(mode="json", exclude_none=True) + for c in self._contents(conv.entries[start:]) + ] + if start: + return _utf8_len(contents) + tools = to_gemini(conv.tools)[0] + return _utf8_len({"systemInstruction": conv.system, "tools": tools, "contents": contents}) + + async def call(self, conv: Conversation) -> ModelTurn: + try: + response = await self._sdk.aio.models.generate_content( + model=self.model_id, + contents=self._contents(conv.entries), + config=self._config(conv), + ) + except genai_errors.ClientError as exc: + if exc.code == 429: + headers = getattr(exc.response, "headers", None) or {} + raise _status_error(429, headers, str(exc)) from exc + raise ProviderCallError("rejected", str(exc), status=exc.code) from exc + except genai_errors.ServerError as exc: + raise ProviderCallError("server", str(exc), status=exc.code) from exc + except httpx.TimeoutException as exc: + raise ProviderCallError("timeout", str(exc)) from exc + except httpx.TransportError as exc: + raise ProviderCallError("connection", str(exc)) from exc + candidate = response.candidates[0] if response.candidates else None + content = candidate.content if candidate else None + parts = (content.parts or []) if content else [] + calls = [] + 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 {}) + 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 + return ModelTurn( + text="".join(p.text for p in parts if p.text and not p.thought), + tool_calls=tuple(calls), + replay=content, # thought signatures go back exactly as received + raw_response=response.model_dump(mode="json", exclude_none=True), + raw_usage=usage, + buckets=None if usage is None else gemini_buckets(usage), + reported_model=response.model_version, + stop_reason=None if reason is None else str(getattr(reason, "value", reason)), + ) + + +_SCRIPT_BUCKETS = { + "anthropic": anthropic_buckets, + "openai": openai_buckets, + "google": gemini_buckets, +} +_SCRIPT_STOP = {"anthropic": "end_turn", "openai": "completed", "google": "STOP"} + + +def _fill_prompt(value: Any, prompt: str) -> Any: + if isinstance(value, str): + return value.replace("{prompt}", prompt) + if isinstance(value, list): + return [_fill_prompt(item, prompt) for item in value] + if isinstance(value, dict): + return {key: _fill_prompt(item, prompt) for key, item in value.items()} + return value + + +class ScriptedClient: + """Plays a YAML script of turns, errors and usage: CI's stand-in for a provider. + + Steps: ``{tools: [{name, arguments}], usage}``, ``{text, usage, stop_reason}`` or + ``{error: {kind, status, retry_after_s}}``; any step may set ``delay_s`` and + ``prompt_contains``. A tools step applies only when every tool it names was given. + """ + + def __init__(self, provider: str, model_id: str, steps: list[dict[str, Any]]): + self.provider = provider + self.model_id = model_id + self._steps = steps + # Keyed by the Conversation object, held strongly: a bare id(conv) can be reused + # by CPython once a conversation is freed (owner amendment on #184). + self._calls: dict[Conversation, int] = {} + + def request_params(self) -> dict[str, Any]: + return {"model": self.model_id} + + def rendered_bytes(self, conv: Conversation, start: int) -> int: + rendered: list[Any] = [] + for entry in conv.entries[start:]: + if isinstance(entry, UserText): + rendered.append({"role": "user", "content": entry.text}) + elif isinstance(entry, ToolResults): + rendered.append([[r.call_id, r.text, r.is_error] for r in entry.results]) + else: + 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) + tools = to_anthropic(conv.tools) + return _utf8_len({"system": conv.system, "tools": tools, "messages": rendered}) + + 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: + return False + given = {t.name for t in conv.tools} + return all(tool["name"] in given for tool in step.get("tools") or []) + + async def call(self, conv: Conversation) -> ModelTurn: + prompt = next((e.text for e in conv.entries if isinstance(e, UserText)), "") + steps = [s for s in self._steps if self._applies(s, conv, prompt)] + index = self._calls.get(conv, 0) + self._calls[conv] = index + 1 + if index >= len(steps): + raise BenchmarkValidationError( + f"scripted model {self.model_id!r} has no step {index + 1} for this conversation" + ) + step = steps[index] + if step.get("delay_s"): + await asyncio.sleep(float(step["delay_s"])) + if "error" in step: + error = step["error"] + raise ProviderCallError( + error["kind"], + f"scripted {error['kind']}", + status=error.get("status"), + retry_after_s=error.get("retry_after_s"), + ) + calls = [] + for position, tool in enumerate(step.get("tools") or [], 1): + arguments, raw = tool_arguments(_fill_prompt(tool.get("arguments", {}), prompt)) + calls.append(ToolCall(f"call_{position}", tool["name"], arguments, raw)) + usage = step.get("usage") + default_stop = "tool_use" if calls and self.provider == "anthropic" else None + return ModelTurn( + text="" if calls else str(step.get("text", "")), + tool_calls=tuple(calls), + replay=None, + raw_response={"scripted_step": step}, + raw_usage=usage, + buckets=None if usage is None else _SCRIPT_BUCKETS[self.provider](usage), + reported_model=self.model_id, + stop_reason=step.get("stop_reason") or default_stop or _SCRIPT_STOP[self.provider], + ) + + +def make_client( + family: ModelFamily, *, timeout_s: float, http_client: Any | None = None +) -> ModelClient: + """The only way production code builds a client; every live API passes the guard.""" + if family.api == "scripted": + script = Path(str(family.raw.get("script", ""))) + if not script.is_absolute(): + raise BenchmarkValidationError( + f"scripted model family {family.id!r} needs an absolute 'script' path, " + f"got {str(script)!r}" + ) + steps = _load_yaml_mapping(script, "model script").get("steps") + if not isinstance(steps, list) or not all(isinstance(s, dict) for s in steps): + raise BenchmarkValidationError(f"model script {script} must hold a 'steps' list") + return ScriptedClient(family.provider, family.model_id, steps) + 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)" + ) + if family.provider != provider: + raise BenchmarkValidationError( + f"model family {family.id!r}: api {family.api!r} carries the {provider!r} key, " + f"not provider {family.provider!r}" + ) + require_live_environment(provider) + 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: + raise BenchmarkValidationError( + f"a worker holds at most one paid key: {', '.join(others)} is set beside {own_key_env}" + ) + if family.max_output_tokens is None: + raise BenchmarkValidationError(f"model family {family.id!r} must set max_output_tokens") + key = os.environ[own_key_env] + if provider == "anthropic": + sdk = anthropic_sdk(key, timeout_s, http_client=http_client) + return AnthropicClient(sdk, family.model_id, family.max_output_tokens) + if provider == "openai": + sdk = openai_sdk(key, timeout_s, http_client=http_client) + return OpenAIResponsesClient(sdk, family.model_id, family.max_output_tokens) + sdk = gemini_sdk(key, timeout_s, http_client=http_client) + return GeminiClient(sdk, family.model_id, family.max_output_tokens) diff --git a/tests/benchmarks/fixtures/agentic/script-anthropic.yml b/tests/benchmarks/fixtures/agentic/script-anthropic.yml new file mode 100644 index 00000000..60d693b5 --- /dev/null +++ b/tests/benchmarks/fixtures/agentic/script-anthropic.yml @@ -0,0 +1,11 @@ +# Scripted model for the agentic tests: a docs tool, then the answer. +# python-docs plays steps 1 and 3, docs-fetch steps 2 and 3, no-docs step 3 only +# (a tools step applies only when the system offers every tool it names). +# Usage is the Anthropic Messages shape. +steps: + - tools: [{name: search_docs, arguments: {query: json}}] + usage: {input_tokens: 1000, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, output_tokens: 100} + - tools: [{name: fetch, arguments: {url: "https://docs.python.org/3/library/json.html"}}] + usage: {input_tokens: 1000, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, output_tokens: 100} + - text: "Scripted answer." + usage: {input_tokens: 1000, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, output_tokens: 100} diff --git a/tests/benchmarks/fixtures/agentic/script-google.yml b/tests/benchmarks/fixtures/agentic/script-google.yml new file mode 100644 index 00000000..ef82eb3d --- /dev/null +++ b/tests/benchmarks/fixtures/agentic/script-google.yml @@ -0,0 +1,11 @@ +# Scripted model for the agentic tests: a docs tool, then the answer. +# python-docs plays steps 1 and 3, docs-fetch steps 2 and 3, no-docs step 3 only +# (a tools step applies only when the system offers every tool it names). +# Usage is the Gemini usage_metadata shape (snake_case, as the SDK dumps it). +steps: + - tools: [{name: search_docs, arguments: {query: json}}] + usage: {prompt_token_count: 1000, cached_content_token_count: 0, tool_use_prompt_token_count: 0, candidates_token_count: 100, thoughts_token_count: 0} + - tools: [{name: fetch, arguments: {url: "https://docs.python.org/3/library/json.html"}}] + usage: {prompt_token_count: 1000, cached_content_token_count: 0, tool_use_prompt_token_count: 0, candidates_token_count: 100, thoughts_token_count: 0} + - text: "Scripted answer." + usage: {prompt_token_count: 1000, cached_content_token_count: 0, tool_use_prompt_token_count: 0, candidates_token_count: 100, thoughts_token_count: 0} diff --git a/tests/benchmarks/fixtures/agentic/script-openai.yml b/tests/benchmarks/fixtures/agentic/script-openai.yml new file mode 100644 index 00000000..fa0da297 --- /dev/null +++ b/tests/benchmarks/fixtures/agentic/script-openai.yml @@ -0,0 +1,23 @@ +# Scripted model for the agentic tests: a docs tool, then the answer. +# python-docs plays steps 1 and 3, docs-fetch steps 2 and 3, no-docs step 3 only +# (a tools step applies only when the system offers every tool it names). +# Usage is the OpenAI Responses shape. +steps: + - tools: [{name: search_docs, arguments: {query: json}}] + usage: + input_tokens: 1000 + input_tokens_details: {cached_tokens: 0, cache_write_tokens: 0} + output_tokens: 100 + output_tokens_details: {reasoning_tokens: 0} + - tools: [{name: fetch, arguments: {url: "https://docs.python.org/3/library/json.html"}}] + usage: + input_tokens: 1000 + input_tokens_details: {cached_tokens: 0, cache_write_tokens: 0} + output_tokens: 100 + output_tokens_details: {reasoning_tokens: 0} + - text: "Scripted answer." + usage: + input_tokens: 1000 + input_tokens_details: {cached_tokens: 0, cache_write_tokens: 0} + output_tokens: 100 + output_tokens_details: {reasoning_tokens: 0} diff --git a/tests/benchmarks/test_agentic_clients.py b/tests/benchmarks/test_agentic_clients.py index d3acacf3..e40de4a7 100644 --- a/tests/benchmarks/test_agentic_clients.py +++ b/tests/benchmarks/test_agentic_clients.py @@ -5,19 +5,30 @@ from __future__ import annotations +import importlib.util import json from collections.abc import Callable +from dataclasses import replace from datetime import UTC, datetime, timedelta from email.utils import format_datetime +from pathlib import Path from typing import Any +import httpx import httpx2 import pytest +import yaml +from benchmarks.adapters.guard import PROVIDER_API_KEY_ENV, LiveProviderDisabledError from benchmarks.agentic.clients import ( + PAID_KEY_ENVS, AnthropicClient, + GeminiClient, OpenAIResponsesClient, + ScriptedClient, anthropic_sdk, + gemini_sdk, + make_client, openai_sdk, parse_retry_after, tool_arguments, @@ -33,7 +44,12 @@ ToolSpec, UserText, ) +from benchmarks.model_matrix import ModelFamily, load_model_matrix, model_family_from_raw +from benchmarks.runner import BenchmarkValidationError +REPO_ROOT = Path(__file__).resolve().parents[2] +MODEL_MATRIX_PATH = REPO_ROOT / "docs" / "benchmarks" / "model-matrix.yml" +FIXTURES = Path(__file__).parent / "fixtures" / "agentic" TOOLS = [ ToolSpec( "search_docs", @@ -377,3 +393,318 @@ def test_rendered_bytes_grows_with_each_entry(provider: str) -> None: assert first < second < third assert client.rendered_bytes(conv, 2) < third - second + 100 # only the added entry assert client.rendered_bytes(conv, 2) >= 20 # "é" is two UTF-8 bytes + + +# --- Task 7: Gemini, scripted client, factory -------------------------------------------------- + +GEMINI_USAGE = { + "promptTokenCount": 1000, + "cachedContentTokenCount": 100, + "toolUsePromptTokenCount": 50, + "candidatesTokenCount": 30, + "thoughtsTokenCount": 20, +} + + +def _gemini_response(parts: list[dict[str, Any]], finish: str = "STOP", **extra: Any): + candidate = {"content": {"role": "model", "parts": parts}, "finishReason": finish, **extra} + return { + "candidates": [candidate], + "usageMetadata": GEMINI_USAGE, + "modelVersion": "gemini-3.8-flash-001", + } + + +class GeminiRecorder(Recorder): + def client(self) -> Any: # an httpx (not httpx2) client: google-genai uses httpx + return httpx.AsyncClient(transport=httpx.MockTransport(self)) + + +def _gemini_ok(body: dict[str, Any], status: int = 200, headers: dict[str, str] | None = None): + return httpx.Response(status, json=body, headers=headers or {}) + + +def _gemini(recorder: GeminiRecorder) -> GeminiClient: + sdk = gemini_sdk("test-key", 30, http_client=recorder.client()) + return GeminiClient(sdk, "gemini-3.8-flash", 32_768) + + +def _matrix_family(family_id: str) -> ModelFamily: + families = load_model_matrix(MODEL_MATRIX_PATH).model_families + (family,) = [f for f in families if f.id == family_id] + return family + + +def _scripted_family(script: Path, provider: str = "anthropic") -> ModelFamily: + return model_family_from_raw( + { + "id": "scripted-test", + "provider": provider, + "model_id": "scripted-1", + "client": "scripted", + "token_count_method": "claude_normalized_payload", + "latency_scope": "request_dispatch_to_final_answer", + "headline_eligible": False, + "headline_ineligibility_reason": "test", + "api": "scripted", + "script": str(script), + } + ) + + +def _write_script(path: Path, steps: list[dict[str, Any]]) -> Path: + path.write_text(yaml.safe_dump({"steps": steps}), encoding="utf-8") + return path + + +def test_gemini_client_makes_one_attempt_and_aiohttp_is_absent() -> None: + sdk = gemini_sdk("test-key", 30) + assert sdk._api_client._http_options.retry_options.attempts == 1 + # google-genai 2.31.0's aiohttp transport retries a connection error once whatever the + # options say (_api_client.py); keep that transport out of the environment + assert importlib.util.find_spec("aiohttp") is None + + +async def test_gemini_sends_one_request_when_the_response_asks_to_continue() -> None: + body = _gemini_response([{"text": "partial"}], "CONTINUATION", continuationToken="dG9r") + recorder = GeminiRecorder(_gemini_ok(body), _gemini_ok(body)) + turn = await _gemini(recorder).call(_conv()) + assert len(recorder.seen) == 1 and turn.stop_reason == "CONTINUATION" + assert turn.text == "partial" and turn.tool_calls == () + + +async def test_gemini_sends_one_request_on_a_server_error() -> None: + error = {"error": {"code": 500, "message": "boom", "status": "INTERNAL"}} + recorder = GeminiRecorder(_gemini_ok(error, 500), _gemini_ok(error, 500)) + with pytest.raises(ProviderCallError) as caught: + await _gemini(recorder).call(_conv()) + assert caught.value.kind == "server" and len(recorder.seen) == 1 + + +async def test_gemini_request_uses_auto_mode_and_disables_automatic_calling() -> None: + call = {"functionCall": {"name": "search_docs", "args": {"query": "json"}}} + recorder = GeminiRecorder(_gemini_ok(_gemini_response([call]))) + turn = await _gemini(recorder).call(_conv()) + body = recorder.body(0) + assert body["toolConfig"]["functionCallingConfig"]["mode"] == "AUTO" + assert body["generationConfig"]["maxOutputTokens"] == 32768 + assert body["systemInstruction"]["parts"] == [{"text": "system prompt"}] + assert body["tools"][0]["functionDeclarations"][0]["name"] == "search_docs" + assert body["contents"] == [{"role": "user", "parts": [{"text": "q?"}]}] + assert turn.buckets == Buckets(950, 0, 100, 50, 20) + assert turn.reported_model == "gemini-3.8-flash-001" + assert turn.tool_calls == (ToolCall("call_1", "search_docs", {"query": "json"}),) + + +async def test_gemini_pairs_two_calls_of_the_same_function_by_position() -> None: + calls = [ + {"text": "thinking", "thought": True, "thoughtSignature": "c2ln"}, + {"functionCall": {"name": "search_docs", "args": {"query": "a"}}}, + {"functionCall": {"name": "search_docs", "args": {"query": "b"}}}, + ] + recorder = GeminiRecorder( + _gemini_ok(_gemini_response(calls)), _gemini_ok(_gemini_response([{"text": "done"}])) + ) + client = _gemini(recorder) + conv = _conv() + turn = await client.call(conv) + assert [c.id for c in turn.tool_calls] == ["call_1", "call_2"] and turn.text == "" + results = tuple( + ToolResult(c.id, c.name, f"result {c.arguments['query']}", False) for c in turn.tool_calls + ) + conv.entries += [turn, ToolResults(results)] + await client.call(conv) + contents = recorder.body(1)["contents"] + assert contents[1] == {"role": "model", "parts": calls} # replayed, signature included + assert contents[-1]["parts"] == [ + {"functionResponse": {"name": "search_docs", "response": {"output": "result a"}}}, + {"functionResponse": {"name": "search_docs", "response": {"output": "result b"}}}, + ] + + +async def test_gemini_sends_an_error_result_under_error_and_keeps_a_provider_id() -> None: + call = {"functionCall": {"id": "fc-9", "name": "search_docs", "args": {"query": "a"}}} + recorder = GeminiRecorder( + _gemini_ok(_gemini_response([call])), _gemini_ok(_gemini_response([{"text": "done"}])) + ) + client = _gemini(recorder) + conv = _conv() + turn = await client.call(conv) + conv.entries += [turn, ToolResults((ToolResult("fc-9", "search_docs", "bad", True),))] + await client.call(conv) + assert recorder.body(1)["contents"][-1]["parts"] == [ + {"functionResponse": {"id": "fc-9", "name": "search_docs", "response": {"error": "bad"}}} + ] + + +@pytest.mark.parametrize("status,kind", [(429, "rate_limited"), (400, "rejected"), (500, "server")]) +async def test_gemini_status_errors_are_classified(status: int, kind: str) -> None: + error = {"error": {"code": status, "message": "boom", "status": "X"}} + recorder = GeminiRecorder(_gemini_ok(error, status, {"retry-after": "3"})) + with pytest.raises(ProviderCallError) as caught: + await _gemini(recorder).call(_conv()) + assert caught.value.kind == kind and caught.value.status == status + assert caught.value.retry_after_s == (3.0 if status == 429 else None) + + +async def test_gemini_timeout_and_connection_errors_are_classified() -> None: + def raise_(error: type[Exception]): + def handler(request: httpx.Request) -> httpx.Response: + raise error("simulated", request=request) + + return handler + + recorder = GeminiRecorder(raise_(httpx.ReadTimeout), raise_(httpx.ConnectError)) + client = _gemini(recorder) + kinds = [] + for _ in range(2): + with pytest.raises(ProviderCallError) as caught: + await client.call(_conv()) + kinds.append(caught.value.kind) + assert kinds == ["timeout", "connection"] and len(recorder.seen) == 2 + + +def _clear_keys(monkeypatch: pytest.MonkeyPatch) -> None: + for name in (*PAID_KEY_ENVS, "BENCHMARK_LIVE_PROVIDERS_ENABLED"): + monkeypatch.delenv(name, raising=False) + + +def test_make_client_refuses_a_live_api_without_the_guard(monkeypatch: pytest.MonkeyPatch) -> None: + _clear_keys(monkeypatch) + monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-not-a-real-key") + with pytest.raises(LiveProviderDisabledError): + make_client(_matrix_family("claude-sonnet-5-5"), timeout_s=30) + + +def test_make_client_refuses_a_second_paid_key(monkeypatch: pytest.MonkeyPatch) -> None: + _clear_keys(monkeypatch) + monkeypatch.setenv("BENCHMARK_LIVE_PROVIDERS_ENABLED", "1") + monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-not-a-real-key-1") + monkeypatch.setenv("OPENAI_API_KEY", "sk-not-a-real-key-2") + with pytest.raises(BenchmarkValidationError, match="OPENAI_API_KEY") as caught: + make_client(_matrix_family("claude-sonnet-5-5"), timeout_s=30) + 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: + _clear_keys(monkeypatch) + with pytest.raises(BenchmarkValidationError, match="openai-chat-completions"): + make_client(_matrix_family("gemma4-12b"), timeout_s=600) + + +def test_make_client_refuses_a_provider_that_does_not_match_its_api( + monkeypatch: pytest.MonkeyPatch, +) -> None: + _clear_keys(monkeypatch) + monkeypatch.setenv("BENCHMARK_LIVE_PROVIDERS_ENABLED", "1") + monkeypatch.setenv("OPENAI_API_KEY", "sk-not-a-real-key") + family = replace(_matrix_family("claude-sonnet-5-5"), provider="openai") + with pytest.raises(BenchmarkValidationError, match="anthropic-messages"): + make_client(family, timeout_s=30) + + +@pytest.mark.parametrize( + "family_id,client_type", + [ + ("claude-sonnet-5-5", AnthropicClient), + ("gpt-6.1-sol", OpenAIResponsesClient), + ("gemini-3.8-flash", GeminiClient), + ], +) +def test_make_client_builds_each_live_client_behind_the_guard( + monkeypatch: pytest.MonkeyPatch, family_id: str, client_type: type +) -> None: + _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") + client = make_client(family, timeout_s=30) # builds an SDK object; sends nothing + assert isinstance(client, client_type) and client.model_id == family.model_id + + +def test_make_client_builds_a_scripted_client_without_any_key( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _clear_keys(monkeypatch) + script = _write_script(tmp_path / "s.yml", [{"text": "hi", "usage": None}]) + client = make_client(_scripted_family(script), timeout_s=30) + assert isinstance(client, ScriptedClient) and client.provider == "anthropic" + with pytest.raises(BenchmarkValidationError, match="absolute"): + make_client(_scripted_family(Path("s.yml")), timeout_s=30) + + +async def test_scripted_client_skips_tool_steps_for_tools_it_was_not_given() -> None: + steps = [ + { + "tools": [{"name": "search_docs", "arguments": {"query": "{prompt}"}}], + "usage": {"input_tokens": 10, "output_tokens": 1}, + }, + {"tools": [{"name": "fetch", "arguments": [1]}], "usage": None}, + {"text": "Scripted answer.", "usage": {"input_tokens": 20, "output_tokens": 2}}, + ] + client = ScriptedClient("anthropic", "scripted-1", steps) + docs = _conv() + first = await client.call(docs) + assert first.tool_calls == (ToolCall("call_1", "search_docs", {"query": "q?"}),) + assert first.buckets == Buckets(10, 0, 0, 1) + answer = await client.call(docs) + assert answer.text == "Scripted answer." and answer.stop_reason == "end_turn" + no_docs = _conv(tools=[]) + answer = await client.call(no_docs) + assert answer.text == "Scripted answer." and answer.tool_calls == () + fetch_only = _conv(tools=[ToolSpec("fetch", "d", {"type": "object"})]) + turn = await client.call(fetch_only) + assert turn.tool_calls == (ToolCall("call_1", "fetch", {}, "[1]"),) and turn.buckets is None + + +async def test_scripted_client_counts_steps_per_conversation_object() -> None: + client = ScriptedClient("openai", "scripted-2", [{"text": "one"}, {"text": "two"}]) + for _ in range(3): # a fresh conversation always starts at the first step + conv = _conv(tools=[]) + assert (await client.call(conv)).text == "one" + assert (await client.call(conv)).stop_reason == "completed" + del conv + conv = _conv(tools=[]) + await client.call(conv) + await client.call(conv) + with pytest.raises(BenchmarkValidationError, match="no step 3"): + await client.call(conv) + + +async def test_scripted_client_applies_a_step_only_to_the_prompt_it_names() -> None: + steps = [ + {"text": "special", "prompt_contains": "magic", "stop_reason": "CONTINUATION"}, + {"text": "plain"}, + ] + client = ScriptedClient("google", "scripted-3", steps) + special = Conversation("s", [], [UserText("a magic question")]) + turn = await client.call(special) + assert (turn.text, turn.stop_reason) == ("special", "CONTINUATION") + assert (await client.call(_conv(tools=[]))).stop_reason == "STOP" + + +async def test_scripted_client_raises_a_scripted_provider_error() -> None: + steps = [ + {"error": {"kind": "rate_limited", "status": 429, "retry_after_s": 0}}, + {"text": "after"}, + ] + client = ScriptedClient("anthropic", "scripted-1", steps) + conv = _conv() + with pytest.raises(ProviderCallError) as caught: + await client.call(conv) + assert (caught.value.kind, caught.value.status, caught.value.retry_after_s) == ( + "rate_limited", + 429, + 0, + ) + assert (await client.call(conv)).text == "after" + + +@pytest.mark.parametrize("provider", ["anthropic", "openai", "google"]) +async def test_committed_scripts_play_tools_then_the_answer(provider: str) -> None: + script = FIXTURES / f"script-{provider}.yml" + client = make_client(_scripted_family(script, provider), timeout_s=30) + conv = _conv(tools=[TOOLS[0], ToolSpec("fetch", "d", {"type": "object"})]) + turns = [await client.call(conv) for _ in range(3)] + assert [c.name for t in turns for c in t.tool_calls] == ["search_docs", "fetch"] + assert turns[-1].text == "Scripted answer." and all(t.buckets for t in turns) From de5c09128dc7baf5723649265376afe07af5409a Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Tue, 3 Nov 2026 22:43:13 +0100 Subject: [PATCH 06/77] feat(benchmarks): add the agentic trajectory loop with caps and retries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The frozen system prompt and run_trajectory: model calls under their own timeout, one ledger unit per attempt with independently computed input bounds (full request, previous usage plus added bytes, full again after a call without usage), the #177 retry policy (4 retries, 2/4/8/16 s, retry-after up to 120 s) with discards for budget stops and exhausted retries, the design §6 caps, tool results truncated and returned, and a trajectory clock that counts successful work only. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/loop.py | 390 +++++++++++++++++++++++ benchmarks/agentic/prompt.py | 13 + tests/benchmarks/test_agentic_loop.py | 436 ++++++++++++++++++++++++++ 3 files changed, 839 insertions(+) create mode 100644 benchmarks/agentic/loop.py create mode 100644 benchmarks/agentic/prompt.py create mode 100644 tests/benchmarks/test_agentic_loop.py diff --git a/benchmarks/agentic/loop.py b/benchmarks/agentic/loop.py new file mode 100644 index 00000000..64ee5c32 --- /dev/null +++ b/benchmarks/agentic/loop.py @@ -0,0 +1,390 @@ +"""One agentic trajectory: caps, clock, retries, bounds and the record (design §6, §10, §12). + +The trajectory clock counts successful work only: model attempts that returned +and tool calls that completed. Grant waits, failed attempts and retry backoff +are recorded apart and never cut a trajectory (owner ruling 6). No call is cut +in flight: each attempt has its own timeout, and a fire is a retried +``timeout``, booked at twice its bound. +""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +import time +from collections.abc import Awaitable, Callable +from dataclasses import asdict, dataclass +from typing import Any, Literal, Protocol + +from benchmarks.agentic.bridge import BridgeCrash, ToolBridge, truncate_utf8 +from benchmarks.agentic.ledger import Outcome +from benchmarks.agentic.prompt import SYSTEM_PROMPT +from benchmarks.agentic.schemas import schemas_sha256 +from benchmarks.agentic.types import ( + Buckets, + Conversation, + ModelClient, + ModelTurn, + ProviderCallError, + ToolResult, + ToolResults, + UserText, +) +from benchmarks.model_matrix import ModelFamily +from benchmarks.runner import BenchmarkValidationError, _utc_now + + +@dataclass(frozen=True) +class Caps: + model_calls: int = 8 + tool_calls: int = 12 + tool_call_s: float = 30.0 + trajectory_s: float = 300.0 + result_bytes: int = 100_000 + model_call_timeout_s: float = 120.0 + + +HOSTED_CAPS = Caps() +AIR_GAPPED_CAPS = Caps(trajectory_s=900.0, model_call_timeout_s=600.0) +MAX_RETRIES = 4 +MAX_RETRY_AFTER_S = 120.0 +RETRYABLE = frozenset({"rate_limited", "server", "timeout", "connection"}) + + +class LedgerPort(Protocol): + async def reserve( + self, + *, + provider: str, + model_id: str, + input_bound: int, + output_bound: int, + kind: str = "model_call", + ) -> str | None: ... + + async def settle(self, unit_id: str, *, outcome: Outcome, buckets: Buckets | None) -> None: ... + + +class TrajectoryDiscarded(Exception): + """A budget stop or exhausted retries: discarded, never scored (design §12, #177).""" + + def __init__( + self, reason: Literal["budget_stop", "retries_exhausted"], record: dict[str, Any] + ) -> None: + super().__init__(reason) + self.reason = reason + self.record = record # the partial record, for audit only + + +class _Failed(Exception): + """Ends the trajectory as a scored failure.""" + + def __init__(self, category: str, message: str, kind: str = "CapReached") -> None: + super().__init__(message) + self.category = category + self.kind = kind + + +def full_input_bound(client: ModelClient, conv: Conversation, framing: int) -> int: + # +1: the system/tools block + return client.rendered_bytes(conv, 0) + framing * (len(conv.entries) + 1) + + +def next_input_bound( + previous: Buckets, *, added_bytes: int, added_entries: int, framing: int +) -> int: + return previous.total_input + previous.output + added_bytes + framing * added_entries + + +def backoff_s(retry: int, retry_after_s: float | None) -> float | None: + """Seconds before 1-based ``retry``; None when the provider asks for more than 120 s.""" + if retry_after_s is not None: + return None if retry_after_s > MAX_RETRY_AFTER_S else retry_after_s + return min(60.0, 2.0**retry) + + +def canonical_messages(conv: Conversation) -> list[dict[str, Any]]: + """Anthropic-Messages shape, visible content only (no thinking or reasoning).""" + messages: list[dict[str, Any]] = [] + for entry in conv.entries: + if isinstance(entry, UserText): + messages.append({"role": "user", "content": entry.text}) + elif isinstance(entry, ToolResults): + content = [ + { + "type": "tool_result", + "tool_use_id": r.call_id, + "content": r.text, + "is_error": r.is_error, + } + for r in entry.results + ] + messages.append({"role": "user", "content": content}) + else: + blocks: list[dict[str, Any]] = [] + if entry.text or not entry.tool_calls: + blocks.append({"type": "text", "text": entry.text}) + blocks += [ + {"type": "tool_use", "id": c.id, "name": c.name, "input": c.arguments} + for c in entry.tool_calls + ] + messages.append({"role": "assistant", "content": blocks}) + return messages + + +def _ms(seconds: float) -> float: + return round(seconds * 1000, 3) + + +class _Trajectory: + def __init__( + self, + client: ModelClient, + bridge: ToolBridge | None, + family: ModelFamily, + prompt: str, + ledger: LedgerPort, + caps: Caps, + seen_tool_args: set[str], + sleep: Callable[[float], Awaitable[None]], + ) -> None: + if family.max_output_tokens is None or family.framing_allowance_tokens is None: + raise BenchmarkValidationError( + f"model family {family.id!r} needs max_output_tokens and " + "framing_allowance_tokens for its spend bounds" + ) + self.client, self.bridge, self.ledger, self.caps = client, bridge, ledger, caps + self.seen, self.sleep = seen_tool_args, sleep + self.output_bound = family.max_output_tokens + self.framing = family.framing_allowance_tokens + tools = list(bridge.tools) if bridge is not None else [] + self.conv = Conversation(SYSTEM_PROMPT, tools, [UserText(prompt)]) + self.model_calls: list[dict[str, Any]] = [] + self.tool_calls: list[dict[str, Any]] = [] + self.seconds: dict[str, float] = dict.fromkeys( + ("used", "model", "tool", "grant_wait", "failed_attempt", "retry_wait"), 0.0 + ) + self.started_at = _utc_now() + self.started = time.perf_counter() + + def record(self, status: str, error: dict[str, str] | None, answer: str) -> dict[str, Any]: + wall = time.perf_counter() - self.started + s = self.seconds + overhead = wall - sum(s[k] for k in s if k != "used") + return { + "status": status, + "error": error, + "answer": answer, + "system_prompt_sha256": hashlib.sha256(SYSTEM_PROMPT.encode("utf-8")).hexdigest(), + "tools_sha256": schemas_sha256([asdict(t) for t in self.conv.tools]), + "canonical_messages": canonical_messages(self.conv), + "model_calls": self.model_calls, + "tool_calls": self.tool_calls, + "timing": { + "wall_ms": _ms(wall), + **{f"{k}_ms": _ms(v) for k, v in s.items()}, + "overhead_ms": _ms(max(0.0, overhead)), + }, + "started_at": self.started_at, + "completed_at": _utc_now(), + } + + def discard( + self, reason: Literal["budget_stop", "retries_exhausted"], message: str + ) -> TrajectoryDiscarded: + error = {"category": reason, "type": "TrajectoryDiscarded", "message": message} + return TrajectoryDiscarded(reason, self.record("discarded", error, "")) + + def use(self, seconds: float, kind: str) -> None: + """Count one unit of successful work; over the allowance ends the trajectory.""" + self.seconds["used"] += seconds + self.seconds[kind] += seconds + if self.seconds["used"] > self.caps.trajectory_s: + raise _Failed( + "cap_trajectory_time", + f"successful work reached {self.seconds['used']:.3f}s, over the " + f"{self.caps.trajectory_s}s trajectory allowance", + ) + + async def run(self) -> str: + previous: Buckets | None = None + previous_count = 0 + while True: + if previous is None: # first call, or the last call reported no usage + bound = full_input_bound(self.client, self.conv, self.framing) + else: + count = len(self.conv.entries) + bound = next_input_bound( + previous, + added_bytes=self.client.rendered_bytes(self.conv, previous_count), + added_entries=count - previous_count, + framing=self.framing, + ) + previous_count = len(self.conv.entries) + turn = await self.model_call(bound) + previous = turn.buckets + self.conv.entries.append(turn) + if not turn.tool_calls: + return turn.text + if len(self.model_calls) >= self.caps.model_calls: + raise _Failed( + "cap_model_calls", + f"model call {len(self.model_calls)} asked for tools; the cap is " + f"{self.caps.model_calls} model calls", + ) + await self.run_tools(turn) + + async def model_call(self, bound: int) -> ModelTurn: + entry: dict[str, Any] = { + "index": len(self.model_calls), + "message_count": len(self.conv.entries), + "request_params": self.client.request_params(), + "input_bound": bound, + "output_bound": self.output_bound, + "attempts": [], + "raw_response": None, + "raw_usage": None, + "buckets": None, + "reported_model": None, + "stop_reason": None, + "wall_ms": None, + } + self.model_calls.append(entry) + retries = 0 + while True: + waited = time.perf_counter() + unit = await self.ledger.reserve( + provider=self.client.provider, + model_id=self.client.model_id, + input_bound=bound, + output_bound=self.output_bound, + ) + waited = time.perf_counter() - waited + self.seconds["grant_wait"] += waited + if unit is None: + raise self.discard("budget_stop", f"the {self.client.provider} spend cap stopped") + started = time.perf_counter() + turn: ModelTurn | None = None + error: ProviderCallError | None = None + timer = asyncio.timeout(self.caps.model_call_timeout_s) + try: + async with timer: + turn = await self.client.call(self.conv) + except ProviderCallError as exc: + error = exc + except TimeoutError: + if not timer.expired(): + raise + error = ProviderCallError( + "timeout", f"model call exceeded its {self.caps.model_call_timeout_s}s timeout" + ) + wall = time.perf_counter() - started + attempt = {"wall_ms": _ms(wall), "wait_ms": _ms(waited), "unit_id": unit} + entry["attempts"].append(attempt) + if turn is not None: + outcome: Outcome = "ok" if turn.buckets is not None else "no_usage" + attempt |= {"outcome": outcome, "status": None} + await self.ledger.settle(unit, outcome=outcome, buckets=turn.buckets) + entry |= { + "raw_response": turn.raw_response, + "raw_usage": turn.raw_usage, + "buckets": None if turn.buckets is None else asdict(turn.buckets), + "reported_model": turn.reported_model, + "stop_reason": turn.stop_reason, + "wall_ms": _ms(wall), + } + 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 + if error.kind not in RETRYABLE: + raise _Failed("provider_rejected", str(error), "ProviderCallError") + retries += 1 + delay = backoff_s(retries, error.retry_after_s) if retries <= MAX_RETRIES else None + if delay is None: + raise self.discard( + "retries_exhausted", + f"{error.kind} after {retries} attempts: {error}", + ) + await self.sleep(delay) + self.seconds["retry_wait"] += delay + + async def run_tools(self, turn: ModelTurn) -> None: + results: list[ToolResult] = [] + for call in turn.tool_calls: + if len(self.tool_calls) >= self.caps.tool_calls: + raise _Failed( + "cap_tool_calls", f"tool call {len(self.tool_calls) + 1} is over the cap" + ) + entry: dict[str, Any] = { + "index": len(self.tool_calls), + "model_call_index": len(self.model_calls) - 1, + "tool": call.name, + "arguments": call.arguments, + "raw_arguments": call.raw_arguments, + "warm": False, + } + self.tool_calls.append(entry) + wall = 0.0 + if call.raw_arguments is not None: # never sent to the bridge (ruling B7) + text, is_error = f"tool arguments must be a JSON object: {call.raw_arguments}", True + elif self.bridge is None: + text, is_error = f"unknown tool {call.name!r}: no tools are available", True + else: + key = ( + f"{call.name}:{json.dumps(call.arguments, sort_keys=True, ensure_ascii=False)}" + ) + entry["warm"] = key in self.seen + started = time.perf_counter() + timer = asyncio.timeout(self.caps.tool_call_s) + try: + async with timer: + outcome = await self.bridge.call(call.name, call.arguments) + except TimeoutError: + if not timer.expired(): + raise + raise _Failed( + "cap_tool_timeout", + f"{call.name} did not complete within {self.caps.tool_call_s}s", + "TimeoutError", + ) from None + except BridgeCrash as exc: + raise _Failed("mcp_protocol_crash", str(exc), "BridgeCrash") from exc + wall = time.perf_counter() - started + self.seen.add(key) + text, is_error = outcome.text, outcome.is_error + sent, truncated = truncate_utf8(text, self.caps.result_bytes) + entry |= { + "result": text, + "result_sha256": hashlib.sha256(text.encode("utf-8")).hexdigest(), + "is_error": is_error, + "truncated": truncated, + "wall_ms": _ms(wall), + } + results.append(ToolResult(call.id, call.name, sent, is_error)) + self.use(wall, "tool") + self.conv.entries.append(ToolResults(tuple(results))) + + +async def run_trajectory( + *, + client: ModelClient, + bridge: ToolBridge | None, + family: ModelFamily, + prompt: str, + ledger: LedgerPort, + caps: Caps, + seen_tool_args: set[str], + sleep: Callable[[float], Awaitable[None]] = asyncio.sleep, +) -> 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) + try: + answer = await trajectory.run() + except _Failed as failure: + error = {"category": failure.category, "type": failure.kind, "message": str(failure)} + return trajectory.record("failed", error, "") + return trajectory.record("succeeded", None, answer) diff --git a/benchmarks/agentic/prompt.py b/benchmarks/agentic/prompt.py new file mode 100644 index 00000000..64b5348e --- /dev/null +++ b/benchmarks/agentic/prompt.py @@ -0,0 +1,13 @@ +"""The frozen system prompt: the same for every system and model (design §6). + +It never names a system. Changing it after the pilot invalidates the run. +""" + +SYSTEM_PROMPT = ( + "You answer questions about the Python standard library.\n" + "Give a concise answer. When the question names a Python version, " + "state the behavior for that version.\n" + "Do not make claims you cannot support.\n" + "Ground your answer in the official Python documentation; if a documentation " + "tool is available, use it before answering and cite the section URL you relied on." +) diff --git a/tests/benchmarks/test_agentic_loop.py b/tests/benchmarks/test_agentic_loop.py new file mode 100644 index 00000000..a03ba7d7 --- /dev/null +++ b/tests/benchmarks/test_agentic_loop.py @@ -0,0 +1,436 @@ +"""One agentic trajectory: caps, clock, retries, bounds, records (design §6, §10, §12).""" + +from __future__ import annotations + +import asyncio +import hashlib +from decimal import Decimal +from pathlib import Path +from typing import Any + +import pytest + +from benchmarks.agentic.bridge import TRUNCATION_MARKER, BridgeCrash, ToolOutcome +from benchmarks.agentic.clients import ScriptedClient +from benchmarks.agentic.ledger import ( + Ledger, + LedgerService, + ModelPrice, + Rates, + Tier, + load_price_snapshot, +) +from benchmarks.agentic.loop import ( + Caps, + TrajectoryDiscarded, + backoff_s, + next_input_bound, + run_trajectory, +) +from benchmarks.agentic.prompt import SYSTEM_PROMPT +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 + +REPO_ROOT = Path(__file__).resolve().parents[2] +MODEL_MATRIX_PATH = REPO_ROOT / "docs" / "benchmarks" / "model-matrix.yml" +PRICE_SNAPSHOT_PATH = REPO_ROOT / "docs" / "benchmarks" / "price-snapshot.yml" +RUN_ID = "loop-test" +PROMPT = "How do I parse JSON in Python 3.13?" +FAKE_TEXT = "The json module encodes and decodes JSON." +D = Decimal + +USAGE = {"input_tokens": 100, "output_tokens": 10} +SEARCH = {"name": "search_docs", "arguments": {"query": "json"}} +TOOL = {"tools": [SEARCH], "usage": USAGE} +ANSWER = {"text": "Scripted answer.", "usage": USAGE} +FAMILY = model_family_from_raw( + { + "id": "scripted-anthropic", + "provider": "anthropic", + "model_id": "scripted-1", + "client": "scripted", + "token_count_method": "claude_normalized_payload", + "latency_scope": "request_dispatch_to_final_answer", + "headline_eligible": False, + "headline_ineligibility_reason": "test", + "api": "scripted", + "arm": "hosted", + "max_input_tokens": 200_000, + "max_output_tokens": 1024, + "output_cap_includes_reasoning": True, + "framing_allowance_tokens": 256, + } +) +FLAT = ModelPrice( + "scripted-1", "anthropic", (Tier(None, Rates(D(1), D(1), D(1), D(1))),), "https://x.invalid" +) + + +class FakeBridge: + """Canned tool outcomes; "no_such_tool" answers as an unknown tool does.""" + + def __init__( + self, + names: tuple[str, ...] = ("search_docs",), + *, + text: str = FAKE_TEXT, + delay: float = 0.0, + crash: bool = False, + ) -> None: + self.tools = [ToolSpec(name, "d", {"type": "object"}) for name in names] + self.text, self.delay, self.crash = text, delay, crash + self.calls: list[tuple[str, dict[str, Any]]] = [] + + async def call(self, name: str, arguments: dict[str, Any]) -> ToolOutcome: + self.calls.append((name, arguments)) + if self.delay: + await asyncio.sleep(self.delay) + if self.crash: + raise BridgeCrash("the server died") + text, is_error = ( + (f"Unknown tool: {name}", True) if name == "no_such_tool" else (self.text, False) + ) + return ToolOutcome(text, hashlib.sha256(text.encode()).hexdigest(), is_error, 1.0) + + +class RecordingLedger: + """Records every reserve's keyword arguments, then forwards to the real service.""" + + def __init__(self, inner: LedgerService, reserve_delay: float = 0.0) -> None: + self.inner, self.reserve_delay = inner, reserve_delay + self.reserves: list[dict[str, Any]] = [] + + async def reserve(self, **kwargs: Any) -> str | None: + self.reserves.append(kwargs) + if self.reserve_delay: + await asyncio.sleep(self.reserve_delay) + return await self.inner.reserve(**kwargs) + + async def settle(self, unit_id: str, **kwargs: Any) -> None: + await self.inner.settle(unit_id, **kwargs) + + +class FixedBytesClient(ScriptedClient): + def __init__(self, sizes: dict[tuple[int, int], int], *args: Any) -> None: + super().__init__(*args) + self.sizes = sizes + + def rendered_bytes(self, conv: Conversation, start: int) -> int: + return self.sizes[(start, len(conv.entries))] + + +class ToolsSeenClient(ScriptedClient): + def __init__(self, *args: Any) -> None: + super().__init__(*args) + self.tools_seen: list[list[ToolSpec]] = [] + + async def call(self, conv: Conversation) -> ModelTurn: + self.tools_seen.append(list(conv.tools)) + return await super().call(conv) + + +class Harness: + def __init__(self, tmp_path: Path) -> None: + self.tmp_path = tmp_path + self.sleeps: list[float] = [] + self.ledgers: list[Ledger] = [] + + async def sleep(self, seconds: float) -> None: + self.sleeps.append(seconds) + + async def run( + self, + steps: list[dict[str, Any]] | None = None, + *, + client: ScriptedClient | None = None, + bridge: Any = "fake", + caps: Caps = Caps(), + family: ModelFamily = FAMILY, + price: ModelPrice = FLAT, + ledger_caps: dict[str, Decimal] | None = None, + seen: set[str] | None = None, + reserve_delay: float = 0.0, + ) -> dict[str, Any]: + self.ledger = Ledger.open( + self.tmp_path / f"ledger-{len(self.ledgers)}", + run_id=RUN_ID, + caps=ledger_caps or {"anthropic": D(180), "openai": D(65), "google": D(180)}, + ) + self.ledgers.append(self.ledger) + service = LedgerService(self.ledger, {family.model_id: price}, {family.model_id: family}) + self.recording = RecordingLedger(service, reserve_delay) + self.bridge = FakeBridge() if bridge == "fake" else bridge + return await run_trajectory( + client=client or ScriptedClient(family.provider, family.model_id, steps or []), + bridge=self.bridge, + family=family, + prompt=PROMPT, + ledger=self.recording, + caps=caps, + seen_tool_args=set() if seen is None else seen, + sleep=self.sleep, + ) + + def reserve_bounds(self) -> list[Decimal]: + return [D(e["bound"]) for e in self.ledger.events(RUN_ID) if e["event"] == "reserve"] + + def settles(self) -> list[dict[str, Any]]: + return [e for e in self.ledger.events(RUN_ID) if e["event"] == "settle"] + + +@pytest.fixture +def harness(tmp_path: Path): + h = Harness(tmp_path) + yield h + for ledger in h.ledgers: + ledger.close() + + +def _outcomes(record: dict[str, Any], index: int = 0) -> list[str]: + return [a["outcome"] for a in record["model_calls"][index]["attempts"]] + + +async def test_trajectory_calls_a_tool_then_answers_and_records_every_call( + harness: Harness, +) -> None: + record = await harness.run([TOOL, ANSWER]) + assert record["status"] == "succeeded" and record["answer"] == "Scripted answer." + assert record["error"] is None + assert [c["tool"] for c in record["tool_calls"]] == ["search_docs"] + assert ( + record["tool_calls"][0]["result"] == FAKE_TEXT and record["tool_calls"][0]["warm"] is False + ) + assert record["model_calls"][1]["message_count"] == 3 + assert record["canonical_messages"][0] == {"role": "user", "content": PROMPT} + assert record["canonical_messages"][1]["content"][0]["type"] == "tool_use" + assert record["canonical_messages"][2]["content"][0] == { + "type": "tool_result", + "tool_use_id": record["canonical_messages"][1]["content"][0]["id"], + "content": FAKE_TEXT, + "is_error": False, + } + assert record["system_prompt_sha256"] == hashlib.sha256(SYSTEM_PROMPT.encode()).hexdigest() + assert record["model_calls"][0]["request_params"] == {"model": "scripted-1"} + assert record["model_calls"][0]["buckets"] == { + "uncached_input": 100, + "cache_write_input": 0, + "cached_input": 0, + "output": 10, + "reasoning": 0, + } + assert set(record["timing"]) == { + "wall_ms", + "used_ms", + "model_ms", + "tool_ms", + "grant_wait_ms", + "failed_attempt_ms", + "retry_wait_ms", + "overhead_ms", + } + assert record["started_at"] and record["completed_at"] + + +async def test_reservations_carry_independently_computed_bounds(harness: Harness) -> None: + # OpenAI family: max_output 32_768, max_input 1_017_232, the committed gpt-6.1-sol rates. + (family,) = [ + f for f in load_model_matrix(MODEL_MATRIX_PATH).model_families if f.id == "gpt-6.1-sol" + ] + price = load_price_snapshot(PRICE_SNAPSHOT_PATH).models["gpt-6.1-sol"] + openai_usage = { + "input_tokens": 1000, + "input_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 0}, + "output_tokens": 50, + } + steps = [ + {"tools": [SEARCH], "usage": openai_usage}, # call 0 + {"error": {"kind": "server", "status": 500}}, # call 1, attempt 1 + {"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} + client = FixedBytesClient(sizes, "openai", "gpt-6.1-sol", steps) + record = await harness.run(client=client, family=family, price=price) + assert record["status"] == "succeeded" + # Every expected value is plain arithmetic here, not a call to the loop's helpers: + # call 0: 500 + 256 * 2 = 1_012 + # call 1: 1_000 + 50 + 300 + 256 * 2 = 1_862 (the retry reserves the same) + # call 2: 2_000 + 256 * (5 + 1) = 3_536 (full request after no usage) + # dollars: input * $2.50 / 1M (cache-write rate, short tier) + 32_768 * $10 / 1M + assert [r["input_bound"] for r in harness.recording.reserves] == [1_012, 1_862, 1_862, 3_536] + assert [r["output_bound"] for r in harness.recording.reserves] == [32_768] * 4 + assert harness.reserve_bounds() == [D("0.33021"), D("0.332335"), D("0.332335"), D("0.33652")] + # a fake that reserved a fixed 200_000 input tokens would book 0.82768 for call 0 and fail here + + +async def test_ninth_model_call_is_a_cap_failure(harness: Harness) -> None: + record = await harness.run([TOOL] * 9 + [ANSWER]) + assert record["status"] == "failed" + assert record["error"]["category"] == "cap_model_calls" and len(record["model_calls"]) == 8 + + +async def test_thirteenth_tool_call_is_a_cap_failure(harness: Harness) -> None: + five = {"tools": [SEARCH] * 5, "usage": USAGE} + record = await harness.run([five, five, five, ANSWER]) + assert record["error"]["category"] == "cap_tool_calls" and len(record["tool_calls"]) == 12 + + +async def test_slow_tool_call_ends_the_trajectory(harness: Harness) -> None: + record = await harness.run( + [TOOL, ANSWER], bridge=FakeBridge(delay=0.2), caps=Caps(tool_call_s=0.05) + ) + assert record["status"] == "failed" and record["error"]["category"] == "cap_tool_timeout" + + +async def test_successful_work_over_the_allowance_is_a_cap_failure(harness: Harness) -> None: + record = await harness.run([{**TOOL, "delay_s": 0.25}, ANSWER], caps=Caps(trajectory_s=0.1)) + assert record["error"]["category"] == "cap_trajectory_time" + assert len(record["model_calls"]) == 1 and len(harness.recording.reserves) == 1 + + +async def test_grant_wait_longer_than_the_trajectory_allowance_still_succeeds( + harness: Harness, +) -> None: + record = await harness.run([TOOL, ANSWER], caps=Caps(trajectory_s=0.2), reserve_delay=0.3) + assert record["status"] == "succeeded" and record["timing"]["grant_wait_ms"] >= 300 + assert record["timing"]["used_ms"] < 200 + + +async def test_failed_attempt_longer_than_the_remaining_allowance_is_retried( + harness: Harness, +) -> None: + slow_error = {"delay_s": 0.5, "error": {"kind": "server", "status": 500}} + record = await harness.run([slow_error, ANSWER], caps=Caps(trajectory_s=0.3)) + assert record["status"] == "succeeded" + assert _outcomes(record) == ["server", "ok"] + assert record["timing"]["failed_attempt_ms"] >= 500 + + +async def test_attempt_over_its_own_timeout_is_a_retried_timeout(harness: Harness) -> None: + slow = {"delay_s": 1, "text": "too late", "usage": USAGE} + record = await harness.run([slow, ANSWER], caps=Caps(model_call_timeout_s=0.1)) + assert record["status"] == "succeeded" and _outcomes(record) == ["timeout", "ok"] + first = harness.settles()[0] + assert first["outcome"] == "timeout" + assert D(first["booked"]) == 2 * harness.reserve_bounds()[0] # booked at 2x its bound + assert harness.sleeps == [2.0] + + +async def test_result_over_the_cap_is_truncated_and_the_loop_continues(harness: Harness) -> None: + record = await harness.run([TOOL, ANSWER], caps=Caps(result_bytes=10)) + call = record["tool_calls"][0] + assert call["truncated"] is True and record["status"] == "succeeded" + assert call["result"] == FAKE_TEXT # the full canonical text is kept + sent = record["canonical_messages"][2]["content"][0]["content"] + assert sent == FAKE_TEXT[:10] + TRUNCATION_MARKER + + +async def test_unknown_tool_call_is_returned_to_the_model_and_the_loop_continues( + harness: Harness, +) -> None: + unknown = {"tools": [{"name": "no_such_tool", "arguments": {}}], "usage": USAGE} + bridge = FakeBridge(("search_docs", "no_such_tool")) + record = await harness.run([unknown, ANSWER], bridge=bridge) + assert record["tool_calls"][0]["is_error"] is True and record["status"] == "succeeded" + assert record["canonical_messages"][2]["content"][0]["is_error"] is True + + +@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 +) -> None: + bad = {"tools": [{"name": "search_docs", "arguments": arguments}], "usage": USAGE} + record = await harness.run([bad, ANSWER]) + assert record["tool_calls"][0]["is_error"] is True and harness.bridge.calls == [] + assert record["tool_calls"][0]["result"].startswith("tool arguments must be a JSON object") + assert record["status"] == "succeeded" + + +async def test_rate_limit_is_retried_honouring_retry_after_and_not_counted_as_a_model_call( + harness: Harness, +) -> None: + limited = {"error": {"kind": "rate_limited", "status": 429, "retry_after_s": 7}} + record = await harness.run([limited, ANSWER]) + assert harness.sleeps == [7.0] and len(record["model_calls"]) == 1 + assert _outcomes(record) == ["rate_limited", "ok"] + assert record["model_calls"][0]["attempts"][0]["status"] == 429 + assert record["timing"]["retry_wait_ms"] == 7000 + + +async def test_server_error_is_booked_at_twice_the_bound_and_retried(harness: Harness) -> None: + record = await harness.run([{"error": {"kind": "server", "status": 500}}, ANSWER]) + assert record["status"] == "succeeded" and _outcomes(record) == ["server", "ok"] + first, second = harness.reserve_bounds() + assert first == second # the retry reuses the failed attempt's bound + assert harness.ledger.spent("anthropic") == 2 * first + D("0.00011") # + (100 + 10) * $1/1M + + +async def test_retries_exhausted_discards_the_trajectory(harness: Harness) -> None: + with pytest.raises(TrajectoryDiscarded) as caught: + await harness.run([{"error": {"kind": "server", "status": 500}}] * 5) + assert caught.value.reason == "retries_exhausted" and harness.sleeps == [2, 4, 8, 16] + assert caught.value.record["status"] == "discarded" + assert len(caught.value.record["model_calls"][0]["attempts"]) == 5 + + +async def test_rejected_request_is_a_scored_failure_booked_at_zero(harness: Harness) -> None: + record = await harness.run([{"error": {"kind": "rejected", "status": 400}}]) + assert record["status"] == "failed" and record["error"]["category"] == "provider_rejected" + assert harness.ledger.spent("anthropic") == 0 and harness.sleeps == [] + + +async def test_budget_stop_discards_the_trajectory(harness: Harness) -> None: + with pytest.raises(TrajectoryDiscarded) as caught: + await harness.run([TOOL, ANSWER], ledger_caps={"anthropic": D("0")}) + assert caught.value.reason == "budget_stop" and caught.value.record["model_calls"] + + +async def test_repeated_tool_arguments_are_marked_warm(harness: Harness) -> None: + seen: set[str] = set() + first = await harness.run([TOOL, ANSWER], seen=seen) + second = await harness.run([TOOL, ANSWER], seen=seen) + assert first["tool_calls"][0]["warm"] is False and second["tool_calls"][0]["warm"] is True + assert seen == {'search_docs:{"query": "json"}'} + + +async def test_empty_final_text_is_an_empty_answer(harness: Harness) -> None: + record = await harness.run([{"text": "", "usage": USAGE}]) + assert record["status"] == "succeeded" and record["answer"] == "" + + +async def test_bridge_crash_fails_the_trajectory_as_a_protocol_crash(harness: Harness) -> None: + record = await harness.run([TOOL, ANSWER], bridge=FakeBridge(crash=True)) + assert record["status"] == "failed" and record["error"]["category"] == "mcp_protocol_crash" + assert record["error"]["type"] == "BridgeCrash" + + +async def test_no_docs_sends_no_tools(harness: Harness) -> None: + client = ToolsSeenClient("anthropic", "scripted-1", [TOOL, ANSWER]) + record = await harness.run(client=client, bridge=None) + assert client.tools_seen == [[]] and record["tool_calls"] == [] + assert record["answer"] == "Scripted answer." + assert record["tools_sha256"] == schemas_sha256([]) + + +def test_input_bounds() -> None: + assert ( + next_input_bound(Buckets(100, 0, 20, 30), added_bytes=500, added_entries=2, framing=256) + == 1162 + ) + + +def test_backoff() -> None: + assert [backoff_s(r, None) for r in (1, 2, 3, 4)] == [2, 4, 8, 16] + assert backoff_s(1, 7.0) == 7.0 and backoff_s(1, 121.0) is None + assert backoff_s(1, 0.0) == 0.0 + assert backoff_s(10, None) == 60 + + +def test_system_prompt_follows_the_design() -> None: + assert ( + "ground your answer in the official python documentation; if a documentation tool is " + "available, use it before answering and cite the section url you relied on" + ) in SYSTEM_PROMPT.lower() + for name in ("python-docs", "docs-fetch", "context7", "mcp", "fetch"): + assert name not in SYSTEM_PROMPT.lower() From a6cdc3dac8e557f0a508eedd2ad77f953f55704a Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Tue, 3 Nov 2026 22:50:04 +0100 Subject: [PATCH 07/77] feat(benchmarks): run agentic jobs in keyless, redacted worker processes Host and worker exchange 8-byte length-prefixed JSON frames, so a frame of any size up to 64 MiB round-trips and a larger one is a harness error. The worker protects its output before anything else: the original stdout becomes the protocol channel, and fds 1 and 2 pass a redactor that replaces its own key, split writes included; a frame holding the own key is refused. The host refuses to start with a provider key, launches only scripted models locally, scans every frame and log for key-shaped strings, arbitrates the ledger, and books a lost worker's unit at twice its bound. Discarded trajectories are rerun at most twice; a budget stop marks the rest of the job not run. Co-Authored-By: Claude Opus 5.5 --- benchmarks/__main__.py | 11 + benchmarks/agentic/host.py | 222 +++++++++++++++ benchmarks/agentic/protocol.py | 59 ++++ benchmarks/agentic/worker.py | 320 +++++++++++++++++++++ tests/benchmarks/test_agentic_host.py | 394 ++++++++++++++++++++++++++ 5 files changed, 1006 insertions(+) create mode 100644 benchmarks/agentic/host.py create mode 100644 benchmarks/agentic/protocol.py create mode 100644 benchmarks/agentic/worker.py create mode 100644 tests/benchmarks/test_agentic_host.py diff --git a/benchmarks/__main__.py b/benchmarks/__main__.py index 22c9dfe3..25b55c5a 100644 --- a/benchmarks/__main__.py +++ b/benchmarks/__main__.py @@ -152,6 +152,11 @@ def _build_parser() -> argparse.ArgumentParser: default=_DEFAULT_CORPUS_SCHEMA, help=f"Path to the corpus JSON schema file (default: {_DEFAULT_CORPUS_SCHEMA}).", ) + + # Spawned by the agentic host, never by hand: it reads its job as frames on stdin. + subparsers.add_parser( + "agentic-worker", help="Internal: run one agentic (model, system) job for the host." + ) return parser @@ -159,6 +164,12 @@ def main(argv: list[str] | None = None) -> int: parser = _build_parser() args = parser.parse_args(argv) + if args.command == "agentic-worker": + # Lazy: the provider SDKs load only in a worker. main_worker protects output first. + from benchmarks.agentic.worker import main_worker + + return main_worker() + if args.command == "run": config = BenchmarkConfig( corpus_path=args.corpus, diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py new file mode 100644 index 00000000..c68bfc3f --- /dev/null +++ b/benchmarks/agentic/host.py @@ -0,0 +1,222 @@ +"""The host orchestrator: launchers, worker supervision and ledger arbitration (design §7.3). + +The host never holds a provider key. It spawns one worker per (model, system), +answers its ledger requests through the one LedgerService, scans every frame +and every log for key-shaped strings, and books a lost worker's unit at twice +its bound. +""" + +from __future__ import annotations + +import asyncio +import json +import os +import sys +from collections.abc import Awaitable, Callable, Mapping, Sequence +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Any, Protocol + +from benchmarks.agentic.bridge import SystemSpec +from benchmarks.agentic.clients import PAID_KEY_ENVS +from benchmarks.agentic.ledger import LedgerService +from benchmarks.agentic.loop import Caps +from benchmarks.agentic.protocol import ( + MAX_FRAME_BYTES, + KeyLeakError, + assert_no_key_shaped, + encode_frame, + read_frame, +) +from benchmarks.agentic.types import Buckets +from benchmarks.model_matrix import ModelFamily +from benchmarks.runner import BenchmarkValidationError + +#: What a local worker may see of the host's environment. Never a key, never the live flag. +_LOCAL_ENV = ("PATH", "HOME", "LANG", "TMPDIR", "XDG_CACHE_HOME", "VIRTUAL_ENV") + + +@dataclass(frozen=True) +class WorkerJob: + job_id: str # f"{family.id}--{system.id}" + family: ModelFamily # family.raw["script"] is absolute for scripted families + system: SystemSpec + trajectories: tuple[dict[str, Any], ...] # {"corpus_id", "prompt", "repeat"}, in run order + caps: Caps + + +class Launcher(Protocol): + def supports(self, family: ModelFamily) -> bool: ... + + def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: ... + + +class LocalLauncher: + """A local process with no provider key: scripted models only (PR 4 adds containers).""" + + def supports(self, family: ModelFamily) -> bool: + return family.api == "scripted" + + 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 refuse_host_keys(environ: Mapping[str, str]) -> None: + held = [name for name in PAID_KEY_ENVS if environ.get(name)] + if held: + raise BenchmarkValidationError( + f"the host must never hold a provider key, but {', '.join(held)} is set: " + "keys go only to the worker of their own provider" + ) + + +async def _supervise( + job: WorkerJob, + *, + launcher: Launcher, + ledger: LedgerService, + on_message: Callable[[WorkerJob, dict[str, Any]], Awaitable[None]], + log_dir: Path, + cwd: Path, + max_frame_bytes: int, +) -> None: + argv, env = launcher.command(job) + log_path = log_dir / f"{job.job_id}.stderr.log" + 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, + ) + assert proc.stdin is not None and proc.stdout is not None + in_flight: str | None = None + reported: set[tuple[str, int]] = set() + done = False + try: + try: + job_frame = { + "type": "job", + "job_id": job.job_id, + "family": job.family.raw, + "system": job.system.raw, + "trajectories": list(job.trajectories), + "caps": asdict(job.caps), + } + proc.stdin.write(encode_frame(job_frame)) + await proc.stdin.drain() + while (message := await read_frame(proc.stdout, limit=max_frame_bytes)) is not None: + where = f"a frame from worker {job.job_id}" + assert_no_key_shaped(json.dumps(message, ensure_ascii=False), where=where) + kind = message.get("type") + reply: dict[str, Any] | None = None + if kind == "reserve": + if in_flight is not None: + raise BenchmarkValidationError(f"worker {job.job_id} reserved twice") + # The job's own provider and model, never the worker's claim. + in_flight = await ledger.reserve( + provider=job.family.provider, + model_id=job.family.model_id, + input_bound=int(message["input_bound"]), + output_bound=int(message["output_bound"]), + kind=str(message.get("kind", "model_call")), + ) + reply = ( + {"type": "grant", "unit_id": in_flight} if in_flight else {"type": "deny"} + ) + elif kind == "settle": + if in_flight is None or message.get("unit_id") != in_flight: + raise BenchmarkValidationError( + f"worker {job.job_id} settled a unit it does not hold" + ) + buckets = message.get("buckets") + await ledger.settle( + in_flight, + outcome=message["outcome"], + buckets=None if buckets is None else Buckets(**buckets), + ) + in_flight = None + reply = {"type": "ack"} + elif kind == "error": + reason = str(message.get("reason")) + if reason == "own key found in output": + raise KeyLeakError(f"worker {job.job_id}: {reason}") + raise BenchmarkValidationError(f"worker {job.job_id} failed: {reason}") + else: + await on_message(job, message) + if kind in ("trajectory", "not_run"): + reported.add((message["corpus_id"], message["repeat"])) + done = done or kind == "done" + if kind in ("trajectory", "discarded"): + reply = {"type": "ack"} + if reply is not None: + proc.stdin.write(encode_frame(reply)) + await proc.stdin.drain() + except (BrokenPipeError, ConnectionResetError): + pass # the worker died; handled as a lost worker below + await proc.wait() + finally: + if proc.returncode is None: + proc.kill() + await proc.wait() + if in_flight is not None: # may have been billed: booked at twice its bound + await ledger.settle(in_flight, outcome="worker_lost", buckets=None) + log_text = log_path.read_text(encoding="utf-8", errors="replace") + assert_no_key_shaped(log_text, where=str(log_path)) + if not done: + for item in job.trajectories: + if (item["corpus_id"], item["repeat"]) not in reported: + await on_message( + job, + { + "type": "not_run", + "corpus_id": item["corpus_id"], + "repeat": item["repeat"], + "reason": "worker_lost", + }, + ) + + +async def run_jobs( + jobs: Sequence[WorkerJob], + *, + launcher: Launcher, + ledger: LedgerService, + on_message: Callable[[WorkerJob, dict[str, Any]], Awaitable[None]], + log_dir: Path, + cwd: Path, + max_frame_bytes: int = MAX_FRAME_BYTES, +) -> None: + """Run every job in its own worker, in parallel; a harness error kills them all.""" + refuse_host_keys(os.environ) + unsupported = sorted({job.family.id for job in jobs if not launcher.supports(job.family)}) + 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)" + ) + 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 + ] + 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 diff --git a/benchmarks/agentic/protocol.py b/benchmarks/agentic/protocol.py new file mode 100644 index 00000000..5e55d50c --- /dev/null +++ b/benchmarks/agentic/protocol.py @@ -0,0 +1,59 @@ +"""Length-prefixed JSON frames between host and worker, and the key scans (ruling B3). + +A frame is an 8-byte big-endian length and compact UTF-8 JSON. Frames of any +size up to MAX_FRAME_BYTES round-trip; a larger one is a harness error on the +side that meets it. +""" + +from __future__ import annotations + +import asyncio +import json +import re +from typing import Any + +from benchmarks.runner import BenchmarkValidationError + +MAX_FRAME_BYTES = 64 * 1024 * 1024 +KEY_SHAPED = re.compile( + r"(? bytes: + body = json.dumps(message, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + 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 +) -> dict[str, Any] | None: + """The next frame; None at a clean EOF or a partial frame (the writer died).""" + try: + length = int.from_bytes(await reader.readexactly(8), "big") + if length > limit: + raise FrameTooLarge(f"a {length}-byte frame is over the {limit}-byte limit") + body = await reader.readexactly(length) + except asyncio.IncompleteReadError: + return None + return json.loads(body) + + +def assert_no_key_shaped(text: str, *, where: str) -> None: + if KEY_SHAPED.search(text): + raise KeyLeakError(f"a key-shaped string was found in {where}") # never the match + + +def contains_own_key(text: str, own_key: str | None) -> bool: + return bool(own_key) and own_key in text diff --git a/benchmarks/agentic/worker.py b/benchmarks/agentic/worker.py new file mode 100644 index 00000000..7eee4cd4 --- /dev/null +++ b/benchmarks/agentic/worker.py @@ -0,0 +1,320 @@ +"""The worker process: output protection, then one (model, system) job (ruling B2). + +``protect_output`` runs before anything else. It keeps the original stdout as +the protocol channel and sends fds 1 and 2 through a redactor that replaces +the worker's own key, so ``print()``, ``sys.stderr``, ``os.write(2, ...)``, +tracebacks and the MCP servers' inherited stderr all pass it. Only +``ProtocolChannel.send`` writes the protocol fd, and it refuses a frame that +holds the own key. +""" + +from __future__ import annotations + +import asyncio +import hashlib +import io +import os +import sys +import threading +from collections import deque +from contextlib import AsyncExitStack +from dataclasses import asdict +from importlib.metadata import version +from typing import Any + +from benchmarks.agentic.bridge import Bridge, SystemSpec, open_bridge, system_spec_from_raw +from benchmarks.agentic.clients import PAID_KEY_ENVS, make_client +from benchmarks.agentic.ledger import Outcome +from benchmarks.agentic.loop import Caps, TrajectoryDiscarded, run_trajectory +from benchmarks.agentic.protocol import KeyLeakError, encode_frame, read_frame +from benchmarks.agentic.schemas import ( + schemas_sha256, + to_anthropic, + to_gemini, + to_openai_responses, +) +from benchmarks.agentic.types import Buckets, ToolSpec +from benchmarks.model_matrix import model_family_from_raw +from benchmarks.runner import BenchmarkValidationError + +MAX_RERUNS = 2 +_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 _write_all(fd: int, data: bytes) -> None: + while data: + data = data[os.write(fd, data) :] + + +def _redact(read_fd: int, sink_fd: int, own_key: str | None) -> None: + key = own_key.encode() if own_key else b"" + hold = max(len(key) - 1, 0) # a key split across two reads is still caught + pending = b"" + while chunk := os.read(read_fd, 65536): + pending += chunk + if key: + pending = pending.replace(key, _REDACTED) + out, pending = (pending[:-hold], pending[-hold:]) if hold else (pending, b"") + try: + _write_all(sink_fd, out) + except OSError: + pass # the sink is gone; keep draining so writers never block + try: + _write_all(sink_fd, pending) + except OSError: + pass + os.close(read_fd) + + +class ProtocolChannel: + def __init__( + self, protocol_fd: int, own_key: str | None, pipe_write_fd: int, thread: threading.Thread + ) -> None: + self._fd = protocol_fd + self._own_key = own_key.encode() if own_key else None + self._pipe_write_fd = pipe_write_fd + self._thread = thread + + def send(self, message: dict[str, Any]) -> None: + """Write one frame; refuse a frame that holds the own key.""" + frame = encode_frame(message) + if self._own_key and self._own_key in frame: + raise KeyLeakError("own key found in output") + _write_all(self._fd, frame) + + def close(self) -> None: + """Drain the redactor: every byte written so far reaches the sink. Restores nothing.""" + sys.stdout.flush() + sys.stderr.flush() + devnull = os.open(os.devnull, os.O_WRONLY) + os.dup2(devnull, 1) + os.dup2(devnull, 2) + os.close(devnull) + os.close(self._pipe_write_fd) + # A grandchild that still holds the pipe cannot keep the worker alive: the thread + # is a daemon, and its bytes are dropped, never written unredacted. + self._thread.join(5) + + +def protect_output(own_key: str | None) -> ProtocolChannel: + # shortcut: fd redirection is POSIX only; the harness runs on macOS and Linux + sys.stdout.flush() + sys.stderr.flush() + protocol_fd = os.dup(1) + sink_fd = os.dup(2) + read_fd, write_fd = os.pipe() + os.dup2(write_fd, 1) + os.dup2(write_fd, 2) + thread = threading.Thread(target=_redact, args=(read_fd, sink_fd, own_key), daemon=True) + thread.start() + sys.stdout = io.TextIOWrapper( + open(1, "wb", closefd=False), + encoding="utf-8", + errors="backslashreplace", + line_buffering=True, + ) + sys.stderr = io.TextIOWrapper( + open(2, "wb", closefd=False), + encoding="utf-8", + errors="backslashreplace", + line_buffering=True, + ) + return ProtocolChannel(protocol_fd, own_key, write_fd, thread) + + +class _HostLedger: + """The loop's LedgerPort over the protocol: each request waits for the host's reply.""" + + def __init__(self, channel: ProtocolChannel, reader: asyncio.StreamReader) -> None: + self._channel, self._reader = channel, reader + + async def request(self, message: dict[str, Any]) -> dict[str, Any]: + self._channel.send(message) + reply = await read_frame(self._reader) + if reply is None: + raise ConnectionError("the host closed the job channel") + return reply + + async def reserve( + self, + *, + provider: str, + model_id: str, + input_bound: int, + output_bound: int, + kind: str = "model_call", + ) -> str | None: + reply = await self.request( + { + "type": "reserve", + "provider": provider, + "model_id": model_id, + "input_bound": input_bound, + "output_bound": output_bound, + "kind": kind, + } + ) + return reply["unit_id"] if reply.get("type") == "grant" else None + + async def settle(self, unit_id: str, *, outcome: Outcome, buckets: Buckets | None) -> None: + await self.request( + { + "type": "settle", + "unit_id": unit_id, + "outcome": outcome, + "buckets": None if buckets is None else asdict(buckets), + } + ) + + +def _converted(provider: str, tools: list[ToolSpec]) -> tuple[list[dict[str, Any]], list[str]]: + if provider == "google": + return to_gemini(tools) + if provider == "openai": + return to_openai_responses(tools), [] + return to_anthropic(tools), [] + + +def _index_sha256() -> str | None: + from mcp_server_python_docs.storage.db import get_index_path + + path = get_index_path() + if not path.exists(): + return None + with path.open("rb") as file: + return hashlib.file_digest(file, "sha256").hexdigest() + + +def _system_info(system: SystemSpec, provider: str, bridge: Bridge | None) -> dict[str, Any]: + tools_raw = bridge.tools_raw if bridge else [] + converted, dropped = _converted(provider, bridge.tools if bridge else []) + return { + "type": "system_info", + "server_info": bridge.server_info if bridge else None, + "tools_raw": tools_raw, + "tools_raw_sha256": schemas_sha256(tools_raw), + "tools_converted": converted, + "tools_converted_sha256": schemas_sha256(converted), + "gemini_dropped": dropped, + "index_sha256": _index_sha256() if system.id == "python-docs" else None, + "client_versions": { + name: version(name) for name in ("anthropic", "openai", "google-genai", "mcp") + }, + } + + +async def _open(stack: AsyncExitStack, system: SystemSpec) -> Bridge | None: + if system.transport == "none": + return None + return await stack.enter_async_context(open_bridge(system)) + + +async def _close(stack: AsyncExitStack) -> None: + try: + await stack.aclose() + except Exception as exc: # noqa: BLE001 - a dead server may fail its own shutdown + print(f"closing the MCP bridge failed: {exc!r}", file=sys.stderr) + + +async def _run_job(channel: ProtocolChannel, reader: asyncio.StreamReader) -> int: + job = await read_frame(reader) + if job is None or job.get("type") != "job": + raise BenchmarkValidationError("the host sent no job") + family = model_family_from_raw(job["family"]) + system = system_spec_from_raw(job["system"]) + caps = Caps(**job["caps"]) + client = make_client(family, timeout_s=caps.model_call_timeout_s) + 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)) + while queue: + item, attempt = queue.popleft() + ident = {"corpus_id": item["corpus_id"], "repeat": item["repeat"]} + try: + record = await run_trajectory( + client=client, + bridge=bridge, + family=family, + prompt=item["prompt"], + ledger=host, + caps=caps, + seen_tool_args=seen, + ) + except TrajectoryDiscarded as discarded: + await host.request( + { + "type": "discarded", + "record": discarded.record, + **ident, + "reason": discarded.reason, + "attempt": attempt, + } + ) + if discarded.reason == "budget_stop": + for rest, _ in queue: + channel.send( + { + "type": "not_run", + "corpus_id": rest["corpus_id"], + "repeat": rest["repeat"], + "reason": "budget_stop", + } + ) + queue.clear() + elif attempt <= MAX_RERUNS: + queue.append((item, attempt + 1)) + else: + channel.send({"type": "not_run", **ident, "reason": "retries_exhausted"}) + continue + await host.request({"type": "trajectory", "record": record, **ident}) + if bridge is not None and (record["error"] or {}).get("category") in _REOPEN_AFTER: + await _close(stack) + stack = AsyncExitStack() + bridge = await _open(stack, system) + finally: + await _close(stack) # 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 + return code + + +async def run_worker(channel: ProtocolChannel, reader: asyncio.StreamReader) -> int: + 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 _report(channel, f"{type(exc).__name__}: {exc}", 2) + + +async def _serve(channel: ProtocolChannel) -> int: + reader = asyncio.StreamReader() + await asyncio.get_running_loop().connect_read_pipe( + lambda: asyncio.StreamReaderProtocol(reader), open(0, "rb", buffering=0, closefd=False) + ) + return await run_worker(channel, reader) + + +def main_worker() -> int: + """``python -m benchmarks agentic-worker``: protect output first, then run the job.""" + # A worker holds at most one paid key (make_client refuses a second): that one is its own. + own_key = next((os.environ[name] for name in PAID_KEY_ENVS if os.environ.get(name)), None) + channel = protect_output(own_key) + try: + return asyncio.run(_serve(channel)) + finally: + channel.close() diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py new file mode 100644 index 00000000..91565d76 --- /dev/null +++ b/tests/benchmarks/test_agentic_host.py @@ -0,0 +1,394 @@ +"""Keyless host, redacted workers and length-prefixed frames (design §7.3; ruling B2, B3). + +Workers are real subprocesses; models are scripted, so nothing reaches a network host. +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +import time +from decimal import Decimal +from pathlib import Path +from typing import Any + +import pytest +import yaml + +from benchmarks.agentic.bridge import system_spec_from_raw +from benchmarks.agentic.clients import PAID_KEY_ENVS +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 +from benchmarks.agentic.protocol import FrameTooLarge, KeyLeakError, assert_no_key_shaped +from benchmarks.model_matrix import ModelFamily, load_model_matrix, model_family_from_raw +from benchmarks.runner import BenchmarkValidationError + +REPO_ROOT = Path(__file__).resolve().parents[2] +MODEL_MATRIX_PATH = REPO_ROOT / "docs" / "benchmarks" / "model-matrix.yml" +FAKE_SERVER = Path(__file__).parent / "fixtures" / "agentic" / "fake_fetch_server.py" +KEY = "sk-ant-synthetic-" + "k" * 40 +D = Decimal +USAGE = {"input_tokens": 1000, "output_tokens": 100} +ANSWER = {"text": "Scripted answer.", "usage": USAGE} +NO_DOCS = system_spec_from_raw({"id": "no-docs", "adapter": "none"}) +FAKE_FETCH = system_spec_from_raw( + { + "id": "docs-fetch", + "adapter": "mcp-stdio", + "command": ["{python}", str(FAKE_SERVER), "--edge"], + "env": {}, + "pass_env": [], + } +) +FLAT = ModelPrice( + "scripted-1", "anthropic", (Tier(None, Rates(D(1), D(1), D(1), D(1))),), "https://x.invalid" +) + + +def _frames(data: bytes) -> list[dict[str, Any]]: + frames = [] + while data: + length = int.from_bytes(data[:8], "big") + frames.append(json.loads(data[8 : 8 + length])) + data = data[8 + length :] + return frames + + +def _family(script: Path) -> ModelFamily: + return model_family_from_raw( + { + "id": "scripted-anthropic", + "provider": "anthropic", + "model_id": "scripted-1", + "client": "scripted", + "token_count_method": "claude_normalized_payload", + "latency_scope": "request_dispatch_to_final_answer", + "headline_eligible": False, + "headline_ineligibility_reason": "test", + "api": "scripted", + "arm": "hosted", + "max_input_tokens": 200_000, + "max_output_tokens": 1024, + "output_cap_includes_reasoning": True, + "framing_allowance_tokens": 256, + "script": str(script), + } + ) + + +def _job( + tmp_path: Path, + steps: list[dict[str, Any]], + *, + system: Any = NO_DOCS, + count: int = 2, + job_id: str | None = None, +) -> WorkerJob: + script = tmp_path / f"script-{job_id or 'main'}.yml" + script.write_text(yaml.safe_dump({"steps": steps}), encoding="utf-8") + family = _family(script) + trajectories = tuple( + {"corpus_id": f"Q{i}", "prompt": f"question {i}", "repeat": 1} for i in range(1, count + 1) + ) + return WorkerJob( + job_id or f"{family.id}--{system.id}", family, system, trajectories, HOSTED_CAPS + ) + + +class Host: + """A ledger, a message collector and run_jobs with the repo root as the worker cwd.""" + + def __init__(self, tmp_path: Path, caps: dict[str, Decimal] | None = None) -> None: + self.tmp_path = tmp_path + self.ledger = Ledger.open( + tmp_path / "ledger", run_id="host-test", caps=caps or {"anthropic": D(180)} + ) + self.received: list[tuple[str, dict[str, Any]]] = [] + + def service(self, family: ModelFamily) -> LedgerService: + return LedgerService(self.ledger, {family.model_id: FLAT}, {family.model_id: family}) + + async def on_message(self, job: WorkerJob, message: dict[str, Any]) -> None: + self.received.append((job.job_id, message)) + + def messages(self, job_id: str | None = None) -> list[dict[str, Any]]: + return [m for j, m in self.received if job_id is None or j == job_id] + + async def run(self, jobs: list[WorkerJob], launcher: Any = None, **kwargs: Any) -> None: + await run_jobs( + jobs, + launcher=launcher or LocalLauncher(), + ledger=self.service(jobs[0].family), + on_message=self.on_message, + log_dir=self.tmp_path / "logs", + cwd=REPO_ROOT, + **kwargs, + ) + + +@pytest.fixture +def host(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + for name in PAID_KEY_ENVS: + monkeypatch.delenv(name, raising=False) + h = Host(tmp_path) + yield h + h.ledger.close() + + +class KeyedLauncher(LocalLauncher): + """A test launcher that hands the worker a key and a wrapped entry point.""" + + def __init__(self, code: str, key: str = KEY) -> None: + self.code, self.key = code, key + + def supports(self, family: ModelFamily) -> bool: + return True + + def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: + _, env = super().command(job) + return [sys.executable, "-c", self.code], {**env, "ANTHROPIC_API_KEY": self.key} + + +def test_host_refuses_to_start_with_a_provider_key_in_its_environment() -> None: + with pytest.raises(BenchmarkValidationError, match="OPENAI_API_KEY") as caught: + refuse_host_keys({"OPENAI_API_KEY": "x-not-a-key"}) + assert "x-not-a-key" not in str(caught.value) + refuse_host_keys({"PATH": "/bin", "OPENAI_API_KEY": ""}) # an empty variable holds no key + + +def test_local_launcher_passes_no_provider_key_and_runs_only_scripted_models( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-not-a-real-key") + monkeypatch.setenv("BENCHMARK_LIVE_PROVIDERS_ENABLED", "1") + job = _job(tmp_path, [ANSWER]) + argv, env = LocalLauncher().command(job) + assert argv == [sys.executable, "-m", "benchmarks", "agentic-worker"] + assert not (set(PAID_KEY_ENVS) | {"BENCHMARK_LIVE_PROVIDERS_ENABLED"}) & set(env) + assert set(env) <= {"PATH", "HOME", "LANG", "TMPDIR", "XDG_CACHE_HOME", "VIRTUAL_ENV"} + families = load_model_matrix(MODEL_MATRIX_PATH).model_families + (anthropic_live_family,) = [f for f in families if f.id == "claude-sonnet-5-5"] + assert LocalLauncher().supports(anthropic_live_family) is False + assert LocalLauncher().supports(job.family) is True + + +@pytest.mark.parametrize( + "text,leaks", + [ + ("sk-ant-api03-" + "a" * 40, True), + ("AIza" + "b" * 35, True), + ("sk-proj-" + "c" * 40, True), + ("a disk-based cache", False), + ("task-runner-" + "d" * 40, False), + ], +) +def test_key_shaped_scan(text: str, leaks: bool) -> None: + if leaks: + with pytest.raises(KeyLeakError, match="test frame") as caught: + assert_no_key_shaped(f"before {text} after", where="test frame") + assert text not in str(caught.value) + else: + assert_no_key_shaped(text, where="test frame") + + +def _run_python(code: str) -> subprocess.CompletedProcess[bytes]: + return subprocess.run( + [sys.executable, "-c", code], cwd=REPO_ROOT, capture_output=True, timeout=60 + ) + + +def test_protect_output_redacts_the_own_key_on_every_stream() -> None: + code = ( + "import os, sys\n" + "from benchmarks.agentic.worker import protect_output\n" + f"KEY = {KEY!r}\n" + "ch = protect_output(KEY)\n" + "print(KEY)\n" + "sys.stderr.write(KEY + '\\n')\n" + "os.write(2, KEY[:10].encode())\n" + "os.write(2, KEY[10:].encode() + b'\\n')\n" + "ch.send({'type': 'done'})\n" + "ch.close()\n" + ) + proc = _run_python(code) + assert proc.returncode == 0, proc.stderr + assert KEY.encode() not in proc.stderr and proc.stderr.count(b"[redacted]") == 3 + assert _frames(proc.stdout) == [{"type": "done"}] # the channel holds only the frame + + +def test_protocol_channel_refuses_a_frame_holding_the_own_key() -> None: + code = ( + "from benchmarks.agentic.protocol import KeyLeakError\n" + "from benchmarks.agentic.worker import protect_output\n" + f"KEY = {KEY!r}\n" + "ch = protect_output(KEY)\n" + "try:\n" + " ch.send({'type': 'trajectory', 'answer': 'x' + KEY})\n" + "except KeyLeakError:\n" + " ch.send({'type': 'refused'})\n" + "ch.close()\n" + ) + proc = _run_python(code) + assert proc.returncode == 0, proc.stderr + assert _frames(proc.stdout) == [{"type": "refused"}] and KEY.encode() not in proc.stdout + + +async def test_host_logs_and_artifacts_never_hold_a_workers_key(host: Host, tmp_path: Path) -> None: + code = ( + "import os, sys\n" + "from benchmarks.agentic import worker\n" + "real = worker.run_worker\n" + "async def leaky(channel, reader):\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" + "worker.run_worker = leaky\n" + "sys.exit(worker.main_worker())\n" + ) + await host.run([_job(tmp_path, [ANSWER])], launcher=KeyedLauncher(code)) + logs = "".join(p.read_text() for p in (tmp_path / "logs").iterdir()) + assert KEY not in logs and logs.count("[redacted]") == 3 + assert all(KEY not in json.dumps(m) for m in host.messages()) + assert [m["type"] for m in host.messages()][-1] == "done" + + +async def test_worker_runs_its_job_over_the_channel_and_reports_done( + host: Host, tmp_path: Path +) -> None: + await host.run([_job(tmp_path, [ANSWER])]) + messages = host.messages() + assert [m["type"] for m in messages] == ["system_info", "trajectory", "trajectory", "done"] + info = messages[0] + assert info["tools_raw"] == [] and info["index_sha256"] is None + assert set(info["client_versions"]) == {"anthropic", "openai", "google-genai", "mcp"} + assert [m["corpus_id"] for m in messages[1:3]] == ["Q1", "Q2"] + assert messages[1]["record"]["answer"] == "Scripted answer." + assert host.ledger.spent("anthropic") == 2 * D("0.0011") # 1000 in + 100 out at $1/1M + assert (tmp_path / "logs" / "scripted-anthropic--no-docs.stderr.log").exists() + + +async def test_worker_exits_with_its_mcp_server_child_still_alive_at_shutdown( + host: Host, tmp_path: Path +) -> None: + pid_step = {"tools": [{"name": "pid", "arguments": {}}], "usage": USAGE} + job = _job(tmp_path, [pid_step, ANSWER], system=FAKE_FETCH, count=1) + started = time.monotonic() + await host.run([job]) + assert time.monotonic() - started < 10 + messages = host.messages() + assert [m["type"] for m in messages] == ["system_info", "trajectory", "done"] + assert len(messages[0]["tools_raw"]) == 4 and messages[0]["server_info"]["name"] + result = messages[1]["record"]["tool_calls"][0]["result"] + server_pid = json.loads(result)["result"] + with pytest.raises(ProcessLookupError): + os.kill(server_pid, 0) + + +async def test_a_trajectory_frame_over_100000_bytes_round_trips_through_a_worker( + host: Host, tmp_path: Path +) -> None: + await host.run([_job(tmp_path, [{"text": "x" * 150_000, "usage": USAGE}], count=1)]) + (received_trajectory,) = [m for m in host.messages() if m["type"] == "trajectory"] + assert received_trajectory["record"]["answer"] == "x" * 150_000 + + +async def test_a_frame_over_the_limit_is_a_harness_error(host: Host, tmp_path: Path) -> None: + with pytest.raises(FrameTooLarge): + await host.run( + [_job(tmp_path, [{"text": "x" * 5_000, "usage": USAGE}])], max_frame_bytes=2_000 + ) + types = [m["type"] for m in host.messages()] + assert types == ["system_info"] # nothing for that trajectory reached on_message + + +async def test_host_settles_a_lost_workers_unit_at_twice_its_bound_and_frees_the_provider( + host: Host, tmp_path: Path +) -> None: + fake_worker = ( + "import json, sys\n" + "inp, out = sys.stdin.buffer, sys.stdout.buffer\n" + "def read():\n" + " n = int.from_bytes(inp.read(8), 'big')\n" + " return json.loads(inp.read(n))\n" + "def send(message):\n" + " body = json.dumps(message).encode()\n" + " out.write(len(body).to_bytes(8, 'big') + body)\n" + " out.flush()\n" + "read()\n" + "send({'type': 'reserve', 'provider': 'anthropic', 'model_id': 'scripted-1',\n" + " 'input_bound': 1000, 'output_bound': 1000, 'kind': 'model_call'})\n" + "read()\n" + "sys.exit(1)\n" + ) + + class LostLauncher(LocalLauncher): + def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: + argv, env = super().command(job) + return ([sys.executable, "-c", fake_worker] if job.job_id == "lost" else argv), env + + lost = _job(tmp_path, [ANSWER], job_id="lost") + normal = _job(tmp_path, [ANSWER], count=1, job_id="normal") + await host.run([lost, normal], launcher=LostLauncher()) + first_bound = D("0.002") # (1000 + 1000) * $1 / 1M + second_job_actual = D("0.0011") + assert host.ledger.spent("anthropic") == 2 * first_bound + second_job_actual + lost_job_messages = host.messages("lost") + assert {(m["type"], m["reason"]) for m in lost_job_messages} == {("not_run", "worker_lost")} + assert len(lost_job_messages) == 2 + assert [m["type"] for m in host.messages("normal")][-1] == "done" + + +async def test_host_aborts_the_run_when_a_worker_frame_holds_a_key_shaped_string( + host: Host, tmp_path: Path +) -> None: + leaky_worker = ( + "import json, sys\n" + "body = json.dumps({'type': 'system_info', 'note': 'sk-ant-' + 'a' * 30}).encode()\n" + "sys.stdout.buffer.write(len(body).to_bytes(8, 'big') + body)\n" + "sys.stdout.buffer.flush()\n" + "import time; time.sleep(30)\n" + ) + started = time.monotonic() + with pytest.raises(KeyLeakError): + await host.run([_job(tmp_path, [ANSWER])], launcher=KeyedLauncher(leaky_worker, key="")) + assert time.monotonic() - started < 10 # the sleeping worker was killed + assert host.messages() == [] + + +async def test_budget_stop_marks_the_rest_of_the_job_not_run(tmp_path: Path) -> None: + host = Host(tmp_path, caps={"anthropic": D("0")}) + try: + await host.run([_job(tmp_path, [ANSWER], count=3)]) + finally: + host.ledger.close() + messages = host.messages() + assert [(m["type"], m.get("reason")) for m in messages] == [ + ("system_info", None), + ("discarded", "budget_stop"), + ("not_run", "budget_stop"), + ("not_run", "budget_stop"), + ("done", None), + ] + assert [m["corpus_id"] for m in messages[1:4]] == ["Q1", "Q2", "Q3"] + + +async def test_retries_exhausted_trajectory_is_rerun_at_most_twice( + host: Host, tmp_path: Path +) -> None: + limited = {"error": {"kind": "rate_limited", "status": 429, "retry_after_s": 0}} + await host.run([_job(tmp_path, [limited] * 5, count=1)]) + messages = host.messages() + discarded = [m for m in messages if m["type"] == "discarded"] + assert [d["attempt"] for d in discarded] == [1, 2, 3] + assert {d["reason"] for d in discarded} == {"retries_exhausted"} + assert [(m["type"], m.get("reason")) for m in messages[-2:]] == [ + ("not_run", "retries_exhausted"), + ("done", None), + ] + assert host.ledger.spent("anthropic") == 0 # every 429 books zero From 142426c9509d23d46c3820c3e02b782ca3a1cb62 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Tue, 3 Nov 2026 22:58:21 +0100 Subject: [PATCH 08/77] feat(benchmarks): add agentic-run with a mocked end-to-end test run_agentic validates everything before any process starts (host keys, an empty --out, the corpus, supported families and systems, price entries and budget fields, the snapshot expiry for any live family), plans one seeded job per (model, system), runs them through keyless workers, and writes the existing artifact layout with one cell per repeat, so score and report read it unchanged. The run summary lists discarded and not-run cells with attempts, and per family the retries, reruns, answer turns, output-cap stops and wall time with retries and grant waits included. CLI: python -m benchmarks agentic-run; exit 3 on a key leak, 2 on any other validation error. The end-to-end test runs three scripted providers against the real python-docs server, a fake fetch server and no-docs, then scores and reports the run. Co-Authored-By: Claude Opus 5.5 --- benchmarks/__main__.py | 62 +++ benchmarks/agentic/loop.py | 7 +- benchmarks/agentic/run.py | 496 ++++++++++++++++++ benchmarks/agentic/worker.py | 9 +- .../fixtures/agentic/model-matrix.yml | 54 ++ tests/benchmarks/fixtures/agentic/prices.yml | 26 + tests/benchmarks/test_agentic_run.py | 396 ++++++++++++++ 7 files changed, 1046 insertions(+), 4 deletions(-) create mode 100644 benchmarks/agentic/run.py create mode 100644 tests/benchmarks/fixtures/agentic/model-matrix.yml create mode 100644 tests/benchmarks/fixtures/agentic/prices.yml create mode 100644 tests/benchmarks/test_agentic_run.py diff --git a/benchmarks/__main__.py b/benchmarks/__main__.py index 25b55c5a..d4c56b24 100644 --- a/benchmarks/__main__.py +++ b/benchmarks/__main__.py @@ -15,6 +15,12 @@ _DEFAULT_MODEL_MATRIX = Path("docs/benchmarks/model-matrix.yml") _DEFAULT_METHODOLOGY = Path("docs/benchmarks/PUBLIC-BENCHMARK-METHODOLOGY.md") _DEFAULT_CORPUS_SCHEMA = Path("docs/benchmarks/corpus.schema.json") +_DEFAULT_AGENTIC_MANIFEST = Path("docs/benchmarks/agentic-manifest.yml") +_DEFAULT_PRICES = Path("docs/benchmarks/price-snapshot.yml") + + +def _ids(value: str) -> tuple[str, ...]: + return tuple(item.strip() for item in value.split(",") if item.strip()) def _build_parser() -> argparse.ArgumentParser: @@ -153,6 +159,32 @@ def _build_parser() -> argparse.ArgumentParser: help=f"Path to the corpus JSON schema file (default: {_DEFAULT_CORPUS_SCHEMA}).", ) + agentic = subparsers.add_parser( + "agentic-run", + help="Run the agentic benchmark (docs/benchmarks/AGENTIC-BENCHMARK-DESIGN.md).", + ) + agentic.add_argument("--corpus", required=True, type=Path, help="Corpus YAML file.") + agentic.add_argument("--out", required=True, type=Path, help="Empty artifact directory.") + agentic.add_argument( + "--ledger-dir", required=True, type=Path, help="Persistent spend ledger directory." + ) + agentic.add_argument("--matrix", type=Path, default=_DEFAULT_MODEL_MATRIX) + agentic.add_argument("--manifest", type=Path, default=_DEFAULT_AGENTIC_MANIFEST) + agentic.add_argument("--prices", type=Path, default=_DEFAULT_PRICES) + for name in ("models", "systems", "questions"): + agentic.add_argument(f"--{name}", type=_ids, metavar="IDS", help="Comma-separated ids.") + 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.") + agentic.add_argument( + "--acknowledge-overrun", + action="append", + default=[], + metavar="PROVIDER", + help="Lift a provider's overrun stop after its bound was corrected.", + ) + # Spawned by the agentic host, never by hand: it reads its job as frames on stdin. subparsers.add_parser( "agentic-worker", help="Internal: run one agentic (model, system) job for the host." @@ -170,6 +202,36 @@ def main(argv: list[str] | None = None) -> int: return main_worker() + 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 + + config = agentic_run.AgenticConfig( + corpus_path=args.corpus, + matrix_path=args.matrix, + manifest_path=args.manifest, + prices_path=args.prices, + ledger_dir=args.ledger_dir, + out_dir=args.out, + models=args.models, + systems=args.systems, + questions=args.questions, + repeats=args.repeats, + seed=args.seed, + run_id=args.run_id, + dry_run=args.dry_run, + acknowledge_overrun=tuple(args.acknowledge_overrun), + ) + try: + summary = agentic_run.run_agentic(config) + 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)) + return 0 + if args.command == "run": config = BenchmarkConfig( corpus_path=args.corpus, diff --git a/benchmarks/agentic/loop.py b/benchmarks/agentic/loop.py index 64ee5c32..9f14bd52 100644 --- a/benchmarks/agentic/loop.py +++ b/benchmarks/agentic/loop.py @@ -19,6 +19,7 @@ from benchmarks.agentic.bridge import BridgeCrash, ToolBridge, truncate_utf8 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.schemas import schemas_sha256 from benchmarks.agentic.types import ( @@ -32,7 +33,7 @@ UserText, ) from benchmarks.model_matrix import ModelFamily -from benchmarks.runner import BenchmarkValidationError, _utc_now +from benchmarks.runner import BenchmarkValidationError @dataclass(frozen=True) @@ -165,7 +166,7 @@ def __init__( self.seconds: dict[str, float] = dict.fromkeys( ("used", "model", "tool", "grant_wait", "failed_attempt", "retry_wait"), 0.0 ) - self.started_at = _utc_now() + self.started_at = _utc_now_ms() self.started = time.perf_counter() def record(self, status: str, error: dict[str, str] | None, answer: str) -> dict[str, Any]: @@ -187,7 +188,7 @@ def record(self, status: str, error: dict[str, str] | None, answer: str) -> dict "overhead_ms": _ms(max(0.0, overhead)), }, "started_at": self.started_at, - "completed_at": _utc_now(), + "completed_at": _utc_now_ms(), } def discard( diff --git a/benchmarks/agentic/run.py b/benchmarks/agentic/run.py new file mode 100644 index 00000000..ffbb0829 --- /dev/null +++ b/benchmarks/agentic/run.py @@ -0,0 +1,496 @@ +"""Agentic run orchestration: plan, artifacts, run summary and ``run_agentic``. + +The run writes the fixed-flow artifact layout (``transcripts|tokens|latency| +scoring|failures//.json``), so ``score`` and ``report`` read it +unchanged. A cell is one repeat of one (system, model): ``----r`` +(owner ruling 7). Every JSON artifact is scanned for key-shaped strings first. +""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +import os +import random +from collections import Counter +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field, replace +from datetime import UTC, date, datetime +from decimal import Decimal +from importlib.metadata import version +from pathlib import Path +from typing import Any, Protocol + +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.host import Launcher, LocalLauncher, WorkerJob, refuse_host_keys, run_jobs +from benchmarks.agentic.ledger import ( + PROVIDER_CAPS, + Ledger, + LedgerService, + load_price_snapshot, + refuse_stale_snapshot, +) +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.worker import MAX_RERUNS +from benchmarks.model_matrix import METHODOLOGY_TOKEN_LABEL, ModelFamily, load_model_matrix +from benchmarks.runner import ( + BenchmarkCell, + BenchmarkValidationError, + Competitor, + Question, + _default_run_id, + _environment_metadata, + _load_questions, + _load_yaml_mapping, + _scoring_record, + _utc_now, + _write_json, + _write_snapshot, +) + +#: Answer-turn stop reasons that mean the output cap cut the answer; the pilot's 1% rule +#: reads their count. A Gemini CONTINUATION stop counts (owner ruling, round 3). +OUTPUT_CAP_STOPS = frozenset({"max_tokens", "max_output_tokens", "MAX_TOKENS", "CONTINUATION"}) + +_REPO_ROOT = Path(benchmarks.__file__).resolve().parent.parent +_CLIENT_PACKAGES = ("anthropic", "openai", "google-genai", "mcp") +_HOSTED_FIELDS = ( + "max_input_tokens", + "max_output_tokens", + "output_cap_includes_reasoning", + "framing_allowance_tokens", +) +_TIMING_SUMS = ("grant_wait", "failed_attempt", "retry_wait") + + +@dataclass(frozen=True) +class AgenticConfig: + corpus_path: Path + matrix_path: Path + manifest_path: Path + prices_path: Path + ledger_dir: Path + out_dir: Path + models: tuple[str, ...] | None = None # family ids; None = every family the launcher supports + systems: tuple[str, ...] | None = None + questions: tuple[str, ...] | None = None + repeats: int = 3 + seed: int | None = None # None = int(sha256(run_id)[:8], 16) + run_id: str | None = None + dry_run: bool = False + acknowledge_overrun: tuple[str, ...] = () + + +def cell_id(system_id: str, family_id: str, repeat: int) -> str: + return f"{system_id}--{family_id}--r{repeat}" + + +def tool_model_key(system_id: str, provider: str, model_id: str) -> str: + return f"{system_id}:{provider}/{model_id}" + + +def plan_jobs( + questions: Sequence[Question], + families: Sequence[ModelFamily], + systems: Sequence[SystemSpec], + *, + repeats: int, + seed: int, + matrix_dir: Path, +) -> list[WorkerJob]: + """One job per (family, system), its trajectories shuffled by a seed per job.""" + jobs: list[WorkerJob] = [] + for family in families: + if family.api == "scripted": + script = family.raw.get("script") + if not isinstance(script, str) or not script: + raise BenchmarkValidationError( + f"scripted model family {family.id!r} needs 'script'" + ) + # Absolute here, so the worker's make_client never depends on its cwd (ruling B9). + raw = {**family.raw, "script": str((matrix_dir / script).resolve())} + family = replace(family, raw=raw) + caps = AIR_GAPPED_CAPS if family.arm == "air-gapped" else HOSTED_CAPS + for system in systems: + order = [(q, r) for q in questions for r in range(1, repeats + 1)] + random.Random(f"{seed}/{family.id}/{system.id}").shuffle(order) + trajectories = tuple( + {"corpus_id": q.id, "prompt": q.prompt, "repeat": r} for q, r in order + ) + jobs.append(WorkerJob(f"{family.id}--{system.id}", family, system, trajectories, caps)) + 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) + + +def _client_versions() -> dict[str, str]: + return {name: version(name) for name in _CLIENT_PACKAGES} + + +class _HasId(Protocol): + @property + def id(self) -> str: ... + + +def _select[T: _HasId](items: Sequence[T], wanted: tuple[str, ...] | None, label: str) -> list[T]: + if wanted is None: + return list(items) + known = {item.id for item in items} + unknown = [w for w in wanted if w not in known] + if unknown: + raise BenchmarkValidationError(f"unknown {label} id(s): {unknown}") + return [item for item in items if item.id in wanted] + + +@dataclass +class _FamilyStats: + records: list[dict[str, Any]] = field(default_factory=list) + retries: Counter[str] = field(default_factory=Counter) + reruns: int = 0 + answer_turns: int = 0 + output_cap_stops: int = 0 + + def add(self, record: dict[str, Any]) -> None: + self.records.append(record) + for call in record["model_calls"]: + for attempt in call["attempts"][:-1]: # every attempt but the last was retried + self.retries[attempt["outcome"]] += 1 + + def summary(self) -> dict[str, Any]: + starts = [r["started_at"] for r in self.records] + ends = [r["completed_at"] for r in self.records] + first, last = (min(starts), max(ends)) if self.records else (None, None) + wall = ( + (datetime.fromisoformat(last) - datetime.fromisoformat(first)).total_seconds() + if first and last + else 0.0 + ) + sums = { + f"{name}_s": round(sum(r["timing"][f"{name}_ms"] for r in self.records) / 1000, 3) + for name in _TIMING_SUMS + } + return { + "retries": dict(self.retries), + "reruns": self.reruns, + "answer_turns": self.answer_turns, + "output_cap_stops": self.output_cap_stops, + "wall_s": round(wall, 3), + **sums, + "first_started_at": first, + "last_completed_at": last, + } + + +class _Collector: + """Turns worker messages into the run's artifacts and summary counts.""" + + def __init__( + self, out: Path, questions: Mapping[str, Question], families: Sequence[ModelFamily] + ): + self.out = out + self.questions = questions + self.families = {f.id: _FamilyStats() for f in families} + self.cells: set[str] = set() + self.succeeded = 0 + self.failed = 0 + self.discarded: list[dict[str, Any]] = [] + self.not_run: list[dict[str, Any]] = [] + + 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) + 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"] + if kind == "not_run": + self.not_run.append( + { + "cell": cell, + "corpus_id": corpus_id, + "reason": message["reason"], + "attempt": message.get("attempt"), + } + ) + return + record = message["record"] + stats = self.families[job.family.id] + stats.add(record) + if kind == "discarded": + reason, attempt = message["reason"], message["attempt"] + self.discarded.append( + {"cell": cell, "corpus_id": corpus_id, "reason": reason, "attempt": attempt} + ) + if reason == "retries_exhausted" and attempt <= MAX_RERUNS: + stats.reruns += 1 + path = self.out / "discarded" / cell / f"{corpus_id}--attempt{attempt}.json" + _write(path, {**record, **self._ident(job, cell, message), "reason": reason}) + return + self._write_cell(job, cell, message, record, stats) + + def _ident(self, job: WorkerJob, cell: str, message: dict[str, Any]) -> dict[str, Any]: + family, system = job.family, job.system + return { + "competitor_id": cell, + "corpus_id": message["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"), + "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") + 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}) + _write( + self.out / "scoring" / cell / f"{corpus_id}.json", + _scoring_record( + BenchmarkCell(Competitor(cell, "agentic", {}), question), + status=status, + tool_model_key=key, + error=error, + ), + ) + _write( + self.out / "tokens" / cell / f"{corpus_id}.json", + { + **base, + "token_label": METHODOLOGY_TOKEN_LABEL, + "input_characters": len(question.prompt), + "output_characters": len(record["answer"]), + "count_model": DEFAULT_COUNT_MODEL, + "anthropic_version": ANTHROPIC_API_VERSION, + "status": "placeholder", + "client_wrapped_tokens": None, + "raw_payload_tokens": None, + "approximation": False, + "notes": "counted after the run (design §8)", + }, + ) + _write( + self.out / "latency" / cell / f"{corpus_id}.json", + { + **base, + "status": status, + "error_category": None if error is None else error["category"], + "latency_ms": record["timing"]["wall_ms"], + "started_at": record["started_at"], + "completed_at": record["completed_at"], + "timing": record["timing"], + }, + ) + if status == "failed": + self.failed += 1 + _write( + self.out / "failures" / cell / f"{corpus_id}.json", + { + **base, + "status": "failed", + "error": error, + "included_in_correctness_denominator": True, + "correctness_score": 0.0, + }, + ) + else: + self.succeeded += 1 + stats.answer_turns += 1 + if record["model_calls"][-1]["stop_reason"] in OUTPUT_CAP_STOPS: + stats.output_cap_stops += 1 + self.cells.add(cell) + + +def run_agentic( + config: AgenticConfig, + *, + launcher: Launcher | None = None, + caps: Mapping[str, Decimal] = PROVIDER_CAPS, + today: date | None = None, +) -> dict[str, Any]: + """Validate everything, then run every planned trajectory; return the run summary.""" + refuse_host_keys(os.environ) + launcher = launcher or LocalLauncher() + out = config.out_dir + if out.exists() and any(out.iterdir()): + raise BenchmarkValidationError( + f"output directory is not empty: {out}; use a new, empty --out for each run" + ) + if config.repeats < 1: + raise BenchmarkValidationError("--repeats must be at least 1") + corpus = _load_questions(_load_yaml_mapping(config.corpus_path, "corpus")) + questions = _select(corpus, config.questions, "corpus question") + matrix = load_model_matrix(config.matrix_path).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)] + ) + if not families: + raise BenchmarkValidationError("no model family to run") + unsupported = [f.id for f in families if not launcher.supports(f)] + 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" + ) + systems = _select(load_systems(config.manifest_path), config.systems, "system") + snapshot = load_price_snapshot(config.prices_path) + for family in families: + if family.output_cap_includes_reasoning is False: + raise BenchmarkValidationError( + f"model family {family.id!r} sets output_cap_includes_reasoning: false; the " + "research note shows thinking inside the cap on every hosted model" + ) + if family.provider in caps: # metered + if family.model_id not in snapshot.models: + raise BenchmarkValidationError(f"no price snapshot entry for {family.model_id!r}") + missing = [name for name in _HOSTED_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): + refuse_stale_snapshot(snapshot, today=today or datetime.now(UTC).date()) + + run_id = config.run_id or _default_run_id() + seed = ( + config.seed + if config.seed is not None + else int(hashlib.sha256(run_id.encode("utf-8")).hexdigest()[:8], 16) + ) + jobs = plan_jobs( + questions, + families, + systems, + repeats=config.repeats, + seed=seed, + matrix_dir=config.matrix_path.parent, + ) + out.mkdir(parents=True, exist_ok=True) + snapshots = out / "snapshots" + _write_snapshot(config.corpus_path, snapshots / "corpus.yml") + _write_snapshot(config.manifest_path, snapshots / "competitor-manifest.yml") + _write_snapshot(config.matrix_path, snapshots / "model-matrix.yml") + _write_snapshot(config.prices_path, snapshots / "price-snapshot.yml") + (snapshots / "system-prompt.txt").write_text(SYSTEM_PROMPT, encoding="utf-8") + environment = { + **_environment_metadata(run_id=run_id, dry_run=config.dry_run), + "mode": "agentic", + "seed": seed, + "client_versions": _client_versions(), + } + _write(out / "environment.json", environment) + planned = [ + { + "cell": cell_id(job.system.id, job.family.id, t["repeat"]), + "competitor_id": cell_id(job.system.id, job.family.id, t["repeat"]), + "corpus_id": t["corpus_id"], + "system_id": job.system.id, + "model_family_id": job.family.id, + "repeat": t["repeat"], + } + for job in jobs + for t in job.trajectories + ] + _write(out / "planned-cells.json", {"cells": planned}) + summary: dict[str, Any] = { + "run_id": run_id, + "dry_run": config.dry_run, + "mode": "agentic", + "started_at": _utc_now(), + "corpus_path": str(config.corpus_path), + "manifest_path": str(config.manifest_path), + "artifact_root": str(out), + "repo_commit": environment["repo_commit"], + "seed": seed, + "repeats": config.repeats, + "models": [f.id for f in families], + "systems": [s.id for s in systems], + "corpus_ids": [q.id for q in questions], + "planned_cells": len(planned), + } + if config.dry_run: # never opens the ledger + return summary + + ledger = Ledger.open(config.ledger_dir, run_id=run_id, caps=caps) + try: + for provider in config.acknowledge_overrun: + ledger.acknowledge_overrun(provider) + overrun = sorted({f.provider for f in families if ledger.stopped(f.provider) == "overrun"}) + if overrun: + raise BenchmarkValidationError( + f"{overrun} stopped on a bound overrun: correct the bound, record the overrun, " + "then rerun with --acknowledge-overrun" + ) + spent_before = {provider: ledger.spent(provider) for provider in caps} + 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}) + collector = _Collector(out, {q.id: q for q in questions}, families) + asyncio.run( + run_jobs( + jobs, + launcher=launcher, + ledger=service, + on_message=collector.on_message, + log_dir=out / "logs", + cwd=_REPO_ROOT, + ) + ) + events = "".join(json.dumps(e, sort_keys=True) + "\n" for e in ledger.events(run_id)) + assert_no_key_shaped(events, where="ledger-events.jsonl") + (out / "ledger-events.jsonl").write_text(events, encoding="utf-8") + scored = collector.succeeded + collector.failed + summary |= { + "completed_at": _utc_now(), + "scored_cells": scored, + "correctness_denominator_cells": scored, + "succeeded_cells": collector.succeeded, + "failed_cells": collector.failed, + "failed_cells_included_in_correctness_denominator": True, + "competitors": sorted(collector.cells), + "discarded": collector.discarded, + "not_run": collector.not_run, + "families": {fid: stats.summary() for fid, stats in collector.families.items()}, + "ledger": { + provider: { + "spent_before": str(spent_before[provider]), + "spent_after": str(ledger.spent(provider)), + "cap": str(caps[provider]), + "stopped": ledger.stopped(provider), + } + for provider in caps + }, + "price_snapshot": { + "captured_on": snapshot.captured_on.isoformat(), + "expires_on": None + if snapshot.expires_on is None + else snapshot.expires_on.isoformat(), + }, + } + _write(out / "run-summary.json", summary) + return summary + finally: + ledger.close() diff --git a/benchmarks/agentic/worker.py b/benchmarks/agentic/worker.py index 7eee4cd4..61b19337 100644 --- a/benchmarks/agentic/worker.py +++ b/benchmarks/agentic/worker.py @@ -270,7 +270,14 @@ async def _run_job(channel: ProtocolChannel, reader: asyncio.StreamReader) -> in elif attempt <= MAX_RERUNS: queue.append((item, attempt + 1)) else: - channel.send({"type": "not_run", **ident, "reason": "retries_exhausted"}) + channel.send( + { + "type": "not_run", + **ident, + "reason": "retries_exhausted", + "attempt": attempt, + } + ) continue await host.request({"type": "trajectory", "record": record, **ident}) if bridge is not None and (record["error"] or {}).get("category") in _REOPEN_AFTER: diff --git a/tests/benchmarks/fixtures/agentic/model-matrix.yml b/tests/benchmarks/fixtures/agentic/model-matrix.yml new file mode 100644 index 00000000..761c56ed --- /dev/null +++ b/tests/benchmarks/fixtures/agentic/model-matrix.yml @@ -0,0 +1,54 @@ +# Scripted model families for the agentic end-to-end tests. One per hosted +# provider, so the ledger meters each provider exactly as a live run would. +# `script` is relative to this directory; plan_jobs makes it absolute. +schema_version: 1 +methodology_token_label: "Claude Tokens (Normalized Payload)" + +model_families: + - id: scripted-anthropic + provider: anthropic + model_id: scripted-1 + api: scripted + arm: hosted + client: scripted + script: script-anthropic.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-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/prices.yml b/tests/benchmarks/fixtures/agentic/prices.yml new file mode 100644 index 00000000..98488dce --- /dev/null +++ b/tests/benchmarks/fixtures/agentic/prices.yml @@ -0,0 +1,26 @@ +# Flat round prices for the scripted fixture models, so a test can compute the +# expected spend by hand: per call, 1,000 input tokens at $1 and 100 output +# tokens at $10 per million cost $0.002. No expiry: scripted runs are never live. +schema_version: 1 +currency: USD +unit: per_million_tokens +captured_on: "2026-10-31" +expires_on: null +source: tests/benchmarks/fixtures/agentic/prices.yml + +models: + - model_id: scripted-1 + provider: anthropic + source_url: https://example.invalid/scripted-fixture + tiers: + - {up_to_input_tokens: null, input: "1", cache_write: "1", cached_input: "0.1", output: "10"} + - model_id: scripted-2 + provider: openai + source_url: https://example.invalid/scripted-fixture + tiers: + - {up_to_input_tokens: null, input: "1", cache_write: "1", cached_input: "0.1", output: "10"} + - model_id: scripted-3 + provider: google + source_url: https://example.invalid/scripted-fixture + tiers: + - {up_to_input_tokens: null, input: "1", cache_write: "1", cached_input: "0.1", output: "10"} diff --git a/tests/benchmarks/test_agentic_run.py b/tests/benchmarks/test_agentic_run.py new file mode 100644 index 00000000..afd96a15 --- /dev/null +++ b/tests/benchmarks/test_agentic_run.py @@ -0,0 +1,396 @@ +"""agentic-run: plan, artifacts, run summary and the mocked end-to-end test (design §6-§12). + +Every model is scripted and every worker is keyless: no test reaches a network host. +""" + +from __future__ import annotations + +import hashlib +import json +import random +from datetime import date +from decimal import Decimal +from pathlib import Path +from typing import Any + +import pytest +import yaml + +from benchmarks.__main__ import main +from benchmarks.agentic.bridge import load_systems +from benchmarks.agentic.clients import PAID_KEY_ENVS +from benchmarks.agentic.host import LocalLauncher +from benchmarks.agentic.loop import MAX_RETRIES +from benchmarks.agentic.protocol import KEY_SHAPED, KeyLeakError +from benchmarks.agentic.run import ( + OUTPUT_CAP_STOPS, + AgenticConfig, + cell_id, + plan_jobs, + run_agentic, + tool_model_key, +) +from benchmarks.model_matrix import load_model_matrix +from benchmarks.report import generate_report +from benchmarks.runner import BenchmarkValidationError, _load_questions, _load_yaml_mapping +from benchmarks.scoring import score_run +from tests.test_mcp_get_docs_cache_smoke import _create_contentful_json_index +from tests.test_stdio_smoke import _isolated_cache_env + +REPO_ROOT = Path(__file__).resolve().parents[2] +FIX = Path(__file__).parent / "fixtures" / "agentic" +SAMPLE_CORPUS = Path(__file__).parent / "fixtures" / "corpus.sample.yml" +CORPUS_SCHEMA = REPO_ROOT / "docs" / "benchmarks" / "corpus.schema.json" +METHODOLOGY_PATH = REPO_ROOT / "docs" / "benchmarks" / "PUBLIC-BENCHMARK-METHODOLOGY.md" +COMMITTED_MATRIX = REPO_ROOT / "docs" / "benchmarks" / "model-matrix.yml" +COMMITTED_MANIFEST = REPO_ROOT / "docs" / "benchmarks" / "agentic-manifest.yml" +COMMITTED_PRICES = REPO_ROOT / "docs" / "benchmarks" / "price-snapshot.yml" +FAKE_SERVER = FIX / "fake_fetch_server.py" +# 3 systems x 2 questions x 2 repeats: python-docs and docs-fetch make 2 calls, no-docs 1, +# so 20 calls of 1,000 input tokens at $1/1M and 100 output tokens at $10/1M. +EXPECTED_ANTHROPIC_SPEND = Decimal("0.04") +EX1 = "fixture_symbol_ex_1()" # a phrase only SYN-EX-001's prompt holds +EX2 = "fixture_symbol_ex_2()" + + +@pytest.fixture(autouse=True) +def _keyless(monkeypatch: pytest.MonkeyPatch) -> None: + for name in PAID_KEY_ENVS: + monkeypatch.delenv(name, raising=False) + + +def _write_manifest(tmp_path: Path) -> Path: + committed = { + s.id: s.raw for s in load_systems(COMMITTED_MANIFEST) + } # python-docs and no-docs as committed + fetch = { + "id": "docs-fetch", + "adapter": "mcp-stdio", + "command": ["{python}", str(FAKE_SERVER)], + "env": {}, + "pass_env": ["HOME"], + } + path = tmp_path / "manifest.yml" + competitors = [committed["python-docs"], fetch, committed["no-docs"]] + path.write_text(yaml.safe_dump({"competitors": competitors}), encoding="utf-8") + return path + + +def _isolated_index(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + env, cache_dir = _isolated_cache_env(tmp_path) + _create_contentful_json_index(cache_dir) + monkeypatch.setenv("XDG_CACHE_HOME", env["XDG_CACHE_HOME"]) + monkeypatch.setenv("HOME", env["HOME"]) + return cache_dir + + +def _config(tmp_path: Path, **overrides: Any) -> AgenticConfig: + values: dict[str, Any] = { + "corpus_path": SAMPLE_CORPUS, + "matrix_path": FIX / "model-matrix.yml", + "manifest_path": COMMITTED_MANIFEST, + "prices_path": FIX / "prices.yml", + "ledger_dir": tmp_path / "ledger", + "out_dir": tmp_path / "run", + "questions": ("SYN-EX-001", "SYN-EX-002"), + "repeats": 2, + "seed": 7, + } + values.update(overrides) + return AgenticConfig(**values) + + +def _matrix_with(tmp_path: Path, scripts: dict[str, list[dict[str, Any]]], extra=()) -> Path: + """The fixture matrix with some families' scripts replaced, plus extra families.""" + data = yaml.safe_load((FIX / "model-matrix.yml").read_text(encoding="utf-8")) + families = data["model_families"] + [dict(f) for f in extra] + for family in families: + if family["id"] in scripts: + script = tmp_path / f"script-{family['id']}.yml" + script.write_text(yaml.safe_dump({"steps": scripts[family["id"]]}), encoding="utf-8") + family["script"] = str(script) + else: + family["script"] = str(FIX / family["script"]) + data["model_families"] = families + path = tmp_path / "matrix.yml" + path.write_text(yaml.safe_dump(data), encoding="utf-8") + return path + + +def test_agentic_run_end_to_end_with_scripted_models( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + cache_dir = _isolated_index(tmp_path, monkeypatch) + manifest = _write_manifest(tmp_path) + monkeypatch.chdir(tmp_path) # the relative script paths must not depend on the cwd + summary = run_agentic(_config(tmp_path, manifest_path=manifest)) + assert summary["planned_cells"] == 36 and summary["succeeded_cells"] == 36 + assert summary["failed_cells"] == 0 and summary["discarded"] == [] and summary["not_run"] == [] + assert summary["scored_cells"] == summary["correctness_denominator_cells"] == 36 + run = tmp_path / "run" + + def tools(system: str) -> list[str]: + path = run / "transcripts" / f"{system}--scripted-anthropic--r1" / "SYN-EX-001.json" + return [c["tool"] for c in json.loads(path.read_text())["tool_calls"]] + + assert (tools("python-docs"), tools("docs-fetch"), tools("no-docs")) == ( + ["search_docs"], + ["fetch"], + [], + ) + transcript = json.loads( + (run / "transcripts" / "no-docs--scripted-openai--r2" / "SYN-EX-002.json").read_text() + ) + assert transcript["tool_model_key"] == "no-docs:openai/scripted-2" + assert (transcript["competitor_id"], transcript["model_family_id"]) == ( + "no-docs--scripted-openai--r2", + "scripted-openai", + ) + info = json.loads((run / "systems" / "scripted-anthropic--python-docs.json").read_text()) + assert len(info["tools_raw"]) == 7 + assert info["index_sha256"] == hashlib.sha256((cache_dir / "index.db").read_bytes()).hexdigest() + assert Decimal(summary["ledger"]["anthropic"]["spent_after"]) == EXPECTED_ANTHROPIC_SPEND + assert Decimal(summary["ledger"]["anthropic"]["spent_before"]) == 0 + assert summary["price_snapshot"] == {"captured_on": "2026-10-31", "expires_on": None} + assert summary["mode"] == "agentic" and summary["seed"] == 7 and summary["repeats"] == 2 + env = json.loads((run / "environment.json").read_text()) + assert env["mode"] == "agentic" and set(env["client_versions"]) >= {"anthropic", "mcp"} + for name in ("corpus.yml", "competitor-manifest.yml", "model-matrix.yml"): + assert (run / "snapshots" / name).is_file() + assert (run / "snapshots" / "competitor-manifest.yml").read_bytes() == manifest.read_bytes() + assert (run / "snapshots" / "system-prompt.txt").read_text().startswith("You answer") + assert ( + len((run / "ledger-events.jsonl").read_text().splitlines()) == 3 * 2 * 20 + ) # reserve+settle + assert len(list((run / "logs").glob("*.stderr.log"))) == 9 + tokens = json.loads( + (run / "tokens" / "no-docs--scripted-openai--r2" / "SYN-EX-002.json").read_text() + ) + assert tokens["status"] == "placeholder" and tokens["count_model"] == "claude-sonnet-5-5" + assert score_run(run, corpus_path=SAMPLE_CORPUS, schema_path=CORPUS_SCHEMA)["total_cells"] == 36 + report = generate_report( + run, model_matrix_path=FIX / "model-matrix.yml", methodology_path=METHODOLOGY_PATH + ).read_text() + assert "scripted-1" in report + for path in run.rglob("*"): + if path.is_file(): + assert KEY_SHAPED.search(path.read_text(errors="replace")) is None + + +def test_plan_jobs_makes_script_paths_absolute_and_orders_each_job_by_seed( + tmp_path: Path, +) -> None: + corpus = _load_yaml_mapping(SAMPLE_CORPUS, "corpus") + questions = [q for q in _load_questions(corpus) if q.id in ("SYN-EX-001", "SYN-EX-002")] + families = load_model_matrix(FIX / "model-matrix.yml").model_families + systems = load_systems(COMMITTED_MANIFEST) + jobs = plan_jobs(questions, families, systems, repeats=2, seed=7, matrix_dir=FIX) + assert len(jobs) == 9 and all(Path(j.family.raw["script"]).is_absolute() for j in jobs) + assert jobs[0].job_id == "scripted-anthropic--python-docs" + for job in jobs: + canonical = [(q.id, r) for q in questions for r in (1, 2)] + random.Random(f"7/{job.family.id}/{job.system.id}").shuffle(canonical) + assert [(t["corpus_id"], t["repeat"]) for t in job.trajectories] == canonical + again = plan_jobs(questions, families, systems, repeats=2, seed=7, matrix_dir=FIX) + assert again == jobs + + +def test_cell_and_tool_model_keys() -> None: + assert cell_id("no-docs", "gpt-6.1-sol", 3) == "no-docs--gpt-6.1-sol--r3" + assert tool_model_key("no-docs", "openai", "gpt-6.1-sol") == "no-docs:openai/gpt-6.1-sol" + assert OUTPUT_CAP_STOPS == {"max_tokens", "max_output_tokens", "MAX_TOKENS", "CONTINUATION"} + + +def test_agentic_run_budget_stop_discards_and_lists_cells_not_run( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _isolated_index(tmp_path, monkeypatch) + manifest = _write_manifest(tmp_path) + caps = {"anthropic": Decimal("0"), "openai": Decimal(65), "google": Decimal(180)} + summary = run_agentic(_config(tmp_path, manifest_path=manifest), caps=caps) + run = tmp_path / "run" + assert len(summary["discarded"]) + len(summary["not_run"]) == 12 + assert {d["reason"] for d in summary["discarded"] + summary["not_run"]} == {"budget_stop"} + assert summary["succeeded_cells"] == 24 and summary["planned_cells"] == 36 + assert not any((run / "scoring").glob("*--scripted-anthropic--*")) + assert len(list((run / "discarded").rglob("*--attempt1.json"))) == len(summary["discarded"]) + assert summary["ledger"]["anthropic"]["stopped"] == "cap" + + +def test_a_live_run_refuses_an_expired_price_snapshot(tmp_path: Path) -> None: + class EveryFamily(LocalLauncher): + def supports(self, family: Any) -> bool: + return True + + def command(self, job: Any) -> Any: + raise AssertionError("no process may start") + + config = _config( + tmp_path, + matrix_path=COMMITTED_MATRIX, + prices_path=COMMITTED_PRICES, + models=("claude-sonnet-5-5",), + ) + with pytest.raises(BenchmarkValidationError, match="2026-12-31"): + run_agentic(config, launcher=EveryFamily(), today=date(2026, 12, 31)) + assert not (tmp_path / "ledger").exists() + + +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}} + script = [ + {**limited, "prompt_contains": EX1}, + {**answer, "prompt_contains": EX1}, + *([{**limited, "prompt_contains": EX2}] * 5), + ] + matrix = _matrix_with(tmp_path, {"scripted-anthropic": script}) + config = _config( + tmp_path, + matrix_path=matrix, + models=("scripted-anthropic",), + systems=("no-docs",), + repeats=1, + ) + summary = run_agentic(config) + fam = summary["families"]["scripted-anthropic"] + assert fam["retries"]["rate_limited"] == 1 + 3 * MAX_RETRIES and fam["reruns"] == 2 + assert [d["attempt"] for d in summary["discarded"]] == [1, 2, 3] + assert len(summary["not_run"]) == 1 and summary["not_run"][0]["reason"] == "retries_exhausted" + assert summary["not_run"][0]["cell"] == "no-docs--scripted-anthropic--r1" + assert summary["succeeded_cells"] == 1 and fam["answer_turns"] == 1 + + +def test_run_summary_wall_time_includes_failed_attempts_backoff_and_grant_waits( + tmp_path: Path, +) -> None: + # Two scripted families of provider anthropic, one no-docs job each, so their units contend + # for the grant. The error step holds the grant for 1.0 s (owner amendment on #184), then + # 0.3 s of backoff, then a 0.1 s answer. + script = [ + {"error": {"kind": "rate_limited", "status": 429, "retry_after_s": 0.3}, "delay_s": 1.0}, + {"text": "ok", "delay_s": 0.1, "usage": {"input_tokens": 1000, "output_tokens": 100}}, + ] + fixture = yaml.safe_load((FIX / "model-matrix.yml").read_text(encoding="utf-8")) + twin = {**fixture["model_families"][0], "id": "scripted-anthropic-b"} + matrix = _matrix_with( + tmp_path, {"scripted-anthropic": script, "scripted-anthropic-b": script}, extra=[twin] + ) + config = _config( + tmp_path, + matrix_path=matrix, + models=("scripted-anthropic", "scripted-anthropic-b"), + systems=("no-docs",), + questions=("SYN-EX-001",), + repeats=1, + ) + summary = run_agentic(config) + assert set(summary["families"]) == {"scripted-anthropic", "scripted-anthropic-b"} + for fam in summary["families"].values(): + assert fam["failed_attempt_s"] >= 0.2 and fam["retry_wait_s"] >= 0.3 + assert fam["wall_s"] >= 0.6 + assert fam["first_started_at"] < fam["last_completed_at"] + assert sum(f["grant_wait_s"] for f in summary["families"].values()) > 0 + + +def test_continuation_answers_count_as_output_cap_stops(tmp_path: Path) -> None: + # One scripted google family, no-docs, all 50 sample questions, repeats 2 = 100 answers. + usage = {"prompt_token_count": 1000, "candidates_token_count": 100} + script = [ + {"text": "partial", "stop_reason": "CONTINUATION", "prompt_contains": EX1, "usage": usage}, + {"text": "Scripted answer.", "usage": usage}, + ] + matrix = _matrix_with(tmp_path, {"scripted-google": script}) + config = _config( + tmp_path, + matrix_path=matrix, + models=("scripted-google",), + systems=("no-docs",), + questions=None, + repeats=2, + ) + summary = run_agentic(config) + fam = summary["families"]["scripted-google"] + assert (fam["output_cap_stops"], fam["answer_turns"]) == (2, 100) # 2% + + +def test_agentic_run_refuses_a_non_empty_out_dir(tmp_path: Path) -> None: + (tmp_path / "run").mkdir() + (tmp_path / "run" / "stale.json").write_text("{}") + with pytest.raises(BenchmarkValidationError, match="not empty"): + run_agentic(_config(tmp_path)) + + +def test_agentic_run_refuses_an_unknown_family_or_system(tmp_path: Path) -> None: + with pytest.raises(BenchmarkValidationError, match="no-such-model"): + run_agentic(_config(tmp_path, models=("no-such-model",))) + with pytest.raises(BenchmarkValidationError, match="context7"): + run_agentic(_config(tmp_path, systems=("context7",))) + + +def test_agentic_run_refuses_a_family_whose_cap_excludes_reasoning(tmp_path: Path) -> None: + fixture = yaml.safe_load((FIX / "model-matrix.yml").read_text(encoding="utf-8")) + odd = {**fixture["model_families"][0], "id": "no-reasoning-in-cap"} + odd["output_cap_includes_reasoning"] = False + matrix = _matrix_with(tmp_path, {}, extra=[odd]) + with pytest.raises(BenchmarkValidationError, match="output_cap_includes_reasoning"): + run_agentic(_config(tmp_path, matrix_path=matrix, models=("no-reasoning-in-cap",))) + + +def test_agentic_run_dry_run_writes_the_plan_without_a_ledger(tmp_path: Path) -> None: + summary = run_agentic(_config(tmp_path, dry_run=True)) + run = tmp_path / "run" + assert summary["dry_run"] is True and summary["planned_cells"] == 36 + planned = json.loads((run / "planned-cells.json").read_text())["cells"] + assert len(planned) == 36 + assert {"cell", "competitor_id", "corpus_id", "repeat", "system_id"} <= set(planned[0]) + assert (run / "environment.json").is_file() and (run / "snapshots" / "corpus.yml").is_file() + assert not (tmp_path / "ledger").exists() + assert not (run / "transcripts").exists() + + +def test_cli_agentic_run_exits_2_with_a_provider_key_set( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("OPENAI_API_KEY", "x-not-a-real-key") + with pytest.raises(SystemExit) as caught: + main(_cli_args(tmp_path)) + assert caught.value.code == 2 + + +def test_cli_agentic_run_exits_3_on_a_key_leak( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + def leak(*args: Any, **kwargs: Any) -> Any: + raise KeyLeakError("a key-shaped string was found in a test frame") + + monkeypatch.setattr("benchmarks.agentic.run.run_agentic", leak) + with pytest.raises(SystemExit) as caught: + main(_cli_args(tmp_path)) + assert caught.value.code == 3 + + +def test_cli_agentic_run_dry_run_prints_the_plan( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + assert main([*_cli_args(tmp_path), "--dry-run", "--repeats", "1", "--run-id", "cli"]) == 0 + printed = json.loads(capsys.readouterr().out) + assert printed["planned_cells"] == 18 and printed["run_id"] == "cli" + + +def _cli_args(tmp_path: Path) -> list[str]: + return [ + "agentic-run", + "--corpus", + str(SAMPLE_CORPUS), + "--out", + str(tmp_path / "run"), + "--ledger-dir", + str(tmp_path / "ledger"), + "--matrix", + str(FIX / "model-matrix.yml"), + "--prices", + str(FIX / "prices.yml"), + "--questions", + "SYN-EX-001,SYN-EX-002", + ] From b0df2236a09471ffec9e9f947da27025cff3fea7 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Tue, 3 Nov 2026 22:58:21 +0100 Subject: [PATCH 09/77] docs(plans): apply the #184 verification amendments to the harness plan Fable's round-3 wording fixes, carried into PR B by owner ruling: the wall-time test's error step holds the grant for 1.0 s; the scripted client keys its step counter by the Conversation object, never id(); ProtocolChannel.close() flushes stdout and stderr first; the reruns test uses 429 with retry_after_s 0 for both questions and test_backoff pins backoff_s(1, 0.0) == 0.0; OUTPUT_CAP_STOPS is defined once. Co-Authored-By: Claude Opus 5.5 --- .../2026-10-31-agentic-benchmark-harness.md | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/docs/plans/2026-10-31-agentic-benchmark-harness.md b/docs/plans/2026-10-31-agentic-benchmark-harness.md index c7672fc8..7b0bce3d 100644 --- a/docs/plans/2026-10-31-agentic-benchmark-harness.md +++ b/docs/plans/2026-10-31-agentic-benchmark-harness.md @@ -1184,8 +1184,10 @@ Scripted script (`family.raw["script"]`, a YAML path): Buckets come from the matching Task 3 function. `arguments` may be any YAML value and goes through `tool_arguments`. `"{prompt}"` in a string argument becomes the first user message. -- The client counts its calls per `Conversation` object (by `id(conv)`). - The n-th call plays the n-th step that applies. +- The client counts its calls per `Conversation` object, held strongly + (a dict keyed by the object itself), never by a bare `id(conv)`, which + CPython reuses once a conversation is freed. The n-th call plays the + n-th step that applies. - A `tools` step applies only when every tool it names is in `conv.tools`, so `no-docs` skips straight to the answer. An optional `delay_s` on any step sleeps first. @@ -1490,6 +1492,7 @@ def test_input_bounds() -> None: def test_backoff() -> None: assert [backoff_s(r, None) for r in (1, 2, 3, 4)] == [2, 4, 8, 16] assert backoff_s(1, 7.0) == 7.0 and backoff_s(1, 121.0) is None + assert backoff_s(1, 0.0) == 0.0 def test_system_prompt_follows_the_design() -> None: assert ("ground your answer in the official python documentation; if a documentation tool is " "available, use it before answering and cite the section url you relied on") in SYSTEM_PROMPT.lower() @@ -1628,9 +1631,10 @@ Worker rules: 1. Close the bridge, so the MCP server child exits and drops its copy of fd 2. 2. Send `done`. - 3. `ProtocolChannel.close()`: point fds 1 and 2 at `/dev/null`, close - the pipe's write end, and join the redactor thread with a 5 s - timeout, so every byte is drained before exit. + 3. `ProtocolChannel.close()`: flush `sys.stdout` and `sys.stderr`, + point fds 1 and 2 at `/dev/null`, close the pipe's write end, and + join the redactor thread with a 5 s timeout, so every byte is + drained before exit. The thread is a daemon, so a grandchild that still holds the pipe cannot keep the worker alive. Its bytes are dropped, never written @@ -1867,8 +1871,8 @@ Run rules: - `answer_turns`: the count of answer turns, one per trajectory that reached an answer; - `output_cap_stops`: the answer turns whose `stop_reason` is in - `OUTPUT_CAP_STOPS = {"max_tokens", "max_output_tokens", "MAX_TOKENS", - "CONTINUATION"}`. This is the count the pilot's 1% rule reads. + `OUTPUT_CAP_STOPS` (the code block above). This is the count the + pilot's 1% rule reads. - `wall_s`: from the first start to the last completion, with retries included (owner ruling 6); - `grant_wait_s`, `failed_attempt_s` and `retry_wait_s`: the sums of @@ -1956,16 +1960,18 @@ def test_a_live_run_refuses_an_expired_price_snapshot(tmp_path, monkeypatch) -> def test_run_summary_counts_retries_and_reruns(tmp_path, monkeypatch) -> None: # one scripted family, no-docs, two questions, repeats 1. The script for the first question: - # 429 (retry_after_s 0) then text. For the second: 429 on every call, so its trajectory is - # discarded three times, then not run. + # 429 (retry_after_s 0) then text. For the second: 429 (retry_after_s 0) on every call, so + # its trajectory is discarded three times, then not run. fam = summary["families"]["scripted-anthropic"] assert fam["retries"]["rate_limited"] == 1 + 3 * MAX_RETRIES and fam["reruns"] == 2 assert [d["attempt"] for d in summary["discarded"]] == [1, 2, 3] and len(summary["not_run"]) == 1 def test_run_summary_wall_time_includes_failed_attempts_backoff_and_grant_waits(tmp_path, monkeypatch) -> None: # a tmp matrix with two scripted families of provider anthropic, one no-docs job each, so - # their units contend for the grant. Each script: 429 with retry_after_s 0.3 and delay_s 0.2 - # (a 0.2 s failed attempt, then 0.3 s of backoff), then text with delay_s 0.1. + # their units contend for the grant. Each script: 429 with retry_after_s 0.3 and delay_s 1.0 + # (a 1.0 s failed attempt that holds the provider's grant, so the other job's grant wait does + # not depend on how fast two processes spawn; then 0.3 s of backoff), then text with + # delay_s 0.1. for fam in summary["families"].values(): assert fam["failed_attempt_s"] >= 0.2 and fam["retry_wait_s"] >= 0.3 assert fam["wall_s"] >= 0.6 From 5dced0aa12cbf58c153e8951d7be5e0167409a40 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Tue, 3 Nov 2026 23:06:10 +0100 Subject: [PATCH 10/77] refactor(benchmarks): remove the fixed-flow adapters replaced by the agentic bridge MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Design §11.1: once the bridge covers python-docs and docs-fetch, the five fixed-flow adapters, the provider base and the OpenAI and Google stubs go, with their tests. The runner keeps only the fake adapter; the guard loses LiveExecutionNotImplementedError. The competitor eligibility gates, the require_live_competitor latch and their tests stay: those tests move from test_competitor_adapters.py to test_competitor_eligibility.py unchanged. CHANGELOG records the harness, the SDK pins, the removals and the pyasn1 security lock. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 18 + benchmarks/adapters/__init__.py | 62 +- benchmarks/adapters/base.py | 110 -- benchmarks/adapters/claude_tokens.py | 17 +- benchmarks/adapters/context7_adapter.py | 333 ----- benchmarks/adapters/deepwiki_adapter.py | 201 --- benchmarks/adapters/eligibility.py | 11 +- benchmarks/adapters/gitmcp_adapter.py | 263 ---- benchmarks/adapters/google_adapter.py | 78 - benchmarks/adapters/guard.py | 55 +- benchmarks/adapters/openai_adapter.py | 78 - .../adapters/python_docs_mcp_adapter.py | 259 ---- benchmarks/adapters/ref_tools_adapter.py | 274 ---- benchmarks/runner.py | 208 +-- .../competitor-manifest.template.yml | 13 +- tests/benchmarks/test_adapters.py | 146 +- tests/benchmarks/test_claude_tokens.py | 4 +- tests/benchmarks/test_competitor_adapters.py | 1287 ----------------- .../benchmarks/test_competitor_eligibility.py | 381 +++++ .../test_python_docs_mcp_adapter.py | 379 ----- tests/benchmarks/test_runner.py | 98 -- 21 files changed, 467 insertions(+), 3808 deletions(-) delete mode 100644 benchmarks/adapters/base.py delete mode 100644 benchmarks/adapters/context7_adapter.py delete mode 100644 benchmarks/adapters/deepwiki_adapter.py delete mode 100644 benchmarks/adapters/gitmcp_adapter.py delete mode 100644 benchmarks/adapters/google_adapter.py delete mode 100644 benchmarks/adapters/openai_adapter.py delete mode 100644 benchmarks/adapters/python_docs_mcp_adapter.py delete mode 100644 benchmarks/adapters/ref_tools_adapter.py delete mode 100644 tests/benchmarks/test_competitor_adapters.py create mode 100644 tests/benchmarks/test_competitor_eligibility.py delete mode 100644 tests/benchmarks/test_python_docs_mcp_adapter.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 011c1834..301b1ece 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,15 @@ this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm ## [Unreleased] +### Added + +- Agentic benchmark harness (development tooling, not part of the package): + `python -m benchmarks agentic-run` runs real models in a tool loop over the + systems under test, with a per-provider spend ledger and keyless, redacted + 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. + ### Changed - The benchmark harness (development tooling, not part of the package) now @@ -21,6 +30,10 @@ this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm - Benchmark harness: the `no-mcp-baseline` adapter alias, which only echoed the prompt, and the `external_provider_calls` field, a constant rather than a measurement. +- Benchmark harness: the five fixed-flow adapters (python-docs, Context7, + GitMCP, DeepWiki, Ref.tools) and the OpenAI and Google provider stubs. The + agentic harness's MCP bridge and SDK clients replace them; the competitor + eligibility gates stay. ### Security @@ -31,6 +44,11 @@ this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm GHSA-955g-x97g-8mcp). Platformdirs 4.14.0 fixes six low-severity advisories in its site and runtime directories; the server uses only the user cache directory, which still honours `XDG_CACHE_HOME` on macOS. +- Development lock: `pyasn1` 0.6.5, pulled in by `google-genai`, is locked + although it is younger than the 14-day rule allows. It fixes four + high-severity denial-of-service advisories that affect 0.6.4 + (GHSA-fm9c-5rcf-2q5p, GHSA-9m75-vc3g-4x39, GHSA-2qm8-x737-gmw5, + GHSA-mm57-4v3p-rchx). - The MCP servers that the benchmark harness starts now get the MCP SDK's default variables plus only: `CONTEXT7_API_KEY` for the Context7 server (npm code), and only in key mode; `PYTHON_DOCS_MCP_DISABLE_AUTO_INDEX` and, when diff --git a/benchmarks/adapters/__init__.py b/benchmarks/adapters/__init__.py index 214118be..90b5a2d9 100644 --- a/benchmarks/adapters/__init__.py +++ b/benchmarks/adapters/__init__.py @@ -1,34 +1,24 @@ -"""Provider adapter interfaces for the v0.5.0 public benchmark (issue #73). +"""Benchmark guards, token counting and competitor eligibility. -Mocked plumbing only: no OpenAI/Google adapter in this package ever -performs network I/O. See ``benchmarks/adapters/base.py`` for the shared -request/response contract, ``benchmarks/adapters/guard.py`` for the -live-provider refusal guardrail, and -``benchmarks/adapters/openai_adapter.py`` / ``google_adapter.py`` for the -mock and guarded live-stub implementations. +``benchmarks/adapters/guard.py`` is the live-provider refusal guardrail +that every live call passes first, including the agentic harness's client +factory (``benchmarks.agentic.clients.make_client``). -``benchmarks/adapters/claude_tokens.py`` (issue #89) is the one exception: -its ``LiveClaudeTokenCounter`` does perform a real, guarded HTTP call to the -Anthropic count-tokens API, confined to the maintainer-run live phase (see -that module's docstring). +``benchmarks/adapters/claude_tokens.py`` (issue #89) performs a real, +guarded HTTP call to the Anthropic count-tokens API, confined to the +maintainer-run live phase (see that module's docstring). -``context7_adapter.py`` / ``gitmcp_adapter.py`` / ``deepwiki_adapter.py`` / -``ref_tools_adapter.py`` (issue #87) are the competitor docs-MCP adapters: -like ``python_docs_mcp_adapter.py`` (issue #86), these model a retrieval -tool call rather than an LLM provider call, so none of them subclass -``ProviderAdapter``. ``eligibility.py`` (issue #87) is the manifest-load-time -eligibility screener that keeps ineligible/excluded competitors out of -scored cells entirely (see that module's docstring). +``eligibility.py`` (issue #87) is the manifest-load-time eligibility +screener that keeps ineligible/excluded competitors out of scored cells +entirely (see that module's docstring). + +The fixed-flow retrieval adapters and the OpenAI/Google provider stubs are +gone: the agentic harness (``benchmarks.agentic``) replaces them with one +MCP bridge for every system and real, guarded SDK clients (design §11.1). """ from __future__ import annotations -from benchmarks.adapters.base import ( - AdapterRequest, - AdapterResponse, - ProviderAdapter, - TokenMetadata, -) from benchmarks.adapters.claude_tokens import ( FakeTokenCounter, LiveClaudeTokenCounter, @@ -37,53 +27,29 @@ build_client_wrapped_envelope, count_cell_tokens, ) -from benchmarks.adapters.context7_adapter import Context7Adapter, Context7Result -from benchmarks.adapters.deepwiki_adapter import DeepWikiAdapter, DeepWikiResult from benchmarks.adapters.eligibility import ( COMPETITOR_ADAPTER_IDS, validate_competitor_eligibility, validate_manifest_eligibility, ) -from benchmarks.adapters.gitmcp_adapter import GitMcpAdapter, GitMcpResult -from benchmarks.adapters.google_adapter import LiveGoogleAdapter, MockGoogleAdapter from benchmarks.adapters.guard import ( - LiveExecutionNotImplementedError, LiveProviderDisabledError, require_live_competitor, require_live_environment, ) -from benchmarks.adapters.openai_adapter import LiveOpenAIAdapter, MockOpenAIAdapter -from benchmarks.adapters.ref_tools_adapter import RefToolsAdapter, RefToolsResult from benchmarks.runner import BenchmarkCellFailure __all__ = [ - "AdapterRequest", - "AdapterResponse", - "ProviderAdapter", - "TokenMetadata", "BenchmarkCellFailure", - "LiveExecutionNotImplementedError", "LiveProviderDisabledError", "require_live_environment", "require_live_competitor", - "MockOpenAIAdapter", - "LiveOpenAIAdapter", - "MockGoogleAdapter", - "LiveGoogleAdapter", "TokenCounter", "FakeTokenCounter", "LiveClaudeTokenCounter", "TokenCountResult", "build_client_wrapped_envelope", "count_cell_tokens", - "Context7Adapter", - "Context7Result", - "GitMcpAdapter", - "GitMcpResult", - "DeepWikiAdapter", - "DeepWikiResult", - "RefToolsAdapter", - "RefToolsResult", "COMPETITOR_ADAPTER_IDS", "validate_competitor_eligibility", "validate_manifest_eligibility", diff --git a/benchmarks/adapters/base.py b/benchmarks/adapters/base.py deleted file mode 100644 index 53100e81..00000000 --- a/benchmarks/adapters/base.py +++ /dev/null @@ -1,110 +0,0 @@ -"""Provider adapter interface contracts. - -Defines the request/response/latency/token-metadata/failure-capture shape -that every provider adapter (mock or, eventually, live) must implement for -issue #73. See ``benchmarks/adapters/guard.py`` for the live-provider -refusal guardrail and ``benchmarks/adapters/openai_adapter.py`` / -``google_adapter.py`` for the mock and live-stub implementations. - -Failure capture reuses ``benchmarks.runner.BenchmarkCellFailure`` directly -(same ``category`` vocabulary: ``tool_failure`` | ``timeout`` | -``mcp_protocol_crash``) so a future runner integration can catch adapter -failures with the exact except clause the runner already uses for -``_execute_cell``. -""" - -from __future__ import annotations - -import time -from abc import ABC, abstractmethod -from dataclasses import dataclass -from typing import Any - -from benchmarks.runner import BenchmarkCellFailure - -__all__ = [ - "AdapterRequest", - "TokenMetadata", - "AdapterResponse", - "ProviderAdapter", - "BenchmarkCellFailure", -] - - -@dataclass(frozen=True) -class AdapterRequest: - """Input to a provider adapter for one benchmark cell.""" - - model_family_id: str - """Matches a ``docs/benchmarks/model-matrix.yml`` entry ``id``.""" - - model_id: str - """The provider's own model identifier, e.g. ``gpt-4o-mini``.""" - - prompt: str - """The corpus question prompt, unmodified (see benchmark methodology's - "Prompting Rules": every system under test receives the same question).""" - - -@dataclass(frozen=True) -class TokenMetadata: - """Token metadata captured from one adapter call. - - ``provider_native_tokens`` is that provider's own billing/usage token - count (e.g. OpenAI ``usage.total_tokens``, Google - ``usage_metadata.total_token_count``). It is diagnostic data only and - must never be reported under the - ``benchmarks.model_matrix.METHODOLOGY_TOKEN_LABEL`` label -- that label - is reserved for the methodology tokenizer's cross-model count, which - this package does not compute (real Claude token counting is confined to - the maintainer-run live phase per PLAN.md Amendment 2026-07-08). - """ - - provider_native_tokens: int | None - provider_token_field: str - - -@dataclass(frozen=True) -class AdapterResponse: - """Structured output from a provider adapter call.""" - - answer: str - latency_ms: float - tokens: TokenMetadata - raw: dict[str, Any] - """Raw, mock-safe provider payload metadata kept for audit/debugging.""" - - -class ProviderAdapter(ABC): - """Base class for a provider adapter. - - Subclasses implement :meth:`_generate` with the provider-specific - behavior (mock or live-stub); this base class provides the shared - latency measurement and generic failure-capture wrapping so every - adapter reports latency and failures the same way. - """ - - provider: str - - def generate(self, request: AdapterRequest) -> AdapterResponse: - """Run one adapter call and return a structured response. - - Any exception raised by :meth:`_generate` other than - ``BenchmarkCellFailure`` is wrapped as a ``BenchmarkCellFailure`` - with category ``tool_failure`` so callers only ever need to catch - one exception type for failure capture. - """ - started = time.perf_counter() - try: - answer, tokens, raw = self._generate(request) - except BenchmarkCellFailure: - raise - except Exception as exc: # noqa: BLE001 - failures are benchmark artifacts - raise BenchmarkCellFailure("tool_failure", str(exc)) from exc - latency_ms = round((time.perf_counter() - started) * 1000, 3) - return AdapterResponse(answer=answer, latency_ms=latency_ms, tokens=tokens, raw=raw) - - @abstractmethod - def _generate(self, request: AdapterRequest) -> tuple[str, TokenMetadata, dict[str, Any]]: - """Provider-specific call. Must not perform any network I/O in mock mode.""" - raise NotImplementedError diff --git a/benchmarks/adapters/claude_tokens.py b/benchmarks/adapters/claude_tokens.py index 64b4532f..a10b71af 100644 --- a/benchmarks/adapters/claude_tokens.py +++ b/benchmarks/adapters/claude_tokens.py @@ -26,10 +26,9 @@ The fixed-flow envelope carries the corpus prompt and the recorded tool calls, but no real client's tool definitions or system prompt; with tool calls it sends name-only tool stubs, so the count includes the API's -tool-use preamble. A provider-adapter mock/live-stub payload -(``MockOpenAIAdapter`` / ``MockGoogleAdapter`` and their live-stub -counterparts) wraps the prompt alone, since no real client SDK call was -made. Exact post-run counting of a real client's request is the new +tool-use preamble. A provider mock payload (one marked ``"mock": True``) +wraps the prompt alone, since no real client SDK call was made. Exact +post-run counting of a real client's request is the new harness's job (design §8), not this module's. """ @@ -232,12 +231,10 @@ def build_client_wrapped_envelope( prompt, one assistant message of ``tool_use`` blocks, and one user message of only the matching ``tool_result`` blocks. - ``provider_mock_payload`` is the raw payload from a provider-adapter - mock/live-stub (``benchmarks.adapters.base.AdapterResponse.raw`` for - ``MockOpenAIAdapter`` / ``MockGoogleAdapter`` and their live-stub - counterparts, identifiable by their ``"mock": True`` marker). Those - adapters never call a real client SDK, so there is no real wrapped - request body to recover; this function then wraps only the prompt text. + ``provider_mock_payload`` is a provider mock's raw payload, identifiable + by its ``"mock": True`` marker. A mock never calls a real client SDK, so + there is no real wrapped request body to recover; this function then + wraps only the prompt text. Returns ``(envelope, approximation)``; ``approximation`` is always ``True`` (see the module docstring, "Envelope exactness"). diff --git a/benchmarks/adapters/context7_adapter.py b/benchmarks/adapters/context7_adapter.py deleted file mode 100644 index 64c0a138..00000000 --- a/benchmarks/adapters/context7_adapter.py +++ /dev/null @@ -1,333 +0,0 @@ -"""Competitor MCP adapter: Context7 (Upstash) -- issue #87. - -Runs Context7's own MCP server as a benchmark system under test and issues -its documented retrieval flow (``resolve-library-id`` -> ``query-docs``) for -one corpus question. - -Like ``benchmarks.adapters.python_docs_mcp_adapter.PythonDocsMcpAdapter`` -(issue #86, the proven template this module mirrors), this adapter is -intentionally **not** a ``benchmarks.adapters.base.ProviderAdapter`` -subclass: that contract models an LLM provider call, not a documentation -retrieval tool call. - -Pin (PLAN-87-competitor-adapters.md section 1.1, live-probed 2026-07-09): -npm ``@upstash/context7-mcp@3.2.3``, run as a local stdio subprocess via -``npx -y @upstash/context7-mcp@3.2.3`` -- the default and strongest-pinned -mode. A remote streamable-HTTP fallback (``https://mcp.context7.com/mcp``) -also exists and is selectable via ``mode="http"``; the hosted doc index -behind either mode is itself unpinnable, so the effective pin is always -"client 3.2.3 + run date" regardless of mode. - -Terms (PLAN-87 section 1.1): Upstash ToS section C.8 forbids benchmarking -without express permission; the maintainer confirmed (assumption A1) -building this adapter now, with live inclusion/publication deferred to a -separate permission decision. Nothing in this module or its tests performs -a live call -- see :func:`benchmarks.adapters.guard.require_live_environment` -/ :func:`benchmarks.adapters.guard.require_live_competitor`, called as the -first statement of :meth:`Context7Adapter.run`. - -Auth (optional): ``CONTEXT7_API_KEY`` raises Context7's free-tier rate -limit; keyless use is real but more rate-limited. A manifest entry that -declares key mode (``key_mode=True``) is gated by -``require_live_environment("context7")`` (same shape as every keyed -provider); a keyless entry is gated by -``require_live_competitor("context7")`` (PLAN-87 section 2.2). The key is -read only in key mode. Neither mode forwards proxy or ``npm_config_*`` -variables to ``npx`` any more; pass them explicitly if a run needs them. -""" - -from __future__ import annotations - -import asyncio -import os -from dataclasses import dataclass -from typing import Any, Protocol - -from benchmarks.adapters.guard import require_live_competitor, require_live_environment -from benchmarks.runner import BenchmarkCellFailure, cell_failure_from -from benchmarks.urls import labeled_value - -#: Pinned npm package + version (PLAN-87 section 1.1). Never reference the -#: unrelated/stale ``mcp/context7`` Docker image -- 13 months stale per the -#: dossier, explicitly rejected. -PINNED_PACKAGE = "@upstash/context7-mcp@3.2.3" - -#: Remote streamable-HTTP fallback endpoint. -DEFAULT_ENDPOINT = "https://mcp.context7.com/mcp" - -#: Environment variable read for the optional API key (also the guard's -#: registered key env for provider id "context7" -- see -#: ``benchmarks.adapters.guard.PROVIDER_API_KEY_ENV``). -API_KEY_ENV = "CONTEXT7_API_KEY" - -DEFAULT_TIMEOUT_SECONDS = 30.0 - - -@dataclass(frozen=True) -class ToolCallRecord: - """One raw MCP tool call/response pair, recorded verbatim for audit.""" - - tool: str - arguments: dict[str, Any] - result: dict[str, Any] | None - is_error: bool - - -@dataclass(frozen=True) -class Context7Result: - """Structured output of one resolve-library-id -> query-docs cell run.""" - - answer: str - tool_calls: list[ToolCallRecord] - - -class _CallToolResult(Protocol): - """Structural subset of ``mcp.types.CallToolResult`` this module needs.""" - - content: list[Any] - structured_content: dict[str, Any] | None - is_error: bool - - -class _CallToolSession(Protocol): - """Structural subset of ``mcp.ClientSession`` this module needs.""" - - async def call_tool( - self, name: str, arguments: dict[str, Any] | None = None - ) -> _CallToolResult: - """Invoke one MCP tool by name and return its raw call result.""" - raise NotImplementedError - - -def _default_command() -> list[str]: - return ["npx", "-y", PINNED_PACKAGE] - - -def _first_text(result: _CallToolResult) -> str | None: - for block in result.content: - text = getattr(block, "text", None) - if isinstance(text, str): - return text - return None - - -def _tool_result_payload(result: _CallToolResult) -> dict[str, Any] | None: - if result.structured_content is not None: - return result.structured_content - text = _first_text(result) - return {"text": text} if text is not None else None - - -def _extract_library_id(result: _CallToolResult) -> str | None: - """Pick the top library id out of a ``resolve-library-id`` result. - - Prefers a structured candidate list under any of a few plausible keys. - Otherwise it reads only the labeled ``- Context7-compatible library ID: - `` line of the first text block. That line is the pinned 3.2.3 - format (``utils.ts#L24-L30``): - https://github.com/upstash/context7/blob/98baa58d3625e2529e000f1c9f658fff25081bbb/packages/mcp/src/lib/utils.ts#L24-L30 - There is no ``/org/project`` fallback: it matched - ``/context7.com/dashboard`` in the team-filter note printed before the - list. HTTP mode's hosted output is not pinned to 3.2.3. If the format - drifts, this returns ``None``, the answer is empty and ``score`` - auto-scores the cell 0.0. Returns ``None`` (never raises) when nothing - yields a candidate, matching the "no hits" honest-empty-answer behavior - of ``benchmarks.adapters.python_docs_mcp_adapter``. - """ - payload = _tool_result_payload(result) - if isinstance(payload, dict): - candidates = payload.get("results") or payload.get("libraries") or payload.get("hits") - if isinstance(candidates, list) and candidates: - first = candidates[0] - if isinstance(first, dict): - library_id = ( - first.get("id") or first.get("libraryId") or first.get("library_id") - ) - if isinstance(library_id, str) and library_id: - return library_id - text = _first_text(result) - return labeled_value(text, "- Context7-compatible library ID") if text else None - - -async def _run_context7_flow( - session: _CallToolSession, - prompt: str, - *, - library_name: str = "Python", -) -> Context7Result: - """Run the documented resolve-library-id -> query-docs flow for one prompt. - - Pure orchestration against a duck-typed ``session`` so it can be unit - tested with a scripted double -- no real transport required. Raises - ``BenchmarkCellFailure`` (category ``tool_failure``) when either tool - call itself reports an error. - """ - tool_calls: list[ToolCallRecord] = [] - - resolve_args: dict[str, Any] = {"libraryName": library_name, "query": prompt} - resolve_result = await session.call_tool("resolve-library-id", resolve_args) - resolve_payload = _tool_result_payload(resolve_result) - tool_calls.append( - ToolCallRecord( - tool="resolve-library-id", - arguments=resolve_args, - result=resolve_payload, - is_error=bool(resolve_result.is_error), - ) - ) - if resolve_result.is_error: - raise BenchmarkCellFailure( - "tool_failure", - f"resolve-library-id returned an error: {_first_text(resolve_result)}", - ) - - library_id = _extract_library_id(resolve_result) - if not library_id: - return Context7Result(answer="", tool_calls=tool_calls) - - query_args: dict[str, Any] = {"libraryId": library_id, "query": prompt} - query_result = await session.call_tool("query-docs", query_args) - query_payload = _tool_result_payload(query_result) - tool_calls.append( - ToolCallRecord( - tool="query-docs", - arguments=query_args, - result=query_payload, - is_error=bool(query_result.is_error), - ) - ) - if query_result.is_error: - raise BenchmarkCellFailure( - "tool_failure", f"query-docs returned an error: {_first_text(query_result)}" - ) - - answer = _first_text(query_result) - if answer is None: - payload = query_payload or {} - answer = str(payload.get("text", "") or payload.get("content", "")) - return Context7Result(answer=answer, tool_calls=tool_calls) - - -def _transport_factory( - *, - mode: str, - command: list[str] | None = None, - endpoint: str | None = None, - headers: dict[str, str] | None = None, - env: dict[str, str] | None = None, -) -> Any: - """Single owned seam for all transport construction (stdio or HTTP). - - Imported lazily inside this function body (not at module scope) so - importing ``context7_adapter`` never requires the ``mcp`` client - submodules unless an actual run is attempted -- same guarantee as - ``python_docs_mcp_adapter``. Tests patch this one symbol (plus - ``subprocess``/``socket.socket`` as defense-in-depth for the stdio - path) to prove fail-closed guard behavior without any transport ever - being constructed. - """ - if mode == "stdio": - from mcp import StdioServerParameters - from mcp.client.stdio import stdio_client - - assert command # narrows for type-checkers; ctor always sets a default - params = StdioServerParameters(command=command[0], args=list(command[1:]), env=env) - return stdio_client(params) - - import httpx2 - from mcp.client.streamable_http import streamable_http_client - - # Built directly, with the timeouts the MCP SDK v2 migration guide - # suggests for keeping v1 behavior (30s, 300s read). The v2 transport - # follows same-origin redirects itself. ``timeout_seconds`` on the - # adapter is not wired into this client; it is enforced only by the - # outer ``asyncio.wait_for`` in ``_run_async``. - http_client = ( - httpx2.AsyncClient(headers=headers, timeout=httpx2.Timeout(30, read=300)) - if headers - else None - ) - assert endpoint - return streamable_http_client(endpoint, http_client=http_client) - - -class Context7Adapter: - """Adapter for Context7's MCP server: resolve-library-id -> query-docs. - - ``run()`` is the synchronous entry point the benchmark runner's - dispatch registry calls per cell (see - ``benchmarks.runner._context7_answer``). - """ - - def __init__( - self, - *, - mode: str = "stdio", - command: list[str] | None = None, - endpoint: str | None = None, - key_mode: bool = False, - api_key: str | None = None, - library_name: str = "Python", - timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS, - ) -> None: - if mode not in {"stdio", "http"}: - raise ValueError(f"Context7Adapter mode must be 'stdio' or 'http', got {mode!r}") - self._mode = mode - self._command = command if command is not None else _default_command() - self._endpoint = endpoint if endpoint is not None else DEFAULT_ENDPOINT - self._key_mode = key_mode - self._api_key = ( - (api_key if api_key is not None else os.environ.get(API_KEY_ENV)) if key_mode else None - ) - self._library_name = library_name - self._timeout_seconds = timeout_seconds - - def run(self, prompt: str) -> Context7Result: - """Run one resolve-library-id -> query-docs cell. - - The applicable live-competitor guard is the FIRST statement here, - before any subprocess spawn or transport construction: key mode - goes through ``require_live_environment("context7")`` (same shape - as every keyed provider); keyless mode goes through - ``require_live_competitor("context7")`` (PLAN-87 section 2.2). - - Raises ``BenchmarkCellFailure`` with category ``tool_failure`` - (guard refusal or a tool-level error), ``timeout``, or - ``mcp_protocol_crash`` -- never a bare exception. - """ - if self._key_mode: - require_live_environment("context7") - else: - require_live_competitor("context7") - try: - return asyncio.run(asyncio.wait_for(self._run_async(prompt), self._timeout_seconds)) - except Exception as exc: # noqa: BLE001 - failures are benchmark artifacts - raise cell_failure_from( - exc, - timeout_seconds=self._timeout_seconds, - label="Context7 resolve-library-id -> query-docs", - ) from exc - - async def _run_async(self, prompt: str) -> Context7Result: - # Imported lazily so importing this module never requires the `mcp` - # client submodules unless an actual run is attempted. - from mcp import ClientSession - - if self._mode == "stdio": - # The pinned npm client also accepts CONTEXT7_API_KEY via - # environment (in addition to the remote HTTP mode's header - # below), so the key -- when present -- is passed through the - # subprocess environment rather than dropped for this mode. The - # SDK merges this dict over its safe defaults (PATH, HOME, ...), - # which npx needs; nothing else from this process is forwarded. - env = {API_KEY_ENV: self._api_key} if self._api_key else None - transport = _transport_factory(mode="stdio", command=self._command, env=env) - else: - headers = {API_KEY_ENV: self._api_key} if self._api_key else None - transport = _transport_factory(mode="http", endpoint=self._endpoint, headers=headers) - - async with transport as streams: - read, write = streams[0], streams[1] - async with ClientSession(read, write) as session: - await session.initialize() - return await _run_context7_flow(session, prompt, library_name=self._library_name) diff --git a/benchmarks/adapters/deepwiki_adapter.py b/benchmarks/adapters/deepwiki_adapter.py deleted file mode 100644 index ba46da81..00000000 --- a/benchmarks/adapters/deepwiki_adapter.py +++ /dev/null @@ -1,201 +0,0 @@ -"""Competitor MCP adapter: DeepWiki (Cognition) -- issue #87. - -Runs DeepWiki's hosted MCP server as a benchmark system under test: a -single ``ask_question`` call against the ``python/cpython`` Devin-generated -wiki. Unlike the other three competitors, DeepWiki's ``ask_question`` -returns an **LLM-generated** answer (PLAN-87 section 1.3, live-probed -2026-07-09: ~13.5s, nondeterministic across identical calls) rather than -retrieved source content -- the manifest's ``answer_generation: "llm"`` -metadata convention (see ``docs/benchmarks/competitor-manifest.template.yml``) -flags this so report generation never hides that an answer-synthesis system -is being scored inside a retrieval benchmark. ``read_wiki_contents`` (an -all-or-nothing ~1.18 MB blob) is not the documented flow and is not used. - -Like ``benchmarks.adapters.python_docs_mcp_adapter.PythonDocsMcpAdapter`` -(issue #86, the proven template this module mirrors), this adapter is -intentionally **not** a ``benchmarks.adapters.base.ProviderAdapter`` -subclass. - -Pin (PLAN-87 section 1.3): weakest of the four -- hosted endpoint -``https://mcp.deepwiki.com/mcp`` + access date + the live -``serverInfo.version`` recorded per run + the target wiki's last-indexed -date. No package/image/self-host exists. Third-party npm "deepwiki" -packages are NOT Cognition's server and must never be referenced here. - -Terms (PLAN-87 section 1.3): no DeepWiki-specific ToS; the Cognition -Platform ToS/AUP contain no benchmark clause but a gray-zone competitive-use -note (DeepWiki's publisher is a competing docs tool). Maintainer decision: -include with disclosure (assumption A3). - -Auth: none. Gated by -:func:`benchmarks.adapters.guard.require_live_competitor` (keyless -two-latch guard, PLAN-87 section 2.2), called as the first statement of -:meth:`DeepWikiAdapter.run`. -""" - -from __future__ import annotations - -import asyncio -from dataclasses import dataclass -from typing import Any, Protocol - -from benchmarks.adapters.guard import require_live_competitor -from benchmarks.runner import BenchmarkCellFailure, cell_failure_from - -DEFAULT_ENDPOINT = "https://mcp.deepwiki.com/mcp" - -#: The wiki target this adapter asks about. Any second target repo is -#: explicitly out of scope for issue #87 (PLAN-87 section 7). -DEFAULT_REPO_NAME = "python/cpython" - -#: 60s, not the 30s default used by the other three competitors -- DeepWiki's -#: verified live round trip is ~13.5s and LLM-generation latency is more -#: variable than plain retrieval (PLAN-87 section 1.3). -DEFAULT_TIMEOUT_SECONDS = 60.0 - - -@dataclass(frozen=True) -class ToolCallRecord: - """One raw MCP tool call/response pair, recorded verbatim for audit.""" - - tool: str - arguments: dict[str, Any] - result: dict[str, Any] | None - is_error: bool - - -@dataclass(frozen=True) -class DeepWikiResult: - """Structured output of one DeepWiki cell run.""" - - answer: str - tool_calls: list[ToolCallRecord] - - -class _CallToolResult(Protocol): - """Structural subset of ``mcp.types.CallToolResult`` this module needs.""" - - content: list[Any] - structured_content: dict[str, Any] | None - is_error: bool - - -class _CallToolSession(Protocol): - """Structural subset of ``mcp.ClientSession`` this module needs.""" - - async def call_tool( - self, name: str, arguments: dict[str, Any] | None = None - ) -> _CallToolResult: - """Invoke one MCP tool by name and return its raw call result.""" - raise NotImplementedError - - -def _first_text(result: _CallToolResult) -> str | None: - for block in result.content: - text = getattr(block, "text", None) - if isinstance(text, str): - return text - return None - - -def _tool_result_payload(result: _CallToolResult) -> dict[str, Any] | None: - if result.structured_content is not None: - return result.structured_content - text = _first_text(result) - return {"text": text} if text is not None else None - - -async def _run_deepwiki_flow( - session: _CallToolSession, - prompt: str, - *, - repo_name: str = DEFAULT_REPO_NAME, -) -> DeepWikiResult: - """Run the single documented ``ask_question`` call for one prompt. - - Pure orchestration against a duck-typed ``session`` so it can be unit - tested with a scripted double -- no real transport required. Raises - ``BenchmarkCellFailure`` (category ``tool_failure``) when the tool call - itself reports an error. - """ - tool_calls: list[ToolCallRecord] = [] - - args: dict[str, Any] = {"repoName": repo_name, "question": prompt} - result = await session.call_tool("ask_question", args) - payload = _tool_result_payload(result) - tool_calls.append( - ToolCallRecord( - tool="ask_question", arguments=args, result=payload, is_error=bool(result.is_error) - ) - ) - if result.is_error: - raise BenchmarkCellFailure( - "tool_failure", f"ask_question returned an error: {_first_text(result)}" - ) - - answer = _first_text(result) - if answer is None: - answer = str((payload or {}).get("answer", "") or (payload or {}).get("text", "")) - return DeepWikiResult(answer=answer, tool_calls=tool_calls) - - -def _transport_factory(endpoint: str) -> Any: - """Single owned seam for all transport construction. - - Imported lazily inside this function body so importing - ``deepwiki_adapter`` never requires the ``mcp`` client submodules - unless an actual run is attempted. Tests patch this one symbol to - prove fail-closed guard behavior without any transport ever being - constructed. - """ - from mcp.client.streamable_http import streamable_http_client - - return streamable_http_client(endpoint) - - -class DeepWikiAdapter: - """Adapter for DeepWiki's hosted MCP server: single ask_question call. - - ``run()`` is the synchronous entry point the benchmark runner's - dispatch registry calls per cell (see - ``benchmarks.runner._deepwiki_answer``). - """ - - def __init__( - self, - *, - endpoint: str | None = None, - repo_name: str = DEFAULT_REPO_NAME, - timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS, - ) -> None: - self._endpoint = endpoint if endpoint is not None else DEFAULT_ENDPOINT - self._repo_name = repo_name - self._timeout_seconds = timeout_seconds - - def run(self, prompt: str) -> DeepWikiResult: - """Run one DeepWiki cell. - - ``require_live_competitor("deepwiki")`` is the FIRST statement - here, before any transport construction (PLAN-87 section 2.2). - - Raises ``BenchmarkCellFailure`` with category ``tool_failure`` - (guard refusal or a tool-level error), ``timeout``, or - ``mcp_protocol_crash`` -- never a bare exception. - """ - require_live_competitor("deepwiki") - try: - return asyncio.run(asyncio.wait_for(self._run_async(prompt), self._timeout_seconds)) - except Exception as exc: # noqa: BLE001 - failures are benchmark artifacts - raise cell_failure_from( - exc, timeout_seconds=self._timeout_seconds, label="DeepWiki ask_question" - ) from exc - - async def _run_async(self, prompt: str) -> DeepWikiResult: - # Imported lazily so importing this module never requires the `mcp` - # client submodules unless an actual run is attempted. - from mcp import ClientSession - - async with _transport_factory(self._endpoint) as (read, write): - async with ClientSession(read, write) as session: - await session.initialize() - return await _run_deepwiki_flow(session, prompt, repo_name=self._repo_name) diff --git a/benchmarks/adapters/eligibility.py b/benchmarks/adapters/eligibility.py index eab4b97f..4b2728ec 100644 --- a/benchmarks/adapters/eligibility.py +++ b/benchmarks/adapters/eligibility.py @@ -31,11 +31,12 @@ moved to ``exclusions:`` -- and is rejected with a message pointing there. Only entries whose ``adapter`` is one of the four competitor adapter ids are -validated. This is deliberate: the existing ``fake`` and -``python-docs-mcp-stdio`` adapters (issues #72/#86) carry no pin/terms -metadata and merged fixtures in ``tests/benchmarks/test_runner.py`` build -manifests without it -- scoping validation to the new competitor ids keeps -this change additive and those merged tests untouched. +validated. This is deliberate: the ``fake`` adapter (issue #72) and the +agentic manifest's own systems (``mcp-stdio``, ``none``) carry no pin/terms +metadata, and fixtures in ``tests/benchmarks/test_runner.py`` build +manifests without it. The fixed-flow competitor adapters themselves are +gone; round 2 runs the competitors through the agentic bridge, behind +these same gates. """ from __future__ import annotations diff --git a/benchmarks/adapters/gitmcp_adapter.py b/benchmarks/adapters/gitmcp_adapter.py deleted file mode 100644 index 4cc15b74..00000000 --- a/benchmarks/adapters/gitmcp_adapter.py +++ /dev/null @@ -1,263 +0,0 @@ -"""Competitor MCP adapter: GitMCP -- issue #87. - -Runs GitMCP's hosted MCP server as a benchmark system under test. GitMCP's -own doc-search tool (``search_cpython_documentation``) is verified (PLAN-87 -section 1.2, live-probed 2026-07-09) to return no results for stdlib -queries -- cpython has no ``llms.txt`` and the tool falls back to indexing -only the repo README -- so the adapter tries doc-search first (the honest, -advertised path; the empty result is a legitimate benchmark finding, not an -exclusion) and falls back to ``search_cpython_code`` -> -``fetch_generic_url_content`` on the top hit's URL when doc-search comes up -empty. - -Like ``benchmarks.adapters.python_docs_mcp_adapter.PythonDocsMcpAdapter`` -(issue #86, the proven template this module mirrors), this adapter is -intentionally **not** a ``benchmarks.adapters.base.ProviderAdapter`` -subclass. - -Pin (PLAN-87 section 1.2): weak -- hosted endpoint -``https://gitmcp.io/python/cpython`` + access date + the live -``serverInfo.version`` recorded per run, plus code reference -``idosal/git-mcp@main`` SHA ``c487a29``. No npm package, tag, release, or -Docker image exists to pin against; the npm package named ``git-mcp`` is an -UNRELATED project and must never be referenced here. Self-hosting needs a -Cloudflare account and is not clean-clone reproducible, so it is not used. - -Terms (PLAN-87 section 1.2): Apache-2.0 code, no hosted-service ToS -document, README explicitly invites programmatic agent access -- -benchmarking is permitted (assumption A2). Keep concurrency low: the -GitHub API quota behind GitMCP is shared. - -Auth: none. Gated by -:func:`benchmarks.adapters.guard.require_live_competitor` (keyless -two-latch guard, PLAN-87 section 2.2), called as the first statement of -:meth:`GitMcpAdapter.run`. -""" - -from __future__ import annotations - -import asyncio -from dataclasses import dataclass -from typing import Any, Protocol - -from benchmarks.adapters.guard import require_live_competitor -from benchmarks.runner import BenchmarkCellFailure, cell_failure_from -from benchmarks.urls import first_web_url - -#: Hosted endpoint pin (PLAN-87 section 1.2). Repository target is fixed to -#: python/cpython -- any second target repo is explicitly out of scope for -#: issue #87 (PLAN-87 section 7). -DEFAULT_ENDPOINT = "https://gitmcp.io/python/cpython" - -#: Code reference recorded alongside the endpoint pin (not fetched at -#: runtime -- purely descriptive metadata for the manifest/template). -CODE_REFERENCE = "idosal/git-mcp@main#c487a29" - -DEFAULT_TIMEOUT_SECONDS = 30.0 - - -@dataclass(frozen=True) -class ToolCallRecord: - """One raw MCP tool call/response pair, recorded verbatim for audit.""" - - tool: str - arguments: dict[str, Any] - result: dict[str, Any] | None - is_error: bool - - -@dataclass(frozen=True) -class GitMcpResult: - """Structured output of one GitMCP cell run.""" - - answer: str - tool_calls: list[ToolCallRecord] - - -class _CallToolResult(Protocol): - """Structural subset of ``mcp.types.CallToolResult`` this module needs.""" - - content: list[Any] - structured_content: dict[str, Any] | None - is_error: bool - - -class _CallToolSession(Protocol): - """Structural subset of ``mcp.ClientSession`` this module needs.""" - - async def call_tool( - self, name: str, arguments: dict[str, Any] | None = None - ) -> _CallToolResult: - """Invoke one MCP tool by name and return its raw call result.""" - raise NotImplementedError - - -def _first_text(result: _CallToolResult) -> str | None: - for block in result.content: - text = getattr(block, "text", None) - if isinstance(text, str): - return text - return None - - -def _tool_result_payload(result: _CallToolResult) -> dict[str, Any] | None: - if result.structured_content is not None: - return result.structured_content - text = _first_text(result) - return {"text": text} if text is not None else None - - -def _extract_first_url(result: _CallToolResult) -> str | None: - """Pick the top hit's URL out of a search result. - - Prefers a structured hit list (``hits``/``results``) with a ``url`` - field, falling back to the first ``http(s)://`` URL in the first text - block (doc search prints ``#### ()[] (Score: ...)``), with - surrounding punctuation dropped by :func:`benchmarks.urls.first_web_url`. - Returns ``None`` (never raises) when neither yields a candidate. - """ - payload = _tool_result_payload(result) - if isinstance(payload, dict): - candidates = payload.get("hits") or payload.get("results") - if isinstance(candidates, list) and candidates: - first = candidates[0] - if isinstance(first, dict): - url = first.get("url") - if isinstance(url, str) and url: - return url - text = _first_text(result) - return first_web_url(text) if text else None - - -async def _run_gitmcp_flow(session: _CallToolSession, prompt: str) -> GitMcpResult: - """Run the doc-search -> (code-search -> fetch) fallback flow for one prompt. - - Pure orchestration against a duck-typed ``session`` so it can be unit - tested with a scripted double -- no real transport required. Raises - ``BenchmarkCellFailure`` (category ``tool_failure``) when any tool call - itself reports an error. - """ - tool_calls: list[ToolCallRecord] = [] - - doc_args: dict[str, Any] = {"query": prompt} - doc_result = await session.call_tool("search_cpython_documentation", doc_args) - doc_payload = _tool_result_payload(doc_result) - tool_calls.append( - ToolCallRecord( - tool="search_cpython_documentation", - arguments=doc_args, - result=doc_payload, - is_error=bool(doc_result.is_error), - ) - ) - if doc_result.is_error: - raise BenchmarkCellFailure( - "tool_failure", - f"search_cpython_documentation returned an error: {_first_text(doc_result)}", - ) - - url = _extract_first_url(doc_result) - if url is None: - code_args: dict[str, Any] = {"query": prompt} - code_result = await session.call_tool("search_cpython_code", code_args) - code_payload = _tool_result_payload(code_result) - tool_calls.append( - ToolCallRecord( - tool="search_cpython_code", - arguments=code_args, - result=code_payload, - is_error=bool(code_result.is_error), - ) - ) - if code_result.is_error: - raise BenchmarkCellFailure( - "tool_failure", - f"search_cpython_code returned an error: {_first_text(code_result)}", - ) - url = _extract_first_url(code_result) - - if url is None: - return GitMcpResult(answer="", tool_calls=tool_calls) - - fetch_args: dict[str, Any] = {"url": url} - fetch_result = await session.call_tool("fetch_generic_url_content", fetch_args) - fetch_payload = _tool_result_payload(fetch_result) - tool_calls.append( - ToolCallRecord( - tool="fetch_generic_url_content", - arguments=fetch_args, - result=fetch_payload, - is_error=bool(fetch_result.is_error), - ) - ) - if fetch_result.is_error: - raise BenchmarkCellFailure( - "tool_failure", - f"fetch_generic_url_content returned an error: {_first_text(fetch_result)}", - ) - - answer = _first_text(fetch_result) - if answer is None: - payload = fetch_payload or {} - answer = str(payload.get("content", "") or payload.get("text", "")) - return GitMcpResult(answer=answer, tool_calls=tool_calls) - - -def _transport_factory(endpoint: str) -> Any: - """Single owned seam for all transport construction. - - Imported lazily inside this function body so importing - ``gitmcp_adapter`` never requires the ``mcp`` client submodules unless - an actual run is attempted. Tests patch this one symbol to prove - fail-closed guard behavior without any transport ever being - constructed. - """ - from mcp.client.streamable_http import streamable_http_client - - return streamable_http_client(endpoint) - - -class GitMcpAdapter: - """Adapter for GitMCP's hosted MCP server: doc-search -> code-search -> fetch. - - ``run()`` is the synchronous entry point the benchmark runner's - dispatch registry calls per cell (see - ``benchmarks.runner._gitmcp_answer``). - """ - - def __init__( - self, - *, - endpoint: str | None = None, - timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS, - ) -> None: - self._endpoint = endpoint if endpoint is not None else DEFAULT_ENDPOINT - self._timeout_seconds = timeout_seconds - - def run(self, prompt: str) -> GitMcpResult: - """Run one GitMCP cell. - - ``require_live_competitor("gitmcp")`` is the FIRST statement here, - before any transport construction (PLAN-87 section 2.2). - - Raises ``BenchmarkCellFailure`` with category ``tool_failure`` - (guard refusal or a tool-level error), ``timeout``, or - ``mcp_protocol_crash`` -- never a bare exception. - """ - require_live_competitor("gitmcp") - try: - return asyncio.run(asyncio.wait_for(self._run_async(prompt), self._timeout_seconds)) - except Exception as exc: # noqa: BLE001 - failures are benchmark artifacts - raise cell_failure_from( - exc, timeout_seconds=self._timeout_seconds, label="GitMCP retrieval flow" - ) from exc - - async def _run_async(self, prompt: str) -> GitMcpResult: - # Imported lazily so importing this module never requires the `mcp` - # client submodules unless an actual run is attempted. - from mcp import ClientSession - - async with _transport_factory(self._endpoint) as (read, write): - async with ClientSession(read, write) as session: - await session.initialize() - return await _run_gitmcp_flow(session, prompt) diff --git a/benchmarks/adapters/google_adapter.py b/benchmarks/adapters/google_adapter.py deleted file mode 100644 index c8aa78ca..00000000 --- a/benchmarks/adapters/google_adapter.py +++ /dev/null @@ -1,78 +0,0 @@ -"""Google-backed provider adapters (mock and guarded live stub). - -No Google SDK is imported or required here -- see the module docstring in -``benchmarks/adapters/guard.py`` for why the live adapter never makes a real -call. Mock and live adapters both never perform network I/O. -""" - -from __future__ import annotations - -from typing import Any - -from benchmarks.adapters.base import AdapterRequest, ProviderAdapter, TokenMetadata -from benchmarks.adapters.guard import LiveExecutionNotImplementedError, require_live_environment -from benchmarks.runner import BenchmarkCellFailure - -PROVIDER_NATIVE_TOKEN_FIELD = "usage_metadata.total_token_count" - - -class MockGoogleAdapter(ProviderAdapter): - """Deterministic Google adapter double. Never makes a network call. - - ``force_failure`` optionally forces a ``BenchmarkCellFailure`` with the - given category (``tool_failure`` | ``timeout`` | ``mcp_protocol_crash``) - instead of a canned answer, so failure-capture behavior can be tested - the same way ``benchmarks.runner`` tests it for the fake competitor - adapter. - """ - - provider = "google" - - def __init__( - self, - *, - fake_answer: str | None = None, - fake_native_tokens: int = 37, - force_failure: str | None = None, - ) -> None: - self._fake_answer = fake_answer - self._fake_native_tokens = fake_native_tokens - self._force_failure = force_failure - - def _generate(self, request: AdapterRequest) -> tuple[str, TokenMetadata, dict[str, Any]]: - if self._force_failure is not None: - raise BenchmarkCellFailure( - self._force_failure, f"forced mock google adapter {self._force_failure}" - ) - answer = self._fake_answer or f"[mock-google:{request.model_id}] {request.prompt}" - tokens = TokenMetadata( - provider_native_tokens=self._fake_native_tokens, - provider_token_field=PROVIDER_NATIVE_TOKEN_FIELD, - ) - raw = { - "provider": self.provider, - "model": request.model_id, - "mock": True, - "usage_metadata": {"total_token_count": self._fake_native_tokens}, - } - return answer, tokens, raw - - -class LiveGoogleAdapter(ProviderAdapter): - """Guarded live-provider stub. Structurally incapable of a network call. - - Calling :meth:`generate` first enforces - :func:`benchmarks.adapters.guard.require_live_environment`, then always - raises :class:`LiveExecutionNotImplementedError` -- live execution is - reserved for a maintainer-run phase, not this mocked-plumbing release. - """ - - provider = "google" - - def _generate(self, request: AdapterRequest) -> tuple[str, TokenMetadata, dict[str, Any]]: - require_live_environment(self.provider) - raise LiveExecutionNotImplementedError( - "live Google execution is not implemented in this release; issue #73 ships " - "mocked plumbing only. Real provider calls are confined to a maintainer-run " - "live phase (see PLAN.md Amendment 2026-07-08)." - ) diff --git a/benchmarks/adapters/guard.py b/benchmarks/adapters/guard.py index 826eba0d..5da2dbb3 100644 --- a/benchmarks/adapters/guard.py +++ b/benchmarks/adapters/guard.py @@ -2,23 +2,17 @@ Issue #73 requires that this implementation refuse to run live providers unless explicit environment variables/config are present. This module is -that guardrail: any live adapter (see ``openai_adapter.LiveOpenAIAdapter`` / -``google_adapter.LiveGoogleAdapter``) must call -:func:`require_live_environment` before doing anything else. - -The OpenAI/Google adapters in this package never make a live or paid API -call, with or without the guard passing -- they are stubs that, after the -guard passes, still refuse via ``LiveExecutionNotImplementedError``. -Actually implementing a live call for those providers is out of scope for -issue #73's mocked plumbing and is reserved for a maintainer-run, -human-supervised phase (see PLAN.md Amendment 2026-07-08). - -Issue #89 is the one exception: ``benchmarks.adapters.claude_tokens``'s -Anthropic count-tokens caller *does* perform a real HTTP call once this -guard passes, because the maintainer-run live phase is exactly what that -call is for (Claude token counting after client-side rewrap, roadmap -decision 5.8). It still never runs in CI or unit tests -- tests use a fake -counter -- and it is structurally incapable of running without both +that guardrail: every live call must pass :func:`require_live_environment` +first. The agentic harness builds every live client through +``benchmarks.agentic.clients.make_client``, which calls it; tests use +scripted clients and mock transports, and never set the flag and a key. + +``benchmarks.adapters.claude_tokens``'s Anthropic count-tokens caller +(issue #89) performs a real HTTP call once this guard passes, because the +maintainer-run live phase is exactly what that call is for (Claude token +counting after client-side rewrap, roadmap decision 5.8). It still never +runs in CI or unit tests -- tests use a fake counter -- and it is +structurally incapable of running without both ``BENCHMARK_LIVE_PROVIDERS_ENABLED`` and ``ANTHROPIC_API_KEY`` set, exactly like every other provider gated here. @@ -48,12 +42,10 @@ #: it gates the Claude count-tokens methodology caller in #: ``benchmarks.adapters.claude_tokens``, not a competitor answer adapter. #: -#: ``ref`` and ``context7`` (issue #87) gate the keyed competitor docs MCP -#: adapters: ``benchmarks.adapters.ref_tools_adapter.RefToolsAdapter`` -#: (always keyed -- Ref.tools requires an API key) and -#: ``benchmarks.adapters.context7_adapter.Context7Adapter`` when its -#: manifest entry declares key mode (Context7 also has a keyless mode; see -#: :func:`require_live_competitor`). +#: ``ref`` and ``context7`` (issue #87) gate the keyed competitor docs MCPs: +#: Ref.tools (always keyed) and Context7 when its manifest entry declares key +#: mode (Context7 also has a keyless mode; see :func:`require_live_competitor`). +#: Round 2 runs them through the agentic bridge. PROVIDER_API_KEY_ENV = { "openai": "OPENAI_API_KEY", "google": "GOOGLE_API_KEY", @@ -85,17 +77,6 @@ class MalformedApiKeyError(LiveProviderDisabledError): """Raised when a provider API key is set but holds characters no HTTP header may carry.""" -class LiveExecutionNotImplementedError(BenchmarkCellFailure): - """Raised after the guard passes: live execution itself is not implemented. - - This package ships mocked plumbing only; it is structurally incapable of - a live call regardless of environment configuration. - """ - - def __init__(self, message: str) -> None: - super().__init__("tool_failure", message) - - def require_live_environment(provider: str) -> None: """Raise :class:`LiveProviderDisabledError` unless live calls are explicitly enabled. @@ -173,10 +154,8 @@ def require_live_competitor(name: str) -> None: 2. ``name`` appears in the comma-separated :data:`LIVE_COMPETITORS_ENV` allowlist (case-insensitive, whitespace-tolerant). - Both conditions must hold. Passing this check does not mean a live call - will be made -- competitor adapters that pass this guard still route all - transport construction through their own ``_transport_factory`` seam, - which nothing in this module or the guard itself invokes. + Both conditions must hold. Passing this check does not by itself make a + live call: nothing in this module opens a transport. """ flag = os.environ.get(LIVE_PROVIDERS_ENABLED_ENV, "").strip().lower() if flag not in _TRUTHY: diff --git a/benchmarks/adapters/openai_adapter.py b/benchmarks/adapters/openai_adapter.py deleted file mode 100644 index b94c969d..00000000 --- a/benchmarks/adapters/openai_adapter.py +++ /dev/null @@ -1,78 +0,0 @@ -"""OpenAI-backed provider adapters (mock and guarded live stub). - -No OpenAI SDK is imported or required here -- see the module docstring in -``benchmarks/adapters/guard.py`` for why the live adapter never makes a real -call. Mock and live adapters both never perform network I/O. -""" - -from __future__ import annotations - -from typing import Any - -from benchmarks.adapters.base import AdapterRequest, ProviderAdapter, TokenMetadata -from benchmarks.adapters.guard import LiveExecutionNotImplementedError, require_live_environment -from benchmarks.runner import BenchmarkCellFailure - -PROVIDER_NATIVE_TOKEN_FIELD = "usage.total_tokens" - - -class MockOpenAIAdapter(ProviderAdapter): - """Deterministic OpenAI adapter double. Never makes a network call. - - ``force_failure`` optionally forces a ``BenchmarkCellFailure`` with the - given category (``tool_failure`` | ``timeout`` | ``mcp_protocol_crash``) - instead of a canned answer, so failure-capture behavior can be tested - the same way ``benchmarks.runner`` tests it for the fake competitor - adapter. - """ - - provider = "openai" - - def __init__( - self, - *, - fake_answer: str | None = None, - fake_native_tokens: int = 42, - force_failure: str | None = None, - ) -> None: - self._fake_answer = fake_answer - self._fake_native_tokens = fake_native_tokens - self._force_failure = force_failure - - def _generate(self, request: AdapterRequest) -> tuple[str, TokenMetadata, dict[str, Any]]: - if self._force_failure is not None: - raise BenchmarkCellFailure( - self._force_failure, f"forced mock openai adapter {self._force_failure}" - ) - answer = self._fake_answer or f"[mock-openai:{request.model_id}] {request.prompt}" - tokens = TokenMetadata( - provider_native_tokens=self._fake_native_tokens, - provider_token_field=PROVIDER_NATIVE_TOKEN_FIELD, - ) - raw = { - "provider": self.provider, - "model": request.model_id, - "mock": True, - "usage": {"total_tokens": self._fake_native_tokens}, - } - return answer, tokens, raw - - -class LiveOpenAIAdapter(ProviderAdapter): - """Guarded live-provider stub. Structurally incapable of a network call. - - Calling :meth:`generate` first enforces - :func:`benchmarks.adapters.guard.require_live_environment`, then always - raises :class:`LiveExecutionNotImplementedError` -- live execution is - reserved for a maintainer-run phase, not this mocked-plumbing release. - """ - - provider = "openai" - - def _generate(self, request: AdapterRequest) -> tuple[str, TokenMetadata, dict[str, Any]]: - require_live_environment(self.provider) - raise LiveExecutionNotImplementedError( - "live OpenAI execution is not implemented in this release; issue #73 ships " - "mocked plumbing only. Real provider calls are confined to a maintainer-run " - "live phase (see PLAN.md Amendment 2026-07-08)." - ) diff --git a/benchmarks/adapters/python_docs_mcp_adapter.py b/benchmarks/adapters/python_docs_mcp_adapter.py deleted file mode 100644 index 4d972eac..00000000 --- a/benchmarks/adapters/python_docs_mcp_adapter.py +++ /dev/null @@ -1,259 +0,0 @@ -"""Offline stdio adapter for python-docs-mcp-server itself (issue #86). - -Runs the product's own MCP server as a benchmark system under test: spawns -it as a local subprocess over stdio, issues the documented retrieval flow -(``search_docs`` -> ``get_docs``) for one corpus question, and returns the -retrieved content plus the raw tool call/response payloads for transcript -recording. - -This adapter is intentionally **not** a -``benchmarks.adapters.base.ProviderAdapter`` subclass: that contract models -an LLM provider call (prompt in, generated answer + token usage out). This -adapter models a documentation *retrieval* tool call instead -- there is no -LLM in this offline work package. Pairing the retrieved context with an LLM -adapter (``benchmarks.adapters.openai_adapter`` / ``google_adapter``, issue -#73) is reserved for a maintainer-run live phase; see the confirmed -composition decision on issue #86 (also PLAN.md Amendment 2026-07-08). - -Offline guarantee (roadmap principle 2.2, preserved at runtime): - -- This module never performs network I/O itself. -- The spawned server process always runs with - ``PYTHON_DOCS_MCP_DISABLE_AUTO_INDEX=1`` so a missing index can never - trigger the server's own auto-index-build fallback - (``mcp_server_python_docs.server._auto_build_symbol_index``), which does - fetch network resources. -- A missing index is instead detected *before* the subprocess is even - spawned (see :meth:`PythonDocsMcpAdapter.run`) and reported as a - ``tool_failure``, never a crash. -- ``search_docs`` and ``get_docs`` themselves only ever read the local - SQLite index; neither performs network I/O (see - ``mcp_server_python_docs.services.search`` / ``services.content``). -""" - -from __future__ import annotations - -import asyncio -import os -import sys -from dataclasses import dataclass -from pathlib import Path -from typing import Any, Protocol - -from benchmarks.runner import BenchmarkCellFailure, cell_failure_from - -#: Environment variable the server checks to skip its own auto-index-build -#: fallback (see ``mcp_server_python_docs.server._auto_build_symbol_index``). -#: Always set for benchmark-spawned servers so a missing index can never -#: trigger a network-touching auto-build. -DISABLE_AUTO_INDEX_ENV = "PYTHON_DOCS_MCP_DISABLE_AUTO_INDEX" - -#: Default per-cell budget for the full search_docs -> get_docs round trip. -DEFAULT_TIMEOUT_SECONDS = 30.0 - -#: Default number of search_docs hits requested; only the top hit is -#: followed up with get_docs (see module docstring "documented retrieval -#: flow"). -DEFAULT_MAX_RESULTS = 3 - - -@dataclass(frozen=True) -class ToolCallRecord: - """One raw MCP tool call/response pair, recorded verbatim for audit.""" - - tool: str - arguments: dict[str, Any] - result: dict[str, Any] | None - is_error: bool - - -@dataclass(frozen=True) -class PythonDocsMcpResult: - """Structured output of one search_docs -> get_docs cell run.""" - - answer: str - tool_calls: list[ToolCallRecord] - - -class _CallToolResult(Protocol): - """Structural subset of ``mcp.types.CallToolResult`` this module needs. - - Naming this as a ``Protocol`` (rather than importing the concrete SDK - type at module scope for the type hint) lets unit tests hand in a - lightweight stand-in without constructing a full MCP session. - """ - - content: list[Any] - structured_content: dict[str, Any] | None - is_error: bool - - -class _CallToolSession(Protocol): - """Structural subset of ``mcp.ClientSession`` this module needs.""" - - async def call_tool( - self, name: str, arguments: dict[str, Any] | None = None - ) -> _CallToolResult: - """Invoke one MCP tool by name and return its raw call result.""" - raise NotImplementedError - - -def _default_command() -> list[str]: - return [sys.executable, "-m", "mcp_server_python_docs", "serve"] - - -def _default_index_path() -> Path: - from mcp_server_python_docs.storage.db import get_index_path - - return get_index_path() - - -def _first_text(result: _CallToolResult) -> str | None: - for block in result.content: - text = getattr(block, "text", None) - if isinstance(text, str): - return text - return None - - -def _tool_result_payload(result: _CallToolResult) -> dict[str, Any] | None: - """Extract a JSON-safe raw payload from a tool call result for the transcript. - - Prefers ``structured_content`` (MCPServer auto-generates this from the - tool's Pydantic return model). Falls back to the first text content - block (e.g. on an error result, where ``structured_content`` is - ``None``) so the transcript still records something useful for audit. - """ - if result.structured_content is not None: - return result.structured_content - text = _first_text(result) - return {"text": text} if text is not None else None - - -async def _run_retrieval_flow( - session: _CallToolSession, - prompt: str, - *, - max_results: int = DEFAULT_MAX_RESULTS, -) -> PythonDocsMcpResult: - """Run the documented search_docs -> get_docs flow for one prompt. - - Pure orchestration logic against a duck-typed ``session`` (only - ``call_tool`` is used) so it can be unit tested with a fake/stubbed - transport -- no real server spawn required. Raises - ``BenchmarkCellFailure`` (category ``tool_failure``) when either tool - call itself reports an error. - """ - tool_calls: list[ToolCallRecord] = [] - - search_args: dict[str, Any] = {"query": prompt, "max_results": max_results} - search_result = await session.call_tool("search_docs", search_args) - search_payload = _tool_result_payload(search_result) - tool_calls.append( - ToolCallRecord( - tool="search_docs", - arguments=search_args, - result=search_payload, - is_error=bool(search_result.is_error), - ) - ) - if search_result.is_error: - raise BenchmarkCellFailure( - "tool_failure", - f"search_docs returned an error: {_first_text(search_result)}", - ) - - hits = (search_payload or {}).get("hits") or [] - if not hits: - return PythonDocsMcpResult(answer="", tool_calls=tool_calls) - - top_hit = hits[0] - get_args: dict[str, Any] = {"slug": top_hit.get("slug"), "version": top_hit.get("version")} - if top_hit.get("anchor"): - get_args["anchor"] = top_hit["anchor"] - get_result = await session.call_tool("get_docs", get_args) - get_payload = _tool_result_payload(get_result) - tool_calls.append( - ToolCallRecord( - tool="get_docs", - arguments=get_args, - result=get_payload, - is_error=bool(get_result.is_error), - ) - ) - if get_result.is_error: - raise BenchmarkCellFailure( - "tool_failure", - f"get_docs returned an error: {_first_text(get_result)}", - ) - - answer = str((get_payload or {}).get("content", "")) - return PythonDocsMcpResult(answer=answer, tool_calls=tool_calls) - - -class PythonDocsMcpAdapter: - """Offline stdio adapter: python-docs-mcp-server as a retrieval tool. - - ``run()`` is the synchronous entry point the benchmark runner's - dispatch registry calls per cell (see - ``benchmarks.runner._python_docs_mcp_stdio_answer``). - """ - - def __init__( - self, - *, - command: list[str] | None = None, - index_path: Path | None = None, - timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS, - max_results: int = DEFAULT_MAX_RESULTS, - ) -> None: - self._command = command if command is not None else _default_command() - self._index_path = index_path - self._timeout_seconds = timeout_seconds - self._max_results = max_results - - def run(self, prompt: str) -> PythonDocsMcpResult: - """Run one search_docs -> get_docs cell. - - Raises ``BenchmarkCellFailure`` with category ``tool_failure`` - (missing index or a tool-level error), ``timeout`` (the round trip - exceeded ``timeout_seconds``), or ``mcp_protocol_crash`` (the stdio - transport/session itself failed) -- never a bare exception, so the - runner's existing except clause for adapter dispatch (see - ``benchmarks.runner._execute_cell``) can catch this uniformly. - """ - index_path = self._index_path if self._index_path is not None else _default_index_path() - if not index_path.exists(): - raise BenchmarkCellFailure( - "tool_failure", - f"no local index found at {index_path}; run 'python-docs-mcp-server " - "build-index --versions ' before running this benchmark adapter " - "(dry-run validates without needing one)", - ) - try: - return asyncio.run(asyncio.wait_for(self._run_async(prompt), self._timeout_seconds)) - except Exception as exc: # noqa: BLE001 - failures are benchmark artifacts - raise cell_failure_from( - exc, - timeout_seconds=self._timeout_seconds, - label="python-docs-mcp-server search_docs -> get_docs", - ) from exc - - async def _run_async(self, prompt: str) -> PythonDocsMcpResult: - # Imported lazily so importing this module never requires the `mcp` - # client submodules unless an actual run is attempted. - from mcp import ClientSession, StdioServerParameters - from mcp.client.stdio import stdio_client - - # The SDK defaults carry HOME and LOCALAPPDATA; platformdirs also reads - # XDG_CACHE_HOME, so the child opens the index this process checked. - env = {DISABLE_AUTO_INDEX_ENV: "1"} - if os.environ.get("XDG_CACHE_HOME"): - env["XDG_CACHE_HOME"] = os.environ["XDG_CACHE_HOME"] - params = StdioServerParameters( - command=self._command[0], args=list(self._command[1:]), env=env - ) - async with stdio_client(params) as (read, write): - async with ClientSession(read, write) as session: - await session.initialize() - return await _run_retrieval_flow(session, prompt, max_results=self._max_results) diff --git a/benchmarks/adapters/ref_tools_adapter.py b/benchmarks/adapters/ref_tools_adapter.py deleted file mode 100644 index b20142df..00000000 --- a/benchmarks/adapters/ref_tools_adapter.py +++ /dev/null @@ -1,274 +0,0 @@ -"""Competitor MCP adapter: Ref.tools -- issue #87. - -Runs Ref.tools' MCP server as a benchmark system under test and issues its -documented retrieval flow (``ref_search_documentation`` -> ``ref_read_url``) -for one corpus question. Ref.tools' own session behavior dedupes repeated -results and trims reads based on session history, so a fresh MCP session -per question is required for comparable results -- the benchmark runner -already instantiates adapters fresh per cell (PLAN-87 section 1.4), so this -is satisfied by construction; nothing here reuses a session across -``run()`` calls. - -Like ``benchmarks.adapters.python_docs_mcp_adapter.PythonDocsMcpAdapter`` -(issue #86, the proven template this module mirrors), this adapter is -intentionally **not** a ``benchmarks.adapters.base.ProviderAdapter`` -subclass. - -Pin (PLAN-87 section 1.4): npm client ``ref-tools-mcp@3.0.3`` (MIT) or -Docker ``mcp/ref-tools-mcp`` digest ``sha256:8b5fcfe3...``; the -``api.ref.tools`` backend is itself unpinnable, so the effective pin is -"client 3.0.3 + run date". This adapter defaults to the vendor-recommended -remote streamable-HTTP mode (``https://api.ref.tools/mcp`` with an -``x-ref-api-key`` header) -- no local Node/npx process required. A legacy -stdio mode (``npx ref-tools-mcp@3.0.3``, env ``REF_API_KEY``) exists but is -not the default here. - -Terms (PLAN-87 section 1.4): no benchmark/evaluation clause, but sections 3 -and 7 of Ref.tools' terms restrict automated/systematic access without -written permission; verdict recorded as -"unclear-permission-recommended". Maintainer decision: build now, live use -needs a maintainer key + credits, publication needs the permission decision -(assumption A4). - -Auth: an API key is REQUIRED (no keyless mode exists for Ref.tools, unlike -GitMCP/DeepWiki/keyless-Context7). Gated by -:func:`benchmarks.adapters.guard.require_live_environment` (registered key -env: ``REF_API_KEY``, see -``benchmarks.adapters.guard.PROVIDER_API_KEY_ENV``), called as the first -statement of :meth:`RefToolsAdapter.run`. -""" - -from __future__ import annotations - -import asyncio -import os -from dataclasses import dataclass -from typing import Any, Protocol - -from benchmarks.adapters.guard import require_live_environment -from benchmarks.runner import BenchmarkCellFailure, cell_failure_from -from benchmarks.urls import first_web_url, labeled_value - -DEFAULT_ENDPOINT = "https://api.ref.tools/mcp" - -#: Header the vendor-recommended remote streamable-HTTP mode requires -#: (PLAN-87 section 1.4). -API_KEY_HEADER = "x-ref-api-key" - -#: Environment variable read for the required API key (also the guard's -#: registered key env for provider id "ref" -- see -#: ``benchmarks.adapters.guard.PROVIDER_API_KEY_ENV``). -API_KEY_ENV = "REF_API_KEY" - -DEFAULT_TIMEOUT_SECONDS = 30.0 - - -@dataclass(frozen=True) -class ToolCallRecord: - """One raw MCP tool call/response pair, recorded verbatim for audit.""" - - tool: str - arguments: dict[str, Any] - result: dict[str, Any] | None - is_error: bool - - -@dataclass(frozen=True) -class RefToolsResult: - """Structured output of one ref_search_documentation -> ref_read_url cell run.""" - - answer: str - tool_calls: list[ToolCallRecord] - - -class _CallToolResult(Protocol): - """Structural subset of ``mcp.types.CallToolResult`` this module needs.""" - - content: list[Any] - structured_content: dict[str, Any] | None - is_error: bool - - -class _CallToolSession(Protocol): - """Structural subset of ``mcp.ClientSession`` this module needs.""" - - async def call_tool( - self, name: str, arguments: dict[str, Any] | None = None - ) -> _CallToolResult: - """Invoke one MCP tool by name and return its raw call result.""" - raise NotImplementedError - - -def _first_text(result: _CallToolResult) -> str | None: - for block in result.content: - text = getattr(block, "text", None) - if isinstance(text, str): - return text - return None - - -def _tool_result_payload(result: _CallToolResult) -> dict[str, Any] | None: - if result.structured_content is not None: - return result.structured_content - text = _first_text(result) - return {"text": text} if text is not None else None - - -def _extract_first_url(result: _CallToolResult) -> str | None: - """Pick the top hit's URL out of a ``ref_search_documentation`` result. - - Prefers a structured hit list (``results``/``hits``) with a ``url`` - field. Otherwise it reads the first text block: each hit there has - ``overview:``, ``url:`` and ``moduleId:`` lines, so the first ``url:`` - line wins over any link inside an overview, and the first - ``http(s)://`` URL is the last resort. Returns ``None`` (never raises) - when nothing yields a candidate. - """ - payload = _tool_result_payload(result) - if isinstance(payload, dict): - candidates = payload.get("results") or payload.get("hits") - if isinstance(candidates, list) and candidates: - first = candidates[0] - if isinstance(first, dict): - url = first.get("url") - if isinstance(url, str) and url: - return url - text = _first_text(result) - if not text: - return None - return labeled_value(text, "url") or first_web_url(text) - - -async def _run_ref_tools_flow(session: _CallToolSession, prompt: str) -> RefToolsResult: - """Run the documented ref_search_documentation -> ref_read_url flow for one prompt. - - Pure orchestration against a duck-typed ``session`` so it can be unit - tested with a scripted double -- no real transport required. Raises - ``BenchmarkCellFailure`` (category ``tool_failure``) when either tool - call itself reports an error. - """ - tool_calls: list[ToolCallRecord] = [] - - search_args: dict[str, Any] = {"query": prompt} - search_result = await session.call_tool("ref_search_documentation", search_args) - search_payload = _tool_result_payload(search_result) - tool_calls.append( - ToolCallRecord( - tool="ref_search_documentation", - arguments=search_args, - result=search_payload, - is_error=bool(search_result.is_error), - ) - ) - if search_result.is_error: - raise BenchmarkCellFailure( - "tool_failure", - f"ref_search_documentation returned an error: {_first_text(search_result)}", - ) - - url = _extract_first_url(search_result) - if url is None: - return RefToolsResult(answer="", tool_calls=tool_calls) - - read_args: dict[str, Any] = {"url": url} - read_result = await session.call_tool("ref_read_url", read_args) - read_payload = _tool_result_payload(read_result) - tool_calls.append( - ToolCallRecord( - tool="ref_read_url", - arguments=read_args, - result=read_payload, - is_error=bool(read_result.is_error), - ) - ) - if read_result.is_error: - raise BenchmarkCellFailure( - "tool_failure", f"ref_read_url returned an error: {_first_text(read_result)}" - ) - - answer = _first_text(read_result) - if answer is None: - payload = read_payload or {} - answer = str(payload.get("content", "") or payload.get("text", "")) - return RefToolsResult(answer=answer, tool_calls=tool_calls) - - -def _transport_factory(endpoint: str, headers: dict[str, str] | None) -> Any: - """Single owned seam for all transport construction. - - Imported lazily inside this function body so importing - ``ref_tools_adapter`` never requires the ``mcp`` client submodules - unless an actual run is attempted. Tests patch this one symbol to - prove fail-closed guard behavior without any transport ever being - constructed. - """ - import httpx2 - from mcp.client.streamable_http import streamable_http_client - - # Built directly, with the timeouts the MCP SDK v2 migration guide - # suggests for keeping v1 behavior (30s, 300s read). The v2 transport - # follows same-origin redirects itself. ``timeout_seconds`` on the - # adapter is not wired into this client; it is enforced only by the - # outer ``asyncio.wait_for`` in ``_run_async``. - http_client = ( - httpx2.AsyncClient(headers=headers, timeout=httpx2.Timeout(30, read=300)) - if headers - else None - ) - return streamable_http_client(endpoint, http_client=http_client) - - -class RefToolsAdapter: - """Adapter for Ref.tools' MCP server: ref_search_documentation -> ref_read_url. - - ``run()`` is the synchronous entry point the benchmark runner's - dispatch registry calls per cell (see - ``benchmarks.runner._ref_tools_answer``). The runner constructs a fresh - instance per cell, which -- combined with this class never reusing a - session across calls -- satisfies Ref.tools' fresh-session-per-question - requirement (see module docstring) by construction. - """ - - def __init__( - self, - *, - endpoint: str | None = None, - api_key: str | None = None, - timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS, - ) -> None: - self._endpoint = endpoint if endpoint is not None else DEFAULT_ENDPOINT - self._api_key = api_key if api_key is not None else os.environ.get(API_KEY_ENV) - self._timeout_seconds = timeout_seconds - - def run(self, prompt: str) -> RefToolsResult: - """Run one Ref.tools cell. - - ``require_live_environment("ref")`` is the FIRST statement here, - before any transport construction -- Ref.tools has no keyless mode - (PLAN-87 section 1.4), so it always goes through the keyed guard, - unlike GitMCP/DeepWiki/keyless-Context7. - - Raises ``BenchmarkCellFailure`` with category ``tool_failure`` - (guard refusal or a tool-level error), ``timeout``, or - ``mcp_protocol_crash`` -- never a bare exception. - """ - require_live_environment("ref") - try: - return asyncio.run(asyncio.wait_for(self._run_async(prompt), self._timeout_seconds)) - except Exception as exc: # noqa: BLE001 - failures are benchmark artifacts - raise cell_failure_from( - exc, - timeout_seconds=self._timeout_seconds, - label="Ref.tools ref_search_documentation -> ref_read_url", - ) from exc - - async def _run_async(self, prompt: str) -> RefToolsResult: - # Imported lazily so importing this module never requires the `mcp` - # client submodules unless an actual run is attempted. - from mcp import ClientSession - - headers = {API_KEY_HEADER: self._api_key} if self._api_key else None - async with _transport_factory(self._endpoint, headers) as (read, write): - async with ClientSession(read, write) as session: - await session.initialize() - return await _run_ref_tools_flow(session, prompt) diff --git a/benchmarks/runner.py b/benchmarks/runner.py index 36e4a9af..f14593c6 100644 --- a/benchmarks/runner.py +++ b/benchmarks/runner.py @@ -1,16 +1,13 @@ """Benchmark runner artifact plumbing. Dispatches each competitor/question cell to an adapter looked up by the -competitor manifest's ``adapter`` id (see ``_ADAPTER_DISPATCH``): the local -fake adapter (issue #72; tests only), or the offline stdio adapter that runs -python-docs-mcp-server itself as a system under test (issue #86, see -``benchmarks.adapters.python_docs_mcp_adapter``). Live LLM provider -adapters (``benchmarks.adapters.openai_adapter`` / ``google_adapter``, -issue #73) and report generation (issue #74/#90) live in separate modules. -Wiring a manifest's model-matrix pairing into this module's per-cell -dispatch remains out of scope -- cell composition stays competitor x -question (see the ``benchmarks.model_matrix`` module docstring for the -confirmed composition decision). +competitor manifest's ``adapter`` id (see ``_ADAPTER_DISPATCH``). Only the +local fake adapter (issue #72; tests only) remains: the fixed-flow +retrieval adapters were replaced by the agentic harness +(``benchmarks.agentic``, ``python -m benchmarks agentic-run``), whose MCP +bridge serves every system and whose artifacts this module's helpers and +the report still share. Report generation (issue #74/#90) lives in a +separate module. Each cell's token record (``_build_token_record``, issue #89) is the one exception to "no network I/O": it fills real counts via the guarded @@ -273,8 +270,7 @@ def _validate_manifest_eligibility(manifest_data: dict[str, Any]) -> None: a per-cell failure). Raises ``BenchmarkValidationError``, which the CLI (``benchmarks/__main__.py``) already maps to exit code 2. - Imported lazily for the same reason ``_python_docs_mcp_stdio_answer`` - imports its adapter lazily: ``benchmarks.adapters.eligibility`` imports + Imported lazily: ``benchmarks.adapters.eligibility`` imports ``BenchmarkValidationError`` from this module, so this module cannot import from ``benchmarks.adapters`` at module scope without a circular import. @@ -340,8 +336,7 @@ def _execute_cell(cell: BenchmarkCell) -> dict[str, Any]: "messages": [{"role": "user", "content": cell.question.prompt}], "answer": answer, # Raw tool call/response payloads for adapters that make them - # available (e.g. the python-docs-mcp-stdio adapter, issue #86). - # None for adapters that do not record raw payloads. + # available. None for adapters that do not record raw payloads. "tool_calls": tool_calls, "error": error, } @@ -398,8 +393,7 @@ def _build_token_record( results for the same cell. A malformed ``ANTHROPIC_API_KEY`` (the guard's ``MalformedApiKeyError``) is a failed count too, never a pending one. - Imported lazily, for the same reason ``_python_docs_mcp_stdio_answer`` - imports its adapter lazily: ``benchmarks.adapters.guard`` and + Imported lazily: ``benchmarks.adapters.guard`` and ``benchmarks.model_matrix`` both import from this module at their own module scope, so this module cannot import from them at module scope without a circular import. @@ -484,10 +478,9 @@ def failed_record(exc: Exception) -> dict[str, Any]: class _CellDispatchResult: """Return value of one adapter dispatch call (see ``_ADAPTER_DISPATCH``). - ``tool_calls`` is optional raw tool call/response metadata (e.g. the - python-docs-mcp-stdio adapter's ``search_docs``/``get_docs`` payloads, - issue #86) merged into the cell's transcript record. Adapters with - nothing extra to record (the fake adapter) leave it ``None``. + ``tool_calls`` is optional raw tool call/response metadata merged into + the cell's transcript record. Adapters with nothing extra to record (the + fake adapter) leave it ``None``. """ answer: str @@ -506,186 +499,15 @@ def _fake_adapter_answer(cell: BenchmarkCell) -> _CellDispatchResult: return _CellDispatchResult(answer=f"[fake:{cell.competitor.id}] {cell.question.prompt}") -def _python_docs_mcp_stdio_answer(cell: BenchmarkCell) -> _CellDispatchResult: - """Dispatch to the offline python-docs-mcp-server stdio adapter (issue #86). - - Imported lazily to avoid a module-level import cycle: adapter modules - import ``BenchmarkCellFailure`` from this module, so this module cannot - import from ``benchmarks.adapters`` at module scope. - """ - from benchmarks.adapters.python_docs_mcp_adapter import PythonDocsMcpAdapter - - result = PythonDocsMcpAdapter().run(cell.question.prompt) - return _CellDispatchResult( - answer=result.answer, - tool_calls=[ - { - "tool": call.tool, - "arguments": call.arguments, - "result": call.result, - "is_error": call.is_error, - } - for call in result.tool_calls - ], - ) - - -def _tool_call_records_to_dicts(tool_calls: Any) -> list[dict[str, Any]]: - """Convert a list of adapter ``ToolCallRecord``s to transcript dicts. - - Shared by the four competitor dispatch functions below (issue #87); - each competitor adapter module defines its own frozen ``ToolCallRecord`` - dataclass (same ``tool``/``arguments``/``result``/``is_error`` shape as - ``python_docs_mcp_adapter.ToolCallRecord``), so this converts any of - them structurally without importing a specific one. - """ - return [ - { - "tool": call.tool, - "arguments": call.arguments, - "result": call.result, - "is_error": call.is_error, - } - for call in tool_calls - ] - - -def _context7_answer(cell: BenchmarkCell) -> _CellDispatchResult: - """Dispatch to the Context7 competitor adapter (issue #87). - - Imported lazily to avoid a module-level import cycle (see - ``_python_docs_mcp_stdio_answer``). Reads endpoint/mode/key-mode/timeout - overrides from the manifest entry's raw config (``cell.competitor.raw``); - the adapter itself reads the actual API key value from - ``CONTEXT7_API_KEY`` (see - ``benchmarks.adapters.context7_adapter.Context7Adapter``). - - Re-validates eligibility (plan §2.4 defense in depth): unreachable for - an excluded competitor by construction, since ``_validate_manifest_eligibility`` - already refused at manifest-load time before any cell was built. - """ - from benchmarks.adapters.context7_adapter import Context7Adapter - from benchmarks.adapters.eligibility import validate_competitor_eligibility - - raw = cell.competitor.raw - validate_competitor_eligibility(raw) - kwargs: dict[str, Any] = {} - if isinstance(raw.get("mode"), str): - kwargs["mode"] = raw["mode"] - if isinstance(raw.get("endpoint"), str): - kwargs["endpoint"] = raw["endpoint"] - if isinstance(raw.get("key_mode"), bool): - kwargs["key_mode"] = raw["key_mode"] - if isinstance(raw.get("timeout_seconds"), (int, float)): - kwargs["timeout_seconds"] = float(raw["timeout_seconds"]) - - result = Context7Adapter(**kwargs).run(cell.question.prompt) - return _CellDispatchResult( - answer=result.answer, tool_calls=_tool_call_records_to_dicts(result.tool_calls) - ) - - -def _gitmcp_answer(cell: BenchmarkCell) -> _CellDispatchResult: - """Dispatch to the GitMCP competitor adapter (issue #87). - - Imported lazily to avoid a module-level import cycle (see - ``_python_docs_mcp_stdio_answer``). - - Re-validates eligibility (plan §2.4 defense in depth): unreachable for - an excluded competitor by construction, since ``_validate_manifest_eligibility`` - already refused at manifest-load time before any cell was built. - """ - from benchmarks.adapters.eligibility import validate_competitor_eligibility - from benchmarks.adapters.gitmcp_adapter import GitMcpAdapter - - raw = cell.competitor.raw - validate_competitor_eligibility(raw) - kwargs: dict[str, Any] = {} - if isinstance(raw.get("endpoint"), str): - kwargs["endpoint"] = raw["endpoint"] - if isinstance(raw.get("timeout_seconds"), (int, float)): - kwargs["timeout_seconds"] = float(raw["timeout_seconds"]) - - result = GitMcpAdapter(**kwargs).run(cell.question.prompt) - return _CellDispatchResult( - answer=result.answer, tool_calls=_tool_call_records_to_dicts(result.tool_calls) - ) - - -def _deepwiki_answer(cell: BenchmarkCell) -> _CellDispatchResult: - """Dispatch to the DeepWiki competitor adapter (issue #87). - - Imported lazily to avoid a module-level import cycle (see - ``_python_docs_mcp_stdio_answer``). - - Re-validates eligibility (plan §2.4 defense in depth): unreachable for - an excluded competitor by construction, since ``_validate_manifest_eligibility`` - already refused at manifest-load time before any cell was built. - """ - from benchmarks.adapters.deepwiki_adapter import DeepWikiAdapter - from benchmarks.adapters.eligibility import validate_competitor_eligibility - - raw = cell.competitor.raw - validate_competitor_eligibility(raw) - kwargs: dict[str, Any] = {} - if isinstance(raw.get("endpoint"), str): - kwargs["endpoint"] = raw["endpoint"] - if isinstance(raw.get("repo_name"), str): - kwargs["repo_name"] = raw["repo_name"] - if isinstance(raw.get("timeout_seconds"), (int, float)): - kwargs["timeout_seconds"] = float(raw["timeout_seconds"]) - - result = DeepWikiAdapter(**kwargs).run(cell.question.prompt) - return _CellDispatchResult( - answer=result.answer, tool_calls=_tool_call_records_to_dicts(result.tool_calls) - ) - - -def _ref_tools_answer(cell: BenchmarkCell) -> _CellDispatchResult: - """Dispatch to the Ref.tools competitor adapter (issue #87). - - Imported lazily to avoid a module-level import cycle (see - ``_python_docs_mcp_stdio_answer``). Reads endpoint/timeout overrides - from the manifest entry's raw config; the adapter itself reads the - required API key value from ``REF_API_KEY`` (see - ``benchmarks.adapters.ref_tools_adapter.RefToolsAdapter``). - - Re-validates eligibility (plan §2.4 defense in depth): unreachable for - an excluded competitor by construction, since ``_validate_manifest_eligibility`` - already refused at manifest-load time before any cell was built. - """ - from benchmarks.adapters.eligibility import validate_competitor_eligibility - from benchmarks.adapters.ref_tools_adapter import RefToolsAdapter - - raw = cell.competitor.raw - validate_competitor_eligibility(raw) - kwargs: dict[str, Any] = {} - if isinstance(raw.get("endpoint"), str): - kwargs["endpoint"] = raw["endpoint"] - if isinstance(raw.get("timeout_seconds"), (int, float)): - kwargs["timeout_seconds"] = float(raw["timeout_seconds"]) - - result = RefToolsAdapter(**kwargs).run(cell.question.prompt) - return _CellDispatchResult( - answer=result.answer, tool_calls=_tool_call_records_to_dicts(result.tool_calls) - ) - - #: Adapter-id -> dispatch function registry (issue #86), replacing the #: prior hardcoded ``_EXECUTABLE_ADAPTERS`` allowlist membership check. #: Adding a new dispatchable adapter means adding one entry here; an #: unrecognized adapter id still fails cleanly with a ``tool_failure`` #: (see ``_dispatch_adapter``), matching the prior allowlist's behavior. -#: The four competitor entries (issue #87) are additionally screened at -#: manifest-load time by ``_validate_manifest_eligibility`` before any cell -#: (and therefore any of these dispatch functions) ever runs. +#: Competitor entries (issue #87) are still screened at manifest-load time by +#: ``_validate_manifest_eligibility`` before any cell runs. _ADAPTER_DISPATCH: dict[str, Callable[[BenchmarkCell], _CellDispatchResult]] = { "fake": _fake_adapter_answer, - "python-docs-mcp-stdio": _python_docs_mcp_stdio_answer, - "context7": _context7_answer, - "gitmcp": _gitmcp_answer, - "deepwiki": _deepwiki_answer, - "ref-tools": _ref_tools_answer, } diff --git a/docs/benchmarks/competitor-manifest.template.yml b/docs/benchmarks/competitor-manifest.template.yml index ce4c2183..8ab899c5 100644 --- a/docs/benchmarks/competitor-manifest.template.yml +++ b/docs/benchmarks/competitor-manifest.template.yml @@ -18,13 +18,12 @@ # fetch of its own (see the run's forbidden-territory list: zero live # network calls anywhere in this task). # -# The `python-docs-mcp-server` (adapter: python-docs-mcp-stdio) entry from -# the methodology's candidate matrix is NOT repeated here -- it carries no -# pin/terms_check metadata (issue #86) and belongs in a full run manifest -# assembled separately; this template covers only the four competitor -# docs-MCP adapters added by issue #87. The fixed flow has no no-MCP -# baseline adapter; the agentic harness adds a `no-docs` arm instead -# (AGENTIC-BENCHMARK-DESIGN.md section 5). +# The fixed-flow adapters these entries once dispatched to are gone +# (AGENTIC-BENCHMARK-DESIGN.md section 11.1). Round 2 runs these +# competitors through the agentic MCP bridge (benchmarks/agentic/bridge.py), +# still behind the pin, terms and eligibility gates recorded here; the +# round-1 systems (python-docs, docs-fetch, no-docs) live in +# docs/benchmarks/agentic-manifest.yml. competitors: # --- Context7 (Upstash) ----------------------------------------------- diff --git a/tests/benchmarks/test_adapters.py b/tests/benchmarks/test_adapters.py index eceaf2ff..23fb9a8f 100644 --- a/tests/benchmarks/test_adapters.py +++ b/tests/benchmarks/test_adapters.py @@ -4,16 +4,7 @@ import pytest -from benchmarks.adapters import ( - AdapterRequest, - BenchmarkCellFailure, - LiveExecutionNotImplementedError, - LiveGoogleAdapter, - LiveOpenAIAdapter, - LiveProviderDisabledError, - MockGoogleAdapter, - MockOpenAIAdapter, -) +from benchmarks.adapters import LiveProviderDisabledError from benchmarks.adapters.guard import ( LIVE_PROVIDERS_ENABLED_ENV, PROVIDER_API_KEY_ENV, @@ -21,88 +12,6 @@ require_live_environment, ) - -def _request(model_id: str = "gpt-4o-mini") -> AdapterRequest: - return AdapterRequest( - model_family_id="openai-test", - model_id=model_id, - prompt="What does pathlib.Path.read_text return?", - ) - - -# --- Mock OpenAI adapter ----------------------------------------------------- - - -def test_mock_openai_adapter_returns_structured_response_without_network() -> None: - adapter = MockOpenAIAdapter() - - response = adapter.generate(_request()) - - assert response.answer - assert response.latency_ms >= 0 - assert response.tokens.provider_native_tokens == 42 - assert response.tokens.provider_token_field == "usage.total_tokens" - assert response.raw["provider"] == "openai" - assert response.raw["mock"] is True - - -def test_mock_openai_adapter_uses_configured_fake_answer() -> None: - adapter = MockOpenAIAdapter(fake_answer="a canned answer", fake_native_tokens=7) - - response = adapter.generate(_request()) - - assert response.answer == "a canned answer" - assert response.tokens.provider_native_tokens == 7 - - -@pytest.mark.parametrize("category", ["tool_failure", "timeout", "mcp_protocol_crash"]) -def test_mock_openai_adapter_captures_forced_failures(category: str) -> None: - adapter = MockOpenAIAdapter(force_failure=category) - - with pytest.raises(BenchmarkCellFailure) as exc_info: - adapter.generate(_request()) - - assert exc_info.value.category == category - - -# --- Mock Google adapter ----------------------------------------------------- - - -def test_mock_google_adapter_returns_structured_response_without_network() -> None: - adapter = MockGoogleAdapter() - - response = adapter.generate( - AdapterRequest( - model_family_id="google-test", - model_id="gemini-1.5-flash", - prompt="What does pathlib.Path.read_text return?", - ) - ) - - assert response.answer - assert response.latency_ms >= 0 - assert response.tokens.provider_native_tokens == 37 - assert response.tokens.provider_token_field == "usage_metadata.total_token_count" - assert response.raw["provider"] == "google" - assert response.raw["mock"] is True - - -@pytest.mark.parametrize("category", ["tool_failure", "timeout", "mcp_protocol_crash"]) -def test_mock_google_adapter_captures_forced_failures(category: str) -> None: - adapter = MockGoogleAdapter(force_failure=category) - - with pytest.raises(BenchmarkCellFailure) as exc_info: - adapter.generate( - AdapterRequest( - model_family_id="google-test", - model_id="gemini-1.5-flash", - prompt="prompt", - ) - ) - - assert exc_info.value.category == category - - # --- Live-provider guardrail -------------------------------------------------- @@ -242,56 +151,3 @@ def test_redact_api_keys_stays_linear_on_a_large_body_with_many_matches( assert redacted == ("[redacted]" + filler) * 20_000 # Rebuilding the string once per match took seconds here; one pass takes milliseconds. assert elapsed < 1.0 - - -# --- Live adapter stubs: guard enforced, no network ever possible ----------- - - -def test_live_openai_adapter_refuses_without_config(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.delenv(LIVE_PROVIDERS_ENABLED_ENV, raising=False) - monkeypatch.delenv(PROVIDER_API_KEY_ENV["openai"], raising=False) - adapter = LiveOpenAIAdapter() - - with pytest.raises(LiveProviderDisabledError): - adapter.generate(_request()) - - -def test_live_openai_adapter_still_refuses_when_config_present( - monkeypatch: pytest.MonkeyPatch, -) -> None: - # Even with the guardrail satisfied, this release never makes a live - # call: live execution is reserved for a maintainer-run phase. - monkeypatch.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") - monkeypatch.setenv(PROVIDER_API_KEY_ENV["openai"], "sk-fake-not-a-real-key") - adapter = LiveOpenAIAdapter() - - with pytest.raises(LiveExecutionNotImplementedError): - adapter.generate(_request()) - - -def test_live_google_adapter_refuses_without_config(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.delenv(LIVE_PROVIDERS_ENABLED_ENV, raising=False) - monkeypatch.delenv(PROVIDER_API_KEY_ENV["google"], raising=False) - adapter = LiveGoogleAdapter() - - with pytest.raises(LiveProviderDisabledError): - adapter.generate( - AdapterRequest( - model_family_id="google-test", model_id="gemini-1.5-flash", prompt="prompt" - ) - ) - - -def test_live_google_adapter_still_refuses_when_config_present( - monkeypatch: pytest.MonkeyPatch, -) -> None: - monkeypatch.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") - monkeypatch.setenv(PROVIDER_API_KEY_ENV["google"], "fake-not-a-real-key") - adapter = LiveGoogleAdapter() - - with pytest.raises(LiveExecutionNotImplementedError): - adapter.generate( - AdapterRequest( - model_family_id="google-test", model_id="gemini-1.5-flash", prompt="prompt" - ) - ) diff --git a/tests/benchmarks/test_claude_tokens.py b/tests/benchmarks/test_claude_tokens.py index bce64545..9cc97a68 100644 --- a/tests/benchmarks/test_claude_tokens.py +++ b/tests/benchmarks/test_claude_tokens.py @@ -79,8 +79,8 @@ def test_envelope_wraps_tool_call_results_as_tool_result_blocks() -> None: def test_envelope_is_approximation_when_built_from_a_provider_mock_payload() -> None: - # MockOpenAIAdapter/MockGoogleAdapter (and their live-stub counterparts) - # never call a real client SDK, so there is no real wrapped envelope to + # A provider mock (a payload marked "mock": True) + # never calls a real client SDK, so there is no real wrapped envelope to # recover -- the methodology requires marking that gap, not guessing. envelope, approximation = build_client_wrapped_envelope( "prompt", provider_mock_payload={"provider": "openai", "mock": True} diff --git a/tests/benchmarks/test_competitor_adapters.py b/tests/benchmarks/test_competitor_adapters.py deleted file mode 100644 index d74b0ef0..00000000 --- a/tests/benchmarks/test_competitor_adapters.py +++ /dev/null @@ -1,1287 +0,0 @@ -"""Tests for the competitor MCP tool adapters (issue #87). - -Covers, per ``PLAN-87-competitor-adapters.md`` section 4 (mirrored as a -comment on issue #87): - -1. Flow tests per adapter against a scripted/fake MCP session -- no real - transport, no subprocess, no network. -2. Failure-category mapping per adapter (``tool_failure`` / ``timeout`` / - ``mcp_protocol_crash``). -3. Guard refusals fail closed: every disabled-env permutation refuses - before any transport construction (each adapter's owned - ``_transport_factory`` seam, plus ``asyncio.run`` and ``socket.socket``, - are all patched to raise if reached). -4. ``require_live_competitor`` latch semantics in isolation. -5. Eligibility/exclusion: per-entry and manifest-level validation, the - runner's manifest-load-time refusal (including the CLI exit-2 path), - the ``exclusions:`` block's byte-for-byte snapshot survival, and the - committed template manifest. -6. Registry integration: each of the four adapter ids dispatches to the - right adapter class via ``benchmarks.runner``. - -Zero network calls anywhere in this file, by construction: every test -either drives pure orchestration functions against a fake session, or -proves a transport-construction seam is never reached. -""" - -from __future__ import annotations - -import asyncio -import json -import socket -import subprocess -import sys -from dataclasses import dataclass, field -from pathlib import Path -from typing import Any - -import pytest -import yaml - -import benchmarks.adapters.context7_adapter as context7_adapter -import benchmarks.adapters.deepwiki_adapter as deepwiki_adapter -import benchmarks.adapters.gitmcp_adapter as gitmcp_adapter -import benchmarks.adapters.python_docs_mcp_adapter as python_docs_mcp_adapter -import benchmarks.adapters.ref_tools_adapter as ref_tools_adapter -from benchmarks.adapters.eligibility import ( - COMPETITOR_ADAPTER_IDS, - validate_competitor_eligibility, - validate_manifest_eligibility, -) -from benchmarks.adapters.guard import ( - LIVE_COMPETITORS_ENV, - LIVE_PROVIDERS_ENABLED_ENV, - PROVIDER_API_KEY_ENV, - LiveProviderDisabledError, - require_live_competitor, -) -from benchmarks.runner import ( - BenchmarkCellFailure, - BenchmarkConfig, - BenchmarkValidationError, - run_benchmark, -) - -_REPO_ROOT = Path(__file__).resolve().parents[2] -_TEMPLATE_MANIFEST_PATH = ( - _REPO_ROOT / "docs" / "benchmarks" / "competitor-manifest.template.yml" -) - -#: Shared fixture URL for GitMCP/Ref.tools search-hit -> fetch/read flow -#: tests below -- kept short to fit within the project's line-length limit. -_PATHLIB_DOC_URL = "https://docs.python.org/3/library/pathlib.html" - - -# --- Shared fake MCP transport (no real session, no network) --------------- - - -@dataclass -class _FakeContentBlock: - text: str - - -@dataclass -class _FakeCallToolResult: - content: list[Any] = field(default_factory=list) - structured_content: dict[str, Any] | None = None - is_error: bool = False - - -class _ScriptedSession: - """A minimal fake MCP session returning one scripted result per tool. - - No real transport, no subprocess, no network -- shared across all four - competitor adapters' flow tests below since each adapter module's - ``_CallToolSession``/``_CallToolResult`` are structural (``Protocol``) - types, not concrete classes to subclass. - """ - - def __init__(self, responses: dict[str, _FakeCallToolResult]) -> None: - self._responses = responses - self.calls: list[tuple[str, dict[str, Any]]] = [] - - async def call_tool( - self, name: str, arguments: dict[str, Any] | None = None - ) -> _FakeCallToolResult: - self.calls.append((name, arguments or {})) - return self._responses[name] - - -def _result( - *, - text: str | None = "ignored", - structured: dict[str, Any] | None = None, - is_error: bool = False, -) -> _FakeCallToolResult: - content = [_FakeContentBlock(text=text)] if text is not None else [] - return _FakeCallToolResult(content=content, structured_content=structured, is_error=is_error) - - -def _patch_no_transport(monkeypatch: pytest.MonkeyPatch, module: Any) -> None: - """Prove no transport/subprocess/socket is ever reached for a guard refusal. - - Patches the adapter module's owned ``_transport_factory`` seam (the one - symbol all transport construction is routed through, per PLAN-87 - section 2.1/Codex round-1 finding 4), plus ``asyncio.run`` (so - ``_run_async`` can never even begin), the global ``socket.socket``, and - the global ``subprocess.Popen`` (defense-in-depth for Context7's stdio - path, matching the fail-closed pattern established by - ``test_python_docs_mcp_adapter.py::test_run_missing_index_check_never_opens_a_socket`` - and PLAN-87 section 4 item 3's "subprocess/stdio + socket.socket" list). - """ - - def _boom(*args: Any, **kwargs: Any) -> Any: - raise AssertionError("network reached") - - monkeypatch.setattr(module, "_transport_factory", _boom) - monkeypatch.setattr(module.asyncio, "run", _boom) - monkeypatch.setattr(socket, "socket", _boom) - monkeypatch.setattr(subprocess, "Popen", _boom) - - -# ============================================================================= -# 1 + 2. Flow tests and failure-category mapping, per adapter -# ============================================================================= - - -# --- Context7: resolve-library-id -> query-docs ----------------------------- - - -async def test_context7_flow_calls_resolve_then_query_and_records_payloads() -> None: - session = _ScriptedSession( - { - "resolve-library-id": _result( - structured={"results": [{"id": "/python/cpython", "title": "Python"}]} - ), - "query-docs": _result(text="TaskGroup docs content"), - } - ) - - result = await context7_adapter._run_context7_flow( - session, "asyncio.TaskGroup", library_name="Python" - ) - - assert result.answer == "TaskGroup docs content" - assert [call.tool for call in result.tool_calls] == ["resolve-library-id", "query-docs"] - assert session.calls[0] == ( - "resolve-library-id", - {"libraryName": "Python", "query": "asyncio.TaskGroup"}, - ) - assert session.calls[1] == ( - "query-docs", - {"libraryId": "/python/cpython", "query": "asyncio.TaskGroup"}, - ) - assert result.tool_calls[0].is_error is False - - -async def test_context7_flow_falls_back_to_text_regex_when_no_structured_candidates() -> None: - # Context7 3.2.3 text: the team-filter note, then the labeled result list. - resolve_text = ( - "Note: results are filtered by your team's library policies. " - "Manage them at https://context7.com/dashboard?tab=policies\n" - "\n" - "Available Libraries:\n" - "- Title: Python\n" - "- Context7-compatible library ID: /python/cpython\n" - "- Description: ...\n" - ) - session = _ScriptedSession( - { - "resolve-library-id": _result(text=resolve_text), - "query-docs": _result(text="content"), - } - ) - - await context7_adapter._run_context7_flow(session, "q") - - assert session.calls[1][1]["libraryId"] == "/python/cpython" - - -async def test_context7_flow_ignores_an_unlabeled_library_id() -> None: - session = _ScriptedSession( - { - "resolve-library-id": _result(text="Best match: /python/cpython (Python stdlib)"), - "query-docs": _result(text="content"), - } - ) - - result = await context7_adapter._run_context7_flow(session, "q") - - assert len(result.tool_calls) == 1 - assert result.answer == "" - - -async def test_context7_flow_falls_back_to_structured_content_when_no_text_block() -> None: - session = _ScriptedSession( - { - "resolve-library-id": _FakeCallToolResult( - content=[], structured_content={"results": [{"id": "/python/cpython"}]} - ), - "query-docs": _FakeCallToolResult( - content=[], structured_content={"content": "structured docs"} - ), - } - ) - - result = await context7_adapter._run_context7_flow(session, "q") - - assert result.answer == "structured docs" - - -async def test_context7_flow_returns_empty_answer_when_no_library_id_found() -> None: - session = _ScriptedSession( - {"resolve-library-id": _result(text="no matches found", structured={"results": []})} - ) - - result = await context7_adapter._run_context7_flow(session, "q") - - assert result.answer == "" - assert len(result.tool_calls) == 1 - assert result.tool_calls[0].tool == "resolve-library-id" - - -async def test_context7_flow_raises_tool_failure_when_resolve_errors() -> None: - session = _ScriptedSession({"resolve-library-id": _result(text="boom", is_error=True)}) - - with pytest.raises(BenchmarkCellFailure) as exc_info: - await context7_adapter._run_context7_flow(session, "q") - - assert exc_info.value.category == "tool_failure" - assert "boom" in str(exc_info.value) - - -async def test_context7_flow_raises_tool_failure_when_query_docs_errors() -> None: - session = _ScriptedSession( - { - "resolve-library-id": _result(structured={"results": [{"id": "/python/cpython"}]}), - "query-docs": _result(text="boom", is_error=True), - } - ) - - with pytest.raises(BenchmarkCellFailure) as exc_info: - await context7_adapter._run_context7_flow(session, "q") - - assert exc_info.value.category == "tool_failure" - - -# --- GitMCP: doc-search -> (code-search -> fetch) fallback ------------------ - - -async def test_gitmcp_flow_uses_doc_search_hit_when_available() -> None: - session = _ScriptedSession( - { - "search_cpython_documentation": _result( - structured={"hits": [{"url": _PATHLIB_DOC_URL}]} - ), - "fetch_generic_url_content": _result(text="pathlib docs"), - } - ) - - result = await gitmcp_adapter._run_gitmcp_flow(session, "pathlib.Path.read_text") - - assert result.answer == "pathlib docs" - assert [call.tool for call in result.tool_calls] == [ - "search_cpython_documentation", - "fetch_generic_url_content", - ] - - -async def test_gitmcp_flow_falls_back_to_code_search_when_doc_search_has_no_hits() -> None: - session = _ScriptedSession( - { - "search_cpython_documentation": _result(structured={"hits": []}, text=""), - "search_cpython_code": _result( - structured={ - "results": [ - { - "url": ( - "https://github.com/python/cpython/blob/main/" - "Doc/library/pathlib.rst" - ) - } - ] - } - ), - "fetch_generic_url_content": _result(text="pathlib rst content"), - } - ) - - result = await gitmcp_adapter._run_gitmcp_flow(session, "pathlib.Path.read_text") - - assert [call.tool for call in result.tool_calls] == [ - "search_cpython_documentation", - "search_cpython_code", - "fetch_generic_url_content", - ] - assert result.answer == "pathlib rst content" - - -async def test_gitmcp_flow_returns_empty_answer_when_no_url_found_anywhere() -> None: - session = _ScriptedSession( - { - "search_cpython_documentation": _result(structured={"hits": []}, text=""), - "search_cpython_code": _result(structured={"results": []}, text=""), - } - ) - - result = await gitmcp_adapter._run_gitmcp_flow(session, "q") - - assert result.answer == "" - assert [call.tool for call in result.tool_calls] == [ - "search_cpython_documentation", - "search_cpython_code", - ] - - -async def test_gitmcp_flow_falls_back_to_structured_content_when_no_text_block() -> None: - session = _ScriptedSession( - { - "search_cpython_documentation": _FakeCallToolResult( - content=[], - structured_content={"hits": [{"url": _PATHLIB_DOC_URL}]}, - ), - "fetch_generic_url_content": _FakeCallToolResult( - content=[], structured_content={"text": "structured fetch text"} - ), - } - ) - - result = await gitmcp_adapter._run_gitmcp_flow(session, "q") - - assert result.answer == "structured fetch text" - - -async def test_gitmcp_flow_fetches_the_doc_search_url_without_its_bracket() -> None: - readme = "https://github.com/python/cpython/blob/main/README.rst" - session = _ScriptedSession( - { - "search_cpython_documentation": _result( - text=f"#### (README.rst)[{readme}] (Score: 1)" - ), - "fetch_generic_url_content": _result(text="readme content"), - } - ) - - await gitmcp_adapter._run_gitmcp_flow(session, "q") - - assert session.calls[1] == ("fetch_generic_url_content", {"url": readme}) - - -async def test_gitmcp_flow_raises_tool_failure_when_doc_search_errors() -> None: - session = _ScriptedSession( - {"search_cpython_documentation": _result(text="boom", is_error=True)} - ) - - with pytest.raises(BenchmarkCellFailure) as exc_info: - await gitmcp_adapter._run_gitmcp_flow(session, "q") - - assert exc_info.value.category == "tool_failure" - - -async def test_gitmcp_flow_raises_tool_failure_when_code_search_errors() -> None: - session = _ScriptedSession( - { - "search_cpython_documentation": _result(structured={"hits": []}, text=""), - "search_cpython_code": _result(text="boom", is_error=True), - } - ) - - with pytest.raises(BenchmarkCellFailure) as exc_info: - await gitmcp_adapter._run_gitmcp_flow(session, "q") - - assert exc_info.value.category == "tool_failure" - - -async def test_gitmcp_flow_raises_tool_failure_when_fetch_errors() -> None: - session = _ScriptedSession( - { - "search_cpython_documentation": _result( - structured={"hits": [{"url": _PATHLIB_DOC_URL}]} - ), - "fetch_generic_url_content": _result(text="boom", is_error=True), - } - ) - - with pytest.raises(BenchmarkCellFailure) as exc_info: - await gitmcp_adapter._run_gitmcp_flow(session, "q") - - assert exc_info.value.category == "tool_failure" - - -# --- DeepWiki: single ask_question call -------------------------------------- - - -async def test_deepwiki_flow_calls_ask_question_and_records_payload() -> None: - session = _ScriptedSession({"ask_question": _result(text="TaskGroup answer")}) - - result = await deepwiki_adapter._run_deepwiki_flow( - session, "asyncio.TaskGroup", repo_name="python/cpython" - ) - - assert result.answer == "TaskGroup answer" - assert session.calls[0] == ( - "ask_question", - {"repoName": "python/cpython", "question": "asyncio.TaskGroup"}, - ) - assert len(result.tool_calls) == 1 - assert result.tool_calls[0].tool == "ask_question" - - -async def test_deepwiki_flow_falls_back_to_structured_answer_when_no_text_block() -> None: - session = _ScriptedSession( - { - "ask_question": _FakeCallToolResult( - content=[], structured_content={"answer": "structured answer"} - ) - } - ) - - result = await deepwiki_adapter._run_deepwiki_flow(session, "q") - - assert result.answer == "structured answer" - - -async def test_deepwiki_flow_raises_tool_failure_on_error() -> None: - session = _ScriptedSession({"ask_question": _result(text="boom", is_error=True)}) - - with pytest.raises(BenchmarkCellFailure) as exc_info: - await deepwiki_adapter._run_deepwiki_flow(session, "q") - - assert exc_info.value.category == "tool_failure" - assert "boom" in str(exc_info.value) - - -# --- Ref.tools: ref_search_documentation -> ref_read_url --------------------- - - -async def test_ref_tools_flow_calls_search_then_read_and_records_payloads() -> None: - session = _ScriptedSession( - { - "ref_search_documentation": _result( - structured={"results": [{"url": _PATHLIB_DOC_URL}]} - ), - "ref_read_url": _result(text="pathlib docs"), - } - ) - - result = await ref_tools_adapter._run_ref_tools_flow(session, "pathlib.Path.read_text") - - assert result.answer == "pathlib docs" - assert session.calls[0] == ("ref_search_documentation", {"query": "pathlib.Path.read_text"}) - assert session.calls[1] == ("ref_read_url", {"url": _PATHLIB_DOC_URL}) - - -async def test_ref_tools_flow_falls_back_to_structured_content_when_no_text_block() -> None: - session = _ScriptedSession( - { - "ref_search_documentation": _FakeCallToolResult( - content=[], - structured_content={"results": [{"url": _PATHLIB_DOC_URL}]}, - ), - "ref_read_url": _FakeCallToolResult( - content=[], structured_content={"content": "structured content"} - ), - } - ) - - result = await ref_tools_adapter._run_ref_tools_flow(session, "q") - - assert result.answer == "structured content" - - -async def test_ref_tools_flow_reads_the_url_line_not_the_overview() -> None: - session = _ScriptedSession( - { - "ref_search_documentation": _result( - text=f"overview: see https://example.org/blog.\nurl: {_PATHLIB_DOC_URL}\n" - ), - "ref_read_url": _result(text="pathlib docs"), - } - ) - - await ref_tools_adapter._run_ref_tools_flow(session, "q") - - assert session.calls[1] == ("ref_read_url", {"url": _PATHLIB_DOC_URL}) - - -async def test_ref_tools_flow_returns_empty_answer_when_no_hits() -> None: - session = _ScriptedSession({"ref_search_documentation": _result(structured={"results": []})}) - - result = await ref_tools_adapter._run_ref_tools_flow(session, "q") - - assert result.answer == "" - assert len(result.tool_calls) == 1 - - -async def test_ref_tools_flow_raises_tool_failure_when_search_errors() -> None: - session = _ScriptedSession({"ref_search_documentation": _result(text="boom", is_error=True)}) - - with pytest.raises(BenchmarkCellFailure) as exc_info: - await ref_tools_adapter._run_ref_tools_flow(session, "q") - - assert exc_info.value.category == "tool_failure" - - -async def test_ref_tools_flow_raises_tool_failure_when_read_errors() -> None: - session = _ScriptedSession( - { - "ref_search_documentation": _result( - structured={"results": [{"url": _PATHLIB_DOC_URL}]} - ), - "ref_read_url": _result(text="boom", is_error=True), - } - ) - - with pytest.raises(BenchmarkCellFailure) as exc_info: - await ref_tools_adapter._run_ref_tools_flow(session, "q") - - assert exc_info.value.category == "tool_failure" - - -# --- run()-level failure-category mapping: timeout / mcp_protocol_crash ----- -# -# Table-driven across all five adapters: each entry pairs the adapter class -# with its Result dataclass and an env-setup function that satisfies that -# adapter's own guard (so the mapping logic inside the try/except in run() -# -- which runs only after the guard passes -- is what's actually exercised). - - -def _enable_python_docs(monkeypatch: pytest.MonkeyPatch) -> None: - # run() only checks that the index file exists before spawning. - monkeypatch.setattr(python_docs_mcp_adapter, "_default_index_path", lambda: Path(__file__)) - - -def _enable_context7_keyless(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") - monkeypatch.setenv(LIVE_COMPETITORS_ENV, "context7") - - -def _enable_gitmcp(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") - monkeypatch.setenv(LIVE_COMPETITORS_ENV, "gitmcp") - - -def _enable_deepwiki(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") - monkeypatch.setenv(LIVE_COMPETITORS_ENV, "deepwiki") - - -def _enable_ref_tools(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") - monkeypatch.setenv(PROVIDER_API_KEY_ENV["ref"], "fake-not-a-real-key") - - -_ADAPTER_MAPPING_CASES = [ - pytest.param( - python_docs_mcp_adapter.PythonDocsMcpAdapter, - python_docs_mcp_adapter.PythonDocsMcpResult, - _enable_python_docs, - id="python-docs", - ), - pytest.param( - context7_adapter.Context7Adapter, - context7_adapter.Context7Result, - _enable_context7_keyless, - id="context7", - ), - pytest.param( - gitmcp_adapter.GitMcpAdapter, gitmcp_adapter.GitMcpResult, _enable_gitmcp, id="gitmcp" - ), - pytest.param( - deepwiki_adapter.DeepWikiAdapter, - deepwiki_adapter.DeepWikiResult, - _enable_deepwiki, - id="deepwiki", - ), - pytest.param( - ref_tools_adapter.RefToolsAdapter, - ref_tools_adapter.RefToolsResult, - _enable_ref_tools, - id="ref-tools", - ), -] - - -@pytest.mark.parametrize("adapter_cls,result_cls,enable_guard", _ADAPTER_MAPPING_CASES) -def test_adapter_maps_a_slow_call_to_a_timeout_failure( - adapter_cls: type, result_cls: type, enable_guard: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - enable_guard(monkeypatch) - - async def _slow_run_async(self: Any, prompt: str) -> Any: - await asyncio.sleep(1) - return result_cls(answer="too late", tool_calls=[]) - - monkeypatch.setattr(adapter_cls, "_run_async", _slow_run_async) - adapter = adapter_cls(timeout_seconds=0.01) - - with pytest.raises(BenchmarkCellFailure) as exc_info: - adapter.run("anything") - - assert exc_info.value.category == "timeout" - - -@pytest.mark.parametrize("adapter_cls,result_cls,enable_guard", _ADAPTER_MAPPING_CASES) -def test_adapter_maps_an_unexpected_transport_error_to_mcp_protocol_crash( - adapter_cls: type, result_cls: type, enable_guard: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - enable_guard(monkeypatch) - - async def _broken_run_async(self: Any, prompt: str) -> Any: - raise RuntimeError("transport closed unexpectedly") - - monkeypatch.setattr(adapter_cls, "_run_async", _broken_run_async) - adapter = adapter_cls() - - with pytest.raises(BenchmarkCellFailure) as exc_info: - adapter.run("anything") - - assert exc_info.value.category == "mcp_protocol_crash" - assert "transport closed unexpectedly" in str(exc_info.value) - - -@pytest.mark.parametrize("adapter_cls,result_cls,enable_guard", _ADAPTER_MAPPING_CASES) -def test_adapter_propagates_benchmark_cell_failure_from_run_async_unchanged( - adapter_cls: type, result_cls: type, enable_guard: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - enable_guard(monkeypatch) - - async def _tool_level_failure(self: Any, prompt: str) -> Any: - raise BenchmarkCellFailure("tool_failure", "boom") - - monkeypatch.setattr(adapter_cls, "_run_async", _tool_level_failure) - adapter = adapter_cls() - - with pytest.raises(BenchmarkCellFailure) as exc_info: - adapter.run("anything") - - assert exc_info.value.category == "tool_failure" - assert "boom" in str(exc_info.value) - - -# mcp 2.3.0 nests a failure raised inside a session two task groups deep. -_NESTED = ExceptionGroup( - "tg", - [ - ExceptionGroup( - "tg", [BenchmarkCellFailure("tool_failure", "search_docs returned an error: boom")] - ) - ], -) -_TWO_LEAVES = ExceptionGroup( - "tg", [BenchmarkCellFailure("tool_failure", "boom"), OSError("pipe closed")] -) - - -@pytest.mark.parametrize( - "raised,message", - [ - pytest.param(_NESTED, "search_docs returned an error: boom", id="nested"), - pytest.param( - _TWO_LEAVES, "BenchmarkCellFailure: boom; OSError: pipe closed", id="two-leaves" - ), - ], -) -@pytest.mark.parametrize("adapter_cls,result_cls,enable_guard", _ADAPTER_MAPPING_CASES) -def test_adapter_maps_a_failure_group_to_its_real_reason( - adapter_cls: type, - result_cls: type, - enable_guard: Any, - raised: BaseExceptionGroup, - message: str, - monkeypatch: pytest.MonkeyPatch, -) -> None: - enable_guard(monkeypatch) - - async def _group_failure(self: Any, prompt: str) -> Any: - raise raised - - monkeypatch.setattr(adapter_cls, "_run_async", _group_failure) - - with pytest.raises(BenchmarkCellFailure) as exc_info: - adapter_cls().run("anything") - assert exc_info.value.category == "tool_failure" - assert str(exc_info.value) == message - assert exc_info.value.__cause__ is raised - - -# ============================================================================= -# 3. Guard refusals fail closed -- every disabled-env permutation, per adapter -# ============================================================================= - - -def _no_env(mp: pytest.MonkeyPatch, competitor: str) -> None: - pass - - -def _flag_only(mp: pytest.MonkeyPatch, competitor: str) -> None: - mp.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") - - -def _flag_plus_wrong_allowlist_entry(mp: pytest.MonkeyPatch, competitor: str) -> None: - mp.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") - mp.setenv(LIVE_COMPETITORS_ENV, f"not-{competitor}") - - -def _allowlist_only_no_flag(mp: pytest.MonkeyPatch, competitor: str) -> None: - mp.setenv(LIVE_COMPETITORS_ENV, competitor) - - -_KEYLESS_REFUSAL_CASES = [ - pytest.param(_no_env, id="no-flag-no-allowlist"), - pytest.param(_flag_only, id="flag-only-no-allowlist"), - pytest.param(_flag_plus_wrong_allowlist_entry, id="flag-plus-wrong-allowlist-entry"), - pytest.param(_allowlist_only_no_flag, id="allowlist-only-no-flag"), -] - -_KEYLESS_ADAPTERS = [ - pytest.param( - context7_adapter, - context7_adapter.Context7Adapter, - "context7", - id="context7-keyless", - ), - pytest.param(gitmcp_adapter, gitmcp_adapter.GitMcpAdapter, "gitmcp", id="gitmcp"), - pytest.param( - deepwiki_adapter, deepwiki_adapter.DeepWikiAdapter, "deepwiki", id="deepwiki" - ), -] - - -@pytest.mark.parametrize("module,make_adapter,competitor", _KEYLESS_ADAPTERS) -@pytest.mark.parametrize("env_setup", _KEYLESS_REFUSAL_CASES) -def test_keyless_competitor_adapters_refuse_and_never_build_transport( - module: Any, - make_adapter: Any, - competitor: str, - env_setup: Any, - monkeypatch: pytest.MonkeyPatch, -) -> None: - monkeypatch.delenv(LIVE_PROVIDERS_ENABLED_ENV, raising=False) - monkeypatch.delenv(LIVE_COMPETITORS_ENV, raising=False) - env_setup(monkeypatch, competitor) - _patch_no_transport(monkeypatch, module) - - with pytest.raises(LiveProviderDisabledError): - make_adapter().run("anything") - - -def _no_env_keyed(mp: pytest.MonkeyPatch, key_env: str) -> None: - pass - - -def _flag_no_key(mp: pytest.MonkeyPatch, key_env: str) -> None: - mp.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") - - -def _key_no_flag(mp: pytest.MonkeyPatch, key_env: str) -> None: - mp.setenv(key_env, "fake-not-a-real-key") - - -_KEYED_REFUSAL_CASES = [ - pytest.param(_no_env_keyed, id="no-flag-no-key"), - pytest.param(_flag_no_key, id="flag-no-key"), - pytest.param(_key_no_flag, id="key-no-flag"), -] - -_KEYED_ADAPTERS = [ - pytest.param( - context7_adapter, - lambda: context7_adapter.Context7Adapter(key_mode=True), - PROVIDER_API_KEY_ENV["context7"], - id="context7-keyed", - ), - pytest.param( - ref_tools_adapter, - ref_tools_adapter.RefToolsAdapter, - PROVIDER_API_KEY_ENV["ref"], - id="ref-tools", - ), -] - - -@pytest.mark.parametrize("module,make_adapter,key_env", _KEYED_ADAPTERS) -@pytest.mark.parametrize("env_setup", _KEYED_REFUSAL_CASES) -def test_keyed_competitor_adapters_refuse_and_never_build_transport( - module: Any, make_adapter: Any, key_env: str, env_setup: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.delenv(LIVE_PROVIDERS_ENABLED_ENV, raising=False) - monkeypatch.delenv(key_env, raising=False) - env_setup(monkeypatch, key_env) - _patch_no_transport(monkeypatch, module) - - with pytest.raises(LiveProviderDisabledError): - make_adapter().run("anything") - - -# --- Context7 hands the spawned or remote server only the key, only in key mode - - -class _TransportReached(Exception): - """Raised by the patched transport seam once it has seen its arguments.""" - - -@pytest.mark.parametrize( - "mode,key_mode,api_key,field_name,expected", - [ - pytest.param("stdio", True, None, "env", {"CONTEXT7_API_KEY": "k"}, id="key-stdio"), - pytest.param("stdio", False, None, "env", None, id="keyless-stdio"), - pytest.param("http", True, None, "headers", {"CONTEXT7_API_KEY": "k"}, id="key-http"), - pytest.param("http", False, None, "headers", None, id="keyless-http"), - pytest.param("stdio", False, "explicit", "env", None, id="keyless-ignores-explicit-key"), - ], -) -def test_context7_passes_only_the_key_and_only_in_key_mode( - mode: str, - key_mode: bool, - api_key: str | None, - field_name: str, - expected: dict[str, str] | None, - monkeypatch: pytest.MonkeyPatch, -) -> None: - monkeypatch.setenv("CONTEXT7_API_KEY", "k") - monkeypatch.setenv("UNRELATED_SECRET", "s") - recorded: dict[str, Any] = {} - - def _record(**kwargs: Any) -> Any: - recorded.update(kwargs) - raise _TransportReached - - monkeypatch.setattr(context7_adapter, "_transport_factory", _record) - - adapter = context7_adapter.Context7Adapter(mode=mode, key_mode=key_mode, api_key=api_key) - with pytest.raises(_TransportReached): - asyncio.run(adapter._run_async("q")) - - assert recorded[field_name] == expected - - -# ============================================================================= -# 4. require_live_competitor latch semantics in isolation -# ============================================================================= - - -def test_require_live_competitor_refuses_without_flag(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.delenv(LIVE_PROVIDERS_ENABLED_ENV, raising=False) - monkeypatch.delenv(LIVE_COMPETITORS_ENV, raising=False) - - with pytest.raises(LiveProviderDisabledError, match=LIVE_PROVIDERS_ENABLED_ENV): - require_live_competitor("gitmcp") - - -def test_require_live_competitor_refuses_with_flag_but_name_absent_from_allowlist( - monkeypatch: pytest.MonkeyPatch, -) -> None: - monkeypatch.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") - monkeypatch.setenv(LIVE_COMPETITORS_ENV, "deepwiki") - - with pytest.raises(LiveProviderDisabledError, match=LIVE_COMPETITORS_ENV): - require_live_competitor("gitmcp") - - -def test_require_live_competitor_refuses_with_allowlist_but_no_flag( - monkeypatch: pytest.MonkeyPatch, -) -> None: - monkeypatch.delenv(LIVE_PROVIDERS_ENABLED_ENV, raising=False) - monkeypatch.setenv(LIVE_COMPETITORS_ENV, "gitmcp") - - with pytest.raises(LiveProviderDisabledError, match=LIVE_PROVIDERS_ENABLED_ENV): - require_live_competitor("gitmcp") - - -def test_require_live_competitor_passes_only_with_both_latches( - monkeypatch: pytest.MonkeyPatch, -) -> None: - monkeypatch.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") - monkeypatch.setenv(LIVE_COMPETITORS_ENV, "gitmcp") - - require_live_competitor("gitmcp") # must not raise - - -def test_require_live_competitor_is_key_independent(monkeypatch: pytest.MonkeyPatch) -> None: - # No PROVIDER_API_KEY_ENV entry is consulted for a keyless competitor -- - # the allowlist is the second latch, not a key. - monkeypatch.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") - monkeypatch.setenv(LIVE_COMPETITORS_ENV, "gitmcp") - monkeypatch.delenv(PROVIDER_API_KEY_ENV["ref"], raising=False) - monkeypatch.delenv(PROVIDER_API_KEY_ENV["context7"], raising=False) - - require_live_competitor("gitmcp") # must not raise despite no key env set anywhere - - -def test_require_live_competitor_allowlist_parsing_tolerant_of_spaces_and_case( - monkeypatch: pytest.MonkeyPatch, -) -> None: - monkeypatch.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") - monkeypatch.setenv(LIVE_COMPETITORS_ENV, " GitMCP , DeepWiki ") - - require_live_competitor("gitmcp") # must not raise - require_live_competitor("deepwiki") # must not raise - require_live_competitor("GITMCP") # must not raise -- case-insensitive on both sides - - -# ============================================================================= -# 5. Eligibility / exclusion screening -# ============================================================================= - - -def _valid_competitor_entry(adapter: str = "gitmcp", **overrides: Any) -> dict[str, Any]: - entry: dict[str, Any] = { - "id": adapter, - "adapter": adapter, - "pin": { - "kind": "endpoint-date", - "value": "https://example.test", - "access_date": "2026-07-09", - }, - "terms_check": { - "verdict": "permitted", - "checked_on": "2026-07-09", - "source_url": "https://example.test/terms", - }, - "eligibility": {"status": "eligible"}, - } - entry.update(overrides) - return entry - - -def test_validate_competitor_eligibility_accepts_a_well_formed_entry() -> None: - validate_competitor_eligibility(_valid_competitor_entry()) # must not raise - - -def test_validate_competitor_eligibility_accepts_conditional_status_with_conditions() -> None: - validate_competitor_eligibility( - _valid_competitor_entry( - eligibility={"status": "conditional", "conditions": ["needs permission"]} - ) - ) # must not raise - - -def test_validate_competitor_eligibility_rejects_missing_pin() -> None: - entry = _valid_competitor_entry() - del entry["pin"] - - with pytest.raises(BenchmarkValidationError, match="pin"): - validate_competitor_eligibility(entry) - - -def test_validate_competitor_eligibility_rejects_unrecognized_pin_kind() -> None: - with pytest.raises(BenchmarkValidationError, match=r"pin\.kind"): - validate_competitor_eligibility( - _valid_competitor_entry( - pin={"kind": "made-up", "value": "x", "access_date": "2026-07-09"} - ) - ) - - -def test_validate_competitor_eligibility_rejects_missing_terms_check() -> None: - entry = _valid_competitor_entry() - del entry["terms_check"] - - with pytest.raises(BenchmarkValidationError, match="terms_check"): - validate_competitor_eligibility(entry) - - -def test_validate_competitor_eligibility_rejects_unrecognized_terms_verdict() -> None: - with pytest.raises(BenchmarkValidationError, match=r"terms_check\.verdict"): - validate_competitor_eligibility( - _valid_competitor_entry( - terms_check={ - "verdict": "maybe", - "checked_on": "2026-07-09", - "source_url": "https://example.test", - } - ) - ) - - -def test_validate_competitor_eligibility_rejects_missing_eligibility() -> None: - entry = _valid_competitor_entry() - del entry["eligibility"] - - with pytest.raises(BenchmarkValidationError, match=r"eligibility\.status"): - validate_competitor_eligibility(entry) - - -def test_validate_competitor_eligibility_rejects_excluded_status_points_to_exclusions() -> None: - with pytest.raises(BenchmarkValidationError, match="exclusions"): - validate_competitor_eligibility( - _valid_competitor_entry(eligibility={"status": "excluded"}) - ) - - -def test_validate_manifest_eligibility_skips_non_competitor_adapter_entries() -> None: - manifest = {"competitors": [{"id": "no-mcp", "adapter": "no-mcp-baseline"}]} - - validate_manifest_eligibility(manifest) # must not raise despite no pin/terms metadata - - -def test_validate_manifest_eligibility_validates_only_competitor_adapter_entries() -> None: - manifest = { - "competitors": [ - {"id": "no-mcp", "adapter": "no-mcp-baseline"}, - _valid_competitor_entry("gitmcp"), - ] - } - - validate_manifest_eligibility(manifest) # must not raise - - -def test_validate_manifest_eligibility_raises_for_excluded_competitor_entry() -> None: - manifest = { - "competitors": [_valid_competitor_entry("gitmcp", eligibility={"status": "excluded"})] - } - - with pytest.raises(BenchmarkValidationError, match="gitmcp"): - validate_manifest_eligibility(manifest) - - -def test_competitor_adapter_ids_are_a_subset_of_the_runner_dispatch_registry() -> None: - from benchmarks.runner import _ADAPTER_DISPATCH - - assert COMPETITOR_ADAPTER_IDS <= set(_ADAPTER_DISPATCH) - - -# --- Integration: runner refuses at manifest-load time, before any cell ---- - - -def _write_yaml(path: Path, data: dict[str, Any]) -> Path: - path.write_text(yaml.safe_dump(data, sort_keys=True), encoding="utf-8") - return path - - -def _corpus(tmp_path: Path) -> Path: - return _write_yaml( - tmp_path / "corpus.yml", - { - "questions": [ - { - "id": "q001", - "prompt": "What does pathlib.Path.read_text return?", - } - ] - }, - ) - - -def test_run_benchmark_refuses_manifest_with_excluded_competitor_entry_and_writes_nothing( - tmp_path: Path, -) -> None: - out_dir = tmp_path / "results" / "excluded" - manifest_path = _write_yaml( - tmp_path / "competitors.yml", - {"competitors": [_valid_competitor_entry("gitmcp", eligibility={"status": "excluded"})]}, - ) - - with pytest.raises(BenchmarkValidationError, match="gitmcp"): - run_benchmark( - BenchmarkConfig( - corpus_path=_corpus(tmp_path), manifest_path=manifest_path, out_dir=out_dir - ) - ) - - assert not out_dir.exists() - - -def test_run_benchmark_refuses_manifest_with_incomplete_pin_metadata(tmp_path: Path) -> None: - out_dir = tmp_path / "results" / "missing-pin" - entry = _valid_competitor_entry("ref-tools") - del entry["pin"] - manifest_path = _write_yaml(tmp_path / "competitors.yml", {"competitors": [entry]}) - - with pytest.raises(BenchmarkValidationError, match="ref-tools"): - run_benchmark( - BenchmarkConfig( - corpus_path=_corpus(tmp_path), manifest_path=manifest_path, out_dir=out_dir - ) - ) - - assert not out_dir.exists() - - -def test_cli_exits_2_for_manifest_with_excluded_competitor_entry(tmp_path: Path) -> None: - out_dir = tmp_path / "results" / "excluded-cli" - manifest_path = _write_yaml( - tmp_path / "competitors.yml", - {"competitors": [_valid_competitor_entry("gitmcp", eligibility={"status": "excluded"})]}, - ) - - result = subprocess.run( - [ - sys.executable, - "-m", - "benchmarks", - "run", - "--corpus", - str(_corpus(tmp_path)), - "--manifest", - str(manifest_path), - "--out", - str(out_dir), - "--dry-run", - ], - capture_output=True, - text=True, - timeout=15, - cwd=_REPO_ROOT, - ) - - assert result.returncode == 2 - assert "gitmcp" in result.stderr - assert not out_dir.exists() - - -def test_exclusions_block_passes_validation_and_survives_snapshot_byte_for_byte( - tmp_path: Path, -) -> None: - out_dir = tmp_path / "results" / "exclusions-block" - manifest_bytes = ( - b"competitors:\n" - b" - id: no-mcp\n" - b" adapter: fake\n" - b"exclusions:\n" - b" - id: some-excluded-competitor\n" - b' reason: "vendor denied benchmarking permission"\n' - b" terms_check:\n" - b" verdict: forbidden-without-permission\n" - b' checked_on: "2026-07-09"\n' - b' source_url: "https://example.test/terms"\n' - b' decided_on: "2026-07-09"\n' - ) - manifest_path = tmp_path / "competitors.yml" - manifest_path.write_bytes(manifest_bytes) - - summary = run_benchmark( - BenchmarkConfig( - corpus_path=_corpus(tmp_path), - manifest_path=manifest_path, - out_dir=out_dir, - run_id="exclusions-block", - ) - ) - - assert summary["succeeded_cells"] == 1 - assert (out_dir / "snapshots" / "competitor-manifest.yml").read_bytes() == manifest_bytes - - -# --- The committed template manifest ---------------------------------------- - - -def test_template_manifest_parses_and_validates() -> None: - data = yaml.safe_load(_TEMPLATE_MANIFEST_PATH.read_text(encoding="utf-8")) - - validate_manifest_eligibility(data) # must not raise - - competitors = data["competitors"] - assert {competitor["adapter"] for competitor in competitors} == COMPETITOR_ADAPTER_IDS - assert data["exclusions"] == [] - - -def test_template_manifest_dry_run_plans_all_four_competitor_cells(tmp_path: Path) -> None: - out_dir = tmp_path / "results" / "template-dry-run" - - summary = run_benchmark( - BenchmarkConfig( - corpus_path=_corpus(tmp_path), - manifest_path=_TEMPLATE_MANIFEST_PATH, - out_dir=out_dir, - run_id="template-dry-run", - dry_run=True, - ) - ) - - assert summary["dry_run"] is True - assert summary["planned_cells"] == 4 - assert not (out_dir / "transcripts").exists() - - -# ============================================================================= -# 6. Registry integration: manifest adapter id -> correct adapter class -# ============================================================================= - - -@pytest.mark.parametrize( - "adapter_id,module,adapter_cls,result_cls,tool_name", - [ - pytest.param( - "context7", - context7_adapter, - context7_adapter.Context7Adapter, - context7_adapter.Context7Result, - "query-docs", - id="context7", - ), - pytest.param( - "gitmcp", - gitmcp_adapter, - gitmcp_adapter.GitMcpAdapter, - gitmcp_adapter.GitMcpResult, - "fetch_generic_url_content", - id="gitmcp", - ), - pytest.param( - "deepwiki", - deepwiki_adapter, - deepwiki_adapter.DeepWikiAdapter, - deepwiki_adapter.DeepWikiResult, - "ask_question", - id="deepwiki", - ), - pytest.param( - "ref-tools", - ref_tools_adapter, - ref_tools_adapter.RefToolsAdapter, - ref_tools_adapter.RefToolsResult, - "ref_read_url", - id="ref-tools", - ), - ], -) -def test_competitor_adapter_is_dispatchable_via_manifest_adapter_id( - adapter_id: str, - module: Any, - adapter_cls: type, - result_cls: type, - tool_name: str, - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - # This test is dispatch-wiring-only (registry -> correct adapter class, - # tool_calls conversion into the transcript shape): it monkeypatches the - # adapter class's own `run` method, so it never touches the guard or any - # transport. Guard behavior is covered in section 3/4 above; flow - # behavior against a scripted session is covered in section 1 above. - def _fake_run(self: Any, prompt: str) -> Any: - return result_cls( - answer=f"fake-answer for {prompt}", - tool_calls=[ - module.ToolCallRecord( - tool=tool_name, arguments={"q": prompt}, result={"ok": True}, is_error=False - ) - ], - ) - - monkeypatch.setattr(adapter_cls, "run", _fake_run) - out_dir = tmp_path / "results" / f"dispatch-{adapter_id}" - - summary = run_benchmark( - BenchmarkConfig( - corpus_path=_corpus(tmp_path), - manifest_path=_write_yaml( - tmp_path / "competitors.yml", {"competitors": [_valid_competitor_entry(adapter_id)]} - ), - out_dir=out_dir, - run_id=f"dispatch-{adapter_id}", - ) - ) - - assert summary["succeeded_cells"] == 1 - transcript = json.loads( - (out_dir / "transcripts" / adapter_id / "q001.json").read_text(encoding="utf-8") - ) - assert transcript["status"] == "succeeded" - assert transcript["answer"].startswith("fake-answer") - assert transcript["adapter"] == adapter_id - assert transcript["tool_calls"][0]["tool"] == tool_name - assert transcript["tool_calls"][0]["is_error"] is False - assert "external_provider_calls" not in transcript diff --git a/tests/benchmarks/test_competitor_eligibility.py b/tests/benchmarks/test_competitor_eligibility.py new file mode 100644 index 00000000..5a3a2d03 --- /dev/null +++ b/tests/benchmarks/test_competitor_eligibility.py @@ -0,0 +1,381 @@ +"""Tests for the competitor guard latch and manifest eligibility gates (issue #87). + +The four fixed-flow competitor adapters and their tests are gone (design +§11.1): round 2 runs the competitors through the agentic MCP bridge. What +stays, and is covered here unchanged: + +1. ``require_live_competitor`` latch semantics in isolation. +2. Eligibility/exclusion: per-entry and manifest-level validation, the + runner's manifest-load-time refusal (including the CLI exit-2 path), + the ``exclusions:`` block's byte-for-byte snapshot survival, and the + committed template manifest. + +Zero network calls anywhere in this file, by construction. +""" + +from __future__ import annotations + +import subprocess +import sys +from pathlib import Path +from typing import Any + +import pytest +import yaml + +from benchmarks.adapters.eligibility import ( + COMPETITOR_ADAPTER_IDS, + validate_competitor_eligibility, + validate_manifest_eligibility, +) +from benchmarks.adapters.guard import ( + LIVE_COMPETITORS_ENV, + LIVE_PROVIDERS_ENABLED_ENV, + PROVIDER_API_KEY_ENV, + LiveProviderDisabledError, + require_live_competitor, +) +from benchmarks.runner import ( + BenchmarkConfig, + BenchmarkValidationError, + run_benchmark, +) + +_REPO_ROOT = Path(__file__).resolve().parents[2] +_TEMPLATE_MANIFEST_PATH = ( + _REPO_ROOT / "docs" / "benchmarks" / "competitor-manifest.template.yml" +) + + +# ============================================================================= +# 1. require_live_competitor latch semantics in isolation +# ============================================================================= + + +def test_require_live_competitor_refuses_without_flag(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv(LIVE_PROVIDERS_ENABLED_ENV, raising=False) + monkeypatch.delenv(LIVE_COMPETITORS_ENV, raising=False) + + with pytest.raises(LiveProviderDisabledError, match=LIVE_PROVIDERS_ENABLED_ENV): + require_live_competitor("gitmcp") + + +def test_require_live_competitor_refuses_with_flag_but_name_absent_from_allowlist( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") + monkeypatch.setenv(LIVE_COMPETITORS_ENV, "deepwiki") + + with pytest.raises(LiveProviderDisabledError, match=LIVE_COMPETITORS_ENV): + require_live_competitor("gitmcp") + + +def test_require_live_competitor_refuses_with_allowlist_but_no_flag( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv(LIVE_PROVIDERS_ENABLED_ENV, raising=False) + monkeypatch.setenv(LIVE_COMPETITORS_ENV, "gitmcp") + + with pytest.raises(LiveProviderDisabledError, match=LIVE_PROVIDERS_ENABLED_ENV): + require_live_competitor("gitmcp") + + +def test_require_live_competitor_passes_only_with_both_latches( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") + monkeypatch.setenv(LIVE_COMPETITORS_ENV, "gitmcp") + + require_live_competitor("gitmcp") # must not raise + + +def test_require_live_competitor_is_key_independent(monkeypatch: pytest.MonkeyPatch) -> None: + # No PROVIDER_API_KEY_ENV entry is consulted for a keyless competitor -- + # the allowlist is the second latch, not a key. + monkeypatch.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") + monkeypatch.setenv(LIVE_COMPETITORS_ENV, "gitmcp") + monkeypatch.delenv(PROVIDER_API_KEY_ENV["ref"], raising=False) + monkeypatch.delenv(PROVIDER_API_KEY_ENV["context7"], raising=False) + + require_live_competitor("gitmcp") # must not raise despite no key env set anywhere + + +def test_require_live_competitor_allowlist_parsing_tolerant_of_spaces_and_case( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") + monkeypatch.setenv(LIVE_COMPETITORS_ENV, " GitMCP , DeepWiki ") + + require_live_competitor("gitmcp") # must not raise + require_live_competitor("deepwiki") # must not raise + require_live_competitor("GITMCP") # must not raise -- case-insensitive on both sides + + +# ============================================================================= +# 2. Eligibility / exclusion screening +# ============================================================================= + + +def _valid_competitor_entry(adapter: str = "gitmcp", **overrides: Any) -> dict[str, Any]: + entry: dict[str, Any] = { + "id": adapter, + "adapter": adapter, + "pin": { + "kind": "endpoint-date", + "value": "https://example.test", + "access_date": "2026-07-09", + }, + "terms_check": { + "verdict": "permitted", + "checked_on": "2026-07-09", + "source_url": "https://example.test/terms", + }, + "eligibility": {"status": "eligible"}, + } + entry.update(overrides) + return entry + + +def test_validate_competitor_eligibility_accepts_a_well_formed_entry() -> None: + validate_competitor_eligibility(_valid_competitor_entry()) # must not raise + + +def test_validate_competitor_eligibility_accepts_conditional_status_with_conditions() -> None: + validate_competitor_eligibility( + _valid_competitor_entry( + eligibility={"status": "conditional", "conditions": ["needs permission"]} + ) + ) # must not raise + + +def test_validate_competitor_eligibility_rejects_missing_pin() -> None: + entry = _valid_competitor_entry() + del entry["pin"] + + with pytest.raises(BenchmarkValidationError, match="pin"): + validate_competitor_eligibility(entry) + + +def test_validate_competitor_eligibility_rejects_unrecognized_pin_kind() -> None: + with pytest.raises(BenchmarkValidationError, match=r"pin\.kind"): + validate_competitor_eligibility( + _valid_competitor_entry( + pin={"kind": "made-up", "value": "x", "access_date": "2026-07-09"} + ) + ) + + +def test_validate_competitor_eligibility_rejects_missing_terms_check() -> None: + entry = _valid_competitor_entry() + del entry["terms_check"] + + with pytest.raises(BenchmarkValidationError, match="terms_check"): + validate_competitor_eligibility(entry) + + +def test_validate_competitor_eligibility_rejects_unrecognized_terms_verdict() -> None: + with pytest.raises(BenchmarkValidationError, match=r"terms_check\.verdict"): + validate_competitor_eligibility( + _valid_competitor_entry( + terms_check={ + "verdict": "maybe", + "checked_on": "2026-07-09", + "source_url": "https://example.test", + } + ) + ) + + +def test_validate_competitor_eligibility_rejects_missing_eligibility() -> None: + entry = _valid_competitor_entry() + del entry["eligibility"] + + with pytest.raises(BenchmarkValidationError, match=r"eligibility\.status"): + validate_competitor_eligibility(entry) + + +def test_validate_competitor_eligibility_rejects_excluded_status_points_to_exclusions() -> None: + with pytest.raises(BenchmarkValidationError, match="exclusions"): + validate_competitor_eligibility( + _valid_competitor_entry(eligibility={"status": "excluded"}) + ) + + +def test_validate_manifest_eligibility_skips_non_competitor_adapter_entries() -> None: + manifest = {"competitors": [{"id": "no-mcp", "adapter": "no-mcp-baseline"}]} + + validate_manifest_eligibility(manifest) # must not raise despite no pin/terms metadata + + +def test_validate_manifest_eligibility_validates_only_competitor_adapter_entries() -> None: + manifest = { + "competitors": [ + {"id": "no-mcp", "adapter": "no-mcp-baseline"}, + _valid_competitor_entry("gitmcp"), + ] + } + + validate_manifest_eligibility(manifest) # must not raise + + +def test_validate_manifest_eligibility_raises_for_excluded_competitor_entry() -> None: + manifest = { + "competitors": [_valid_competitor_entry("gitmcp", eligibility={"status": "excluded"})] + } + + with pytest.raises(BenchmarkValidationError, match="gitmcp"): + validate_manifest_eligibility(manifest) + + +# --- Integration: runner refuses at manifest-load time, before any cell ---- + + +def _write_yaml(path: Path, data: dict[str, Any]) -> Path: + path.write_text(yaml.safe_dump(data, sort_keys=True), encoding="utf-8") + return path + + +def _corpus(tmp_path: Path) -> Path: + return _write_yaml( + tmp_path / "corpus.yml", + { + "questions": [ + { + "id": "q001", + "prompt": "What does pathlib.Path.read_text return?", + } + ] + }, + ) + + +def test_run_benchmark_refuses_manifest_with_excluded_competitor_entry_and_writes_nothing( + tmp_path: Path, +) -> None: + out_dir = tmp_path / "results" / "excluded" + manifest_path = _write_yaml( + tmp_path / "competitors.yml", + {"competitors": [_valid_competitor_entry("gitmcp", eligibility={"status": "excluded"})]}, + ) + + with pytest.raises(BenchmarkValidationError, match="gitmcp"): + run_benchmark( + BenchmarkConfig( + corpus_path=_corpus(tmp_path), manifest_path=manifest_path, out_dir=out_dir + ) + ) + + assert not out_dir.exists() + + +def test_run_benchmark_refuses_manifest_with_incomplete_pin_metadata(tmp_path: Path) -> None: + out_dir = tmp_path / "results" / "missing-pin" + entry = _valid_competitor_entry("ref-tools") + del entry["pin"] + manifest_path = _write_yaml(tmp_path / "competitors.yml", {"competitors": [entry]}) + + with pytest.raises(BenchmarkValidationError, match="ref-tools"): + run_benchmark( + BenchmarkConfig( + corpus_path=_corpus(tmp_path), manifest_path=manifest_path, out_dir=out_dir + ) + ) + + assert not out_dir.exists() + + +def test_cli_exits_2_for_manifest_with_excluded_competitor_entry(tmp_path: Path) -> None: + out_dir = tmp_path / "results" / "excluded-cli" + manifest_path = _write_yaml( + tmp_path / "competitors.yml", + {"competitors": [_valid_competitor_entry("gitmcp", eligibility={"status": "excluded"})]}, + ) + + result = subprocess.run( + [ + sys.executable, + "-m", + "benchmarks", + "run", + "--corpus", + str(_corpus(tmp_path)), + "--manifest", + str(manifest_path), + "--out", + str(out_dir), + "--dry-run", + ], + capture_output=True, + text=True, + timeout=15, + cwd=_REPO_ROOT, + ) + + assert result.returncode == 2 + assert "gitmcp" in result.stderr + assert not out_dir.exists() + + +def test_exclusions_block_passes_validation_and_survives_snapshot_byte_for_byte( + tmp_path: Path, +) -> None: + out_dir = tmp_path / "results" / "exclusions-block" + manifest_bytes = ( + b"competitors:\n" + b" - id: no-mcp\n" + b" adapter: fake\n" + b"exclusions:\n" + b" - id: some-excluded-competitor\n" + b' reason: "vendor denied benchmarking permission"\n' + b" terms_check:\n" + b" verdict: forbidden-without-permission\n" + b' checked_on: "2026-07-09"\n' + b' source_url: "https://example.test/terms"\n' + b' decided_on: "2026-07-09"\n' + ) + manifest_path = tmp_path / "competitors.yml" + manifest_path.write_bytes(manifest_bytes) + + summary = run_benchmark( + BenchmarkConfig( + corpus_path=_corpus(tmp_path), + manifest_path=manifest_path, + out_dir=out_dir, + run_id="exclusions-block", + ) + ) + + assert summary["succeeded_cells"] == 1 + assert (out_dir / "snapshots" / "competitor-manifest.yml").read_bytes() == manifest_bytes + + +# --- The committed template manifest ---------------------------------------- + + +def test_template_manifest_parses_and_validates() -> None: + data = yaml.safe_load(_TEMPLATE_MANIFEST_PATH.read_text(encoding="utf-8")) + + validate_manifest_eligibility(data) # must not raise + + competitors = data["competitors"] + assert {competitor["adapter"] for competitor in competitors} == COMPETITOR_ADAPTER_IDS + assert data["exclusions"] == [] + + +def test_template_manifest_dry_run_plans_all_four_competitor_cells(tmp_path: Path) -> None: + out_dir = tmp_path / "results" / "template-dry-run" + + summary = run_benchmark( + BenchmarkConfig( + corpus_path=_corpus(tmp_path), + manifest_path=_TEMPLATE_MANIFEST_PATH, + out_dir=out_dir, + run_id="template-dry-run", + dry_run=True, + ) + ) + + assert summary["dry_run"] is True + assert summary["planned_cells"] == 4 + assert not (out_dir / "transcripts").exists() + diff --git a/tests/benchmarks/test_python_docs_mcp_adapter.py b/tests/benchmarks/test_python_docs_mcp_adapter.py deleted file mode 100644 index 9620f890..00000000 --- a/tests/benchmarks/test_python_docs_mcp_adapter.py +++ /dev/null @@ -1,379 +0,0 @@ -"""Tests for the offline stdio python-docs-mcp-server adapter (issue #86). - -All tests here drive the adapter against a fake/stubbed MCP transport (a -scripted session double) -- no real server subprocess is spawned. Two -exceptions: ``test_run_maps_a_failure_inside_a_real_stdio_session`` spawns -a silent child (``python -c "import sys; sys.stdin.read()"``) that only -holds the stdio pipe open, with no network and no server; and the optional -integration test at the bottom spawns the real server only when a local -index already exists at the default cache path, and is skipped otherwise -(per the issue's acceptance criteria). -""" - -from __future__ import annotations - -import asyncio -import socket -import sys -from dataclasses import dataclass, field -from pathlib import Path -from typing import Any - -import pytest -from mcp import ClientSession - -from benchmarks.adapters.python_docs_mcp_adapter import ( - PythonDocsMcpAdapter, - PythonDocsMcpResult, - _default_index_path, - _run_retrieval_flow, - _tool_result_payload, -) -from benchmarks.runner import BenchmarkCellFailure - - -@dataclass -class _FakeContentBlock: - text: str - - -@dataclass -class _FakeCallToolResult: - content: list[Any] = field(default_factory=list) - structured_content: dict[str, Any] | None = None - is_error: bool = False - - -class _ScriptedSession: - """A minimal fake MCP session returning one scripted result per tool. - - No real transport, no subprocess, no network -- this is the - "fake/stubbed MCP transport" the issue's acceptance criteria requires - for unit tests of the search_docs -> get_docs flow. - """ - - def __init__(self, responses: dict[str, _FakeCallToolResult]) -> None: - self._responses = responses - self.calls: list[tuple[str, dict[str, Any]]] = [] - - async def call_tool( - self, name: str, arguments: dict[str, Any] | None = None - ) -> _FakeCallToolResult: - self.calls.append((name, arguments or {})) - return self._responses[name] - - -def _search_result(hits: list[dict[str, Any]]) -> _FakeCallToolResult: - return _FakeCallToolResult( - content=[_FakeContentBlock(text="ignored")], - structured_content={"hits": hits, "note": None}, - is_error=False, - ) - - -def _get_result(content: str, **extra: Any) -> _FakeCallToolResult: - payload = { - "content": content, - "slug": "lib/m.html", - "title": "t", - "version": "3.13", - **extra, - } - return _FakeCallToolResult( - content=[_FakeContentBlock(text="ignored")], - structured_content=payload, - is_error=False, - ) - - -def _error_result(message: str) -> _FakeCallToolResult: - return _FakeCallToolResult( - content=[_FakeContentBlock(text=message)], - structured_content=None, - is_error=True, - ) - - -# --- _run_retrieval_flow: pure orchestration against a fake session -------- - - -async def test_retrieval_flow_calls_search_then_get_docs_and_records_raw_payloads() -> None: - hit = {"slug": "lib/asyncio-task.html", "anchor": "asyncio.TaskGroup", "version": "3.13"} - session = _ScriptedSession( - { - "search_docs": _search_result([hit]), - "get_docs": _get_result("TaskGroup docs content"), - } - ) - - result = await _run_retrieval_flow(session, "asyncio.TaskGroup", max_results=3) - - assert result.answer == "TaskGroup docs content" - assert [call.tool for call in result.tool_calls] == ["search_docs", "get_docs"] - assert session.calls[0] == ("search_docs", {"query": "asyncio.TaskGroup", "max_results": 3}) - assert session.calls[1] == ( - "get_docs", - {"slug": "lib/asyncio-task.html", "version": "3.13", "anchor": "asyncio.TaskGroup"}, - ) - assert result.tool_calls[0].result == {"hits": [hit], "note": None} - assert result.tool_calls[0].is_error is False - assert result.tool_calls[1].is_error is False - - -async def test_retrieval_flow_returns_empty_answer_when_search_has_no_hits() -> None: - session = _ScriptedSession({"search_docs": _search_result([])}) - - result = await _run_retrieval_flow(session, "no such symbol") - - assert result.answer == "" - assert len(result.tool_calls) == 1 - assert result.tool_calls[0].tool == "search_docs" - - -async def test_retrieval_flow_omits_anchor_argument_when_hit_has_no_anchor() -> None: - hit = {"slug": "lib/page.html", "anchor": None, "version": "3.13"} - session = _ScriptedSession( - {"search_docs": _search_result([hit]), "get_docs": _get_result("page content")} - ) - - await _run_retrieval_flow(session, "anything") - - assert session.calls[1] == ("get_docs", {"slug": "lib/page.html", "version": "3.13"}) - - -async def test_retrieval_flow_raises_tool_failure_when_search_docs_errors() -> None: - session = _ScriptedSession({"search_docs": _error_result("boom")}) - - with pytest.raises(BenchmarkCellFailure) as exc_info: - await _run_retrieval_flow(session, "anything") - - assert exc_info.value.category == "tool_failure" - assert "boom" in str(exc_info.value) - - -async def test_retrieval_flow_raises_tool_failure_when_get_docs_errors() -> None: - hit = {"slug": "lib/missing.html", "anchor": None, "version": "3.13"} - session = _ScriptedSession( - { - "search_docs": _search_result([hit]), - "get_docs": _error_result("Page not found"), - } - ) - - with pytest.raises(BenchmarkCellFailure) as exc_info: - await _run_retrieval_flow(session, "anything") - - assert exc_info.value.category == "tool_failure" - assert "Page not found" in str(exc_info.value) - - -# --- _tool_result_payload --------------------------------------------------- - - -def test_tool_result_payload_prefers_structured_content() -> None: - result = _get_result("x") - - assert _tool_result_payload(result) == result.structured_content - - -def test_tool_result_payload_falls_back_to_first_text_block_on_error() -> None: - result = _error_result("Error executing tool get_docs: not found") - - assert _tool_result_payload(result) == {"text": "Error executing tool get_docs: not found"} - - -# --- PythonDocsMcpAdapter.run(): missing index -> tool_failure, no spawn --- - - -def test_run_fails_with_tool_failure_when_index_is_missing_and_never_spawns( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - def _fail_if_called(*args: Any, **kwargs: Any) -> Any: - raise AssertionError("asyncio.run must not be called when the index is missing") - - monkeypatch.setattr("benchmarks.adapters.python_docs_mcp_adapter.asyncio.run", _fail_if_called) - adapter = PythonDocsMcpAdapter(index_path=tmp_path / "does-not-exist.db") - - with pytest.raises(BenchmarkCellFailure) as exc_info: - adapter.run("anything") - - assert exc_info.value.category == "tool_failure" - assert "no local index found" in str(exc_info.value) - - -def test_run_missing_index_check_never_opens_a_socket( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - def _fail_if_called(*args: Any, **kwargs: Any) -> Any: - raise AssertionError("no socket should be opened when the index is missing") - - monkeypatch.setattr(socket, "socket", _fail_if_called) - adapter = PythonDocsMcpAdapter(index_path=tmp_path / "does-not-exist.db") - - with pytest.raises(BenchmarkCellFailure): - adapter.run("anything") - - -def test_run_uses_default_index_path_when_none_is_configured( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: - monkeypatch.setattr( - "benchmarks.adapters.python_docs_mcp_adapter._default_index_path", - lambda: tmp_path / "default-missing.db", - ) - adapter = PythonDocsMcpAdapter() - - with pytest.raises(BenchmarkCellFailure) as exc_info: - adapter.run("anything") - - assert "default-missing.db" in str(exc_info.value) - - -# --- PythonDocsMcpAdapter.run(): failure-category mapping ------------------ - - -def test_run_maps_a_slow_call_to_a_timeout_failure( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - index_path = tmp_path / "index.db" - index_path.write_text("existence is all `run()` checks before spawning") - - async def _slow_run_async(self: PythonDocsMcpAdapter, prompt: str) -> PythonDocsMcpResult: - await asyncio.sleep(1) - return PythonDocsMcpResult(answer="too late", tool_calls=[]) - - monkeypatch.setattr(PythonDocsMcpAdapter, "_run_async", _slow_run_async) - adapter = PythonDocsMcpAdapter(index_path=index_path, timeout_seconds=0.01) - - with pytest.raises(BenchmarkCellFailure) as exc_info: - adapter.run("anything") - - assert exc_info.value.category == "timeout" - - -def test_run_maps_an_unexpected_transport_error_to_mcp_protocol_crash( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - index_path = tmp_path / "index.db" - index_path.write_text("existence is all `run()` checks before spawning") - - async def _broken_run_async(self: PythonDocsMcpAdapter, prompt: str) -> PythonDocsMcpResult: - raise RuntimeError("stdio pipe closed unexpectedly") - - monkeypatch.setattr(PythonDocsMcpAdapter, "_run_async", _broken_run_async) - adapter = PythonDocsMcpAdapter(index_path=index_path) - - with pytest.raises(BenchmarkCellFailure) as exc_info: - adapter.run("anything") - - assert exc_info.value.category == "mcp_protocol_crash" - assert "stdio pipe closed unexpectedly" in str(exc_info.value) - - -def test_run_propagates_benchmark_cell_failure_from_run_async_unchanged( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - index_path = tmp_path / "index.db" - index_path.write_text("existence is all `run()` checks before spawning") - - async def _tool_level_failure(self: PythonDocsMcpAdapter, prompt: str) -> PythonDocsMcpResult: - raise BenchmarkCellFailure("tool_failure", "search_docs returned an error: boom") - - monkeypatch.setattr(PythonDocsMcpAdapter, "_run_async", _tool_level_failure) - adapter = PythonDocsMcpAdapter(index_path=index_path) - - with pytest.raises(BenchmarkCellFailure) as exc_info: - adapter.run("anything") - - assert exc_info.value.category == "tool_failure" - assert "boom" in str(exc_info.value) - - -def test_run_maps_a_failure_inside_a_real_stdio_session( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - index_path = tmp_path / "index.db" - index_path.write_text("existence is all `run()` checks before spawning") - - async def _failing_initialize(self: ClientSession) -> Any: - raise BenchmarkCellFailure("tool_failure", "boom inside the session") - - monkeypatch.setattr(ClientSession, "initialize", _failing_initialize) - adapter = PythonDocsMcpAdapter( - command=[sys.executable, "-c", "import sys; sys.stdin.read()"], - index_path=index_path, - timeout_seconds=20, - ) - - with pytest.raises(BenchmarkCellFailure) as exc_info: - adapter.run("anything") - - assert exc_info.value.category == "tool_failure" - assert str(exc_info.value) == "boom inside the session" - assert isinstance(exc_info.value.__cause__, ExceptionGroup) - - -# --- The spawned server gets only the environment it needs - - -class _TransportReached(Exception): - """Raised by the patched stdio client once it has seen its parameters.""" - - -@pytest.mark.parametrize( - "xdg_cache_home,expected", - [ - pytest.param( - "/tmp/bench-cache", - {"PYTHON_DOCS_MCP_DISABLE_AUTO_INDEX": "1", "XDG_CACHE_HOME": "/tmp/bench-cache"}, - id="cache-location-set", - ), - pytest.param(None, {"PYTHON_DOCS_MCP_DISABLE_AUTO_INDEX": "1"}, id="cache-location-unset"), - ], -) -def test_server_env_holds_only_the_auto_index_switch_and_cache_location( - xdg_cache_home: str | None, expected: dict[str, str], monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setenv("UNRELATED_SECRET", "s") - if xdg_cache_home is None: - monkeypatch.delenv("XDG_CACHE_HOME", raising=False) - else: - monkeypatch.setenv("XDG_CACHE_HOME", xdg_cache_home) - recorded: dict[str, Any] = {} - - def _record(params: Any) -> Any: - recorded["env"] = params.env - raise _TransportReached - - monkeypatch.setattr("mcp.client.stdio.stdio_client", _record) - - with pytest.raises(_TransportReached): - asyncio.run(PythonDocsMcpAdapter()._run_async("q")) - - assert recorded["env"] == expected - - -# --- Optional integration test: real server spawn, skipped without an index - - -@pytest.mark.skipif( - not _default_index_path().exists(), - reason="requires a locally built python-docs-mcp-server index", -) -def test_real_server_round_trip_when_a_local_index_exists() -> None: - adapter = PythonDocsMcpAdapter(timeout_seconds=60) - - try: - result = adapter.run("os.path.join") - except BenchmarkCellFailure as exc: - # A locally built but symbol-only index (no content ingestion) is a - # legitimate dev state; get_docs then fails, and that failure must - # surface as a recorded tool_failure, not as an mcp_protocol_crash. - # A timeout is the only other acceptable outcome for this - # environment-specific smoke test. - assert exc.category in {"tool_failure", "timeout"}, str(exc) - return - - assert isinstance(result.answer, str) - assert result.tool_calls - assert result.tool_calls[0].tool == "search_docs" diff --git a/tests/benchmarks/test_runner.py b/tests/benchmarks/test_runner.py index d82ae39a..c5dec8ca 100644 --- a/tests/benchmarks/test_runner.py +++ b/tests/benchmarks/test_runner.py @@ -408,104 +408,6 @@ def test_cli_dry_run_outputs_summary(tmp_path: Path) -> None: assert (out_dir / "run-summary.json").is_file() -# --- python-docs-mcp-stdio adapter dispatch (issue #86) --------------------- -# -# These tests exercise the runner's dispatch-registry wiring only, via a -# fake product-adapter class monkeypatched over the real one -- no real MCP -# server subprocess is spawned. See tests/benchmarks/test_python_docs_mcp_adapter.py -# for the adapter's own unit tests against a fake/stubbed MCP transport. - - -class _FakeProductAdapter: - """Stands in for ``PythonDocsMcpAdapter`` to test dispatch wiring only.""" - - def __init__(self, *args: Any, **kwargs: Any) -> None: - pass - - def run(self, prompt: str) -> Any: - from benchmarks.adapters.python_docs_mcp_adapter import ( - PythonDocsMcpResult, - ToolCallRecord, - ) - - return PythonDocsMcpResult( - answer=f"fake-retrieved-content for {prompt}", - tool_calls=[ - ToolCallRecord( - tool="search_docs", - arguments={"query": prompt, "max_results": 3}, - result={"hits": [{"slug": "lib/x.html", "anchor": "a1"}]}, - is_error=False, - ), - ToolCallRecord( - tool="get_docs", - arguments={"slug": "lib/x.html", "anchor": "a1"}, - result={"content": f"fake-retrieved-content for {prompt}"}, - is_error=False, - ), - ], - ) - - -def test_python_docs_mcp_stdio_adapter_is_dispatchable_and_records_tool_calls( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr( - "benchmarks.adapters.python_docs_mcp_adapter.PythonDocsMcpAdapter", - _FakeProductAdapter, - ) - out_dir = tmp_path / "results" / "product-adapter" - - summary = run_benchmark( - BenchmarkConfig( - corpus_path=_corpus(tmp_path), - manifest_path=_manifest( - tmp_path, - [{"id": "python-docs-mcp-server", "adapter": "python-docs-mcp-stdio"}], - ), - out_dir=out_dir, - run_id="product-adapter", - ) - ) - - assert summary["succeeded_cells"] == 1 - transcript = json.loads( - (out_dir / "transcripts" / "python-docs-mcp-server" / "q001.json").read_text( - encoding="utf-8" - ) - ) - assert transcript["status"] == "succeeded" - assert transcript["answer"].startswith("fake-retrieved-content") - assert transcript["tool_calls"][0]["tool"] == "search_docs" - assert transcript["tool_calls"][1]["tool"] == "get_docs" - assert "external_provider_calls" not in transcript - - -def test_dry_run_validates_python_docs_mcp_stdio_manifest_without_an_index( - tmp_path: Path, -) -> None: - # dry-run must validate and plan cells for the new adapter without ever - # touching a local index or spawning a subprocess (issue #86). - out_dir = tmp_path / "results" / "product-adapter-dry-run" - - summary = run_benchmark( - BenchmarkConfig( - corpus_path=_corpus(tmp_path), - manifest_path=_manifest( - tmp_path, - [{"id": "python-docs-mcp-server", "adapter": "python-docs-mcp-stdio"}], - ), - out_dir=out_dir, - run_id="product-adapter-dry-run", - dry_run=True, - ) - ) - - assert summary["dry_run"] is True - assert summary["planned_cells"] == 1 - assert not (out_dir / "transcripts").exists() - - def test_unrecognized_adapter_id_fails_cleanly_without_crashing(tmp_path: Path) -> None: out_dir = tmp_path / "results" / "unknown-adapter" From 1c2ac10a39dd0635f89b53da914cde7663027b74 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Tue, 3 Nov 2026 23:13:07 +0100 Subject: [PATCH 11/77] fix(benchmarks): resolve the CodeQL findings in the agentic harness The ledger lock file is created owner-only (0o600), not world-readable; a test pins it. The worker closes the text streams it opened over fds 1 and 2 when its channel closes, reads stdin through sys.stdin, and suppresses sink errors with contextlib.suppress. Protocol stubs raise NotImplementedError under a docstring instead of a bare ellipsis. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/bridge.py | 4 ++- benchmarks/agentic/host.py | 8 +++-- benchmarks/agentic/ledger.py | 2 +- benchmarks/agentic/loop.py | 6 ++-- benchmarks/agentic/run.py | 4 ++- benchmarks/agentic/types.py | 6 ++-- benchmarks/agentic/worker.py | 46 +++++++++++++------------ tests/benchmarks/test_agentic_ledger.py | 5 +++ 8 files changed, 49 insertions(+), 32 deletions(-) diff --git a/benchmarks/agentic/bridge.py b/benchmarks/agentic/bridge.py index 854283a5..ece210d8 100644 --- a/benchmarks/agentic/bridge.py +++ b/benchmarks/agentic/bridge.py @@ -62,7 +62,9 @@ class BridgeCrash(Exception): class ToolBridge(Protocol): tools: list[ToolSpec] - async def call(self, name: str, arguments: dict[str, Any]) -> ToolOutcome: ... + async def call(self, name: str, arguments: dict[str, Any]) -> ToolOutcome: + """Call one tool; a dead transport raises :class:`BridgeCrash`.""" + raise NotImplementedError def _strings(value: Any, label: str) -> tuple[str, ...]: diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index c68bfc3f..9d9e69b5 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -46,9 +46,13 @@ class WorkerJob: class Launcher(Protocol): - def supports(self, family: ModelFamily) -> bool: ... + def supports(self, family: ModelFamily) -> bool: + """Whether this launcher can run the family's worker.""" + raise NotImplementedError - def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: ... + def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: + """The worker's argv and its whole environment.""" + raise NotImplementedError class LocalLauncher: diff --git a/benchmarks/agentic/ledger.py b/benchmarks/agentic/ledger.py index f930cf6a..9dbf6992 100644 --- a/benchmarks/agentic/ledger.py +++ b/benchmarks/agentic/ledger.py @@ -249,7 +249,7 @@ def open( ) -> Ledger: ledger_dir.mkdir(parents=True, exist_ok=True) lock_path = ledger_dir / ".lock" - fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o644) + fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o600) 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) diff --git a/benchmarks/agentic/loop.py b/benchmarks/agentic/loop.py index 9f14bd52..108fb6eb 100644 --- a/benchmarks/agentic/loop.py +++ b/benchmarks/agentic/loop.py @@ -62,9 +62,11 @@ async def reserve( input_bound: int, output_bound: int, kind: str = "model_call", - ) -> str | None: ... + ) -> str | None: + """A unit id, or None when the provider's cap refuses the unit.""" - async def settle(self, unit_id: str, *, outcome: Outcome, buckets: Buckets | None) -> None: ... + async def settle(self, unit_id: str, *, outcome: Outcome, buckets: Buckets | None) -> None: + """Book the unit's outcome and free the provider.""" class TrajectoryDiscarded(Exception): diff --git a/benchmarks/agentic/run.py b/benchmarks/agentic/run.py index ffbb0829..711917a5 100644 --- a/benchmarks/agentic/run.py +++ b/benchmarks/agentic/run.py @@ -137,7 +137,9 @@ def _client_versions() -> dict[str, str]: class _HasId(Protocol): @property - def id(self) -> str: ... + def id(self) -> str: + """The id a selection names.""" + raise NotImplementedError def _select[T: _HasId](items: Sequence[T], wanted: tuple[str, ...] | None, label: str) -> list[T]: diff --git a/benchmarks/agentic/types.py b/benchmarks/agentic/types.py index 2684ef16..ae84011c 100644 --- a/benchmarks/agentic/types.py +++ b/benchmarks/agentic/types.py @@ -101,15 +101,15 @@ class ModelClient(Protocol): 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. System, tools and ``entries[start:]`` when ``start == 0``, else ``entries[start:]`` only. """ - ... + raise NotImplementedError async def call(self, conv: Conversation) -> ModelTurn: """One HTTP request; raises :class:`ProviderCallError`.""" - ... + raise NotImplementedError diff --git a/benchmarks/agentic/worker.py b/benchmarks/agentic/worker.py index 61b19337..42b69a78 100644 --- a/benchmarks/agentic/worker.py +++ b/benchmarks/agentic/worker.py @@ -17,7 +17,7 @@ import sys import threading from collections import deque -from contextlib import AsyncExitStack +from contextlib import AsyncExitStack, suppress from dataclasses import asdict from importlib.metadata import version from typing import Any @@ -57,25 +57,27 @@ def _redact(read_fd: int, sink_fd: int, own_key: str | None) -> None: if key: pending = pending.replace(key, _REDACTED) out, pending = (pending[:-hold], pending[-hold:]) if hold else (pending, b"") - try: + with suppress(OSError): # the sink is gone; keep draining so no writer blocks _write_all(sink_fd, out) - except OSError: - pass # the sink is gone; keep draining so writers never block - try: + with suppress(OSError): _write_all(sink_fd, pending) - except OSError: - pass os.close(read_fd) class ProtocolChannel: def __init__( - self, protocol_fd: int, own_key: str | None, pipe_write_fd: int, thread: threading.Thread + self, + protocol_fd: int, + own_key: str | None, + pipe_write_fd: int, + thread: threading.Thread, + streams: tuple[io.TextIOWrapper, io.TextIOWrapper], ) -> None: self._fd = protocol_fd self._own_key = own_key.encode() if own_key else None self._pipe_write_fd = pipe_write_fd self._thread = thread + self._streams = streams def send(self, message: dict[str, Any]) -> None: """Write one frame; refuse a frame that holds the own key.""" @@ -96,6 +98,17 @@ def close(self) -> None: # A grandchild that still holds the pipe cannot keep the worker alive: the thread # is a daemon, and its bytes are dropped, never written unredacted. self._thread.join(5) + for stream in self._streams: # fds 1 and 2 stay open (closefd=False) + stream.close() + + +def _text_stream(fd: int) -> io.TextIOWrapper: + return io.TextIOWrapper( + open(fd, "wb", closefd=False), # closed by ProtocolChannel.close() + encoding="utf-8", + errors="backslashreplace", + line_buffering=True, + ) def protect_output(own_key: str | None) -> ProtocolChannel: @@ -109,19 +122,8 @@ def protect_output(own_key: str | None) -> ProtocolChannel: os.dup2(write_fd, 2) thread = threading.Thread(target=_redact, args=(read_fd, sink_fd, own_key), daemon=True) thread.start() - sys.stdout = io.TextIOWrapper( - open(1, "wb", closefd=False), - encoding="utf-8", - errors="backslashreplace", - line_buffering=True, - ) - sys.stderr = io.TextIOWrapper( - open(2, "wb", closefd=False), - encoding="utf-8", - errors="backslashreplace", - line_buffering=True, - ) - return ProtocolChannel(protocol_fd, own_key, write_fd, thread) + sys.stdout, sys.stderr = streams = (_text_stream(1), _text_stream(2)) + return ProtocolChannel(protocol_fd, own_key, write_fd, thread, streams) class _HostLedger: @@ -311,7 +313,7 @@ async def run_worker(channel: ProtocolChannel, reader: asyncio.StreamReader) -> async def _serve(channel: ProtocolChannel) -> int: reader = asyncio.StreamReader() await asyncio.get_running_loop().connect_read_pipe( - lambda: asyncio.StreamReaderProtocol(reader), open(0, "rb", buffering=0, closefd=False) + lambda: asyncio.StreamReaderProtocol(reader), sys.stdin ) return await run_worker(channel, reader) diff --git a/tests/benchmarks/test_agentic_ledger.py b/tests/benchmarks/test_agentic_ledger.py index 08e05b16..103cdf97 100644 --- a/tests/benchmarks/test_agentic_ledger.py +++ b/tests/benchmarks/test_agentic_ledger.py @@ -352,6 +352,11 @@ 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_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 + + def test_a_killed_ledger_holder_releases_the_lock_and_its_unit_is_booked_at_twice_its_bound( tmp_path: Path, ) -> None: From f9271df376b7de85356bedd94882e1c39d93b848 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:01:41 +0100 Subject: [PATCH 12/77] fix(benchmarks): never follow a redirect and pin each provider endpoint Round 2 A1 and C16. The production clients of all three SDKs no longer follow redirects: a 307 or 308 is one POST, booked as a rejected call, and no request reaches the redirect target. Each SDK's base URL is pinned, so ANTHROPIC_BASE_URL, OPENAI_BASE_URL or GOOGLE_GEMINI_BASE_URL cannot send a key to another host. Tests inject only a transport into the production client construction. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/clients.py | 47 +++++++++----- tests/benchmarks/test_agentic_clients.py | 79 +++++++++++++++++++++--- 2 files changed, 104 insertions(+), 22 deletions(-) diff --git a/benchmarks/agentic/clients.py b/benchmarks/agentic/clients.py index 3c9c286f..6b2fde6c 100644 --- a/benchmarks/agentic/clients.py +++ b/benchmarks/agentic/clients.py @@ -93,27 +93,41 @@ def _utf8_len(payload: Any) -> int: return len(json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")) +#: Pinned, so no *_BASE_URL variable can send a key to another host. +ANTHROPIC_BASE_URL = "https://api.anthropic.com" +OPENAI_BASE_URL = "https://api.openai.com/v1" +GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/" + + +def _client_args(transport: Any | None) -> dict[str, Any]: + """Never follow a redirect: it would be a second request, possibly carrying the key away. + + Tests inject only a transport; every other client setting is the production one. + """ + return {"follow_redirects": False, **({} if transport is None else {"transport": transport})} + + def anthropic_sdk( - api_key: str, timeout_s: float, *, http_client: httpx2.AsyncClient | None = None + api_key: str, timeout_s: float, *, transport: httpx2.AsyncBaseTransport | None = None ) -> anthropic.AsyncAnthropic: return anthropic.AsyncAnthropic( - api_key=api_key, max_retries=0, timeout=timeout_s, http_client=http_client + api_key=api_key, + base_url=ANTHROPIC_BASE_URL, + max_retries=0, + timeout=timeout_s, + http_client=anthropic.DefaultAsyncHttpxClient(**_client_args(transport)), ) def openai_sdk( - api_key: str, - timeout_s: float, - *, - base_url: str | None = None, - http_client: httpx2.AsyncClient | None = None, + api_key: str, timeout_s: float, *, transport: httpx2.AsyncBaseTransport | None = None ) -> openai.AsyncOpenAI: return openai.AsyncOpenAI( api_key=api_key, - base_url=base_url, + base_url=OPENAI_BASE_URL, max_retries=0, timeout=timeout_s, - http_client=http_client, + http_client=openai.DefaultAsyncHttpxClient(**_client_args(transport)), ) @@ -280,15 +294,16 @@ async def call(self, conv: Conversation) -> ModelTurn: def gemini_sdk( - api_key: str, timeout_s: float, *, http_client: httpx.AsyncClient | None = None + api_key: str, timeout_s: float, *, transport: httpx.AsyncBaseTransport | None = None ) -> genai.Client: return genai.Client( api_key=api_key, vertexai=False, http_options=genai_types.HttpOptions( + base_url=GEMINI_BASE_URL, timeout=int(timeout_s * 1000), retry_options=genai_types.HttpRetryOptions(attempts=1), - httpx_async_client=http_client, + httpx_async_client=httpx.AsyncClient(**_client_args(transport)), ), ) @@ -388,6 +403,8 @@ async def call(self, conv: Conversation) -> ModelTurn: raise ProviderCallError("rejected", str(exc), status=exc.code) from exc except genai_errors.ServerError as exc: raise ProviderCallError("server", str(exc), status=exc.code) from exc + except genai_errors.APIError as exc: # any other status, a redirect included + raise ProviderCallError("rejected", str(exc), status=exc.code) from exc except httpx.TimeoutException as exc: raise ProviderCallError("timeout", str(exc)) from exc except httpx.TransportError as exc: @@ -512,7 +529,7 @@ async def call(self, conv: Conversation) -> ModelTurn: def make_client( - family: ModelFamily, *, timeout_s: float, http_client: Any | None = None + family: ModelFamily, *, timeout_s: float, transport: Any | None = None ) -> ModelClient: """The only way production code builds a client; every live API passes the guard.""" if family.api == "scripted": @@ -548,10 +565,10 @@ def make_client( raise BenchmarkValidationError(f"model family {family.id!r} must set max_output_tokens") key = os.environ[own_key_env] if provider == "anthropic": - sdk = anthropic_sdk(key, timeout_s, http_client=http_client) + sdk = anthropic_sdk(key, timeout_s, transport=transport) return AnthropicClient(sdk, family.model_id, family.max_output_tokens) if provider == "openai": - sdk = openai_sdk(key, timeout_s, http_client=http_client) + sdk = openai_sdk(key, timeout_s, transport=transport) return OpenAIResponsesClient(sdk, family.model_id, family.max_output_tokens) - sdk = gemini_sdk(key, timeout_s, http_client=http_client) + sdk = gemini_sdk(key, timeout_s, transport=transport) return GeminiClient(sdk, family.model_id, family.max_output_tokens) diff --git a/tests/benchmarks/test_agentic_clients.py b/tests/benchmarks/test_agentic_clients.py index e40de4a7..3ef6c2dd 100644 --- a/tests/benchmarks/test_agentic_clients.py +++ b/tests/benchmarks/test_agentic_clients.py @@ -146,8 +146,8 @@ def __call__(self, request: httpx2.Request) -> httpx2.Response: return response(request) return response - def client(self) -> httpx2.AsyncClient: - return httpx2.AsyncClient(transport=httpx2.MockTransport(self)) + def transport(self) -> Any: + return httpx2.MockTransport(self) def body(self, index: int) -> dict[str, Any]: return json.loads(self.seen[index].content) @@ -158,12 +158,12 @@ def _ok(body: dict[str, Any], status: int = 200, headers: dict[str, str] | None def _anthropic(recorder: Recorder) -> AnthropicClient: - sdk = anthropic_sdk("test-key", 30, http_client=recorder.client()) + sdk = anthropic_sdk("test-key", 30, transport=recorder.transport()) return AnthropicClient(sdk, "claude-sonnet-5-5", 32_768) def _openai(recorder: Recorder) -> OpenAIResponsesClient: - sdk = openai_sdk("test-key", 30, http_client=recorder.client()) + sdk = openai_sdk("test-key", 30, transport=recorder.transport()) return OpenAIResponsesClient(sdk, "gpt-6.1-sol", 32_768) @@ -416,8 +416,8 @@ def _gemini_response(parts: list[dict[str, Any]], finish: str = "STOP", **extra: class GeminiRecorder(Recorder): - def client(self) -> Any: # an httpx (not httpx2) client: google-genai uses httpx - return httpx.AsyncClient(transport=httpx.MockTransport(self)) + def transport(self) -> Any: # an httpx (not httpx2) transport: google-genai uses httpx + return httpx.MockTransport(self) def _gemini_ok(body: dict[str, Any], status: int = 200, headers: dict[str, str] | None = None): @@ -425,7 +425,7 @@ def _gemini_ok(body: dict[str, Any], status: int = 200, headers: dict[str, str] def _gemini(recorder: GeminiRecorder) -> GeminiClient: - sdk = gemini_sdk("test-key", 30, http_client=recorder.client()) + sdk = gemini_sdk("test-key", 30, transport=recorder.transport()) return GeminiClient(sdk, "gemini-3.8-flash", 32_768) @@ -708,3 +708,68 @@ async def test_committed_scripts_play_tools_then_the_answer(provider: str) -> No turns = [await client.call(conv) for _ in range(3)] assert [c.name for t in turns for c in t.tool_calls] == ["search_docs", "fetch"] assert turns[-1].text == "Scripted answer." and all(t.buckets for t in turns) + + +# --- Round 2: redirects, pinned endpoints ------------------------------------------------------ + +ELSEWHERE = "https://elsewhere.invalid/collect" +OK_BODIES = { + "anthropic": ANTHROPIC_ANSWER, + "openai": _openai_response([OPENAI_MESSAGE]), + "google": _gemini_response([{"text": "ok"}]), +} + + +def _live_client(provider: str, recorder: Recorder) -> Any: + return {"anthropic": _anthropic, "openai": _openai, "google": _gemini}[provider](recorder) # type: ignore[operator] + + +def _recorder(provider: str, *responses: Any) -> Recorder: + return GeminiRecorder(*responses) if provider == "google" else Recorder(*responses) + + +def _response(provider: str, status: int, body: Any = None, headers: Any = None) -> Any: + kind = httpx if provider == "google" else httpx2 + return kind.Response(status, json=body or {}, headers=headers or {}) + + +@pytest.mark.parametrize("status", [307, 308]) +@pytest.mark.parametrize("provider", ["anthropic", "openai", "google"]) +async def test_a_redirect_is_never_followed_and_is_a_rejected_call( + provider: str, status: int +) -> None: + # Production client construction; the test injects only the transport. + recorder = _recorder( + provider, + _response(provider, status, headers={"location": ELSEWHERE}), + _response(provider, 200, OK_BODIES[provider]), + ) + with pytest.raises(ProviderCallError) as caught: + await _live_client(provider, recorder).call(_conv()) + assert (caught.value.kind, caught.value.status) == ("rejected", status) + assert [r.method for r in recorder.seen] == ["POST"] + assert "elsewhere.invalid" not in {r.url.host for r in recorder.seen} + + +@pytest.mark.parametrize( + "family_id,env,host", + [ + ("claude-sonnet-5-5", "ANTHROPIC_BASE_URL", "api.anthropic.com"), + ("gpt-6.1-sol", "OPENAI_BASE_URL", "api.openai.com"), + ("gemini-3.8-flash", "GOOGLE_GEMINI_BASE_URL", "generativelanguage.googleapis.com"), + ], +) +async def test_a_base_url_variable_cannot_redirect_a_key( + monkeypatch: pytest.MonkeyPatch, family_id: str, env: str, host: str +) -> None: + _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(env, "https://attacker.invalid/v1") + recorder = _recorder( + family.provider, _response(family.provider, 200, OK_BODIES[family.provider]) + ) + client = make_client(family, timeout_s=30, transport=recorder.transport()) + await client.call(_conv()) + assert [r.url.host for r in recorder.seen] == [host] From 4f70cc2b261bd78141cf98d029eb7817847a0893 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:02:08 +0100 Subject: [PATCH 13/77] fix(benchmarks): rebuild a lost overrun stop when the ledger replays Round 2 A2. Replay now stops a provider from any ok settle whose booked actual cost exceeds its bound, so a crash between that settle and its stop event cannot lift the stop. A later resume event still lifts it. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/ledger.py | 4 ++++ tests/benchmarks/test_agentic_ledger.py | 17 +++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/benchmarks/agentic/ledger.py b/benchmarks/agentic/ledger.py index 9dbf6992..3daa211a 100644 --- a/benchmarks/agentic/ledger.py +++ b/benchmarks/agentic/ledger.py @@ -302,6 +302,10 @@ def _apply(self, event: dict[str, Any]) -> None: self._units[event["unit_id"]] = (provider, Decimal(event["bound"])) elif kind == "settle": self._spent[provider] = self.spent(provider) + Decimal(event["booked"]) + _, bound = self._units[event["unit_id"]] + if event["outcome"] == "ok" and Decimal(event["booked"]) > bound: + # Rebuilt from the settle itself: a crash may have lost the stop event. + self._stops[provider] = "overrun" elif kind == "stop" and event["reason"] == "overrun": # Only an overrun stop survives a reopen: a cap stop is re-checked against the # caps of the new run, so a raised cap lets the provider run again. diff --git a/tests/benchmarks/test_agentic_ledger.py b/tests/benchmarks/test_agentic_ledger.py index 103cdf97..711d0a4a 100644 --- a/tests/benchmarks/test_agentic_ledger.py +++ b/tests/benchmarks/test_agentic_ledger.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import json import subprocess import sys from datetime import date @@ -301,6 +302,22 @@ def test_reserve_raises_when_a_unit_is_already_in_flight(tmp_path: Path) -> None ledger.close() +def test_an_overrun_whose_stop_event_was_lost_still_stops_the_provider(tmp_path: Path) -> None: + # A crash between the settle and its stop event: reserve $1, settle ok at $2, no stop. + ledger = _open(tmp_path, anthropic="10") + unit = _reserve(ledger, "anthropic", "1") + assert unit is not None + ledger.settle(unit, outcome="ok", actual=D("2"), buckets=Buckets(1, 0, 0, 1)) + ledger.close() + path = tmp_path / "anthropic.jsonl" + lines = path.read_text(encoding="utf-8").splitlines(keepends=True) + assert [json.loads(line)["event"] for line in lines] == ["reserve", "settle", "stop"] + path.write_text("".join(lines[:2]), encoding="utf-8") + ledger = _open(tmp_path, anthropic="10") + assert ledger.stopped("anthropic") == "overrun" + ledger.close() + + def test_actual_above_bound_stops_the_provider_until_acknowledged(tmp_path: Path) -> None: ledger = _open(tmp_path, anthropic="10") unit = _reserve(ledger, "anthropic", "2") From 320d30a5255afe24565becbc95f6e356c5d2ed34 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:03:01 +0100 Subject: [PATCH 14/77] fix(benchmarks): key-scan every input's bytes before writing any snapshot Round 2 A3. run_agentic reads the corpus, manifest, matrix and price snapshot once, scans those exact bytes for key shapes before anything is written, dry runs included, and writes the scanned bytes as the snapshots. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/run.py | 16 +++++++++++----- tests/benchmarks/test_agentic_run.py | 10 ++++++++++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/benchmarks/agentic/run.py b/benchmarks/agentic/run.py index 711917a5..8c6faf63 100644 --- a/benchmarks/agentic/run.py +++ b/benchmarks/agentic/run.py @@ -50,7 +50,6 @@ _scoring_record, _utc_now, _write_json, - _write_snapshot, ) #: Answer-turn stop reasons that mean the output cap cut the answer; the pilot's 1% rule @@ -391,12 +390,19 @@ 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}") out.mkdir(parents=True, exist_ok=True) snapshots = out / "snapshots" - _write_snapshot(config.corpus_path, snapshots / "corpus.yml") - _write_snapshot(config.manifest_path, snapshots / "competitor-manifest.yml") - _write_snapshot(config.matrix_path, snapshots / "model-matrix.yml") - _write_snapshot(config.prices_path, snapshots / "price-snapshot.yml") + snapshots.mkdir() + for name, data in inputs.items(): # the exact bytes that were scanned + (snapshots / name).write_bytes(data) (snapshots / "system-prompt.txt").write_text(SYSTEM_PROMPT, encoding="utf-8") environment = { **_environment_metadata(run_id=run_id, dry_run=config.dry_run), diff --git a/tests/benchmarks/test_agentic_run.py b/tests/benchmarks/test_agentic_run.py index afd96a15..1072078e 100644 --- a/tests/benchmarks/test_agentic_run.py +++ b/tests/benchmarks/test_agentic_run.py @@ -314,6 +314,16 @@ def test_continuation_answers_count_as_output_cap_stops(tmp_path: Path) -> None: assert (fam["output_cap_stops"], fam["answer_turns"]) == (2, 100) # 2% +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 + manifest.write_text(COMMITTED_MANIFEST.read_text() + f"\n# {key_shape}\n", encoding="utf-8") + with pytest.raises(KeyLeakError) as caught: + run_agentic(_config(tmp_path, manifest_path=manifest, dry_run=True)) + assert key_shape not in str(caught.value) + assert not (tmp_path / "run" / "snapshots").exists() + + def test_agentic_run_refuses_a_non_empty_out_dir(tmp_path: Path) -> None: (tmp_path / "run").mkdir() (tmp_path / "run" / "stale.json").write_text("{}") From 2de42ca671e8f84c1ed4f8309a0a95d77e0ba51b Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:03:55 +0100 Subject: [PATCH 15/77] fix(benchmarks): refuse provider keys in a system's server environment Round 2 A4 (with Fable keys Low 1 and Nit 2). system_spec_from_raw refuses any PROVIDER_API_KEY_ENV name in pass_env or as an env key, and scans every env value for key shapes, so a manifest can never hand a key to an MCP server. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/bridge.py | 9 +++++++++ tests/benchmarks/test_agentic_bridge.py | 24 ++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/benchmarks/agentic/bridge.py b/benchmarks/agentic/bridge.py index ece210d8..f43bdb97 100644 --- a/benchmarks/agentic/bridge.py +++ b/benchmarks/agentic/bridge.py @@ -21,6 +21,8 @@ from mcp import ClientSession, MCPError, StdioServerParameters, stdio_client 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.agentic.types import ToolSpec from benchmarks.runner import ( _SAFE_ID, @@ -95,6 +97,13 @@ def system_spec_from_raw(raw: Mapping[str, Any]) -> SystemSpec: ): raise BenchmarkValidationError(f"system {system_id!r} 'env' must map strings to strings") pass_env = _strings(raw.get("pass_env") or [], f"system {system_id!r} 'pass_env'") + keys = sorted(set(PROVIDER_API_KEY_ENV.values()) & (set(pass_env) | set(env))) + if keys: + raise BenchmarkValidationError( + f"system {system_id!r} must not receive provider keys {keys} through env or pass_env" + ) + for name, value in env.items(): + assert_no_key_shaped(value, where=f"system {system_id!r} env {name!r}") return SystemSpec(system_id, transport, command, dict(env), pass_env, dict(raw)) diff --git a/tests/benchmarks/test_agentic_bridge.py b/tests/benchmarks/test_agentic_bridge.py index 57adba9a..7832aa69 100644 --- a/tests/benchmarks/test_agentic_bridge.py +++ b/tests/benchmarks/test_agentic_bridge.py @@ -106,6 +106,30 @@ def test_system_spec_from_raw_refuses_a_bad_entry(raw: dict) -> None: system_spec_from_raw(raw) +_KEY_SHAPE = "sk-ant-api03-" + "A" * 90 + + +@pytest.mark.parametrize( + "env,pass_env,match", + [ + ({}, ["HOME", "ANTHROPIC_API_KEY"], "ANTHROPIC_API_KEY"), + ({}, ["CONTEXT7_API_KEY"], "CONTEXT7_API_KEY"), + ({"OPENAI_API_KEY": "x"}, [], "OPENAI_API_KEY"), + ({"REF_API_KEY": "x"}, [], "REF_API_KEY"), + ({"TOKEN": _KEY_SHAPE}, [], "key-shaped"), + ], +) +def test_a_system_never_receives_a_provider_key( + env: dict[str, str], pass_env: list[str], match: str +) -> None: + from benchmarks.runner import BenchmarkValidationError + + raw = {"id": "x", "adapter": "mcp-stdio", "command": ["a"], "env": env, "pass_env": pass_env} + with pytest.raises(BenchmarkValidationError, match=match) as caught: + system_spec_from_raw(raw) + assert _KEY_SHAPE not in str(caught.value) + + async def test_bridge_lists_the_real_server_tools_unfiltered(python_docs: SystemSpec) -> None: async with open_bridge(python_docs) as bridge: assert {t.name for t in bridge.tools} == { From fc279f6ea244b2949eb41ef4546686f50e0ec0ed Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:05:21 +0100 Subject: [PATCH 16/77] fix(benchmarks): honour Retry-After on retryable 5xx and clamp negatives Round 2 A5 (with Fable spend Low 4). All three clients now carry Retry-After on 5xx responses as on 429, Gemini ServerError included, so a 503 asking for 90 s waits 90 s; the loop's 120 s ceiling applies to both. A negative Retry-After is clamped to 0. The Gemini status test now expects the 500's Retry-After to be kept. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/clients.py | 30 +++++++++++------------- tests/benchmarks/test_agentic_clients.py | 17 +++++++++++++- tests/benchmarks/test_agentic_loop.py | 24 +++++++++++++++++++ 3 files changed, 54 insertions(+), 17 deletions(-) diff --git a/benchmarks/agentic/clients.py b/benchmarks/agentic/clients.py index 6b2fde6c..047d4381 100644 --- a/benchmarks/agentic/clients.py +++ b/benchmarks/agentic/clients.py @@ -64,15 +64,18 @@ def tool_arguments(value: Any) -> tuple[dict[str, Any], str | None]: def parse_retry_after(headers: Mapping[str, str]) -> float | None: - """Seconds to wait from ``retry-after-ms`` or ``retry-after`` (seconds or an HTTP date).""" + """Seconds to wait from ``retry-after-ms`` or ``retry-after`` (seconds or an HTTP date). + + A negative value is clamped to 0; the loop refuses anything above 120 s. + """ try: if (ms := headers.get("retry-after-ms")) is not None: - return float(ms) / 1000 + return max(0.0, float(ms) / 1000) value = headers.get("retry-after") if value is None: return None try: - return float(value) + return max(0.0, float(value)) except ValueError: when = parsedate_to_datetime(value) return max(0.0, (when - datetime.now(UTC)).total_seconds()) @@ -81,12 +84,13 @@ def parse_retry_after(headers: Mapping[str, str]) -> float | None: def _status_error(status: int, headers: Mapping[str, str], message: str) -> ProviderCallError: - if status == 429: + """429 and 5xx are retried, honouring retry-after; any other status is rejected.""" + if status == 429 or status >= 500: + kind = "rate_limited" if status == 429 else "server" return ProviderCallError( - "rate_limited", message, status=status, retry_after_s=parse_retry_after(headers) + kind, message, status=status, retry_after_s=parse_retry_after(headers) ) - kind = "server" if status >= 500 else "rejected" - return ProviderCallError(kind, message, status=status) + return ProviderCallError("rejected", message, status=status) def _utf8_len(payload: Any) -> int: @@ -396,15 +400,9 @@ async def call(self, conv: Conversation) -> ModelTurn: contents=self._contents(conv.entries), config=self._config(conv), ) - except genai_errors.ClientError as exc: - if exc.code == 429: - headers = getattr(exc.response, "headers", None) or {} - raise _status_error(429, headers, str(exc)) from exc - raise ProviderCallError("rejected", str(exc), status=exc.code) from exc - except genai_errors.ServerError as exc: - raise ProviderCallError("server", str(exc), status=exc.code) from exc - except genai_errors.APIError as exc: # any other status, a redirect included - raise ProviderCallError("rejected", str(exc), status=exc.code) from exc + except genai_errors.APIError as exc: # 4xx, 5xx, and any other status (a redirect) + headers = getattr(exc.response, "headers", None) or {} + raise _status_error(exc.code, headers, str(exc)) from exc except httpx.TimeoutException as exc: raise ProviderCallError("timeout", str(exc)) from exc except httpx.TransportError as exc: diff --git a/tests/benchmarks/test_agentic_clients.py b/tests/benchmarks/test_agentic_clients.py index 3ef6c2dd..3bbddfc5 100644 --- a/tests/benchmarks/test_agentic_clients.py +++ b/tests/benchmarks/test_agentic_clients.py @@ -368,6 +368,21 @@ def test_parse_retry_after_accepts_an_http_date() -> None: assert parse_retry_after({}) is None +def test_parse_retry_after_clamps_a_negative_value_to_zero() -> None: + assert parse_retry_after({"retry-after": "-5"}) == 0.0 + assert parse_retry_after({"retry-after-ms": "-1500"}) == 0.0 + + +@pytest.mark.parametrize("provider", ["anthropic", "openai", "google"]) +async def test_a_retryable_5xx_carries_its_retry_after(provider: str) -> None: + error = {"error": {"code": 503, "message": "busy", "status": "UNAVAILABLE"}} + body = error if provider == "google" else ERROR_BODY + recorder = _recorder(provider, _response(provider, 503, body, {"retry-after": "90"})) + with pytest.raises(ProviderCallError) as caught: + await _live_client(provider, recorder).call(_conv()) + assert (caught.value.kind, caught.value.retry_after_s) == ("server", 90.0) + + @pytest.mark.parametrize("provider", ["anthropic", "openai"]) def test_rendered_bytes_grows_with_each_entry(provider: str) -> None: client = _anthropic(Recorder()) if provider == "anthropic" else _openai(Recorder()) @@ -544,7 +559,7 @@ async def test_gemini_status_errors_are_classified(status: int, kind: str) -> No with pytest.raises(ProviderCallError) as caught: await _gemini(recorder).call(_conv()) assert caught.value.kind == kind and caught.value.status == status - assert caught.value.retry_after_s == (3.0 if status == 429 else None) + assert caught.value.retry_after_s == (None if status == 400 else 3.0) # 429 and 5xx async def test_gemini_timeout_and_connection_errors_are_classified() -> None: diff --git a/tests/benchmarks/test_agentic_loop.py b/tests/benchmarks/test_agentic_loop.py index a03ba7d7..13d3623b 100644 --- a/tests/benchmarks/test_agentic_loop.py +++ b/tests/benchmarks/test_agentic_loop.py @@ -358,6 +358,30 @@ async def test_rate_limit_is_retried_honouring_retry_after_and_not_counted_as_a_ assert record["timing"]["retry_wait_ms"] == 7000 +async def test_a_503_with_retry_after_waits_that_long_before_its_retry(harness: Harness) -> None: + import httpx2 + + from benchmarks.agentic.clients import AnthropicClient, anthropic_sdk + + answer = { + "id": "msg_1", + "type": "message", + "role": "assistant", + "model": "scripted-1", + "content": [{"type": "text", "text": "ok"}], + "stop_reason": "end_turn", + "stop_sequence": None, + "usage": {"input_tokens": 100, "output_tokens": 10}, + } + replies = [ + httpx2.Response(503, json={"type": "error"}, headers={"retry-after": "90"}), + httpx2.Response(200, json=answer), + ] + sdk = anthropic_sdk("test-key", 30, transport=httpx2.MockTransport(lambda _: replies.pop(0))) + record = await harness.run(client=AnthropicClient(sdk, "scripted-1", 1024)) # type: ignore[arg-type] + assert harness.sleeps == [90.0] and _outcomes(record) == ["server", "ok"] + + async def test_server_error_is_booked_at_twice_the_bound_and_retried(harness: Harness) -> None: record = await harness.run([{"error": {"kind": "server", "status": 500}}, ANSWER]) assert record["status"] == "succeeded" and _outcomes(record) == ["server", "ok"] From 1569efdc43986e2298376b940ad76544303a633c Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:07:07 +0100 Subject: [PATCH 17/77] fix(benchmarks): record late turns and count every answer turn Round 2 A6 (with Fable spend Low 1; amends ruling 17). A model turn, or the tool results that came back, is appended to the conversation before the trajectory clock runs, so canonical_messages keeps a turn that ends the trajectory. Each model call records tool_calls_requested, and the run summary counts every answer turn (a turn without tool calls) in answer_turns and output_cap_stops, whatever the trajectory's outcome: 98 normal answers plus 2 late MAX_TOKENS answers report 2 of 100. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/loop.py | 12 ++++++++-- benchmarks/agentic/run.py | 6 ++--- tests/benchmarks/test_agentic_loop.py | 20 ++++++++++++++++ tests/benchmarks/test_agentic_run.py | 34 ++++++++++++++++++++++++++- 4 files changed, 66 insertions(+), 6 deletions(-) diff --git a/benchmarks/agentic/loop.py b/benchmarks/agentic/loop.py index 108fb6eb..6488ed9f 100644 --- a/benchmarks/agentic/loop.py +++ b/benchmarks/agentic/loop.py @@ -227,7 +227,6 @@ async def run(self) -> str: previous_count = len(self.conv.entries) turn = await self.model_call(bound) previous = turn.buckets - self.conv.entries.append(turn) if not turn.tool_calls: return turn.text if len(self.model_calls) >= self.caps.model_calls: @@ -252,6 +251,7 @@ async def model_call(self, bound: int) -> ModelTurn: "reported_model": None, "stop_reason": None, "wall_ms": None, + "tool_calls_requested": None, # 0 marks an answer turn } self.model_calls.append(entry) retries = 0 @@ -296,7 +296,9 @@ async def model_call(self, bound: int) -> ModelTurn: "reported_model": turn.reported_model, "stop_reason": turn.stop_reason, "wall_ms": _ms(wall), + "tool_calls_requested": len(turn.tool_calls), } + self.conv.entries.append(turn) # kept even when the clock now ends the trajectory self.use(wall, "model") return turn assert error is not None @@ -317,6 +319,13 @@ async def model_call(self, bound: int) -> ModelTurn: async def run_tools(self, turn: ModelTurn) -> None: results: list[ToolResult] = [] + try: + await self._run_tools(turn, results) + finally: # results that came back stay in the record, even when a cap ends the turn + if results: + self.conv.entries.append(ToolResults(tuple(results))) + + async def _run_tools(self, turn: ModelTurn, results: list[ToolResult]) -> None: for call in turn.tool_calls: if len(self.tool_calls) >= self.caps.tool_calls: raise _Failed( @@ -369,7 +378,6 @@ async def run_tools(self, turn: ModelTurn) -> None: } results.append(ToolResult(call.id, call.name, sent, is_error)) self.use(wall, "tool") - self.conv.entries.append(ToolResults(tuple(results))) async def run_trajectory( diff --git a/benchmarks/agentic/run.py b/benchmarks/agentic/run.py index 8c6faf63..86172de0 100644 --- a/benchmarks/agentic/run.py +++ b/benchmarks/agentic/run.py @@ -164,6 +164,9 @@ def add(self, record: dict[str, Any]) -> None: for call in record["model_calls"]: for attempt in call["attempts"][:-1]: # every attempt but the last was retried self.retries[attempt["outcome"]] += 1 + if call["tool_calls_requested"] == 0: # an answer turn, whatever the outcome + self.answer_turns += 1 + self.output_cap_stops += call["stop_reason"] in OUTPUT_CAP_STOPS def summary(self) -> dict[str, Any]: starts = [r["started_at"] for r in self.records] @@ -320,9 +323,6 @@ def _write_cell( ) else: self.succeeded += 1 - stats.answer_turns += 1 - if record["model_calls"][-1]["stop_reason"] in OUTPUT_CAP_STOPS: - stats.output_cap_stops += 1 self.cells.add(cell) diff --git a/tests/benchmarks/test_agentic_loop.py b/tests/benchmarks/test_agentic_loop.py index 13d3623b..6c06201d 100644 --- a/tests/benchmarks/test_agentic_loop.py +++ b/tests/benchmarks/test_agentic_loop.py @@ -289,6 +289,26 @@ async def test_successful_work_over_the_allowance_is_a_cap_failure(harness: Harn assert len(record["model_calls"]) == 1 and len(harness.recording.reserves) == 1 +async def test_a_late_answer_is_still_recorded(harness: Harness) -> None: + late = {"text": "late", "delay_s": 0.25, "stop_reason": "max_tokens", "usage": USAGE} + record = await harness.run([late], caps=Caps(trajectory_s=0.1)) + assert record["error"]["category"] == "cap_trajectory_time" + assert record["canonical_messages"][-1] == { + "role": "assistant", + "content": [{"type": "text", "text": "late"}], + } + assert record["model_calls"][0]["tool_calls_requested"] == 0 + + +async def test_late_tool_results_are_still_recorded(harness: Harness) -> None: + record = await harness.run( + [TOOL, ANSWER], bridge=FakeBridge(delay=0.25), caps=Caps(trajectory_s=0.1) + ) + assert record["error"]["category"] == "cap_trajectory_time" + assert record["canonical_messages"][-1]["content"][0]["content"] == FAKE_TEXT + assert record["model_calls"][0]["tool_calls_requested"] == 1 + + async def test_grant_wait_longer_than_the_trajectory_allowance_still_succeeds( harness: Harness, ) -> None: diff --git a/tests/benchmarks/test_agentic_run.py b/tests/benchmarks/test_agentic_run.py index 1072078e..cc842e0d 100644 --- a/tests/benchmarks/test_agentic_run.py +++ b/tests/benchmarks/test_agentic_run.py @@ -20,7 +20,7 @@ from benchmarks.agentic.bridge import load_systems from benchmarks.agentic.clients import PAID_KEY_ENVS from benchmarks.agentic.host import LocalLauncher -from benchmarks.agentic.loop import MAX_RETRIES +from benchmarks.agentic.loop import MAX_RETRIES, Caps from benchmarks.agentic.protocol import KEY_SHAPED, KeyLeakError from benchmarks.agentic.run import ( OUTPUT_CAP_STOPS, @@ -314,6 +314,38 @@ def test_continuation_answers_count_as_output_cap_stops(tmp_path: Path) -> None: assert (fam["output_cap_stops"], fam["answer_turns"]) == (2, 100) # 2% +def test_late_max_tokens_answers_count_as_answer_turns_and_cap_stops( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + # Codex's case: 98 normal answers plus 2 answers that arrive after the trajectory allowance + # and stopped at the output cap. Both late ones fail the trajectory; both still count. + monkeypatch.setattr("benchmarks.agentic.run.HOSTED_CAPS", Caps(trajectory_s=0.2)) + usage = {"prompt_token_count": 1000, "candidates_token_count": 100} + script = [ + { + "text": "cut", + "stop_reason": "MAX_TOKENS", + "delay_s": 0.4, + "prompt_contains": EX1, + "usage": usage, + }, + {"text": "Scripted answer.", "usage": usage}, + ] + matrix = _matrix_with(tmp_path, {"scripted-google": script}) + config = _config( + tmp_path, + matrix_path=matrix, + models=("scripted-google",), + systems=("no-docs",), + questions=None, + repeats=2, + ) + summary = run_agentic(config) + fam = summary["families"]["scripted-google"] + assert summary["failed_cells"] == 2 + assert (fam["output_cap_stops"], fam["answer_turns"]) == (2, 100) + + 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 From 80500124b696c017ceeb8dafd0ab1fd23dd17d32 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:10:17 +0100 Subject: [PATCH 18/77] fix(benchmarks): match real key shapes, with start and end boundaries Round 2 B10 (with Fable keys Nit on the digit prefix). KEY_SHAPED now matches the real shapes: sk-ant-api- plus 80 or more characters, sk-[proj-|svcacct-] plus 40 or more, and AIza plus exactly 35, each ending at a boundary. A key starts a token or follows a URL escape such as %20, so random standard and URL-safe base64 no longer match (the old pattern fired on the test's seed), and a digit-prefixed Anthropic key still does. A leak names its place and pattern, never the match. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/protocol.py | 20 +++++++++---- tests/benchmarks/test_agentic_host.py | 43 ++++++++++++++++++++------- 2 files changed, 46 insertions(+), 17 deletions(-) diff --git a/benchmarks/agentic/protocol.py b/benchmarks/agentic/protocol.py index 5e55d50c..51d6f9c2 100644 --- a/benchmarks/agentic/protocol.py +++ b/benchmarks/agentic/protocol.py @@ -15,10 +15,17 @@ from benchmarks.runner import BenchmarkValidationError MAX_FRAME_BYTES = 64 * 1024 * 1024 -KEY_SHAPED = re.compile( - r"(?{p})" for name, p in KEY_PATTERNS.items())) class KeyLeakError(BenchmarkValidationError): @@ -51,8 +58,9 @@ async def read_frame( def assert_no_key_shaped(text: str, *, where: str) -> None: - if KEY_SHAPED.search(text): - raise KeyLeakError(f"a key-shaped string was found in {where}") # never the match + if match := KEY_SHAPED.search(text): + # Names the place and the pattern, never the match. + raise KeyLeakError(f"a key-shaped string ({match.lastgroup} pattern) was found in {where}") def contains_own_key(text: str, own_key: str | None) -> bool: diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 91565d76..5610071f 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -175,23 +175,44 @@ def test_local_launcher_passes_no_provider_key_and_runs_only_scripted_models( assert LocalLauncher().supports(job.family) is True +ANTHROPIC_SHAPE = "sk-ant-api03-" + "a" * 90 + + @pytest.mark.parametrize( - "text,leaks", + "text,pattern", [ - ("sk-ant-api03-" + "a" * 40, True), - ("AIza" + "b" * 35, True), - ("sk-proj-" + "c" * 40, True), - ("a disk-based cache", False), - ("task-runner-" + "d" * 40, False), + (ANTHROPIC_SHAPE, "anthropic"), + ("AIza" + "b" * 35, "google"), + ("sk-proj-" + "c" * 40, "openai"), + ("sk-svcacct-" + "c" * 40, "openai"), + ("sk-" + "c" * 48, "openai"), + ("q=%20" + ANTHROPIC_SHAPE, "anthropic"), # URL-encoded: a digit just before the key + ("7" + ANTHROPIC_SHAPE, "anthropic"), + ("q=%2B" + "sk-proj-" + "c" * 40, "openai"), + ("a disk-based cache", None), + ("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 ], ) -def test_key_shaped_scan(text: str, leaks: bool) -> None: - if leaks: - with pytest.raises(KeyLeakError, match="test frame") as caught: +def test_key_shaped_scan(text: str, pattern: str | None) -> None: + if pattern: + with pytest.raises(KeyLeakError, match=f"test frame.*{pattern}|{pattern}.*test frame"): assert_no_key_shaped(f"before {text} after", where="test frame") + with pytest.raises(KeyLeakError) as caught: + assert_no_key_shaped(text, where="test frame") assert text not in str(caught.value) else: - assert_no_key_shaped(text, where="test frame") + assert_no_key_shaped(f"before {text} after", where="test frame") + + +def test_random_base64_is_not_key_shaped() -> None: + import base64 + import random + + data = random.Random(20261107).randbytes(3 * 1024 * 1024) # the old pattern fired here + for text in (base64.b64encode(data), base64.urlsafe_b64encode(data)): + assert_no_key_shaped(text.decode("ascii"), where="random base64") def _run_python(code: str) -> subprocess.CompletedProcess[bytes]: @@ -349,7 +370,7 @@ async def test_host_aborts_the_run_when_a_worker_frame_holds_a_key_shaped_string ) -> None: leaky_worker = ( "import json, sys\n" - "body = json.dumps({'type': 'system_info', 'note': 'sk-ant-' + 'a' * 30}).encode()\n" + "body = json.dumps({'type': 'system_info', 'note': 'sk-ant-api03-' + 'a' * 90}).encode()\n" "sys.stdout.buffer.write(len(body).to_bytes(8, 'big') + body)\n" "sys.stdout.buffer.flush()\n" "import time; time.sleep(30)\n" From 8b3c0cbdd12db5e026cad7a3a2c790edbc5ec836 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:12:25 +0100 Subject: [PATCH 19/77] fix(benchmarks): a worker error costs its own cells, and aborts are written Round 2 B7 (ponytail must fix). An error frame that is neither a key leak nor FrameTooLarge is handled like a lost worker: its in-flight unit is booked at twice its bound, its unreported trajectories are not_run with reason worker_error, the other jobs finish, and the run summary lists the error under worker_errors. run_agentic always writes ledger-events.jsonl and run-summary.json, with status completed or aborted and the abort reason, even when the run stops. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/host.py | 11 ++- benchmarks/agentic/run.py | 106 ++++++++++++++++----------- tests/benchmarks/test_agentic_run.py | 50 +++++++++++++ 3 files changed, 124 insertions(+), 43 deletions(-) diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index 9d9e69b5..8b4b4bee 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -23,6 +23,7 @@ from benchmarks.agentic.loop import Caps from benchmarks.agentic.protocol import ( MAX_FRAME_BYTES, + FrameTooLarge, KeyLeakError, assert_no_key_shaped, encode_frame, @@ -100,6 +101,7 @@ async def _supervise( in_flight: str | None = None reported: set[tuple[str, int]] = set() done = False + lost_reason = "worker_lost" try: try: job_frame = { @@ -148,7 +150,12 @@ async def _supervise( reason = str(message.get("reason")) if reason == "own key found in output": raise KeyLeakError(f"worker {job.job_id}: {reason}") - raise BenchmarkValidationError(f"worker {job.job_id} failed: {reason}") + if reason.startswith("FrameTooLarge:"): + raise FrameTooLarge(f"worker {job.job_id}: {reason}") + # 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) if kind in ("trajectory", "not_run"): @@ -179,7 +186,7 @@ async def _supervise( "type": "not_run", "corpus_id": item["corpus_id"], "repeat": item["repeat"], - "reason": "worker_lost", + "reason": lost_reason, }, ) diff --git a/benchmarks/agentic/run.py b/benchmarks/agentic/run.py index 86172de0..59193c6b 100644 --- a/benchmarks/agentic/run.py +++ b/benchmarks/agentic/run.py @@ -30,6 +30,7 @@ PROVIDER_CAPS, Ledger, LedgerService, + PriceSnapshot, load_price_snapshot, refuse_stale_snapshot, ) @@ -207,6 +208,7 @@ def __init__( self.failed = 0 self.discarded: list[dict[str, Any]] = [] self.not_run: list[dict[str, Any]] = [] + self.worker_errors: list[dict[str, Any]] = [] async def on_message(self, job: WorkerJob, message: dict[str, Any]) -> None: kind = message["type"] @@ -214,6 +216,9 @@ async def on_message(self, job: WorkerJob, message: dict[str, Any]) -> None: info = {k: v for k, v in message.items() if k != "type"} _write(self.out / "systems" / f"{job.job_id}.json", info) 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"]) @@ -457,48 +462,67 @@ def run_agentic( 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}) collector = _Collector(out, {q.id: q for q in questions}, families) - asyncio.run( - run_jobs( - jobs, - launcher=launcher, - ledger=service, - on_message=collector.on_message, - log_dir=out / "logs", - cwd=_REPO_ROOT, + try: + asyncio.run( + run_jobs( + jobs, + launcher=launcher, + ledger=service, + on_message=collector.on_message, + log_dir=out / "logs", + cwd=_REPO_ROOT, + ) ) - ) - events = "".join(json.dumps(e, sort_keys=True) + "\n" for e in ledger.events(run_id)) - assert_no_key_shaped(events, where="ledger-events.jsonl") - (out / "ledger-events.jsonl").write_text(events, encoding="utf-8") - scored = collector.succeeded + collector.failed - summary |= { - "completed_at": _utc_now(), - "scored_cells": scored, - "correctness_denominator_cells": scored, - "succeeded_cells": collector.succeeded, - "failed_cells": collector.failed, - "failed_cells_included_in_correctness_denominator": True, - "competitors": sorted(collector.cells), - "discarded": collector.discarded, - "not_run": collector.not_run, - "families": {fid: stats.summary() for fid, stats in collector.families.items()}, - "ledger": { - provider: { - "spent_before": str(spent_before[provider]), - "spent_after": str(ledger.spent(provider)), - "cap": str(caps[provider]), - "stopped": ledger.stopped(provider), - } - for provider in caps - }, - "price_snapshot": { - "captured_on": snapshot.captured_on.isoformat(), - "expires_on": None - if snapshot.expires_on is None - else snapshot.expires_on.isoformat(), - }, - } - _write(out / "run-summary.json", summary) + except BaseException as exc: # still write what was spent and what ran + summary |= {"status": "aborted", "abort_reason": f"{type(exc).__name__}: {exc}"} + raise + finally: + _write_outcome(out, summary, collector, ledger, run_id, caps, spent_before, snapshot) return summary finally: ledger.close() + + +def _write_outcome( + out: Path, + summary: dict[str, Any], + collector: _Collector, + ledger: Ledger, + run_id: str, + caps: Mapping[str, Decimal], + spent_before: Mapping[str, Decimal], + snapshot: PriceSnapshot, +) -> None: + """ledger-events.jsonl and run-summary.json, for a completed or an aborted run.""" + events = "".join(json.dumps(e, sort_keys=True) + "\n" for e in ledger.events(run_id)) + assert_no_key_shaped(events, where="ledger-events.jsonl") + (out / "ledger-events.jsonl").write_text(events, encoding="utf-8") + scored = collector.succeeded + collector.failed + summary.setdefault("status", "completed") + summary |= { + "completed_at": _utc_now(), + "scored_cells": scored, + "correctness_denominator_cells": scored, + "succeeded_cells": collector.succeeded, + "failed_cells": collector.failed, + "failed_cells_included_in_correctness_denominator": True, + "competitors": sorted(collector.cells), + "discarded": collector.discarded, + "not_run": collector.not_run, + "worker_errors": collector.worker_errors, + "families": {fid: stats.summary() for fid, stats in collector.families.items()}, + "ledger": { + provider: { + "spent_before": str(spent_before[provider]), + "spent_after": str(ledger.spent(provider)), + "cap": str(caps[provider]), + "stopped": ledger.stopped(provider), + } + for provider in caps + }, + "price_snapshot": { + "captured_on": snapshot.captured_on.isoformat(), + "expires_on": None if snapshot.expires_on is None else snapshot.expires_on.isoformat(), + }, + } + _write(out / "run-summary.json", summary) diff --git a/tests/benchmarks/test_agentic_run.py b/tests/benchmarks/test_agentic_run.py index cc842e0d..066f814c 100644 --- a/tests/benchmarks/test_agentic_run.py +++ b/tests/benchmarks/test_agentic_run.py @@ -356,6 +356,56 @@ def test_a_key_shape_in_an_input_file_is_refused_before_any_snapshot(tmp_path: P assert not (tmp_path / "run" / "snapshots").exists() +def test_a_worker_error_costs_only_its_own_cells(tmp_path: Path) -> None: + # Usage that cannot be bucketed (cached > input) raises BenchmarkValidationError in the + # openai worker; the anthropic job still finishes and the summary lists the failure. + bad = { + "text": "x", + "usage": {"input_tokens": 100, "input_tokens_details": {"cached_tokens": 200}}, + } + matrix = _matrix_with(tmp_path, {"scripted-openai": [bad]}) + config = _config( + tmp_path, + matrix_path=matrix, + models=("scripted-anthropic", "scripted-openai"), + systems=("no-docs",), + questions=("SYN-EX-001",), + repeats=1, + ) + summary = run_agentic(config) + assert summary["status"] == "completed" and summary["succeeded_cells"] == 1 + assert summary["not_run"] == [ + { + "cell": "no-docs--scripted-openai--r1", + "corpus_id": "SYN-EX-001", + "reason": "worker_error", + "attempt": None, + } + ] + (error,) = summary["worker_errors"] + assert error["job_id"] == "scripted-openai--no-docs" and "negative" in error["reason"] + assert Decimal(summary["ledger"]["openai"]["spent_after"]) > 0 # its unit, at 2x the bound + + +def test_an_aborted_run_still_writes_its_summary_and_ledger_events(tmp_path: Path) -> None: + leak = {"text": "sk-ant-api03-" + "a" * 90, "usage": {"input_tokens": 1, "output_tokens": 1}} + matrix = _matrix_with(tmp_path, {"scripted-anthropic": [leak]}) + config = _config( + tmp_path, + matrix_path=matrix, + models=("scripted-anthropic",), + systems=("no-docs",), + questions=("SYN-EX-001",), + repeats=1, + ) + with pytest.raises(KeyLeakError): + run_agentic(config) + run = tmp_path / "run" + summary = json.loads((run / "run-summary.json").read_text()) + assert summary["status"] == "aborted" and "KeyLeakError" in summary["abort_reason"] + assert (run / "ledger-events.jsonl").read_text().count('"event": "reserve"') == 1 + + def test_agentic_run_refuses_a_non_empty_out_dir(tmp_path: Path) -> None: (tmp_path / "run").mkdir() (tmp_path / "run" / "stale.json").write_text("{}") From d1fbeec44e06b9f5d0e1da8b7d01abb33b9f8977 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:13:05 +0100 Subject: [PATCH 20/77] fix(benchmarks): latency counts successful work and overhead only Round 2 B8. A cell's latency_ms is used_ms plus overhead_ms; grant waits, failed attempts and retry backoff are excluded, and the latency record's timing keeps the full split. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/run.py | 5 ++++- tests/benchmarks/test_agentic_run.py | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/benchmarks/agentic/run.py b/benchmarks/agentic/run.py index 59193c6b..af0d9005 100644 --- a/benchmarks/agentic/run.py +++ b/benchmarks/agentic/run.py @@ -308,7 +308,10 @@ def _write_cell( **base, "status": status, "error_category": None if error is None else error["category"], - "latency_ms": record["timing"]["wall_ms"], + # Successful work plus overhead: no grant wait, failed attempt or backoff. + "latency_ms": round( + record["timing"]["used_ms"] + record["timing"]["overhead_ms"], 3 + ), "started_at": record["started_at"], "completed_at": record["completed_at"], "timing": record["timing"], diff --git a/tests/benchmarks/test_agentic_run.py b/tests/benchmarks/test_agentic_run.py index 066f814c..7de9247c 100644 --- a/tests/benchmarks/test_agentic_run.py +++ b/tests/benchmarks/test_agentic_run.py @@ -293,6 +293,29 @@ def test_run_summary_wall_time_includes_failed_attempts_backoff_and_grant_waits( assert sum(f["grant_wait_s"] for f in summary["families"].values()) > 0 +def test_latency_counts_successful_work_and_overhead_only(tmp_path: Path) -> None: + script = [ + {"error": {"kind": "rate_limited", "status": 429, "retry_after_s": 0.3}, "delay_s": 0.2}, + {"text": "ok", "usage": {"input_tokens": 1000, "output_tokens": 100}}, + ] + matrix = _matrix_with(tmp_path, {"scripted-anthropic": script}) + config = _config( + tmp_path, + matrix_path=matrix, + models=("scripted-anthropic",), + systems=("no-docs",), + questions=("SYN-EX-001",), + repeats=1, + ) + run_agentic(config) + cell = tmp_path / "run" / "latency" / "no-docs--scripted-anthropic--r1" / "SYN-EX-001.json" + latency = json.loads(cell.read_text()) + timing = latency["timing"] + assert latency["latency_ms"] == round(timing["used_ms"] + timing["overhead_ms"], 3) + assert latency["latency_ms"] < timing["wall_ms"] - 400 # no failed attempt, no backoff + assert set(timing) >= {"grant_wait_ms", "failed_attempt_ms", "retry_wait_ms"} + + def test_continuation_answers_count_as_output_cap_stops(tmp_path: Path) -> None: # One scripted google family, no-docs, all 50 sample questions, repeats 2 = 100 answers. usage = {"prompt_token_count": 1000, "candidates_token_count": 100} From bdde1a5474d315379b071c28217d4168d905b9ff Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:13:38 +0100 Subject: [PATCH 21/77] test(benchmarks): pin the MCP server reopen after a crash Round 2 B9. Against the fake fetch server, Q1's script calls die and Q2's calls pid: Q1 is failed with mcp_protocol_crash, Q2 succeeds on the reopened server, then the worker reports done. With the reopen disabled the test fails on Q2. Co-Authored-By: Claude Opus 5.5 --- tests/benchmarks/test_agentic_host.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 5610071f..50ded828 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -311,6 +311,31 @@ async def test_worker_exits_with_its_mcp_server_child_still_alive_at_shutdown( os.kill(server_pid, 0) +async def test_a_crashed_mcp_server_is_reopened_for_the_next_trajectory( + host: Host, tmp_path: Path +) -> None: + script = [ + { + "tools": [{"name": "die", "arguments": {}}], + "usage": USAGE, + "prompt_contains": "question 1", + }, + { + "tools": [{"name": "pid", "arguments": {}}], + "usage": USAGE, + "prompt_contains": "question 2", + }, + ANSWER, + ] + await host.run([_job(tmp_path, script, system=FAKE_FETCH, count=2)]) + messages = host.messages() + assert [m["type"] for m in messages] == ["system_info", "trajectory", "trajectory", "done"] + first, second = (m["record"] for m in messages[1:3]) + assert (messages[1]["corpus_id"], first["status"]) == ("Q1", "failed") + assert first["error"]["category"] == "mcp_protocol_crash" + assert (messages[2]["corpus_id"], second["status"]) == ("Q2", "succeeded") + + async def test_a_trajectory_frame_over_100000_bytes_round_trips_through_a_worker( host: Host, tmp_path: Path ) -> None: From b52323dafcba7d3dbf0c26810b4bd66508f3a67f Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:15:04 +0100 Subject: [PATCH 22/77] fix(benchmarks): gate competitors by id too, and drop the caller-less latch Round 2 B11. validate_manifest_eligibility screens an entry whose id or adapter is a competitor id, so a competitor run through the agentic bridge (adapter mcp-stdio) still needs its pin and terms metadata. require_live_competitor, LIVE_COMPETITORS_ENV, their re-export and their six tests are deleted: nothing calls them since the fixed-flow adapters went. Round 2 brings the latch back with a caller. Co-Authored-By: Claude Opus 5.5 --- benchmarks/adapters/__init__.py | 2 - benchmarks/adapters/eligibility.py | 13 ++- benchmarks/adapters/guard.py | 58 +---------- .../benchmarks/test_competitor_eligibility.py | 98 ++++--------------- 4 files changed, 29 insertions(+), 142 deletions(-) diff --git a/benchmarks/adapters/__init__.py b/benchmarks/adapters/__init__.py index 90b5a2d9..12faa1ca 100644 --- a/benchmarks/adapters/__init__.py +++ b/benchmarks/adapters/__init__.py @@ -34,7 +34,6 @@ ) from benchmarks.adapters.guard import ( LiveProviderDisabledError, - require_live_competitor, require_live_environment, ) from benchmarks.runner import BenchmarkCellFailure @@ -43,7 +42,6 @@ "BenchmarkCellFailure", "LiveProviderDisabledError", "require_live_environment", - "require_live_competitor", "TokenCounter", "FakeTokenCounter", "LiveClaudeTokenCounter", diff --git a/benchmarks/adapters/eligibility.py b/benchmarks/adapters/eligibility.py index 4b2728ec..2ebfe212 100644 --- a/benchmarks/adapters/eligibility.py +++ b/benchmarks/adapters/eligibility.py @@ -141,9 +141,10 @@ def validate_manifest_eligibility(manifest_data: dict[str, Any]) -> None: Called once, on the raw parsed manifest ``dict`` (before ``benchmarks.runner._load_competitors`` builds :class:`Competitor` instances and before any cell executes) by - ``benchmarks.runner.run_benchmark``. Entries whose ``adapter`` is not one - of :data:`COMPETITOR_ADAPTER_IDS` are skipped -- this validator only - applies to the four competitor docs-MCP adapters (see module docstring). + ``benchmarks.runner.run_benchmark``. Entries whose ``adapter`` and ``id`` + are both outside :data:`COMPETITOR_ADAPTER_IDS` are skipped -- this + validator only applies to the four competitor docs MCPs (see module + docstring). Malformed entries in other respects (missing ``id``, missing ``adapter``, non-mapping items) are left to ``benchmarks.runner._load_competitors``'s own validation, which runs @@ -155,5 +156,9 @@ def validate_manifest_eligibility(manifest_data: dict[str, Any]) -> None: for item in competitors: if not isinstance(item, dict): continue - if item.get("adapter") in COMPETITOR_ADAPTER_IDS: + # By id too: round 2 runs a competitor through the agentic bridge (adapter mcp-stdio). + if ( + item.get("adapter") in COMPETITOR_ADAPTER_IDS + or item.get("id") in COMPETITOR_ADAPTER_IDS + ): validate_competitor_eligibility(item) diff --git a/benchmarks/adapters/guard.py b/benchmarks/adapters/guard.py index 5da2dbb3..734efe36 100644 --- a/benchmarks/adapters/guard.py +++ b/benchmarks/adapters/guard.py @@ -16,14 +16,8 @@ ``BENCHMARK_LIVE_PROVIDERS_ENABLED`` and ``ANTHROPIC_API_KEY`` set, exactly like every other provider gated here. -Issue #87 adds :func:`require_live_competitor` for the keyless competitor -docs MCPs (GitMCP, DeepWiki, and Context7 in its default keyless mode): they -have no per-provider API key to gate on, so a second non-secret latch -(:data:`LIVE_COMPETITORS_ENV`, a comma-separated allowlist) stands in for -the key, keeping the same two-latch shape (global flag + per-target opt-in) -as the keyed providers above. Keyed competitors (Context7 in key mode, -Ref.tools) still go through :func:`require_live_environment` via their own -``PROVIDER_API_KEY_ENV`` entries. +The keyless competitors' allowlist latch is gone with the fixed-flow +adapters that called it; round 2 brings it back together with its caller. """ from __future__ import annotations @@ -44,8 +38,7 @@ #: #: ``ref`` and ``context7`` (issue #87) gate the keyed competitor docs MCPs: #: Ref.tools (always keyed) and Context7 when its manifest entry declares key -#: mode (Context7 also has a keyless mode; see :func:`require_live_competitor`). -#: Round 2 runs them through the agentic bridge. +#: mode. Round 2 runs them through the agentic bridge. PROVIDER_API_KEY_ENV = { "openai": "OPENAI_API_KEY", "google": "GOOGLE_API_KEY", @@ -54,15 +47,6 @@ "context7": "CONTEXT7_API_KEY", } -#: Comma-separated allowlist of keyless competitor names permitted to run -#: live (issue #87). Parsed case-insensitively with surrounding whitespace -#: stripped from each item -- e.g. ``"gitmcp, DeepWiki"`` allows both -#: ``gitmcp`` and ``deepwiki``. This is the second latch for -#: :func:`require_live_competitor`; it deliberately holds no secret, so a -#: keyless competitor still requires two explicit, independent opt-ins -#: (the shared global flag plus this per-target allowlist) rather than one. -LIVE_COMPETITORS_ENV = "BENCHMARK_LIVE_COMPETITORS" - _TRUTHY = {"1", "true", "yes"} @@ -140,39 +124,3 @@ def redact_api_keys(text: str) -> str: position = end parts.append(text[position:]) return "".join(parts) - - -def require_live_competitor(name: str) -> None: - """Raise :class:`LiveProviderDisabledError` unless a keyless competitor is explicitly enabled. - - Two non-secret latches, both required (issue #87, Codex round-1 finding - 3: flag-only gating would weaken the guard posture below the keyed - providers' two-condition shape): - - 1. ``BENCHMARK_LIVE_PROVIDERS_ENABLED`` is set to a truthy value (same - flag, same check, as :func:`require_live_environment`). - 2. ``name`` appears in the comma-separated :data:`LIVE_COMPETITORS_ENV` - allowlist (case-insensitive, whitespace-tolerant). - - Both conditions must hold. Passing this check does not by itself make a - live call: nothing in this module opens a transport. - """ - flag = os.environ.get(LIVE_PROVIDERS_ENABLED_ENV, "").strip().lower() - if flag not in _TRUTHY: - raise LiveProviderDisabledError( - "live competitor calls are disabled: set " - f"{LIVE_PROVIDERS_ENABLED_ENV}=1 to pass the live-competitor guardrail check " - f"for competitor {name!r} (this does not by itself enable live calls; " - "see benchmarks/adapters/guard.py)" - ) - allowlist = { - item.strip().lower() - for item in os.environ.get(LIVE_COMPETITORS_ENV, "").split(",") - if item.strip() - } - if name.strip().lower() not in allowlist: - raise LiveProviderDisabledError( - f"live competitor calls are disabled: {name!r} is not present in " - f"{LIVE_COMPETITORS_ENV} (comma-separated allowlist); set " - f"{LIVE_COMPETITORS_ENV}={name},... to enable it" - ) diff --git a/tests/benchmarks/test_competitor_eligibility.py b/tests/benchmarks/test_competitor_eligibility.py index 5a3a2d03..993bda61 100644 --- a/tests/benchmarks/test_competitor_eligibility.py +++ b/tests/benchmarks/test_competitor_eligibility.py @@ -1,14 +1,12 @@ -"""Tests for the competitor guard latch and manifest eligibility gates (issue #87). +"""Tests for the competitor manifest eligibility gates (issue #87). The four fixed-flow competitor adapters and their tests are gone (design -§11.1): round 2 runs the competitors through the agentic MCP bridge. What -stays, and is covered here unchanged: - -1. ``require_live_competitor`` latch semantics in isolation. -2. Eligibility/exclusion: per-entry and manifest-level validation, the - runner's manifest-load-time refusal (including the CLI exit-2 path), - the ``exclusions:`` block's byte-for-byte snapshot survival, and the - committed template manifest. +§11.1): round 2 runs the competitors through the agentic MCP bridge, and +brings the keyless competitors' allowlist latch back with its caller. What +stays, and is covered here: per-entry and manifest-level validation (by +adapter or id), the runner's manifest-load-time refusal (including the CLI +exit-2 path), the ``exclusions:`` block's byte-for-byte snapshot survival, +and the committed template manifest. Zero network calls anywhere in this file, by construction. """ @@ -28,13 +26,6 @@ validate_competitor_eligibility, validate_manifest_eligibility, ) -from benchmarks.adapters.guard import ( - LIVE_COMPETITORS_ENV, - LIVE_PROVIDERS_ENABLED_ENV, - PROVIDER_API_KEY_ENV, - LiveProviderDisabledError, - require_live_competitor, -) from benchmarks.runner import ( BenchmarkConfig, BenchmarkValidationError, @@ -48,71 +39,7 @@ # ============================================================================= -# 1. require_live_competitor latch semantics in isolation -# ============================================================================= - - -def test_require_live_competitor_refuses_without_flag(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.delenv(LIVE_PROVIDERS_ENABLED_ENV, raising=False) - monkeypatch.delenv(LIVE_COMPETITORS_ENV, raising=False) - - with pytest.raises(LiveProviderDisabledError, match=LIVE_PROVIDERS_ENABLED_ENV): - require_live_competitor("gitmcp") - - -def test_require_live_competitor_refuses_with_flag_but_name_absent_from_allowlist( - monkeypatch: pytest.MonkeyPatch, -) -> None: - monkeypatch.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") - monkeypatch.setenv(LIVE_COMPETITORS_ENV, "deepwiki") - - with pytest.raises(LiveProviderDisabledError, match=LIVE_COMPETITORS_ENV): - require_live_competitor("gitmcp") - - -def test_require_live_competitor_refuses_with_allowlist_but_no_flag( - monkeypatch: pytest.MonkeyPatch, -) -> None: - monkeypatch.delenv(LIVE_PROVIDERS_ENABLED_ENV, raising=False) - monkeypatch.setenv(LIVE_COMPETITORS_ENV, "gitmcp") - - with pytest.raises(LiveProviderDisabledError, match=LIVE_PROVIDERS_ENABLED_ENV): - require_live_competitor("gitmcp") - - -def test_require_live_competitor_passes_only_with_both_latches( - monkeypatch: pytest.MonkeyPatch, -) -> None: - monkeypatch.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") - monkeypatch.setenv(LIVE_COMPETITORS_ENV, "gitmcp") - - require_live_competitor("gitmcp") # must not raise - - -def test_require_live_competitor_is_key_independent(monkeypatch: pytest.MonkeyPatch) -> None: - # No PROVIDER_API_KEY_ENV entry is consulted for a keyless competitor -- - # the allowlist is the second latch, not a key. - monkeypatch.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") - monkeypatch.setenv(LIVE_COMPETITORS_ENV, "gitmcp") - monkeypatch.delenv(PROVIDER_API_KEY_ENV["ref"], raising=False) - monkeypatch.delenv(PROVIDER_API_KEY_ENV["context7"], raising=False) - - require_live_competitor("gitmcp") # must not raise despite no key env set anywhere - - -def test_require_live_competitor_allowlist_parsing_tolerant_of_spaces_and_case( - monkeypatch: pytest.MonkeyPatch, -) -> None: - monkeypatch.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") - monkeypatch.setenv(LIVE_COMPETITORS_ENV, " GitMCP , DeepWiki ") - - require_live_competitor("gitmcp") # must not raise - require_live_competitor("deepwiki") # must not raise - require_live_competitor("GITMCP") # must not raise -- case-insensitive on both sides - - -# ============================================================================= -# 2. Eligibility / exclusion screening +# Eligibility / exclusion screening # ============================================================================= @@ -227,6 +154,15 @@ def test_validate_manifest_eligibility_raises_for_excluded_competitor_entry() -> validate_manifest_eligibility(manifest) +def test_validate_manifest_eligibility_screens_a_competitor_by_its_id_too() -> None: + # Round 2 runs competitors through the agentic bridge (adapter mcp-stdio), so the id alone + # must bring the pin and terms gate. + manifest = {"competitors": [{"id": "context7", "adapter": "mcp-stdio", "command": ["x"]}]} + + with pytest.raises(BenchmarkValidationError, match="context7"): + validate_manifest_eligibility(manifest) + + # --- Integration: runner refuses at manifest-load time, before any cell ---- From 674b08d6171a66d91d7dab939cd6a2866da541c9 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:17:07 +0100 Subject: [PATCH 23/77] feat(benchmarks): one durable default ledger, with its spend printed at start Round 2 B12. --ledger-dir defaults to platformdirs.user_data_dir("mcp-python-docs-benchmarks")/ledger and can still be overridden, so every run's spend counts against the same caps. At start, run_agentic prints each provider's spent_before and cap to stderr (stdout stays the summary JSON). A test runs twice on the default and checks the second run starts where the first ended. Co-Authored-By: Claude Opus 5.5 --- benchmarks/__main__.py | 6 ++-- benchmarks/agentic/run.py | 16 ++++++++++ tests/benchmarks/test_agentic_run.py | 44 ++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+), 2 deletions(-) diff --git a/benchmarks/__main__.py b/benchmarks/__main__.py index d4c56b24..847f6a58 100644 --- a/benchmarks/__main__.py +++ b/benchmarks/__main__.py @@ -166,7 +166,9 @@ def _build_parser() -> argparse.ArgumentParser: agentic.add_argument("--corpus", required=True, type=Path, help="Corpus YAML file.") agentic.add_argument("--out", required=True, type=Path, help="Empty artifact directory.") agentic.add_argument( - "--ledger-dir", required=True, type=Path, help="Persistent spend ledger directory." + "--ledger-dir", + type=Path, + help="Spend ledger directory (default: one durable per-user path, shared by every run).", ) agentic.add_argument("--matrix", type=Path, default=_DEFAULT_MODEL_MATRIX) agentic.add_argument("--manifest", type=Path, default=_DEFAULT_AGENTIC_MANIFEST) @@ -212,7 +214,7 @@ def main(argv: list[str] | None = None) -> int: matrix_path=args.matrix, manifest_path=args.manifest, prices_path=args.prices, - ledger_dir=args.ledger_dir, + ledger_dir=args.ledger_dir or agentic_run.default_ledger_dir(), out_dir=args.out, models=args.models, systems=args.systems, diff --git a/benchmarks/agentic/run.py b/benchmarks/agentic/run.py index af0d9005..747e5b16 100644 --- a/benchmarks/agentic/run.py +++ b/benchmarks/agentic/run.py @@ -13,6 +13,7 @@ import json import os import random +import sys from collections import Counter from collections.abc import Mapping, Sequence from dataclasses import dataclass, field, replace @@ -22,6 +23,8 @@ from pathlib import Path from typing import Any, Protocol +import platformdirs + import benchmarks from benchmarks.adapters.claude_tokens import ANTHROPIC_API_VERSION, DEFAULT_COUNT_MODEL from benchmarks.agentic.bridge import SystemSpec, load_systems @@ -58,6 +61,13 @@ OUTPUT_CAP_STOPS = frozenset({"max_tokens", "max_output_tokens", "MAX_TOKENS", "CONTINUATION"}) _REPO_ROOT = Path(benchmarks.__file__).resolve().parent.parent + + +def default_ledger_dir() -> Path: + """One durable per-user ledger, so every run's spend counts against the same caps.""" + return Path(platformdirs.user_data_dir("mcp-python-docs-benchmarks")) / "ledger" + + _CLIENT_PACKAGES = ("anthropic", "openai", "google-genai", "mcp") _HOSTED_FIELDS = ( "max_input_tokens", @@ -462,6 +472,12 @@ def run_agentic( "then rerun with --acknowledge-overrun" ) spent_before = {provider: ledger.spent(provider) for provider in caps} + for provider, cap in caps.items(): # stderr: stdout carries the summary JSON + print( + f"ledger {config.ledger_dir}: {provider} " + f"spent {spent_before[provider]} of cap {cap}", + file=sys.stderr, + ) 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}) collector = _Collector(out, {q.id: q for q in questions}, families) diff --git a/tests/benchmarks/test_agentic_run.py b/tests/benchmarks/test_agentic_run.py index 7de9247c..a9d55692 100644 --- a/tests/benchmarks/test_agentic_run.py +++ b/tests/benchmarks/test_agentic_run.py @@ -493,6 +493,50 @@ def test_cli_agentic_run_dry_run_prints_the_plan( assert printed["planned_cells"] == 18 and printed["run_id"] == "cli" +def test_runs_share_one_durable_ledger_by_default( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + import platformdirs + + from benchmarks.agentic.run import default_ledger_dir + + monkeypatch.setenv("HOME", str(tmp_path / "home")) + monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "home" / "data")) + expected = Path(platformdirs.user_data_dir("mcp-python-docs-benchmarks")) / "ledger" + assert default_ledger_dir() == expected and str(tmp_path) in str(expected) + spent = [] + for run in ("first", "second"): + args = [ + "agentic-run", + "--corpus", + str(SAMPLE_CORPUS), + "--out", + str(tmp_path / run), + "--matrix", + str(FIX / "model-matrix.yml"), + "--manifest", + str(COMMITTED_MANIFEST), + "--prices", + str(FIX / "prices.yml"), + "--models", + "scripted-anthropic", + "--systems", + "no-docs", + "--questions", + "SYN-EX-001", + "--repeats", + "1", + ] + assert main(args) == 0 + captured = capsys.readouterr() + ledger = json.loads(captured.out)["ledger"]["anthropic"] + spent.append((Decimal(ledger["spent_before"]), Decimal(ledger["spent_after"]))) + assert "anthropic" in captured.err and "cap 180" in captured.err + (first_before, first_after), (second_before, second_after) = spent + assert first_before == 0 and second_before == first_after > 0 + assert (expected / "anthropic.jsonl").is_file() + + def _cli_args(tmp_path: Path) -> list[str]: return [ "agentic-run", From 67760c9d2cacf944e3eab68323062058d516cce2 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:18:45 +0100 Subject: [PATCH 24/77] refactor(benchmarks): family stats keep running aggregates, not records Round 2 B13. _FamilyStats no longer holds each trajectory record: it keeps the first start, the last completion and the summed grant-wait, failed-attempt and retry-wait milliseconds, which is all the summary reads. The run-summary tests cover the output unchanged. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/run.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/benchmarks/agentic/run.py b/benchmarks/agentic/run.py index 747e5b16..515e18cd 100644 --- a/benchmarks/agentic/run.py +++ b/benchmarks/agentic/run.py @@ -164,14 +164,20 @@ def _select[T: _HasId](items: Sequence[T], wanted: tuple[str, ...] | None, label @dataclass class _FamilyStats: - records: list[dict[str, Any]] = field(default_factory=list) + # Running aggregates only: a record can be megabytes, and a run holds thousands. + first_started_at: str | None = None + last_completed_at: str | None = None + timing_ms: Counter[str] = field(default_factory=Counter) retries: Counter[str] = field(default_factory=Counter) reruns: int = 0 answer_turns: int = 0 output_cap_stops: int = 0 def add(self, record: dict[str, Any]) -> None: - self.records.append(record) + self.first_started_at = min(filter(None, (self.first_started_at, record["started_at"]))) + self.last_completed_at = max(filter(None, (self.last_completed_at, record["completed_at"]))) + for name in _TIMING_SUMS: + self.timing_ms[name] += record["timing"][f"{name}_ms"] for call in record["model_calls"]: for attempt in call["attempts"][:-1]: # every attempt but the last was retried self.retries[attempt["outcome"]] += 1 @@ -180,18 +186,13 @@ def add(self, record: dict[str, Any]) -> None: self.output_cap_stops += call["stop_reason"] in OUTPUT_CAP_STOPS def summary(self) -> dict[str, Any]: - starts = [r["started_at"] for r in self.records] - ends = [r["completed_at"] for r in self.records] - first, last = (min(starts), max(ends)) if self.records else (None, None) + first, last = self.first_started_at, self.last_completed_at wall = ( (datetime.fromisoformat(last) - datetime.fromisoformat(first)).total_seconds() if first and last else 0.0 ) - sums = { - f"{name}_s": round(sum(r["timing"][f"{name}_ms"] for r in self.records) / 1000, 3) - for name in _TIMING_SUMS - } + sums = {f"{name}_s": round(self.timing_ms[name] / 1000, 3) for name in _TIMING_SUMS} return { "retries": dict(self.retries), "reruns": self.reruns, From 3be9261aeb79105fc147f8420d0b091526c326e2 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:21:06 +0100 Subject: [PATCH 25/77] refactor(benchmarks): drop dead code; the truncation marker names its cap Round 2 B14. Deleted contains_own_key (no caller), ToolOutcome.sha256 and wall_ms (the loop measures and hashes for itself), RESULT_CAP_BYTES and clamp_input_bound (inlined as min). run.py imports _HOSTED_REQUIRED_FIELDS from the model matrix and _client_versions from the worker instead of copying them. TRUNCATION_MARKER is built from the cap in force, so a 10-byte cap no longer claims 100000 (the loop test now pins the text). Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/bridge.py | 26 +++++++------------------ benchmarks/agentic/ledger.py | 6 +----- benchmarks/agentic/protocol.py | 4 ---- benchmarks/agentic/run.py | 23 ++++++++-------------- benchmarks/agentic/worker.py | 9 ++++++--- tests/benchmarks/test_agentic_bridge.py | 7 +++---- tests/benchmarks/test_agentic_ledger.py | 6 ------ tests/benchmarks/test_agentic_loop.py | 6 +++--- 8 files changed, 28 insertions(+), 59 deletions(-) diff --git a/benchmarks/agentic/bridge.py b/benchmarks/agentic/bridge.py index f43bdb97..f36bf2d2 100644 --- a/benchmarks/agentic/bridge.py +++ b/benchmarks/agentic/bridge.py @@ -7,11 +7,9 @@ from __future__ import annotations -import hashlib import json import os import sys -import time from collections.abc import AsyncIterator, Mapping from contextlib import asynccontextmanager from dataclasses import dataclass @@ -33,8 +31,7 @@ cell_failure_from, ) -RESULT_CAP_BYTES = 100_000 -TRUNCATION_MARKER = "\n[benchmark harness: tool result truncated at 100000 UTF-8 bytes]" +TRUNCATION_MARKER = "\n[benchmark harness: tool result truncated at {limit} UTF-8 bytes]" _TRANSPORTS: dict[str, Literal["stdio", "none"]] = {"mcp-stdio": "stdio", "none": "none"} @@ -52,9 +49,7 @@ class SystemSpec: @dataclass(frozen=True) class ToolOutcome: text: str # full canonical text, before truncation - sha256: str # sha256 of `text` as UTF-8 is_error: bool - wall_ms: float class BridgeCrash(Exception): @@ -123,13 +118,14 @@ def canonical_text(result: CallToolResult) -> str: ) -def truncate_utf8(text: str, limit: int = RESULT_CAP_BYTES) -> tuple[str, bool]: - """Cut to the longest prefix whose UTF-8 fits ``limit``, plus the marker.""" +def truncate_utf8(text: str, limit: int) -> tuple[str, bool]: + """Cut to the longest prefix whose UTF-8 fits ``limit``, plus the marker naming the cap.""" data = text.encode("utf-8") if len(data) <= limit: return text, False # The prefix is valid UTF-8 except for a character the cut split; "ignore" drops it. - return data[:limit].decode("utf-8", errors="ignore") + TRUNCATION_MARKER, True + prefix = data[:limit].decode("utf-8", errors="ignore") + return prefix + TRUNCATION_MARKER.format(limit=limit), True class Bridge: @@ -149,24 +145,16 @@ def __init__( ] async def call(self, name: str, arguments: dict[str, Any]) -> ToolOutcome: - started = time.perf_counter() 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 - text, is_error = str(exc.message), True + return ToolOutcome(text=str(exc.message), is_error=True) except Exception as exc: # noqa: BLE001 - any other failure means the session is gone failure = cell_failure_from(exc, timeout_seconds=0.0, label=f"MCP tool {name}") raise BridgeCrash(str(failure)) from exc - else: - text, is_error = canonical_text(result), bool(result.is_error) - return ToolOutcome( - text=text, - sha256=hashlib.sha256(text.encode("utf-8")).hexdigest(), - is_error=is_error, - wall_ms=(time.perf_counter() - started) * 1000, - ) + return ToolOutcome(text=canonical_text(result), is_error=bool(result.is_error)) @asynccontextmanager diff --git a/benchmarks/agentic/ledger.py b/benchmarks/agentic/ledger.py index 3daa211a..d3a5a5d1 100644 --- a/benchmarks/agentic/ledger.py +++ b/benchmarks/agentic/ledger.py @@ -211,10 +211,6 @@ def bound_cost(price: ModelPrice, *, input_bound: int, output_bound: int) -> Dec return (input_bound * input_rate + output_bound * rates.output) / _MILLION -def clamp_input_bound(bound: int, max_input_tokens: int) -> int: - return min(bound, max_input_tokens) - - def booked_cost(outcome: Outcome, *, bound: Decimal, actual: Decimal | None) -> Decimal: if outcome == "ok": if actual is None: @@ -437,7 +433,7 @@ async def reserve( raise BenchmarkValidationError(f"no price snapshot entry for model {model_id!r}") family = self._families.get(model_id) if family is not None and family.max_input_tokens is not None: - input_bound = clamp_input_bound(input_bound, family.max_input_tokens) + input_bound = min(input_bound, family.max_input_tokens) # a larger request is refused 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 diff --git a/benchmarks/agentic/protocol.py b/benchmarks/agentic/protocol.py index 51d6f9c2..df8404b3 100644 --- a/benchmarks/agentic/protocol.py +++ b/benchmarks/agentic/protocol.py @@ -61,7 +61,3 @@ def assert_no_key_shaped(text: str, *, where: str) -> None: if match := KEY_SHAPED.search(text): # Names the place and the pattern, never the match. raise KeyLeakError(f"a key-shaped string ({match.lastgroup} pattern) was found in {where}") - - -def contains_own_key(text: str, own_key: str | None) -> bool: - return bool(own_key) and own_key in text diff --git a/benchmarks/agentic/run.py b/benchmarks/agentic/run.py index 515e18cd..fa4f0562 100644 --- a/benchmarks/agentic/run.py +++ b/benchmarks/agentic/run.py @@ -19,7 +19,6 @@ from dataclasses import dataclass, field, replace from datetime import UTC, date, datetime from decimal import Decimal -from importlib.metadata import version from pathlib import Path from typing import Any, Protocol @@ -40,8 +39,13 @@ 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.worker import MAX_RERUNS -from benchmarks.model_matrix import METHODOLOGY_TOKEN_LABEL, ModelFamily, load_model_matrix +from benchmarks.agentic.worker import MAX_RERUNS, _client_versions +from benchmarks.model_matrix import ( + _HOSTED_REQUIRED_FIELDS, + METHODOLOGY_TOKEN_LABEL, + ModelFamily, + load_model_matrix, +) from benchmarks.runner import ( BenchmarkCell, BenchmarkValidationError, @@ -68,13 +72,6 @@ def default_ledger_dir() -> Path: return Path(platformdirs.user_data_dir("mcp-python-docs-benchmarks")) / "ledger" -_CLIENT_PACKAGES = ("anthropic", "openai", "google-genai", "mcp") -_HOSTED_FIELDS = ( - "max_input_tokens", - "max_output_tokens", - "output_cap_includes_reasoning", - "framing_allowance_tokens", -) _TIMING_SUMS = ("grant_wait", "failed_attempt", "retry_wait") @@ -141,10 +138,6 @@ def _write(path: Path, data: dict[str, Any]) -> None: _write_json(path, data) -def _client_versions() -> dict[str, str]: - return {name: version(name) for name in _CLIENT_PACKAGES} - - class _HasId(Protocol): @property def id(self) -> str: @@ -389,7 +382,7 @@ def run_agentic( if family.provider in caps: # metered if family.model_id not in snapshot.models: raise BenchmarkValidationError(f"no price snapshot entry for {family.model_id!r}") - missing = [name for name in _HOSTED_FIELDS if getattr(family, name) is None] + 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): diff --git a/benchmarks/agentic/worker.py b/benchmarks/agentic/worker.py index 42b69a78..0e24eddd 100644 --- a/benchmarks/agentic/worker.py +++ b/benchmarks/agentic/worker.py @@ -201,12 +201,15 @@ def _system_info(system: SystemSpec, provider: str, bridge: Bridge | None) -> di "tools_converted_sha256": schemas_sha256(converted), "gemini_dropped": dropped, "index_sha256": _index_sha256() if system.id == "python-docs" else None, - "client_versions": { - name: version(name) for name in ("anthropic", "openai", "google-genai", "mcp") - }, + "client_versions": _client_versions(), } +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: if system.transport == "none": return None diff --git a/tests/benchmarks/test_agentic_bridge.py b/tests/benchmarks/test_agentic_bridge.py index 7832aa69..c890d6f5 100644 --- a/tests/benchmarks/test_agentic_bridge.py +++ b/tests/benchmarks/test_agentic_bridge.py @@ -2,7 +2,6 @@ from __future__ import annotations -import hashlib from pathlib import Path import pytest @@ -71,7 +70,9 @@ def test_canonical_text_joins_text_blocks_and_marks_other_blocks() -> None: def test_truncate_utf8_cuts_on_a_character_boundary_and_marks_it() -> None: text = "a" * 99_999 + "é" + "tail" # "é" is 2 bytes and straddles byte 100,000 - assert truncate_utf8(text, 100_000) == ("a" * 99_999 + TRUNCATION_MARKER, True) + marker = TRUNCATION_MARKER.format(limit=100_000) + assert truncate_utf8(text, 100_000) == ("a" * 99_999 + marker, True) + assert "truncated at 100000 UTF-8 bytes" in marker def test_truncate_utf8_leaves_a_result_at_the_limit_untouched() -> None: @@ -145,8 +146,6 @@ async def test_bridge_lists_the_real_server_tools_unfiltered(python_docs: System assert all("inputSchema" in t for t in bridge.tools_raw) outcome = await bridge.call("get_docs", {"slug": "library/json.html", "version": "3.13"}) assert outcome.is_error is False and "json module" in outcome.text - assert outcome.sha256 == hashlib.sha256(outcome.text.encode()).hexdigest() - assert outcome.wall_ms > 0 async def test_bridge_returns_an_unknown_tool_as_an_error_result(python_docs: SystemSpec) -> None: diff --git a/tests/benchmarks/test_agentic_ledger.py b/tests/benchmarks/test_agentic_ledger.py index 711d0a4a..e3a11a2c 100644 --- a/tests/benchmarks/test_agentic_ledger.py +++ b/tests/benchmarks/test_agentic_ledger.py @@ -24,7 +24,6 @@ actual_cost, booked_cost, bound_cost, - clamp_input_bound, load_price_snapshot, refuse_stale_snapshot, ) @@ -250,11 +249,6 @@ def test_bound_cost_uses_openai_cache_write_rate_and_uncached_rate_elsewhere() - assert bound_cost(anthropic, input_bound=1_000_000, output_bound=0) == D("2") -def test_input_bound_is_clamped_to_the_model_maximum() -> None: - assert clamp_input_bound(2_000_000, 1_048_576) == 1_048_576 - assert clamp_input_bound(10, 1_048_576) == 10 - - @pytest.mark.parametrize( "outcome,expected", [ diff --git a/tests/benchmarks/test_agentic_loop.py b/tests/benchmarks/test_agentic_loop.py index 6c06201d..60d23d6c 100644 --- a/tests/benchmarks/test_agentic_loop.py +++ b/tests/benchmarks/test_agentic_loop.py @@ -10,7 +10,7 @@ import pytest -from benchmarks.agentic.bridge import TRUNCATION_MARKER, BridgeCrash, ToolOutcome +from benchmarks.agentic.bridge import BridgeCrash, ToolOutcome from benchmarks.agentic.clients import ScriptedClient from benchmarks.agentic.ledger import ( Ledger, @@ -91,7 +91,7 @@ async def call(self, name: str, arguments: dict[str, Any]) -> ToolOutcome: text, is_error = ( (f"Unknown tool: {name}", True) if name == "no_such_tool" else (self.text, False) ) - return ToolOutcome(text, hashlib.sha256(text.encode()).hexdigest(), is_error, 1.0) + return ToolOutcome(text, is_error) class RecordingLedger: @@ -343,7 +343,7 @@ async def test_result_over_the_cap_is_truncated_and_the_loop_continues(harness: assert call["truncated"] is True and record["status"] == "succeeded" assert call["result"] == FAKE_TEXT # the full canonical text is kept sent = record["canonical_messages"][2]["content"][0]["content"] - assert sent == FAKE_TEXT[:10] + TRUNCATION_MARKER + assert sent == FAKE_TEXT[:10] + "\n[benchmark harness: tool result truncated at 10 UTF-8 bytes]" async def test_unknown_tool_call_is_returned_to_the_model_and_the_loop_continues( From 2dbaf730a010d86ddbaa56d577a752f9dbae193c Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:23:11 +0100 Subject: [PATCH 26/77] fix(benchmarks): an OpenAI response with status failed is a server error Round 2 C15. A Responses API 200 whose status is failed raises ProviderCallError("server"), so it is booked at twice its bound and retried rather than read as an empty answer. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/clients.py | 3 +++ tests/benchmarks/test_agentic_clients.py | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/benchmarks/agentic/clients.py b/benchmarks/agentic/clients.py index 047d4381..7de2455a 100644 --- a/benchmarks/agentic/clients.py +++ b/benchmarks/agentic/clients.py @@ -274,6 +274,9 @@ async def call(self, conv: Conversation) -> ModelTurn: raise ProviderCallError("timeout", str(exc)) from exc except openai.APIConnectionError as exc: raise ProviderCallError("connection", str(exc)) from exc + if response.status == "failed": # a 200 that carries a server-side failure + detail = response.error.message if response.error else "no error detail" + raise ProviderCallError("server", f"response failed: {detail}") calls, texts = [], [] for item in response.output: if item.type == "function_call": diff --git a/tests/benchmarks/test_agentic_clients.py b/tests/benchmarks/test_agentic_clients.py index 3bbddfc5..663f77a6 100644 --- a/tests/benchmarks/test_agentic_clients.py +++ b/tests/benchmarks/test_agentic_clients.py @@ -305,6 +305,15 @@ async def test_openai_stop_reason_is_normalized(status: str, details: Any, expec assert turn.stop_reason == expected +async def test_openai_failed_response_is_a_server_error() -> None: + body = _openai_response([], status="failed") + body["error"] = {"code": "server_error", "message": "the model failed"} + recorder = Recorder(_ok(body)) + with pytest.raises(ProviderCallError) as caught: + await _openai(recorder).call(_conv()) + assert caught.value.kind == "server" and "the model failed" in str(caught.value) + + async def test_openai_request_never_asks_for_extended_cache_retention() -> None: recorder = Recorder( _ok(_openai_response([OPENAI_CALL])), _ok(_openai_response([OPENAI_MESSAGE])) From 70ecaac9932e56113a9025d55d02ffae5f90d282 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:23:11 +0100 Subject: [PATCH 27/77] docs(benchmarks): the template's Ref.tools session note names the bridge Round 2 C17. The note now reads "the bridge opens a fresh MCP session per cell" instead of naming the deleted RefToolsAdapter. Co-Authored-By: Claude Opus 5.5 --- docs/benchmarks/competitor-manifest.template.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/benchmarks/competitor-manifest.template.yml b/docs/benchmarks/competitor-manifest.template.yml index 8ab899c5..eba09b21 100644 --- a/docs/benchmarks/competitor-manifest.template.yml +++ b/docs/benchmarks/competitor-manifest.template.yml @@ -150,7 +150,7 @@ competitors: conditions: - "Requires a maintainer API key and paid credits to run live (free tier: 200 one-time credits, ~1 credit per tool call)." - "Publishing comparative results needs a written-permission decision from Ref.tools at the live-authoring phase (T13)." - - "Each question must use a fresh MCP session (Ref.tools dedupes/trims within a session) -- satisfied by construction: the runner instantiates a fresh RefToolsAdapter per cell." + - "Each question must use a fresh MCP session (Ref.tools dedupes/trims within a session) -- satisfied by construction: the bridge opens a fresh MCP session per cell." # No competitor from the methodology's initial candidate matrix is excluded # in this TEMPLATE -- all four are built and included above (each still From ec354c5551101182cfd041ea0c1115f6783ca985 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:25:06 +0100 Subject: [PATCH 28/77] fix(benchmarks): the worker redacts every provider secret it holds Round 2 D18. protect_output now reads every set PROVIDER_API_KEY_ENV value, not only the first paid key: the redactor replaces each one (a secret split across two writes included), and ProtocolChannel.send refuses a frame holding any of them. A test passes two keys and a server secret with no key shape to a worker that prints all three; none reaches its log. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/worker.py | 45 +++++++++++++++------------ tests/benchmarks/test_agentic_host.py | 40 ++++++++++++++++++++++-- 2 files changed, 62 insertions(+), 23 deletions(-) diff --git a/benchmarks/agentic/worker.py b/benchmarks/agentic/worker.py index 0e24eddd..f173ec05 100644 --- a/benchmarks/agentic/worker.py +++ b/benchmarks/agentic/worker.py @@ -2,10 +2,10 @@ ``protect_output`` runs before anything else. It keeps the original stdout as the protocol channel and sends fds 1 and 2 through a redactor that replaces -the worker's own key, so ``print()``, ``sys.stderr``, ``os.write(2, ...)``, -tracebacks and the MCP servers' inherited stderr all pass it. Only -``ProtocolChannel.send`` writes the protocol fd, and it refuses a frame that -holds the own key. +every provider secret the worker holds (each set ``PROVIDER_API_KEY_ENV`` +value), so ``print()``, ``sys.stderr``, ``os.write(2, ...)``, tracebacks and +the MCP servers' inherited stderr all pass it. Only ``ProtocolChannel.send`` +writes the protocol fd, and it refuses a frame that holds any of them. """ from __future__ import annotations @@ -22,8 +22,9 @@ from importlib.metadata import version from typing import Any +from benchmarks.adapters.guard import PROVIDER_API_KEY_ENV from benchmarks.agentic.bridge import Bridge, SystemSpec, open_bridge, system_spec_from_raw -from benchmarks.agentic.clients import PAID_KEY_ENVS, make_client +from benchmarks.agentic.clients import make_client from benchmarks.agentic.ledger import Outcome from benchmarks.agentic.loop import Caps, TrajectoryDiscarded, run_trajectory from benchmarks.agentic.protocol import KeyLeakError, encode_frame, read_frame @@ -48,14 +49,19 @@ def _write_all(fd: int, data: bytes) -> None: data = data[os.write(fd, data) :] -def _redact(read_fd: int, sink_fd: int, own_key: str | None) -> None: - key = own_key.encode() if own_key else b"" - hold = max(len(key) - 1, 0) # a key split across two reads is still caught +def _secrets() -> tuple[bytes, ...]: + """Every provider secret set in this process's environment, longest first.""" + values = {os.environ.get(name, "") for name in PROVIDER_API_KEY_ENV.values()} + return tuple(sorted((v.encode() for v in values if v), key=len, reverse=True)) + + +def _redact(read_fd: int, sink_fd: int, secrets: tuple[bytes, ...]) -> None: + hold = max((len(s) for s in secrets), default=1) - 1 # a split secret is still caught pending = b"" while chunk := os.read(read_fd, 65536): pending += chunk - if key: - pending = pending.replace(key, _REDACTED) + for secret in secrets: + pending = pending.replace(secret, _REDACTED) out, pending = (pending[:-hold], pending[-hold:]) if hold else (pending, b"") with suppress(OSError): # the sink is gone; keep draining so no writer blocks _write_all(sink_fd, out) @@ -68,21 +74,21 @@ class ProtocolChannel: def __init__( self, protocol_fd: int, - own_key: str | None, + secrets: tuple[bytes, ...], pipe_write_fd: int, thread: threading.Thread, streams: tuple[io.TextIOWrapper, io.TextIOWrapper], ) -> None: self._fd = protocol_fd - self._own_key = own_key.encode() if own_key else None + self._secrets = secrets self._pipe_write_fd = pipe_write_fd self._thread = thread self._streams = streams def send(self, message: dict[str, Any]) -> None: - """Write one frame; refuse a frame that holds the own key.""" + """Write one frame; refuse a frame that holds any of the worker's secrets.""" frame = encode_frame(message) - if self._own_key and self._own_key in frame: + if any(secret in frame for secret in self._secrets): raise KeyLeakError("own key found in output") _write_all(self._fd, frame) @@ -111,19 +117,20 @@ def _text_stream(fd: int) -> io.TextIOWrapper: ) -def protect_output(own_key: str | None) -> ProtocolChannel: +def protect_output() -> ProtocolChannel: # shortcut: fd redirection is POSIX only; the harness runs on macOS and Linux sys.stdout.flush() sys.stderr.flush() protocol_fd = os.dup(1) sink_fd = os.dup(2) + secrets = _secrets() read_fd, write_fd = os.pipe() os.dup2(write_fd, 1) os.dup2(write_fd, 2) - thread = threading.Thread(target=_redact, args=(read_fd, sink_fd, own_key), daemon=True) + thread = threading.Thread(target=_redact, args=(read_fd, sink_fd, secrets), daemon=True) thread.start() sys.stdout, sys.stderr = streams = (_text_stream(1), _text_stream(2)) - return ProtocolChannel(protocol_fd, own_key, write_fd, thread, streams) + return ProtocolChannel(protocol_fd, secrets, write_fd, thread, streams) class _HostLedger: @@ -323,9 +330,7 @@ async def _serve(channel: ProtocolChannel) -> int: def main_worker() -> int: """``python -m benchmarks agentic-worker``: protect output first, then run the job.""" - # A worker holds at most one paid key (make_client refuses a second): that one is its own. - own_key = next((os.environ[name] for name in PAID_KEY_ENVS if os.environ.get(name)), None) - channel = protect_output(own_key) + channel = protect_output() try: return asyncio.run(_serve(channel)) finally: diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 50ded828..b3c9fac4 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -216,8 +216,10 @@ def test_random_base64_is_not_key_shaped() -> None: def _run_python(code: str) -> subprocess.CompletedProcess[bytes]: + """Run ``code`` as a worker would, holding KEY as its Anthropic key.""" + env = {**os.environ, "ANTHROPIC_API_KEY": KEY} return subprocess.run( - [sys.executable, "-c", code], cwd=REPO_ROOT, capture_output=True, timeout=60 + [sys.executable, "-c", code], cwd=REPO_ROOT, capture_output=True, timeout=60, env=env ) @@ -226,7 +228,7 @@ def test_protect_output_redacts_the_own_key_on_every_stream() -> None: "import os, sys\n" "from benchmarks.agentic.worker import protect_output\n" f"KEY = {KEY!r}\n" - "ch = protect_output(KEY)\n" + "ch = protect_output()\n" "print(KEY)\n" "sys.stderr.write(KEY + '\\n')\n" "os.write(2, KEY[:10].encode())\n" @@ -245,7 +247,7 @@ def test_protocol_channel_refuses_a_frame_holding_the_own_key() -> None: "from benchmarks.agentic.protocol import KeyLeakError\n" "from benchmarks.agentic.worker import protect_output\n" f"KEY = {KEY!r}\n" - "ch = protect_output(KEY)\n" + "ch = protect_output()\n" "try:\n" " ch.send({'type': 'trajectory', 'answer': 'x' + KEY})\n" "except KeyLeakError:\n" @@ -279,6 +281,38 @@ async def test_host_logs_and_artifacts_never_hold_a_workers_key(host: Host, tmp_ assert [m["type"] for m in host.messages()][-1] == "done" +async def test_a_worker_redacts_every_provider_secret_it_holds( + host: Host, tmp_path: Path +) -> None: + # Two keys plus a secret that has no key shape (a competitor's server key). + secrets = { + "ANTHROPIC_API_KEY": KEY, + "OPENAI_API_KEY": "openai-synthetic-secret-" + "o" * 30, + "REF_API_KEY": "plain-server-secret-77", + } + + class SecretsLauncher(KeyedLauncher): + def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: + argv, env = super().command(job) + return argv, {**env, **secrets} + + code = ( + "import os, sys\n" + "from benchmarks.agentic import worker\n" + "real = worker.run_worker\n" + "async def leaky(channel, reader):\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" + "worker.run_worker = leaky\n" + "sys.exit(worker.main_worker())\n" + ) + await host.run([_job(tmp_path, [ANSWER])], launcher=SecretsLauncher(code)) + logs = "".join(p.read_text() for p in (tmp_path / "logs").iterdir()) + assert not [name for name, value in secrets.items() if value in logs] + assert logs.count("[redacted]") == 3 + + async def test_worker_runs_its_job_over_the_channel_and_reports_done( host: Host, tmp_path: Path ) -> None: From 28ed21a2b9e31ca05bba900c24df185e413ad157 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:26:34 +0100 Subject: [PATCH 29/77] fix(benchmarks): a worker silent past its deadline is a lost worker Round 2 D19. The host reads each worker frame under asyncio.timeout(trajectory_s + model_call_timeout_s), which covers one model call, a trajectory's remaining tool calls and a 120 s backoff. On expiry the worker is killed and handled as lost: its unit is booked at twice its bound and its trajectories are not_run. A worker that writes 8 bytes and sleeps no longer holds the run. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/host.py | 21 ++++++++++++++++++--- tests/benchmarks/test_agentic_host.py | 21 ++++++++++++++++++++- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index 8b4b4bee..26e83073 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -76,6 +76,19 @@ def refuse_host_keys(environ: Mapping[str, str]) -> None: ) +async def _read( + reader: asyncio.StreamReader, caps: Caps, max_frame_bytes: int +) -> dict[str, Any] | None: + """The next frame, or TimeoutError once the worker has been silent too long. + + Between two frames a worker runs at most one model call (model_call_timeout_s) or the + rest of a trajectory's tool calls (trajectory_s), plus a backoff of at most 120 s, which + model_call_timeout_s (300 s or more) covers. + """ + async with asyncio.timeout(caps.trajectory_s + caps.model_call_timeout_s): + return await read_frame(reader, limit=max_frame_bytes) + + async def _supervise( job: WorkerJob, *, @@ -114,7 +127,7 @@ async def _supervise( } proc.stdin.write(encode_frame(job_frame)) await proc.stdin.drain() - while (message := await read_frame(proc.stdout, limit=max_frame_bytes)) is not None: + while (message := await _read(proc.stdout, job.caps, max_frame_bytes)) is not None: where = f"a frame from worker {job.job_id}" assert_no_key_shaped(json.dumps(message, ensure_ascii=False), where=where) kind = message.get("type") @@ -166,8 +179,10 @@ async def _supervise( if reply is not None: proc.stdin.write(encode_frame(reply)) await proc.stdin.drain() - except (BrokenPipeError, ConnectionResetError): - pass # the worker died; handled as a lost worker below + except (BrokenPipeError, ConnectionResetError, TimeoutError): + pass # the worker died or stalled; handled as a lost worker below + if proc.returncode is None: + proc.kill() await proc.wait() finally: if proc.returncode is None: diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index b3c9fac4..6e586d4e 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -10,6 +10,7 @@ import subprocess import sys import time +from dataclasses import replace from decimal import Decimal from pathlib import Path from typing import Any @@ -21,7 +22,7 @@ from benchmarks.agentic.clients import PAID_KEY_ENVS 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 +from benchmarks.agentic.loop import HOSTED_CAPS, Caps from benchmarks.agentic.protocol import FrameTooLarge, KeyLeakError, assert_no_key_shaped from benchmarks.model_matrix import ModelFamily, load_model_matrix, model_family_from_raw from benchmarks.runner import BenchmarkValidationError @@ -424,6 +425,24 @@ def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: assert [m["type"] for m in host.messages("normal")][-1] == "done" +async def test_a_worker_that_stalls_mid_frame_is_a_lost_worker( + host: Host, tmp_path: Path +) -> None: + stalled = ( + "import sys, time\n" + "sys.stdout.buffer.write((100).to_bytes(8, 'big'))\n" + "sys.stdout.buffer.flush()\n" + "time.sleep(30)\n" + ) + job = replace( + _job(tmp_path, [ANSWER]), caps=Caps(trajectory_s=0.2, model_call_timeout_s=0.3) + ) + started = time.monotonic() + await host.run([job], launcher=KeyedLauncher(stalled, key="")) + assert time.monotonic() - started < 10 # the host's read deadline, not the 30 s sleep + assert {(m["type"], m["reason"]) for m in host.messages()} == {("not_run", "worker_lost")} + + async def test_host_aborts_the_run_when_a_worker_frame_holds_a_key_shaped_string( host: Host, tmp_path: Path ) -> None: From 7902cd4f814f0b8029415b9d8b75f2924ac7821f Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:27:27 +0100 Subject: [PATCH 30/77] fix(benchmarks): redact a key shape in a worker log before stopping the run Round 2 D20. When the host's scan finds a key shape in a worker's stderr log, it first rewrites that log with every match replaced by [redacted], then raises KeyLeakError naming the log and the pattern, so the leaked bytes never stay on disk. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/host.py | 9 +++++++-- benchmarks/agentic/protocol.py | 9 +++++++++ tests/benchmarks/test_agentic_host.py | 11 +++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index 26e83073..9472362f 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -28,6 +28,7 @@ assert_no_key_shaped, encode_frame, read_frame, + redact_key_shaped, ) from benchmarks.agentic.types import Buckets from benchmarks.model_matrix import ModelFamily @@ -190,8 +191,12 @@ async def _supervise( await proc.wait() if in_flight is not None: # may have been billed: booked at twice its bound await ledger.settle(in_flight, outcome="worker_lost", buckets=None) - log_text = log_path.read_text(encoding="utf-8", errors="replace") - assert_no_key_shaped(log_text, where=str(log_path)) + redacted, pattern = redact_key_shaped(log_path.read_bytes()) + if pattern: + log_path.write_bytes(redacted) # the leaked bytes never stay on disk + raise KeyLeakError( + f"a key-shaped string ({pattern} pattern) was found in {log_path}; redacted there" + ) if not done: for item in job.trajectories: if (item["corpus_id"], item["repeat"]) not in reported: diff --git a/benchmarks/agentic/protocol.py b/benchmarks/agentic/protocol.py index df8404b3..634ac7ac 100644 --- a/benchmarks/agentic/protocol.py +++ b/benchmarks/agentic/protocol.py @@ -26,6 +26,7 @@ "google": _START + r"AIza[0-9A-Za-z_-]{35}" + _END, } KEY_SHAPED = re.compile("|".join(f"(?P<{name}>{p})" for name, p in KEY_PATTERNS.items())) +_KEY_SHAPED_BYTES = re.compile(KEY_SHAPED.pattern.encode()) class KeyLeakError(BenchmarkValidationError): @@ -57,6 +58,14 @@ async def read_frame( return json.loads(body) +def redact_key_shaped(data: bytes) -> tuple[bytes, str | None]: + """``data`` with every key shape replaced by ``[redacted]``, and the first pattern's name.""" + match = _KEY_SHAPED_BYTES.search(data) + if match is None: + return data, None + return _KEY_SHAPED_BYTES.sub(b"[redacted]", data), match.lastgroup + + def assert_no_key_shaped(text: str, *, where: str) -> None: if match := KEY_SHAPED.search(text): # Names the place and the pattern, never the match. diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 6e586d4e..68356a53 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -443,6 +443,17 @@ async def test_a_worker_that_stalls_mid_frame_is_a_lost_worker( assert {(m["type"], m["reason"]) for m in host.messages()} == {("not_run", "worker_lost")} +async def test_a_key_shape_in_a_worker_log_is_redacted_before_the_run_stops( + host: Host, tmp_path: Path +) -> None: + leaked = "sk-ant-api03-" + "z" * 90 + noisy = f"import sys\nsys.stderr.write('debug: token={leaked}\\n')\n" + with pytest.raises(KeyLeakError, match="anthropic"): + await host.run([_job(tmp_path, [ANSWER])], launcher=KeyedLauncher(noisy, key="")) + (log,) = (tmp_path / "logs").iterdir() + assert log.read_text() == "debug: token=[redacted]\n" + + async def test_host_aborts_the_run_when_a_worker_frame_holds_a_key_shaped_string( host: Host, tmp_path: Path ) -> None: From 920f01329be687b4701066d0708b4d3c0298e847 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:29:13 +0100 Subject: [PATCH 31/77] fix(benchmarks): the agentic host refuses every provider key name Round 2 D21. refuse_host_keys checks every PROVIDER_API_KEY_ENV name, REF_API_KEY and CONTEXT7_API_KEY included. Only agentic-run calls it: the fixed-flow run command still counts tokens with ANTHROPIC_API_KEY on the host. The agentic test fixtures clear every key name. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/host.py | 6 ++++-- tests/benchmarks/test_agentic_host.py | 9 ++++++++- tests/benchmarks/test_agentic_run.py | 4 ++-- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index 9472362f..a6729971 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -17,8 +17,8 @@ from pathlib import Path from typing import Any, Protocol +from benchmarks.adapters.guard import PROVIDER_API_KEY_ENV from benchmarks.agentic.bridge import SystemSpec -from benchmarks.agentic.clients import PAID_KEY_ENVS from benchmarks.agentic.ledger import LedgerService from benchmarks.agentic.loop import Caps from benchmarks.agentic.protocol import ( @@ -69,7 +69,9 @@ def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: def refuse_host_keys(environ: Mapping[str, str]) -> None: - held = [name for name in PAID_KEY_ENVS if environ.get(name)] + # Every key name, competitors included. Only agentic-run calls this: the fixed-flow + # `run` command still counts tokens with ANTHROPIC_API_KEY on the host. + held = sorted(name for name in set(PROVIDER_API_KEY_ENV.values()) if environ.get(name)) if held: raise BenchmarkValidationError( f"the host must never hold a provider key, but {', '.join(held)} is set: " diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 68356a53..87af71f6 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -18,6 +18,7 @@ import pytest import yaml +from benchmarks.adapters.guard import PROVIDER_API_KEY_ENV from benchmarks.agentic.bridge import system_spec_from_raw from benchmarks.agentic.clients import PAID_KEY_ENVS from benchmarks.agentic.host import LocalLauncher, WorkerJob, refuse_host_keys, run_jobs @@ -132,7 +133,7 @@ async def run(self, jobs: list[WorkerJob], launcher: Any = None, **kwargs: Any) @pytest.fixture def host(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): - for name in PAID_KEY_ENVS: + for name in PROVIDER_API_KEY_ENV.values(): monkeypatch.delenv(name, raising=False) h = Host(tmp_path) yield h @@ -160,6 +161,12 @@ def test_host_refuses_to_start_with_a_provider_key_in_its_environment() -> None: refuse_host_keys({"PATH": "/bin", "OPENAI_API_KEY": ""}) # an empty variable holds no key +@pytest.mark.parametrize("name", ["REF_API_KEY", "CONTEXT7_API_KEY", "GOOGLE_API_KEY"]) +def test_host_refuses_every_provider_key_name(name: str) -> None: + with pytest.raises(BenchmarkValidationError, match=name): + refuse_host_keys({name: "x-not-a-key"}) + + def test_local_launcher_passes_no_provider_key_and_runs_only_scripted_models( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/tests/benchmarks/test_agentic_run.py b/tests/benchmarks/test_agentic_run.py index a9d55692..979e66b2 100644 --- a/tests/benchmarks/test_agentic_run.py +++ b/tests/benchmarks/test_agentic_run.py @@ -17,8 +17,8 @@ import yaml from benchmarks.__main__ import main +from benchmarks.adapters.guard import PROVIDER_API_KEY_ENV from benchmarks.agentic.bridge import load_systems -from benchmarks.agentic.clients import PAID_KEY_ENVS from benchmarks.agentic.host import LocalLauncher from benchmarks.agentic.loop import MAX_RETRIES, Caps from benchmarks.agentic.protocol import KEY_SHAPED, KeyLeakError @@ -55,7 +55,7 @@ @pytest.fixture(autouse=True) def _keyless(monkeypatch: pytest.MonkeyPatch) -> None: - for name in PAID_KEY_ENVS: + for name in PROVIDER_API_KEY_ENV.values(): monkeypatch.delenv(name, raising=False) From 09ad0ff51773bf7a4f293106e1cb02ab11aefe5d Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:30:40 +0100 Subject: [PATCH 32/77] fix(benchmarks): a provider key may hold only [A-Za-z0-9_.-] Round 2 D22. require_live_environment refuses a key with any other character (+, /, =, a quote, a percent escape), not only whitespace, control and non-ASCII characters, before any request could quote it. Co-Authored-By: Claude Opus 5.5 --- benchmarks/adapters/guard.py | 13 ++++++++----- tests/benchmarks/test_adapters.py | 13 +++++++++++++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/benchmarks/adapters/guard.py b/benchmarks/adapters/guard.py index 734efe36..dd693dac 100644 --- a/benchmarks/adapters/guard.py +++ b/benchmarks/adapters/guard.py @@ -23,6 +23,7 @@ from __future__ import annotations import os +import re from benchmarks.runner import BenchmarkCellFailure @@ -48,6 +49,8 @@ } _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_.-]+") class LiveProviderDisabledError(BenchmarkCellFailure): @@ -69,8 +72,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. - 3. That variable's raw value is ASCII, with no whitespace or - non-printable character (an HTTP client error would quote such a key). + 3. That variable's raw value uses only ``[A-Za-z0-9_.-]`` (an HTTP client error + would quote any other character). All conditions must hold. Passing this check does not mean a live call will be made -- see the module docstring. @@ -92,10 +95,10 @@ def require_live_environment(provider: str) -> None: f"live provider calls are disabled: missing required {key_env} for " f"provider {provider!r}" ) - if not raw_key.isascii() or any(char.isspace() or not char.isprintable() for char in raw_key): + if not _KEY_CHARACTERS.fullmatch(raw_key): raise MalformedApiKeyError( - f"live provider calls are disabled: {key_env} contains whitespace, control or " - "non-ASCII characters" + f"live provider calls are disabled: {key_env} holds a character outside " + "[A-Za-z0-9_.-]" ) diff --git a/tests/benchmarks/test_adapters.py b/tests/benchmarks/test_adapters.py index 23fb9a8f..9ab61a62 100644 --- a/tests/benchmarks/test_adapters.py +++ b/tests/benchmarks/test_adapters.py @@ -81,6 +81,19 @@ def test_require_live_environment_refuses_a_malformed_key_without_leaking_it( assert "日" not in str(exc_info.value) +@pytest.mark.parametrize("api_key", ["fake+key", "fake/key", "fake=key", 'fake"key', "fake%20key"]) +def test_require_live_environment_accepts_only_key_characters( + monkeypatch: pytest.MonkeyPatch, api_key: str +) -> None: + monkeypatch.setenv(LIVE_PROVIDERS_ENABLED_ENV, "1") + monkeypatch.setenv(PROVIDER_API_KEY_ENV["openai"], api_key) + + with pytest.raises(LiveProviderDisabledError): + require_live_environment("openai") + monkeypatch.setenv(PROVIDER_API_KEY_ENV["openai"], "sk-proj-AZaz09_.-") + require_live_environment("openai") # letters, digits, "_", "." and "-" pass + + def test_redact_api_keys_removes_a_key_that_contains_another_key( monkeypatch: pytest.MonkeyPatch, ) -> None: From 952430fc0cced873f0bb5541dc86d8761a55d317 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:31:38 +0100 Subject: [PATCH 33/77] fix(benchmarks): the worker imports the provider SDKs after protecting output Round 2 D23. The clients, loop and schemas modules, which load the anthropic, openai and google-genai SDKs, are imported inside _run_job, after main_worker has called protect_output, so anything an SDK prints at import passes the redactor. A test checks that importing the CLI and the worker module loads none of the three. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/worker.py | 16 ++++++++-------- tests/benchmarks/test_agentic_host.py | 12 ++++++++++++ 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/benchmarks/agentic/worker.py b/benchmarks/agentic/worker.py index f173ec05..40bf94f2 100644 --- a/benchmarks/agentic/worker.py +++ b/benchmarks/agentic/worker.py @@ -24,16 +24,8 @@ from benchmarks.adapters.guard import PROVIDER_API_KEY_ENV from benchmarks.agentic.bridge import Bridge, SystemSpec, open_bridge, system_spec_from_raw -from benchmarks.agentic.clients import make_client from benchmarks.agentic.ledger import Outcome -from benchmarks.agentic.loop import Caps, TrajectoryDiscarded, run_trajectory from benchmarks.agentic.protocol import KeyLeakError, encode_frame, read_frame -from benchmarks.agentic.schemas import ( - schemas_sha256, - to_anthropic, - to_gemini, - to_openai_responses, -) from benchmarks.agentic.types import Buckets, ToolSpec from benchmarks.model_matrix import model_family_from_raw from benchmarks.runner import BenchmarkValidationError @@ -179,6 +171,8 @@ 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 + if provider == "google": return to_gemini(tools) if provider == "openai": @@ -197,6 +191,8 @@ def _index_sha256() -> str | None: def _system_info(system: SystemSpec, provider: str, bridge: Bridge | None) -> dict[str, Any]: + from benchmarks.agentic.schemas import schemas_sha256 + tools_raw = bridge.tools_raw if bridge else [] converted, dropped = _converted(provider, bridge.tools if bridge else []) return { @@ -231,6 +227,10 @@ async def _close(stack: AsyncExitStack) -> None: async def _run_job(channel: ProtocolChannel, reader: asyncio.StreamReader) -> int: + # Imported here, after protect_output: the provider SDKs load behind the redactor. + from benchmarks.agentic.clients import make_client + from benchmarks.agentic.loop import Caps, TrajectoryDiscarded, run_trajectory + job = await read_frame(reader) if job is None or job.get("type") != "job": raise BenchmarkValidationError("the host sent no job") diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 87af71f6..2df23d19 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -250,6 +250,18 @@ def test_protect_output_redacts_the_own_key_on_every_stream() -> None: assert _frames(proc.stdout) == [{"type": "done"}] # the channel holds only the frame +def test_a_worker_loads_no_provider_sdk_before_protecting_its_output() -> None: + # The modules a worker imports before main_worker calls protect_output. + code = ( + "import sys\n" + "import benchmarks.__main__, benchmarks.agentic.worker\n" + "print(sorted(m for m in ('anthropic', 'openai', 'google.genai') if m in sys.modules))\n" + ) + proc = _run_python(code) + assert proc.returncode == 0, proc.stderr + assert proc.stdout.decode().strip() == "[]" + + def test_protocol_channel_refuses_a_frame_holding_the_own_key() -> None: code = ( "from benchmarks.agentic.protocol import KeyLeakError\n" From a8675da3064375bcc59698cc1103a06891bf3916 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:32:06 +0100 Subject: [PATCH 34/77] fix(benchmarks): fchmod the ledger lock file to 0o600 after opening it Round 2 D24. O_CREAT's mode applies only when the file is created, so a lock file left world-readable stayed so. The ledger now sets 0o600 on the open descriptor every time. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/ledger.py | 1 + tests/benchmarks/test_agentic_ledger.py | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/benchmarks/agentic/ledger.py b/benchmarks/agentic/ledger.py index d3a5a5d1..de01a832 100644 --- a/benchmarks/agentic/ledger.py +++ b/benchmarks/agentic/ledger.py @@ -246,6 +246,7 @@ 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) diff --git a/tests/benchmarks/test_agentic_ledger.py b/tests/benchmarks/test_agentic_ledger.py index e3a11a2c..2d2e8876 100644 --- a/tests/benchmarks/test_agentic_ledger.py +++ b/tests/benchmarks/test_agentic_ledger.py @@ -368,6 +368,14 @@ def test_the_lock_file_is_private_to_its_owner(tmp_path: Path) -> None: assert (tmp_path / ".lock").stat().st_mode & 0o077 == 0 +def test_an_existing_world_readable_lock_file_is_made_private(tmp_path: Path) -> None: + lock = tmp_path / ".lock" + lock.touch() + lock.chmod(0o644) + _open(tmp_path, anthropic="10").close() + assert lock.stat().st_mode & 0o777 == 0o600 + + def test_a_killed_ledger_holder_releases_the_lock_and_its_unit_is_booked_at_twice_its_bound( tmp_path: Path, ) -> None: From 9b12ea54e57e0aacdf0116ca235de64bcc2f3d1c Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:34:30 +0100 Subject: [PATCH 35/77] test(benchmarks): pin the no-usage chain from the loop to the ledger Round 2 E25. The bounds test now asserts that the call without usage is recorded as no_usage and that its settle is booked at 2 x 0.332335, and a service test asserts that settle(ok, buckets=None) writes a no_usage event at twice the bound. Recording ok in the loop, dropping the service's conversion, or booking it at zero each fails one of them. Co-Authored-By: Claude Opus 5.5 --- tests/benchmarks/test_agentic_ledger.py | 12 ++++++++++++ tests/benchmarks/test_agentic_loop.py | 4 ++++ 2 files changed, 16 insertions(+) diff --git a/tests/benchmarks/test_agentic_ledger.py b/tests/benchmarks/test_agentic_ledger.py index 2d2e8876..e1df9710 100644 --- a/tests/benchmarks/test_agentic_ledger.py +++ b/tests/benchmarks/test_agentic_ledger.py @@ -503,6 +503,18 @@ async def test_service_clamps_the_input_bound_to_the_family_maximum(tmp_path: Pa ledger.close() +async def test_service_books_an_ok_without_usage_as_no_usage(tmp_path: Path) -> None: + ledger, service = _service(tmp_path, anthropic="10", openai="10") + unit = await service.reserve( + provider="anthropic", model_id="a", input_bound=500, output_bound=500 + ) + assert unit is not None + await service.settle(unit, outcome="ok", buckets=None) + settle = _event(ledger, "settle", unit) + assert settle["outcome"] == "no_usage" and D(settle["booked"]) == 2 * D("0.001") + ledger.close() + + def test_committed_matrix_largest_single_call_bound_is_below_every_margin() -> None: matrix, snap = load_model_matrix(MODEL_MATRIX_PATH), load_price_snapshot(PRICE_SNAPSHOT_PATH) hosted = [f for f in matrix.model_families if f.arm == "hosted"] diff --git a/tests/benchmarks/test_agentic_loop.py b/tests/benchmarks/test_agentic_loop.py index 60d23d6c..363b74ae 100644 --- a/tests/benchmarks/test_agentic_loop.py +++ b/tests/benchmarks/test_agentic_loop.py @@ -262,6 +262,10 @@ async def test_reservations_carry_independently_computed_bounds(harness: Harness assert [r["output_bound"] for r in harness.recording.reserves] == [32_768] * 4 assert harness.reserve_bounds() == [D("0.33021"), D("0.332335"), D("0.332335"), D("0.33652")] # a fake that reserved a fixed 200_000 input tokens would book 0.82768 for call 0 and fail here + # The call without usage is recorded and booked as no_usage, at twice its bound. + assert _outcomes(record, 1) == ["server", "no_usage"] + third = harness.settles()[2] + assert third["outcome"] == "no_usage" and D(third["booked"]) == 2 * D("0.332335") async def test_ninth_model_call_is_a_cap_failure(harness: Harness) -> None: From b36cb6bac6145434fe14f848971de020fa8ca51d Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:35:41 +0100 Subject: [PATCH 36/77] fix(benchmarks): the host never reserves below the family's output cap Round 2 E26. The host reserves max(the worker's output_bound, the family's max_output_tokens), so a worker that sends 0 cannot shrink a unit's bound. The lost-worker test now sends the family cap (1024) and its expected bound follows. Its fake worker is a shared helper. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/host.py | 5 ++- tests/benchmarks/test_agentic_host.py | 56 ++++++++++++++++++++------- 2 files changed, 47 insertions(+), 14 deletions(-) diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index a6729971..6049b9dc 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -143,7 +143,10 @@ async def _supervise( provider=job.family.provider, model_id=job.family.model_id, input_bound=int(message["input_bound"]), - output_bound=int(message["output_bound"]), + # Never below the cap the family sends: a worker cannot shrink its bound. + output_bound=max( + int(message["output_bound"]), job.family.max_output_tokens or 0 + ), kind=str(message.get("kind", "model_call")), ) reply = ( diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 2df23d19..83107a77 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -407,10 +407,9 @@ async def test_a_frame_over_the_limit_is_a_harness_error(host: Host, tmp_path: P assert types == ["system_info"] # nothing for that trajectory reached on_message -async def test_host_settles_a_lost_workers_unit_at_twice_its_bound_and_frees_the_provider( - host: Host, tmp_path: Path -) -> None: - fake_worker = ( +def _fake_worker(*frames: dict[str, Any]) -> str: + """A worker that reads its job, sends ``frames`` (reading each reply), then exits 1.""" + return ( "import json, sys\n" "inp, out = sys.stdin.buffer, sys.stdout.buffer\n" "def read():\n" @@ -421,21 +420,42 @@ async def test_host_settles_a_lost_workers_unit_at_twice_its_bound_and_frees_the " out.write(len(body).to_bytes(8, 'big') + body)\n" " out.flush()\n" "read()\n" - "send({'type': 'reserve', 'provider': 'anthropic', 'model_id': 'scripted-1',\n" - " 'input_bound': 1000, 'output_bound': 1000, 'kind': 'model_call'})\n" - "read()\n" + f"for frame in {frames!r}:\n" + " send(frame)\n" + " read()\n" "sys.exit(1)\n" ) - class LostLauncher(LocalLauncher): - def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: - argv, env = super().command(job) - return ([sys.executable, "-c", fake_worker] if job.job_id == "lost" else argv), env +def _reserve_frame(output_bound: int) -> dict[str, Any]: + return { + "type": "reserve", + "provider": "anthropic", + "model_id": "scripted-1", + "input_bound": 1000, + "output_bound": output_bound, + "kind": "model_call", + } + + +class LostLauncher(LocalLauncher): + """Runs ``code`` for the job named "lost" and a real worker for every other job.""" + + def __init__(self, code: str) -> None: + self.code = code + + def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: + argv, env = super().command(job) + return ([sys.executable, "-c", self.code] if job.job_id == "lost" else argv), env + + +async def test_host_settles_a_lost_workers_unit_at_twice_its_bound_and_frees_the_provider( + host: Host, tmp_path: Path +) -> None: lost = _job(tmp_path, [ANSWER], job_id="lost") normal = _job(tmp_path, [ANSWER], count=1, job_id="normal") - await host.run([lost, normal], launcher=LostLauncher()) - first_bound = D("0.002") # (1000 + 1000) * $1 / 1M + await host.run([lost, normal], launcher=LostLauncher(_fake_worker(_reserve_frame(1024)))) + first_bound = D("0.002024") # (1000 + 1024) * $1 / 1M second_job_actual = D("0.0011") assert host.ledger.spent("anthropic") == 2 * first_bound + second_job_actual lost_job_messages = host.messages("lost") @@ -444,6 +464,16 @@ def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: assert [m["type"] for m in host.messages("normal")][-1] == "done" +async def test_host_never_reserves_less_than_the_familys_output_cap( + host: Host, tmp_path: Path +) -> None: + lost = _job(tmp_path, [ANSWER], job_id="lost") + await host.run([lost], launcher=LostLauncher(_fake_worker(_reserve_frame(0)))) + (reserve,) = [e for e in host.ledger.events("host-test") if e["event"] == "reserve"] + assert reserve["output_bound"] == 1024 # the family's max_output_tokens, not the worker's 0 + assert host.ledger.spent("anthropic") == 2 * D("0.002024") + + async def test_a_worker_that_stalls_mid_frame_is_a_lost_worker( host: Host, tmp_path: Path ) -> None: From 523fbc9cc3720c7d1a282893aa393bc5fbd9db69 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:36:09 +0100 Subject: [PATCH 37/77] fix(benchmarks): read an unquoted datetime in the price snapshot as a date Round 2 E27. YAML reads an unquoted expires_on such as 2026-12-31 00:00:00 as a datetime, which never equals a date and cannot be compared with today's date. _date now takes its date part. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/ledger.py | 2 ++ tests/benchmarks/test_agentic_ledger.py | 12 ++++++++++++ 2 files changed, 14 insertions(+) diff --git a/benchmarks/agentic/ledger.py b/benchmarks/agentic/ledger.py index de01a832..67b95f65 100644 --- a/benchmarks/agentic/ledger.py +++ b/benchmarks/agentic/ledger.py @@ -105,6 +105,8 @@ def load_price_snapshot(path: Path) -> PriceSnapshot: def _date(value: Any, field: str) -> date | None: + if isinstance(value, datetime): # YAML reads an unquoted "2026-12-31 00:00:00" this way + return value.date() if value is None or isinstance(value, date): return value try: diff --git a/tests/benchmarks/test_agentic_ledger.py b/tests/benchmarks/test_agentic_ledger.py index e1df9710..f64d4b50 100644 --- a/tests/benchmarks/test_agentic_ledger.py +++ b/tests/benchmarks/test_agentic_ledger.py @@ -180,6 +180,18 @@ def test_stale_snapshot_is_refused_from_its_expiry_day() -> None: refuse_stale_snapshot(snap, today=date(2026, 12, 31)) +def test_an_unquoted_datetime_expiry_is_read_as_its_date(tmp_path: Path) -> None: + path = tmp_path / "prices.yml" + path.write_text( + "captured_on: 2026-10-31\nexpires_on: 2026-12-31 00:00:00\nmodels:\n" + _GOOD_MODEL, + encoding="utf-8", + ) + snap = load_price_snapshot(path) # YAML reads the unquoted value as a datetime + assert (snap.captured_on, snap.expires_on) == (date(2026, 10, 31), date(2026, 12, 31)) + with pytest.raises(BenchmarkValidationError, match="2026-12-31"): + refuse_stale_snapshot(snap, today=date(2026, 12, 31)) + + _GOOD_MODEL = ( " - model_id: m\n" " provider: anthropic\n" From b91511610a6d005eeeb644d699012d6a437d9793 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:37:11 +0100 Subject: [PATCH 38/77] fix(benchmarks): all-zero usage counts as no usage Round 2 E28. An ok whose buckets are all zero is booked as no_usage, at twice its bound, by the ledger service, and the loop records it as no_usage and prices the next call on the full request again, as after a call that reported no usage at all. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/ledger.py | 2 +- benchmarks/agentic/loop.py | 11 ++++++++--- benchmarks/agentic/types.py | 5 +++++ tests/benchmarks/test_agentic_ledger.py | 12 ++++++++++++ tests/benchmarks/test_agentic_loop.py | 10 ++++++++++ 5 files changed, 36 insertions(+), 4 deletions(-) diff --git a/benchmarks/agentic/ledger.py b/benchmarks/agentic/ledger.py index 67b95f65..069d8939 100644 --- a/benchmarks/agentic/ledger.py +++ b/benchmarks/agentic/ledger.py @@ -461,7 +461,7 @@ async def reserve( async def settle(self, unit_id: str, *, outcome: Outcome, buckets: Buckets | None) -> None: provider, price, input_bound = self._units.pop(unit_id) try: - if outcome == "ok" and buckets is None: + if outcome == "ok" and (buckets is None or buckets.is_empty): outcome = "no_usage" self._ledger.settle( unit_id, diff --git a/benchmarks/agentic/loop.py b/benchmarks/agentic/loop.py index 6488ed9f..3e205ee7 100644 --- a/benchmarks/agentic/loop.py +++ b/benchmarks/agentic/loop.py @@ -136,6 +136,11 @@ def canonical_messages(conv: Conversation) -> list[dict[str, Any]]: return messages +def _usage(turn: ModelTurn) -> Buckets | None: + """The turn's usage, or None when none, or only zeros, was reported.""" + return None if turn.buckets is None or turn.buckets.is_empty else turn.buckets + + def _ms(seconds: float) -> float: return round(seconds * 1000, 3) @@ -226,7 +231,7 @@ async def run(self) -> str: ) previous_count = len(self.conv.entries) turn = await self.model_call(bound) - previous = turn.buckets + previous = _usage(turn) # None: the next bound is the full request again if not turn.tool_calls: return turn.text if len(self.model_calls) >= self.caps.model_calls: @@ -286,9 +291,9 @@ async def model_call(self, bound: int) -> ModelTurn: attempt = {"wall_ms": _ms(wall), "wait_ms": _ms(waited), "unit_id": unit} entry["attempts"].append(attempt) if turn is not None: - outcome: Outcome = "ok" if turn.buckets is not None else "no_usage" + outcome: Outcome = "ok" if _usage(turn) else "no_usage" attempt |= {"outcome": outcome, "status": None} - await self.ledger.settle(unit, outcome=outcome, buckets=turn.buckets) + await self.ledger.settle(unit, outcome=outcome, buckets=_usage(turn)) entry |= { "raw_response": turn.raw_response, "raw_usage": turn.raw_usage, diff --git a/benchmarks/agentic/types.py b/benchmarks/agentic/types.py index ae84011c..fdbcd84d 100644 --- a/benchmarks/agentic/types.py +++ b/benchmarks/agentic/types.py @@ -29,6 +29,11 @@ class Buckets: def total_input(self) -> int: return self.uncached_input + self.cache_write_input + self.cached_input + @property + def is_empty(self) -> bool: + """All zero: no usage was really reported.""" + return self.total_input == 0 and self.output == 0 + @dataclass(frozen=True) class ToolCall: diff --git a/tests/benchmarks/test_agentic_ledger.py b/tests/benchmarks/test_agentic_ledger.py index f64d4b50..d7c165d3 100644 --- a/tests/benchmarks/test_agentic_ledger.py +++ b/tests/benchmarks/test_agentic_ledger.py @@ -515,6 +515,18 @@ async def test_service_clamps_the_input_bound_to_the_family_maximum(tmp_path: Pa ledger.close() +async def test_service_books_an_ok_with_all_zero_usage_as_no_usage(tmp_path: Path) -> None: + ledger, service = _service(tmp_path, anthropic="10", openai="10") + unit = await service.reserve( + provider="anthropic", model_id="a", input_bound=500, output_bound=500 + ) + assert unit is not None + await service.settle(unit, outcome="ok", buckets=Buckets(0, 0, 0, 0)) + settle = _event(ledger, "settle", unit) + assert settle["outcome"] == "no_usage" and D(settle["booked"]) == 2 * D("0.001") + ledger.close() + + async def test_service_books_an_ok_without_usage_as_no_usage(tmp_path: Path) -> None: ledger, service = _service(tmp_path, anthropic="10", openai="10") unit = await service.reserve( diff --git a/tests/benchmarks/test_agentic_loop.py b/tests/benchmarks/test_agentic_loop.py index 363b74ae..5beb49ec 100644 --- a/tests/benchmarks/test_agentic_loop.py +++ b/tests/benchmarks/test_agentic_loop.py @@ -268,6 +268,16 @@ async def test_reservations_carry_independently_computed_bounds(harness: Harness assert third["outcome"] == "no_usage" and D(third["booked"]) == 2 * D("0.332335") +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) + 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. + assert [r["input_bound"] for r in harness.recording.reserves] == [1_012, 3_024] + + async def test_ninth_model_call_is_a_cap_failure(harness: Harness) -> None: record = await harness.run([TOOL] * 9 + [ANSWER]) assert record["status"] == "failed" From b2a1df33f09fc5b0ab443c085b8aee7bac28c60e Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:37:47 +0100 Subject: [PATCH 39/77] fix(benchmarks): a discarded cell is not listed again as not_run Round 2 E29. When a worker is lost after discarding a trajectory, the host no longer reports that trajectory a second time as not_run with reason worker_lost: discarded counts as reported. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/host.py | 2 +- tests/benchmarks/test_agentic_host.py | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index 6049b9dc..b9419e08 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -177,7 +177,7 @@ async def _supervise( break else: await on_message(job, message) - if kind in ("trajectory", "not_run"): + if kind in ("trajectory", "not_run", "discarded"): # never listed twice reported.add((message["corpus_id"], message["repeat"])) done = done or kind == "done" if kind in ("trajectory", "discarded"): diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 83107a77..e2e3d4fd 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -464,6 +464,25 @@ async def test_host_settles_a_lost_workers_unit_at_twice_its_bound_and_frees_the assert [m["type"] for m in host.messages("normal")][-1] == "done" +async def test_a_discarded_cell_is_not_listed_again_when_its_worker_is_lost( + host: Host, tmp_path: Path +) -> None: + discarded = { + "type": "discarded", + "record": {"status": "discarded"}, + "corpus_id": "Q1", + "repeat": 1, + "reason": "retries_exhausted", + "attempt": 1, + } + lost = _job(tmp_path, [ANSWER], job_id="lost") + await host.run([lost], launcher=LostLauncher(_fake_worker(discarded))) + assert [(m["type"], m["corpus_id"], m["reason"]) for m in host.messages()] == [ + ("discarded", "Q1", "retries_exhausted"), + ("not_run", "Q2", "worker_lost"), + ] + + async def test_host_never_reserves_less_than_the_familys_output_cap( host: Host, tmp_path: Path ) -> None: From 3dd0e0ea9ac675c7f7c3206884554d4a4f980604 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:38:46 +0100 Subject: [PATCH 40/77] feat(benchmarks): the run summary counts input bounds exceeded per provider Round 2 E30. Each provider's ledger entry in run-summary.json reports input_bound_exceeded: this run's settles whose reported input passed the reserved input bound, which the pilot reads to check the one-token-per-byte assumption. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/run.py | 8 +++++++- tests/benchmarks/test_agentic_run.py | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/benchmarks/agentic/run.py b/benchmarks/agentic/run.py index fa4f0562..9f541030 100644 --- a/benchmarks/agentic/run.py +++ b/benchmarks/agentic/run.py @@ -507,7 +507,12 @@ def _write_outcome( snapshot: PriceSnapshot, ) -> None: """ledger-events.jsonl and run-summary.json, for a completed or an aborted run.""" - events = "".join(json.dumps(e, sort_keys=True) + "\n" for e in ledger.events(run_id)) + run_events = ledger.events(run_id) + events = "".join(json.dumps(e, sort_keys=True) + "\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") scored = collector.succeeded + collector.failed @@ -530,6 +535,7 @@ def _write_outcome( "spent_after": str(ledger.spent(provider)), "cap": str(caps[provider]), "stopped": ledger.stopped(provider), + "input_bound_exceeded": exceeded[provider], } for provider in caps }, diff --git a/tests/benchmarks/test_agentic_run.py b/tests/benchmarks/test_agentic_run.py index 979e66b2..caf97392 100644 --- a/tests/benchmarks/test_agentic_run.py +++ b/tests/benchmarks/test_agentic_run.py @@ -293,6 +293,25 @@ def test_run_summary_wall_time_includes_failed_attempts_backoff_and_grant_waits( assert sum(f["grant_wait_s"] for f in summary["families"].values()) > 0 +def test_run_summary_counts_input_bounds_exceeded_per_provider(tmp_path: Path) -> None: + # 8,000 reported input tokens exceed the first call's input bound (about 1,000), while + # the dollars stay under the bound, so there is no overrun stop. + big_input = {"text": "ok", "usage": {"input_tokens": 8000, "output_tokens": 0}} + matrix = _matrix_with(tmp_path, {"scripted-anthropic": [big_input]}) + config = _config( + tmp_path, + matrix_path=matrix, + models=("scripted-anthropic",), + systems=("no-docs",), + questions=("SYN-EX-001",), + repeats=1, + ) + summary = run_agentic(config) + assert summary["ledger"]["anthropic"]["input_bound_exceeded"] == 1 + assert summary["ledger"]["openai"]["input_bound_exceeded"] == 0 + assert summary["ledger"]["anthropic"]["stopped"] is None + + def test_latency_counts_successful_work_and_overhead_only(tmp_path: Path) -> None: script = [ {"error": {"kind": "rate_limited", "status": 429, "retry_after_s": 0.3}, "delay_s": 0.2}, From ac8da8f270df01f83f10b05a3ce4314f13442b95 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 00:40:22 +0100 Subject: [PATCH 41/77] fix(benchmarks): a hosted model call may run 300 s, as long as its trajectory Round 2 F31 (owner ruling on the ponytail risk note). The hosted per-call timeout goes from 120 s to 300 s, equal to trajectory_s, so a legitimate 32,768-token answer is not cut off, billed at twice its bound and retried. The local arm stays at 600 s. The run summary reports each family's timed-out model attempts. The plan's Caps block says 300 s; the methodology states no per-call timeout. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/loop.py | 2 +- benchmarks/agentic/run.py | 3 +++ .../2026-10-31-agentic-benchmark-harness.md | 2 +- tests/benchmarks/test_agentic_loop.py | 9 +++++++++ tests/benchmarks/test_agentic_run.py | 20 +++++++++++++++++++ 5 files changed, 34 insertions(+), 2 deletions(-) diff --git a/benchmarks/agentic/loop.py b/benchmarks/agentic/loop.py index 3e205ee7..89d88f31 100644 --- a/benchmarks/agentic/loop.py +++ b/benchmarks/agentic/loop.py @@ -43,7 +43,7 @@ class Caps: tool_call_s: float = 30.0 trajectory_s: float = 300.0 result_bytes: int = 100_000 - model_call_timeout_s: float = 120.0 + model_call_timeout_s: float = 300.0 # = trajectory_s: a long legitimate answer is never cut HOSTED_CAPS = Caps() diff --git a/benchmarks/agentic/run.py b/benchmarks/agentic/run.py index 9f541030..2c9b1d0b 100644 --- a/benchmarks/agentic/run.py +++ b/benchmarks/agentic/run.py @@ -162,6 +162,7 @@ class _FamilyStats: last_completed_at: str | None = None timing_ms: Counter[str] = field(default_factory=Counter) retries: Counter[str] = field(default_factory=Counter) + timeouts: int = 0 # every model attempt that hit its own timeout reruns: int = 0 answer_turns: int = 0 output_cap_stops: int = 0 @@ -174,6 +175,7 @@ def add(self, record: dict[str, Any]) -> None: for call in record["model_calls"]: for attempt in call["attempts"][:-1]: # every attempt but the last was retried self.retries[attempt["outcome"]] += 1 + self.timeouts += sum(a["outcome"] == "timeout" for a in call["attempts"]) if call["tool_calls_requested"] == 0: # an answer turn, whatever the outcome self.answer_turns += 1 self.output_cap_stops += call["stop_reason"] in OUTPUT_CAP_STOPS @@ -188,6 +190,7 @@ def summary(self) -> dict[str, Any]: sums = {f"{name}_s": round(self.timing_ms[name] / 1000, 3) for name in _TIMING_SUMS} return { "retries": dict(self.retries), + "timeouts": self.timeouts, "reruns": self.reruns, "answer_turns": self.answer_turns, "output_cap_stops": self.output_cap_stops, diff --git a/docs/plans/2026-10-31-agentic-benchmark-harness.md b/docs/plans/2026-10-31-agentic-benchmark-harness.md index 7b0bce3d..789b73f3 100644 --- a/docs/plans/2026-10-31-agentic-benchmark-harness.md +++ b/docs/plans/2026-10-31-agentic-benchmark-harness.md @@ -1305,7 +1305,7 @@ class Caps: tool_call_s: float = 30.0 trajectory_s: float = 300.0 result_bytes: int = 100_000 - model_call_timeout_s: float = 120.0 + model_call_timeout_s: float = 300.0 # = trajectory_s (owner ruling, #197 round 2) HOSTED_CAPS = Caps() AIR_GAPPED_CAPS = Caps(trajectory_s=900.0, model_call_timeout_s=600.0) MAX_RETRIES = 4 diff --git a/tests/benchmarks/test_agentic_loop.py b/tests/benchmarks/test_agentic_loop.py index 5beb49ec..b6e1badd 100644 --- a/tests/benchmarks/test_agentic_loop.py +++ b/tests/benchmarks/test_agentic_loop.py @@ -21,6 +21,8 @@ load_price_snapshot, ) from benchmarks.agentic.loop import ( + AIR_GAPPED_CAPS, + HOSTED_CAPS, Caps, TrajectoryDiscarded, backoff_s, @@ -478,6 +480,13 @@ def test_input_bounds() -> None: ) +def test_a_hosted_model_call_may_run_as_long_as_its_trajectory() -> None: + # Owner ruling (#197 round 2): a legitimate 32,768-token answer must not be cut off, + # billed and retried. The local arm keeps 600 s. + assert HOSTED_CAPS.model_call_timeout_s == HOSTED_CAPS.trajectory_s == 300.0 + assert AIR_GAPPED_CAPS.model_call_timeout_s == 600.0 + + def test_backoff() -> None: assert [backoff_s(r, None) for r in (1, 2, 3, 4)] == [2, 4, 8, 16] assert backoff_s(1, 7.0) == 7.0 and backoff_s(1, 121.0) is None diff --git a/tests/benchmarks/test_agentic_run.py b/tests/benchmarks/test_agentic_run.py index caf97392..45000b16 100644 --- a/tests/benchmarks/test_agentic_run.py +++ b/tests/benchmarks/test_agentic_run.py @@ -312,6 +312,26 @@ def test_run_summary_counts_input_bounds_exceeded_per_provider(tmp_path: Path) - assert summary["ledger"]["anthropic"]["stopped"] is None +def test_run_summary_counts_model_call_timeouts_per_family( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr("benchmarks.agentic.run.HOSTED_CAPS", Caps(model_call_timeout_s=0.1)) + usage = {"input_tokens": 1000, "output_tokens": 100} + script = [{"text": "slow", "delay_s": 0.5, "usage": usage}, {"text": "ok", "usage": usage}] + matrix = _matrix_with(tmp_path, {"scripted-anthropic": script}) + config = _config( + tmp_path, + matrix_path=matrix, + models=("scripted-anthropic",), + systems=("no-docs",), + questions=("SYN-EX-001",), + repeats=1, + ) + summary = run_agentic(config) + assert summary["families"]["scripted-anthropic"]["timeouts"] == 1 + assert summary["succeeded_cells"] == 1 + + def test_latency_counts_successful_work_and_overhead_only(tmp_path: Path) -> None: script = [ {"error": {"kind": "rate_limited", "status": 429, "retry_after_s": 0.3}, "delay_s": 0.2}, From e73fbd976cd6d528a0dce9d778d091d7a99771b6 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 01:06:22 +0100 Subject: [PATCH 42/77] fix(benchmarks): every worker log is scrubbed on every exit The log scan ran only after a clean supervisor exit. A frame that held a key raised first, and a cancelled supervisor never reached it, so the key stayed in that worker's stderr log. The scrub now runs in the finally, once the worker is dead; the KeyLeakError for a log hit is still raised only on the clean path. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/host.py | 6 ++++-- tests/benchmarks/test_agentic_host.py | 27 +++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index b9419e08..ba330ea8 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -194,11 +194,13 @@ async def _supervise( if proc.returncode is None: proc.kill() await proc.wait() + # On every exit, a raise or a cancel included: the leaked bytes never stay on disk. + redacted, pattern = redact_key_shaped(log_path.read_bytes()) + if pattern: + log_path.write_bytes(redacted) if in_flight is not None: # may have been billed: booked at twice its bound await ledger.settle(in_flight, outcome="worker_lost", buckets=None) - redacted, pattern = redact_key_shaped(log_path.read_bytes()) if pattern: - log_path.write_bytes(redacted) # the leaked bytes never stay on disk raise KeyLeakError( f"a key-shaped string ({pattern} pattern) was found in {log_path}; redacted there" ) diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index e2e3d4fd..b08a5c29 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -522,6 +522,33 @@ async def test_a_key_shape_in_a_worker_log_is_redacted_before_the_run_stops( assert log.read_text() == "debug: token=[redacted]\n" +async def test_every_worker_log_is_scrubbed_when_a_frame_leak_aborts_the_run( + host: Host, tmp_path: Path +) -> None: + # Both workers log the key. "leak" then sends it in a frame, which aborts the run; + # "quiet" is cancelled with the rest. Neither log may keep the key. + leaked = "sk-ant-api03-" + "z" * 90 + code = ( + "import json, sys, time\n" + "job = json.loads(sys.stdin.buffer.read(int.from_bytes(sys.stdin.buffer.read(8), 'big')))\n" + f"sys.stderr.write('debug: {leaked}\\n')\n" + "sys.stderr.flush()\n" + "if job['job_id'] == 'leak':\n" + " time.sleep(0.5)\n" + f" body = json.dumps({{'type': 'system_info', 'note': '{leaked}'}}).encode()\n" + " sys.stdout.buffer.write(len(body).to_bytes(8, 'big') + body)\n" + " sys.stdout.buffer.flush()\n" + "time.sleep(30)\n" + ) + jobs = [_job(tmp_path, [ANSWER], job_id=job_id) for job_id in ("leak", "quiet")] + with pytest.raises(KeyLeakError): + await host.run(jobs, launcher=KeyedLauncher(code, key="")) + logs = sorted((tmp_path / "logs").iterdir()) + assert [log.name for log in logs] == ["leak.stderr.log", "quiet.stderr.log"] + for log in logs: + assert log.read_text() == "debug: [redacted]\n" + + async def test_host_aborts_the_run_when_a_worker_frame_holds_a_key_shaped_string( host: Host, tmp_path: Path ) -> None: From 80d6a525c1d49f5dc82da8ef652dca001c542648 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 01:07:37 +0100 Subject: [PATCH 43/77] fix(benchmarks): the host lets a worker exit after its error frame The host killed a worker as soon as it read an error frame, so the worker's redactor never drained and the last stderr lines were lost. It now waits up to 5 s for the worker to exit before killing it. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/host.py | 3 +++ tests/benchmarks/test_agentic_host.py | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index ba330ea8..834cd4d5 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -13,6 +13,7 @@ import os import sys from collections.abc import Awaitable, Callable, Mapping, Sequence +from contextlib import suppress from dataclasses import asdict, dataclass from pathlib import Path from typing import Any, Protocol @@ -167,6 +168,8 @@ async def _supervise( reply = {"type": "ack"} elif kind == "error": reason = str(message.get("reason")) + 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:"): diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index b08a5c29..4b7a94ed 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -522,6 +522,27 @@ async def test_a_key_shape_in_a_worker_log_is_redacted_before_the_run_stops( assert log.read_text() == "debug: token=[redacted]\n" +async def test_a_line_logged_just_before_an_error_frame_reaches_the_log( + host: Host, tmp_path: Path +) -> None: + # Like the worker's redactor, this worker drains its log after the error frame. + code = ( + "import json, os, sys, time\n" + "sys.stdin.buffer.read(int.from_bytes(sys.stdin.buffer.read(8), 'big'))\n" + "log = os.fdopen(2, 'wb', buffering=1 << 16)\n" + "log.write(b'last line before the error\\n')\n" + "body = json.dumps({'type': 'error', 'reason': 'RuntimeError: boom'}).encode()\n" + "sys.stdout.buffer.write(len(body).to_bytes(8, 'big') + body)\n" + "sys.stdout.buffer.flush()\n" + "time.sleep(0.5)\n" + "log.flush()\n" + ) + await host.run([_job(tmp_path, [ANSWER])], launcher=KeyedLauncher(code, key="")) + (log,) = (tmp_path / "logs").iterdir() + assert log.read_text() == "last line before the error\n" + assert host.messages()[0] == {"type": "worker_error", "reason": "RuntimeError: boom"} + + async def test_every_worker_log_is_scrubbed_when_a_frame_leak_aborts_the_run( host: Host, tmp_path: Path ) -> None: From dea32e20eb0a91b0f2ccf0e9c6a52349ca5f56d9 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 01:09:03 +0100 Subject: [PATCH 44/77] fix(benchmarks): a discard that owes its rerun is still listed when its worker is lost E29 counted every discarded message as reported. A retries_exhausted discard still owes a rerun, and its last attempt sends its own not_run, so a lost worker left that cell out of the summary. Only a budget_stop discard is final now. The test covers both reasons. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/host.py | 6 +++++- tests/benchmarks/test_agentic_host.py | 16 ++++++++++++---- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index 834cd4d5..de86cb50 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -180,7 +180,11 @@ async def _supervise( break else: await on_message(job, message) - if kind in ("trajectory", "not_run", "discarded"): # never listed twice + # 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"])) done = done or kind == "done" if kind in ("trajectory", "discarded"): diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 4b7a94ed..2b7894ce 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -464,21 +464,29 @@ async def test_host_settles_a_lost_workers_unit_at_twice_its_bound_and_frees_the assert [m["type"] for m in host.messages("normal")][-1] == "done" -async def test_a_discarded_cell_is_not_listed_again_when_its_worker_is_lost( - host: Host, tmp_path: Path +@pytest.mark.parametrize( + "reason,q1_lost", + [ + ("retries_exhausted", True), # its rerun is still owed + ("budget_stop", False), # final: never listed twice + ], +) +async def test_only_a_final_discard_keeps_a_cell_off_the_worker_lost_list( + host: Host, tmp_path: Path, reason: str, q1_lost: bool ) -> None: discarded = { "type": "discarded", "record": {"status": "discarded"}, "corpus_id": "Q1", "repeat": 1, - "reason": "retries_exhausted", + "reason": reason, "attempt": 1, } lost = _job(tmp_path, [ANSWER], job_id="lost") await host.run([lost], launcher=LostLauncher(_fake_worker(discarded))) assert [(m["type"], m["corpus_id"], m["reason"]) for m in host.messages()] == [ - ("discarded", "Q1", "retries_exhausted"), + ("discarded", "Q1", reason), + *([("not_run", "Q1", "worker_lost")] if q1_lost else []), ("not_run", "Q2", "worker_lost"), ] From c89c79468e444ad1eaa41fba662eb9663adde7eb Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 01:09:37 +0100 Subject: [PATCH 45/77] refactor(benchmarks): read each worker frame with asyncio.wait_for inline _read wrapped one call; the deadline and its reason now sit at the loop. Covered by test_a_worker_that_stalls_mid_frame_is_a_lost_worker. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/host.py | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index de86cb50..615f4c1a 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -80,19 +80,6 @@ def refuse_host_keys(environ: Mapping[str, str]) -> None: ) -async def _read( - reader: asyncio.StreamReader, caps: Caps, max_frame_bytes: int -) -> dict[str, Any] | None: - """The next frame, or TimeoutError once the worker has been silent too long. - - Between two frames a worker runs at most one model call (model_call_timeout_s) or the - rest of a trajectory's tool calls (trajectory_s), plus a backoff of at most 120 s, which - model_call_timeout_s (300 s or more) covers. - """ - async with asyncio.timeout(caps.trajectory_s + caps.model_call_timeout_s): - return await read_frame(reader, limit=max_frame_bytes) - - async def _supervise( job: WorkerJob, *, @@ -131,7 +118,14 @@ async def _supervise( } proc.stdin.write(encode_frame(job_frame)) await proc.stdin.drain() - while (message := await _read(proc.stdout, job.caps, max_frame_bytes)) is not None: + # 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) kind = message.get("type") From 8ea038cd807b7618d1d99ce74f5f78175ec3209b Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 01:10:55 +0100 Subject: [PATCH 46/77] fix(benchmarks): every step after the ledger opens ends in the run's outcome files The overrun check, the acknowledgements and the spend print ran before the try that writes run-summary.json and ledger-events.jsonl. A run that stopped on a reopened overrun had already booked the recovery of an unsettled unit, yet wrote neither file. One try now covers every step after a successful open. spent_before is read right after the open, so it includes the recovery. _write_outcome becomes a nested function with no arguments (ponytail 5). Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/run.py | 140 +++++++++++++-------------- tests/benchmarks/test_agentic_run.py | 42 ++++++++ 2 files changed, 110 insertions(+), 72 deletions(-) diff --git a/benchmarks/agentic/run.py b/benchmarks/agentic/run.py index 2c9b1d0b..5b417586 100644 --- a/benchmarks/agentic/run.py +++ b/benchmarks/agentic/run.py @@ -32,7 +32,6 @@ PROVIDER_CAPS, Ledger, LedgerService, - PriceSnapshot, load_price_snapshot, refuse_stale_snapshot, ) @@ -459,7 +458,57 @@ def run_agentic( return summary ledger = Ledger.open(config.ledger_dir, run_id=run_id, caps=caps) - try: + spent_before = {provider: ledger.spent(provider) for provider in caps} # after any recovery + collector = _Collector(out, {q.id: q for q in questions}, families) + + def write_outcome() -> 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) + # 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") + scored = collector.succeeded + collector.failed + summary.setdefault("status", "completed") + summary.update( + { + "completed_at": _utc_now(), + "scored_cells": scored, + "correctness_denominator_cells": scored, + "succeeded_cells": collector.succeeded, + "failed_cells": collector.failed, + "failed_cells_included_in_correctness_denominator": True, + "competitors": sorted(collector.cells), + "discarded": collector.discarded, + "not_run": collector.not_run, + "worker_errors": collector.worker_errors, + "families": {fid: stats.summary() for fid, stats in collector.families.items()}, + "ledger": { + provider: { + "spent_before": str(spent_before[provider]), + "spent_after": str(ledger.spent(provider)), + "cap": str(caps[provider]), + "stopped": ledger.stopped(provider), + "input_bound_exceeded": exceeded[provider], + } + for provider in caps + }, + "price_snapshot": { + "captured_on": snapshot.captured_on.isoformat(), + "expires_on": ( + None if snapshot.expires_on is None else snapshot.expires_on.isoformat() + ), + }, + } + ) + _write(out / "run-summary.json", summary) + + try: # every step after the open, the overrun check included, ends in write_outcome for provider in config.acknowledge_overrun: ledger.acknowledge_overrun(provider) overrun = sorted({f.provider for f in families if ledger.stopped(f.provider) == "overrun"}) @@ -468,7 +517,6 @@ def run_agentic( f"{overrun} stopped on a bound overrun: correct the bound, record the overrun, " "then rerun with --acknowledge-overrun" ) - spent_before = {provider: ledger.spent(provider) for provider in caps} for provider, cap in caps.items(): # stderr: stdout carries the summary JSON print( f"ledger {config.ledger_dir}: {provider} " @@ -477,74 +525,22 @@ def run_agentic( ) 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}) - collector = _Collector(out, {q.id: q for q in questions}, families) - try: - asyncio.run( - run_jobs( - jobs, - launcher=launcher, - ledger=service, - on_message=collector.on_message, - log_dir=out / "logs", - cwd=_REPO_ROOT, - ) + asyncio.run( + 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 - finally: - _write_outcome(out, summary, collector, ledger, run_id, caps, spent_before, snapshot) - return summary + ) + except BaseException as exc: # still write what was spent and what ran + summary |= {"status": "aborted", "abort_reason": f"{type(exc).__name__}: {exc}"} + raise finally: - ledger.close() - - -def _write_outcome( - out: Path, - summary: dict[str, Any], - collector: _Collector, - ledger: Ledger, - run_id: str, - caps: Mapping[str, Decimal], - spent_before: Mapping[str, Decimal], - snapshot: PriceSnapshot, -) -> 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) - # 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") - scored = collector.succeeded + collector.failed - summary.setdefault("status", "completed") - summary |= { - "completed_at": _utc_now(), - "scored_cells": scored, - "correctness_denominator_cells": scored, - "succeeded_cells": collector.succeeded, - "failed_cells": collector.failed, - "failed_cells_included_in_correctness_denominator": True, - "competitors": sorted(collector.cells), - "discarded": collector.discarded, - "not_run": collector.not_run, - "worker_errors": collector.worker_errors, - "families": {fid: stats.summary() for fid, stats in collector.families.items()}, - "ledger": { - provider: { - "spent_before": str(spent_before[provider]), - "spent_after": str(ledger.spent(provider)), - "cap": str(caps[provider]), - "stopped": ledger.stopped(provider), - "input_bound_exceeded": exceeded[provider], - } - for provider in caps - }, - "price_snapshot": { - "captured_on": snapshot.captured_on.isoformat(), - "expires_on": None if snapshot.expires_on is None else snapshot.expires_on.isoformat(), - }, - } - _write(out / "run-summary.json", summary) + try: + write_outcome() + finally: + ledger.close() + return summary diff --git a/tests/benchmarks/test_agentic_run.py b/tests/benchmarks/test_agentic_run.py index 45000b16..b0c81563 100644 --- a/tests/benchmarks/test_agentic_run.py +++ b/tests/benchmarks/test_agentic_run.py @@ -20,6 +20,7 @@ from benchmarks.adapters.guard import PROVIDER_API_KEY_ENV from benchmarks.agentic.bridge import load_systems from benchmarks.agentic.host import LocalLauncher +from benchmarks.agentic.ledger import Ledger from benchmarks.agentic.loop import MAX_RETRIES, Caps from benchmarks.agentic.protocol import KEY_SHAPED, KeyLeakError from benchmarks.agentic.run import ( @@ -30,6 +31,7 @@ run_agentic, tool_model_key, ) +from benchmarks.agentic.types import Buckets from benchmarks.model_matrix import load_model_matrix from benchmarks.report import generate_report from benchmarks.runner import BenchmarkValidationError, _load_questions, _load_yaml_mapping @@ -468,6 +470,46 @@ def test_an_aborted_run_still_writes_its_summary_and_ledger_events(tmp_path: Pat assert (run / "ledger-events.jsonl").read_text().count('"event": "reserve"') == 1 +def test_a_run_that_stops_on_a_reopened_overrun_still_writes_its_outcome(tmp_path: Path) -> None: + # An earlier run left an Anthropic $1 unit settled at $2 and an OpenAI $0.50 unit unsettled. + earlier = Ledger.open(tmp_path / "ledger", run_id="earlier") + units = { + provider: earlier.reserve( + provider, + model_id="m", + kind="model_call", + bound=Decimal(bound), + input_bound=1, + output_bound=1, + ) + for provider, bound in (("anthropic", "1"), ("openai", "0.50")) + } + earlier.settle( + str(units["anthropic"]), outcome="ok", actual=Decimal("2"), buckets=Buckets(1, 0, 0, 1) + ) + earlier.close() + config = _config( + tmp_path, + models=("scripted-anthropic", "scripted-openai"), + systems=("no-docs",), + questions=("SYN-EX-001",), + repeats=1, + ) + with pytest.raises(BenchmarkValidationError, match="overrun"): + run_agentic(config) + run = tmp_path / "run" + summary = json.loads((run / "run-summary.json").read_text()) + assert summary["status"] == "aborted" and "overrun" in summary["abort_reason"] + events = (run / "ledger-events.jsonl").read_text().splitlines() + (recovery,) = [json.loads(line) for line in events] + assert (recovery["provider"], recovery["outcome"], recovery["booked"]) == ( + "openai", + "unsettled_at_load", + "1.00", + ) + assert summary["ledger"]["openai"]["spent_after"] == "1.00" + + def test_agentic_run_refuses_a_non_empty_out_dir(tmp_path: Path) -> None: (tmp_path / "run").mkdir() (tmp_path / "run" / "stale.json").write_text("{}") From 936c52afd3e413318a1572489b0730d949472f84 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 01:13:14 +0100 Subject: [PATCH 47/77] fix(benchmarks): a competitor key reaches only its own system A4 refused every provider key for every system, so Ref.tools and Context7 could never receive their own keys. Every provider key is still refused, the three paid ones always, except REF_API_KEY for ref-tools and CONTEXT7_API_KEY for context7. PAID_KEY_ENVS moves to guard.py, so the bridge needs nothing from clients. Co-Authored-By: Claude Opus 5.5 --- benchmarks/adapters/guard.py | 3 ++ benchmarks/agentic/bridge.py | 6 +++- benchmarks/agentic/clients.py | 8 ++++-- tests/benchmarks/test_agentic_bridge.py | 35 ++++++++++++++++++++++++ tests/benchmarks/test_agentic_clients.py | 3 +- tests/benchmarks/test_agentic_host.py | 3 +- 6 files changed, 50 insertions(+), 8 deletions(-) diff --git a/benchmarks/adapters/guard.py b/benchmarks/adapters/guard.py index dd693dac..9409e00a 100644 --- a/benchmarks/adapters/guard.py +++ b/benchmarks/adapters/guard.py @@ -48,6 +48,9 @@ "context7": "CONTEXT7_API_KEY", } +#: The model providers' keys: they pay for every call, and no docs system ever receives one. +PAID_KEY_ENVS = ("ANTHROPIC_API_KEY", "OPENAI_API_KEY", "GOOGLE_API_KEY") + _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_.-]+") diff --git a/benchmarks/agentic/bridge.py b/benchmarks/agentic/bridge.py index f36bf2d2..c99d6ffa 100644 --- a/benchmarks/agentic/bridge.py +++ b/benchmarks/agentic/bridge.py @@ -34,6 +34,8 @@ TRUNCATION_MARKER = "\n[benchmark harness: tool result truncated at {limit} UTF-8 bytes]" _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. +_OWN_KEYS = {"ref-tools": PROVIDER_API_KEY_ENV["ref"], "context7": PROVIDER_API_KEY_ENV["context7"]} @dataclass(frozen=True) @@ -92,7 +94,9 @@ def system_spec_from_raw(raw: Mapping[str, Any]) -> SystemSpec: ): raise BenchmarkValidationError(f"system {system_id!r} 'env' must map strings to strings") pass_env = _strings(raw.get("pass_env") or [], f"system {system_id!r} 'pass_env'") - keys = sorted(set(PROVIDER_API_KEY_ENV.values()) & (set(pass_env) | set(env))) + # Every provider key, the paid ones always, except a competitor's key for its own system. + refused = set(PROVIDER_API_KEY_ENV.values()) - {_OWN_KEYS.get(system_id)} + keys = sorted(refused & (set(pass_env) | set(env))) if keys: raise BenchmarkValidationError( f"system {system_id!r} must not receive provider keys {keys} through env or pass_env" diff --git a/benchmarks/agentic/clients.py b/benchmarks/agentic/clients.py index 7de2455a..3e39ca0b 100644 --- a/benchmarks/agentic/clients.py +++ b/benchmarks/agentic/clients.py @@ -25,7 +25,11 @@ from google.genai import errors as genai_errors from google.genai import types as genai_types -from benchmarks.adapters.guard import PROVIDER_API_KEY_ENV, require_live_environment +from benchmarks.adapters.guard import ( + 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.types import ( Conversation, @@ -40,8 +44,6 @@ from benchmarks.model_matrix import ModelFamily from benchmarks.runner import BenchmarkValidationError, _load_yaml_mapping -PAID_KEY_ENVS = ("ANTHROPIC_API_KEY", "OPENAI_API_KEY", "GOOGLE_API_KEY") - #: Live API -> the one provider whose key it may carry. _LIVE_APIS = { "anthropic-messages": "anthropic", diff --git a/tests/benchmarks/test_agentic_bridge.py b/tests/benchmarks/test_agentic_bridge.py index c890d6f5..0a0d16c7 100644 --- a/tests/benchmarks/test_agentic_bridge.py +++ b/tests/benchmarks/test_agentic_bridge.py @@ -7,6 +7,7 @@ import pytest from mcp.types import CallToolResult, ImageContent, TextContent +from benchmarks.adapters.guard import PAID_KEY_ENVS from benchmarks.agentic.bridge import ( TRUNCATION_MARKER, BridgeCrash, @@ -131,6 +132,40 @@ def test_a_system_never_receives_a_provider_key( assert _KEY_SHAPE not in str(caught.value) +@pytest.mark.parametrize("system_id", ["python-docs", "ref-tools", "context7"]) +@pytest.mark.parametrize("name", PAID_KEY_ENVS) +@pytest.mark.parametrize("through", ["env", "pass_env"]) +def test_a_paid_key_reaches_no_system(system_id: str, name: str, through: str) -> None: + from benchmarks.runner import BenchmarkValidationError + + raw = {"id": system_id, "adapter": "mcp-stdio", "command": ["a"], "env": {}, "pass_env": []} + raw[through] = {name: "x"} if through == "env" else [name] + with pytest.raises(BenchmarkValidationError, match=name): + system_spec_from_raw(raw) + + +@pytest.mark.parametrize( + "system_id,name,allowed", + [ + ("ref-tools", "REF_API_KEY", True), + ("python-docs", "REF_API_KEY", False), + ("context7", "CONTEXT7_API_KEY", True), + ("ref-tools", "CONTEXT7_API_KEY", False), + ], +) +def test_a_competitor_key_reaches_only_its_own_system( + system_id: str, name: str, allowed: bool +) -> None: + from benchmarks.runner import BenchmarkValidationError + + raw = {"id": system_id, "adapter": "mcp-stdio", "command": ["a"], "pass_env": [name]} + if allowed: + assert system_spec_from_raw(raw).pass_env == (name,) + else: + with pytest.raises(BenchmarkValidationError, match=name): + system_spec_from_raw(raw) + + async def test_bridge_lists_the_real_server_tools_unfiltered(python_docs: SystemSpec) -> None: async with open_bridge(python_docs) as bridge: assert {t.name for t in bridge.tools} == { diff --git a/tests/benchmarks/test_agentic_clients.py b/tests/benchmarks/test_agentic_clients.py index 663f77a6..621815e3 100644 --- a/tests/benchmarks/test_agentic_clients.py +++ b/tests/benchmarks/test_agentic_clients.py @@ -19,9 +19,8 @@ import pytest import yaml -from benchmarks.adapters.guard import PROVIDER_API_KEY_ENV, LiveProviderDisabledError +from benchmarks.adapters.guard import PAID_KEY_ENVS, PROVIDER_API_KEY_ENV, LiveProviderDisabledError from benchmarks.agentic.clients import ( - PAID_KEY_ENVS, AnthropicClient, GeminiClient, OpenAIResponsesClient, diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 2b7894ce..0c40edb4 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -18,9 +18,8 @@ import pytest import yaml -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 system_spec_from_raw -from benchmarks.agentic.clients import PAID_KEY_ENVS 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 1b376fff30c1a3d4b7e1b281f6b57f6690591595 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 01:13:41 +0100 Subject: [PATCH 48/77] docs(benchmarks): the Ref.tools session note states a round-2 requirement The note said the bridge opens a fresh MCP session per cell, "satisfied by construction". It does not: a worker opens one session per job and reuses it across cells. The note now states what round 2 must build, in the owner's words, and a test pins it. Co-Authored-By: Claude Opus 5.5 --- docs/benchmarks/competitor-manifest.template.yml | 2 +- tests/benchmarks/test_competitor_eligibility.py | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/docs/benchmarks/competitor-manifest.template.yml b/docs/benchmarks/competitor-manifest.template.yml index eba09b21..e8e77af7 100644 --- a/docs/benchmarks/competitor-manifest.template.yml +++ b/docs/benchmarks/competitor-manifest.template.yml @@ -150,7 +150,7 @@ competitors: conditions: - "Requires a maintainer API key and paid credits to run live (free tier: 200 one-time credits, ~1 credit per tool call)." - "Publishing comparative results needs a written-permission decision from Ref.tools at the live-authoring phase (T13)." - - "Each question must use a fresh MCP session (Ref.tools dedupes/trims within a session) -- satisfied by construction: the bridge opens a fresh MCP session per cell." + - "Each question must use a fresh MCP session (Ref.tools dedupes/trims within a session). Requirement for round 2: the bridge must open a fresh MCP session per cell for Ref.tools (today one session per job, reused across cells)." # No competitor from the methodology's initial candidate matrix is excluded # in this TEMPLATE -- all four are built and included above (each still diff --git a/tests/benchmarks/test_competitor_eligibility.py b/tests/benchmarks/test_competitor_eligibility.py index 993bda61..ff877edd 100644 --- a/tests/benchmarks/test_competitor_eligibility.py +++ b/tests/benchmarks/test_competitor_eligibility.py @@ -288,6 +288,17 @@ def test_exclusions_block_passes_validation_and_survives_snapshot_byte_for_byte( # --- The committed template manifest ---------------------------------------- +def test_template_states_the_ref_tools_session_requirement_for_round_2() -> None: + data = yaml.safe_load(_TEMPLATE_MANIFEST_PATH.read_text(encoding="utf-8")) + (ref,) = [c for c in data["competitors"] if c["id"] == "ref-tools"] + conditions = " ".join(ref["eligibility"]["conditions"]) + assert ( + "Requirement for round 2: the bridge must open a fresh MCP session per cell for " + "Ref.tools (today one session per job, reused across cells)." in conditions + ) + assert "satisfied by construction" not in conditions + + def test_template_manifest_parses_and_validates() -> None: data = yaml.safe_load(_TEMPLATE_MANIFEST_PATH.read_text(encoding="utf-8")) From 34a702ebe10aca08c191e753831d550e1b95e3e3 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 01:16:43 +0100 Subject: [PATCH 49/77] fix(benchmarks): no proxy or CA variable in a worker's env steers a call The three SDK clients trusted the environment, so HTTPS_PROXY could route a keyed call through another host and SSL_CERT_FILE could swap its CA. They now set trust_env=False. anthropic 1.15.0's DefaultAsyncHttpxClient still mounts env proxies when no transport is given, so the http, https and all proxy routes are also mounted direct. The test fakes every transport constructor, the Anthropic SDK's own included, so no request can leave the process. PR 4's egress proxy must be passed explicitly. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/clients.py | 10 +++++- tests/benchmarks/test_agentic_clients.py | 40 ++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/benchmarks/agentic/clients.py b/benchmarks/agentic/clients.py index 3e39ca0b..9a7be814 100644 --- a/benchmarks/agentic/clients.py +++ b/benchmarks/agentic/clients.py @@ -108,9 +108,17 @@ def _utf8_len(payload: Any) -> int: def _client_args(transport: Any | None) -> 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. """ - return {"follow_redirects": False, **({} if transport is None else {"transport": transport})} + # shortcut: no proxy from the env; PR 4's egress proxy must be passed explicitly (proxy=...) + return { + "follow_redirects": False, + "trust_env": False, + "mounts": {"http://": None, "https://": None, "all://": None}, + **({} if transport is None else {"transport": transport}), + } def anthropic_sdk( diff --git a/tests/benchmarks/test_agentic_clients.py b/tests/benchmarks/test_agentic_clients.py index 621815e3..d4ffd19c 100644 --- a/tests/benchmarks/test_agentic_clients.py +++ b/tests/benchmarks/test_agentic_clients.py @@ -14,6 +14,7 @@ from pathlib import Path from typing import Any +import anthropic import httpx import httpx2 import pytest @@ -796,3 +797,42 @@ async def test_a_base_url_variable_cannot_redirect_a_key( client = make_client(family, timeout_s=30, transport=recorder.transport()) await client.call(_conv()) assert [r.url.host for r in recorder.seen] == [host] + + +@pytest.mark.parametrize( + "family_id,host", + [ + ("claude-sonnet-5-5", "api.anthropic.com"), + ("gpt-6.1-sol", "api.openai.com"), + ("gemini-3.8-flash", "generativelanguage.googleapis.com"), + ], +) +async def test_a_proxy_variable_cannot_steer_a_call( + monkeypatch: pytest.MonkeyPatch, family_id: str, host: str +) -> None: + # No transport injected: the client builds its own, one per route, and the test sees + # which one carries the call. A proxy variable would mount a proxy route for https. + _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("HTTPS_PROXY", "http://proxy.invalid:3128") + 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) + + # Every place a transport is built, the Anthropic SDK's own included: none is real. + for module in (kind._client, anthropic._base_client): + monkeypatch.setattr(module, "AsyncHTTPTransport", transport) + await make_client(family, timeout_s=30).call(_conv()) + assert routes == [None] # the direct route, never a proxy + assert [r.url.host for r in recorder.seen] == [host] From dbc5d71a69324555f6b5d83edcf1a9d407d9f9e4 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 01:38:34 +0100 Subject: [PATCH 50/77] fix(benchmarks): a second abort cannot cut a worker's teardown short When two workers failed together, the abort of the second cancelled the first worker's supervisor while it awaited proc.wait() in its finally, so that worker's log kept its key and its open unit was never booked. Teardown (kill, wait, scrub, settle) now runs as its own task, shielded from the supervisor's cancellation; the supervisor waits for it to end, then re-raises the cancellation. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/host.py | 39 ++++++++++++++++-------- tests/benchmarks/test_agentic_host.py | 43 +++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 12 deletions(-) diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index 615f4c1a..d640de4a 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -80,6 +80,22 @@ def refuse_host_keys(environ: Mapping[str, str]) -> None: ) +async def _teardown( + proc: asyncio.subprocess.Process, log_path: Path, ledger: LedgerService, in_flight: str | None +) -> str | None: + """Kill the worker, scrub its log and book its open unit; the log's key pattern, if any.""" + if proc.returncode is None: + proc.kill() + await proc.wait() + # On every exit, a raise or a cancel included: the leaked bytes never stay on disk. + redacted, pattern = redact_key_shaped(log_path.read_bytes()) + if pattern: + log_path.write_bytes(redacted) + if in_flight is not None: # may have been billed: booked at twice its bound + await ledger.settle(in_flight, outcome="worker_lost", buckets=None) + return pattern + + async def _supervise( job: WorkerJob, *, @@ -188,19 +204,18 @@ async def _supervise( await proc.stdin.drain() except (BrokenPipeError, ConnectionResetError, TimeoutError): pass # the worker died or stalled; handled as a lost worker below - if proc.returncode is None: - proc.kill() - await proc.wait() finally: - if proc.returncode is None: - proc.kill() - await proc.wait() - # On every exit, a raise or a cancel included: the leaked bytes never stay on disk. - redacted, pattern = redact_key_shaped(log_path.read_bytes()) - if pattern: - log_path.write_bytes(redacted) - if in_flight is not None: # may have been billed: booked at twice its bound - await ledger.settle(in_flight, outcome="worker_lost", buckets=None) + # Runs to its end even when a second abort cancels this task meanwhile; then re-raise. + teardown = asyncio.ensure_future(_teardown(proc, 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" diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 0c40edb4..be416410 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -577,6 +577,49 @@ async def test_every_worker_log_is_scrubbed_when_a_frame_leak_aborts_the_run( assert log.read_text() == "debug: [redacted]\n" +async def test_a_teardown_cancelled_by_a_second_abort_still_scrubs_and_settles( + host: Host, tmp_path: Path +) -> None: + # A holds a unit, then leaks a key. A grandchild keeps A's pipes open, so A's teardown + # waits for it. B leaks next, and its abort cancels A mid-teardown. + leaked = "sk-ant-api03-" + "z" * 90 + marker = str(tmp_path / "a-leaks") + code = ( + "import json, subprocess, sys, time\n" + "from pathlib import Path\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" + "def send(message):\n" + " body = json.dumps(message).encode()\n" + " out.write(len(body).to_bytes(8, 'big') + body)\n" + " out.flush()\n" + "job = read()\n" + f"sys.stderr.write('debug: {leaked}\\n')\n" + "sys.stderr.flush()\n" + "if job['job_id'] == 'a':\n" + f" send({_reserve_frame(1024)!r})\n" + " read()\n" + " subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(3)'])\n" + f" Path({marker!r}).touch()\n" + "else:\n" + f" while not Path({marker!r}).exists():\n" + " time.sleep(0.05)\n" + " time.sleep(0.3)\n" + f"send({{'type': 'system_info', 'note': '{leaked}'}})\n" + "time.sleep(30)\n" + ) + jobs = [_job(tmp_path, [ANSWER], job_id=job_id) for job_id in ("a", "b")] + with pytest.raises(KeyLeakError): + await host.run(jobs, launcher=KeyedLauncher(code, key="")) + logs = sorted((tmp_path / "logs").iterdir()) + assert [log.read_text() for log in logs] == ["debug: [redacted]\n"] * 2 + 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")) + ] + + async def test_host_aborts_the_run_when_a_worker_frame_holds_a_key_shaped_string( host: Host, tmp_path: Path ) -> None: From b0d0b4435de1560b5397ad5af70ef43275a8dc91 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 01:39:48 +0100 Subject: [PATCH 51/77] fix(benchmarks): a provider key is never a literal in a system's env Round 3 let a competitor's own key through env as well as pass_env, so a manifest could carry REF_API_KEY's value in plain text and snapshot it. Every provider key name is now refused as an env key, for every system; a competitor's own key reaches its system only through pass_env. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/bridge.py | 8 +++++--- tests/benchmarks/test_agentic_run.py | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/benchmarks/agentic/bridge.py b/benchmarks/agentic/bridge.py index c99d6ffa..fc6d0b1e 100644 --- a/benchmarks/agentic/bridge.py +++ b/benchmarks/agentic/bridge.py @@ -94,9 +94,11 @@ def system_spec_from_raw(raw: Mapping[str, Any]) -> SystemSpec: ): raise BenchmarkValidationError(f"system {system_id!r} 'env' must map strings to strings") pass_env = _strings(raw.get("pass_env") or [], f"system {system_id!r} 'pass_env'") - # Every provider key, the paid ones always, except a competitor's key for its own system. - refused = set(PROVIDER_API_KEY_ENV.values()) - {_OWN_KEYS.get(system_id)} - keys = sorted(refused & (set(pass_env) | set(env))) + # Every provider key, the paid ones always. A competitor's own key reaches its own system + # only through pass_env, never as a literal in the manifest. + names = set(PROVIDER_API_KEY_ENV.values()) + passed = (names - {_OWN_KEYS.get(system_id)}) & set(pass_env) + keys = sorted((names & set(env)) | passed) if keys: raise BenchmarkValidationError( f"system {system_id!r} must not receive provider keys {keys} through env or pass_env" diff --git a/tests/benchmarks/test_agentic_run.py b/tests/benchmarks/test_agentic_run.py index b0c81563..0ccc4011 100644 --- a/tests/benchmarks/test_agentic_run.py +++ b/tests/benchmarks/test_agentic_run.py @@ -48,6 +48,7 @@ COMMITTED_MANIFEST = REPO_ROOT / "docs" / "benchmarks" / "agentic-manifest.yml" COMMITTED_PRICES = REPO_ROOT / "docs" / "benchmarks" / "price-snapshot.yml" FAKE_SERVER = FIX / "fake_fetch_server.py" +TEMPLATE_MANIFEST = REPO_ROOT / "docs" / "benchmarks" / "competitor-manifest.template.yml" # 3 systems x 2 questions x 2 repeats: python-docs and docs-fetch make 2 calls, no-docs 1, # so 20 calls of 1,000 input tokens at $1/1M and 100 output tokens at $10/1M. EXPECTED_ANTHROPIC_SPEND = Decimal("0.04") @@ -420,6 +421,27 @@ def test_a_key_shape_in_an_input_file_is_refused_before_any_snapshot(tmp_path: P assert not (tmp_path / "run" / "snapshots").exists() +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"] + ref |= {"adapter": "mcp-stdio", "command": ["{python}", str(FAKE_SERVER)], **fields} + path = tmp_path / "manifest.yml" + path.write_text(yaml.safe_dump({"competitors": [ref]}), encoding="utf-8") + return path + + +def test_a_competitor_key_reaches_its_system_only_through_pass_env(tmp_path: Path) -> None: + secret = "ref_synthetic_secret_123" + literal = _ref_tools_manifest(tmp_path, env={"REF_API_KEY": secret}) + with pytest.raises(BenchmarkValidationError, match="REF_API_KEY") as caught: + run_agentic(_config(tmp_path, manifest_path=literal, dry_run=True)) + assert secret not in str(caught.value) + assert not (tmp_path / "run" / "snapshots").exists() + passed = _ref_tools_manifest(tmp_path, env={}, pass_env=["REF_API_KEY"]) + summary = run_agentic(_config(tmp_path, manifest_path=passed, dry_run=True)) + assert summary["systems"] == ["ref-tools"] + + def test_a_worker_error_costs_only_its_own_cells(tmp_path: Path) -> None: # Usage that cannot be bucketed (cached > input) raises BenchmarkValidationError in the # openai worker; the anthropic job still finishes and the summary lists the failure. From 08aef3d95316d945ae09980a2ee04e5c3e87644a Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 01:41:17 +0100 Subject: [PATCH 52/77] fix(benchmarks): no CA variable reaches any of the three SDK clients google-genai builds its own SSL contexts, one for httpx and one for websockets, from SSL_CERT_FILE and SSL_CERT_DIR whenever none is given. gemini_sdk now passes one context built from certifi's bundle (already locked) as client_args verify and async_client_args verify and ssl. The new test sets SSL_CERT_FILE to a missing file and builds each client with no transport injected and nothing patched; construction is the assertion, and no request is made. Gemini failed before this fix. The Anthropic and OpenAI cases pin round 3's trust_env=False: with it removed, all three cases fail. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/clients.py | 7 +++++++ tests/benchmarks/test_agentic_clients.py | 10 ++++++++++ 2 files changed, 17 insertions(+) diff --git a/benchmarks/agentic/clients.py b/benchmarks/agentic/clients.py index 9a7be814..641d8686 100644 --- a/benchmarks/agentic/clients.py +++ b/benchmarks/agentic/clients.py @@ -10,6 +10,7 @@ import asyncio import json import os +import ssl from collections.abc import Mapping, Sequence from datetime import UTC, datetime from email.utils import parsedate_to_datetime @@ -17,6 +18,7 @@ from typing import Any import anthropic +import certifi import httpx import httpx2 import openai @@ -313,6 +315,9 @@ async def call(self, conv: Conversation) -> ModelTurn: def gemini_sdk( api_key: str, timeout_s: float, *, transport: httpx.AsyncBaseTransport | 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"). + ca = ssl.create_default_context(cafile=certifi.where()) return genai.Client( api_key=api_key, vertexai=False, @@ -321,6 +326,8 @@ def gemini_sdk( timeout=int(timeout_s * 1000), retry_options=genai_types.HttpRetryOptions(attempts=1), httpx_async_client=httpx.AsyncClient(**_client_args(transport)), + client_args={"verify": ca}, + async_client_args={"verify": ca, "ssl": ca}, ), ) diff --git a/tests/benchmarks/test_agentic_clients.py b/tests/benchmarks/test_agentic_clients.py index d4ffd19c..56ebc97e 100644 --- a/tests/benchmarks/test_agentic_clients.py +++ b/tests/benchmarks/test_agentic_clients.py @@ -836,3 +836,13 @@ def handle(request: Any) -> Any: await make_client(family, timeout_s=30).call(_conv()) assert routes == [None] # the direct route, never a proxy assert [r.url.host for r in recorder.seen] == [host] + + +@pytest.mark.parametrize("build", [anthropic_sdk, openai_sdk, gemini_sdk]) +def test_a_ca_variable_cannot_swap_a_clients_trust_store( + monkeypatch: pytest.MonkeyPatch, build: Callable[..., Any] +) -> None: + # Construction is the assertion: a client that reads SSL_CERT_FILE fails to load it. + # No transport is injected and nothing is patched; no request is made. + monkeypatch.setenv("SSL_CERT_FILE", "/nonexistent/ca.pem") + build("test-key", 30) From dd6a307ff7ff4c942c063dcec39ec3dca16ada61 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 01:41:55 +0100 Subject: [PATCH 53/77] docs(benchmarks): PR 4's worker env is an allowlist with no proxy or CA variable A SOCKS ALL_PROXY makes the Anthropic SDK build a SOCKS transport at construction, which fails without socksio, and the CA variables would swap a client's trust store. The local launcher already passes an allowlist; a new test pins that it holds none of these variables. The shortcut comment and the plan's PR 4 list now require the same of PR 4's container launcher, and require its egress proxy to be passed explicitly. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/clients.py | 4 +++- .../2026-10-31-agentic-benchmark-harness.md | 7 ++++++- tests/benchmarks/test_agentic_host.py | 18 ++++++++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/benchmarks/agentic/clients.py b/benchmarks/agentic/clients.py index 641d8686..71d980da 100644 --- a/benchmarks/agentic/clients.py +++ b/benchmarks/agentic/clients.py @@ -114,7 +114,9 @@ def _client_args(transport: Any | None) -> dict[str, Any]: 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. """ - # shortcut: no proxy from the env; PR 4's egress proxy must be passed explicitly (proxy=...) + # 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). return { "follow_redirects": False, "trust_env": False, diff --git a/docs/plans/2026-10-31-agentic-benchmark-harness.md b/docs/plans/2026-10-31-agentic-benchmark-harness.md index 789b73f3..f9ddeb30 100644 --- a/docs/plans/2026-10-31-agentic-benchmark-harness.md +++ b/docs/plans/2026-10-31-agentic-benchmark-harness.md @@ -2114,7 +2114,12 @@ Open PR B with `gh pr create` against `main`: - **PR 4:** - the Dockerfile and the container launcher (`--env-file`, one key per container, `--read-only`, tmpfs, `--cap-drop ALL`); - - the per-worker egress proxy and its logs; + - the per-worker egress proxy and its logs, passed to each SDK client + explicitly (the clients ignore proxy and CA variables); + - the container launcher's worker environment as an allowlist that + excludes every `*_PROXY`, `SSL_CERT_*` and `REQUESTS_CA_BUNDLE` + variable (a SOCKS `ALL_PROXY` crashes the Anthropic SDK at + construction; #197 round 4); - the isolation probe and the run script; - the Ollama client (`OllamaChatClient`), `to_openai_chat`, `ollama_buckets`, the unmetered `ollama` ledger provider and the diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index be416410..483b3f89 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -182,6 +182,24 @@ def test_local_launcher_passes_no_provider_key_and_runs_only_scripted_models( assert LocalLauncher().supports(job.family) is True +def test_local_launcher_passes_no_proxy_or_ca_variable( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + # A SOCKS ALL_PROXY crashes the Anthropic client; a CA variable swaps the trust store. + for name in ("HTTPS_PROXY", "http_proxy", "ALL_PROXY", "NO_PROXY", "SSL_CERT_FILE"): + monkeypatch.setenv(name, "socks5://proxy.invalid:1080") + monkeypatch.setenv("SSL_CERT_DIR", "/nonexistent") + monkeypatch.setenv("REQUESTS_CA_BUNDLE", "/nonexistent/ca.pem") + _, env = LocalLauncher().command(_job(tmp_path, [ANSWER])) + assert not [ + name + for name in env + if name.upper().endswith("_PROXY") + or name.startswith("SSL_CERT_") + or name == "REQUESTS_CA_BUNDLE" + ] + + ANTHROPIC_SHAPE = "sk-ant-api03-" + "a" * 90 From e65aee025bb8c9e85a56655c46b907b6337327de Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 01:42:05 +0100 Subject: [PATCH 54/77] refactor(benchmarks): derive PAID_KEY_ENVS from PROVIDER_API_KEY_ENV One list of key names, so the two cannot drift apart. The value is unchanged; the host, bridge and client tests that use it still pass. Co-Authored-By: Claude Opus 5.5 --- benchmarks/adapters/guard.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/benchmarks/adapters/guard.py b/benchmarks/adapters/guard.py index 9409e00a..a2aa6ec9 100644 --- a/benchmarks/adapters/guard.py +++ b/benchmarks/adapters/guard.py @@ -49,7 +49,7 @@ } #: The model providers' keys: they pay for every call, and no docs system ever receives one. -PAID_KEY_ENVS = ("ANTHROPIC_API_KEY", "OPENAI_API_KEY", "GOOGLE_API_KEY") +PAID_KEY_ENVS = tuple(PROVIDER_API_KEY_ENV[p] for p in ("anthropic", "openai", "google")) _TRUTHY = {"1", "true", "yes"} #: Every provider key is made of these; anything else could be quoted by an HTTP error. From bf6037efad16b9be10100555202805286545da36 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 01:45:20 +0100 Subject: [PATCH 55/77] fix(benchmarks): a rerun counts once it has run The summary counted a rerun when a retries_exhausted discard was sent, so a worker lost before the rerun still reported one. Each trajectory frame now carries its attempt, and the collector counts a rerun for any trajectory or discard whose attempt is above 1. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/run.py | 5 +-- benchmarks/agentic/worker.py | 3 +- tests/benchmarks/test_agentic_host.py | 1 + tests/benchmarks/test_agentic_run.py | 55 +++++++++++++++++++++++++++ 4 files changed, 60 insertions(+), 4 deletions(-) diff --git a/benchmarks/agentic/run.py b/benchmarks/agentic/run.py index 5b417586..393c174b 100644 --- a/benchmarks/agentic/run.py +++ b/benchmarks/agentic/run.py @@ -38,7 +38,7 @@ 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.worker import MAX_RERUNS, _client_versions +from benchmarks.agentic.worker import _client_versions from benchmarks.model_matrix import ( _HOSTED_REQUIRED_FIELDS, METHODOLOGY_TOKEN_LABEL, @@ -242,13 +242,12 @@ async def on_message(self, job: WorkerJob, message: dict[str, Any]) -> None: record = message["record"] stats = self.families[job.family.id] stats.add(record) + stats.reruns += message["attempt"] > 1 # a rerun counts once it has run if kind == "discarded": reason, attempt = message["reason"], message["attempt"] self.discarded.append( {"cell": cell, "corpus_id": corpus_id, "reason": reason, "attempt": attempt} ) - if reason == "retries_exhausted" and attempt <= MAX_RERUNS: - stats.reruns += 1 path = self.out / "discarded" / cell / f"{corpus_id}--attempt{attempt}.json" _write(path, {**record, **self._ident(job, cell, message), "reason": reason}) return diff --git a/benchmarks/agentic/worker.py b/benchmarks/agentic/worker.py index 40bf94f2..7e07bd78 100644 --- a/benchmarks/agentic/worker.py +++ b/benchmarks/agentic/worker.py @@ -291,7 +291,8 @@ async def _run_job(channel: ProtocolChannel, reader: asyncio.StreamReader) -> in } ) continue - await host.request({"type": "trajectory", "record": record, **ident}) + 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() diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 483b3f89..8314e4dc 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -360,6 +360,7 @@ async def test_worker_runs_its_job_over_the_channel_and_reports_done( assert info["tools_raw"] == [] and info["index_sha256"] is None assert set(info["client_versions"]) == {"anthropic", "openai", "google-genai", "mcp"} assert [m["corpus_id"] for m in messages[1:3]] == ["Q1", "Q2"] + assert [m["attempt"] for m in messages[1:3]] == [1, 1] # a rerun counts by its attempt assert messages[1]["record"]["answer"] == "Scripted answer." assert host.ledger.spent("anthropic") == 2 * D("0.0011") # 1000 in + 100 out at $1/1M assert (tmp_path / "logs" / "scripted-anthropic--no-docs.stderr.log").exists() diff --git a/tests/benchmarks/test_agentic_run.py b/tests/benchmarks/test_agentic_run.py index 0ccc4011..b077768d 100644 --- a/tests/benchmarks/test_agentic_run.py +++ b/tests/benchmarks/test_agentic_run.py @@ -8,6 +8,7 @@ import hashlib import json import random +import sys from datetime import date from decimal import Decimal from pathlib import Path @@ -264,6 +265,60 @@ def test_run_summary_counts_retries_and_reruns(tmp_path: Path) -> None: assert summary["succeeded_cells"] == 1 and fam["answer_turns"] == 1 +class _LostAfterDiscard(LocalLauncher): + """A worker that reports one retries_exhausted discard, then dies before its rerun.""" + + def command(self, job: Any) -> tuple[list[str], dict[str, str]]: + _, env = super().command(job) + timing = {f"{name}_ms": 0 for name in ("grant_wait", "failed_attempt", "retry_wait")} + record = { + "status": "discarded", + "started_at": "2026-11-04T00:00:00.000Z", + "completed_at": "2026-11-04T00:00:01.000Z", + "timing": timing, + "model_calls": [], + } + frame = { + "type": "discarded", + "record": record, + "corpus_id": "SYN-EX-001", + "repeat": 1, + "reason": "retries_exhausted", + "attempt": 1, + } + 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"body = json.dumps({frame!r}).encode()\n" + "out.write(len(body).to_bytes(8, 'big') + body)\n" + "out.flush()\n" + "inp.read(int.from_bytes(inp.read(8), 'big'))\n" + "sys.exit(1)\n" + ) + return [sys.executable, "-c", code], env + + +def test_a_rerun_that_never_ran_is_not_counted(tmp_path: Path) -> None: + config = _config( + tmp_path, + models=("scripted-anthropic",), + systems=("no-docs",), + questions=("SYN-EX-001",), + repeats=1, + ) + summary = run_agentic(config, launcher=_LostAfterDiscard()) + assert summary["not_run"] == [ + { + "cell": "no-docs--scripted-anthropic--r1", + "corpus_id": "SYN-EX-001", + "reason": "worker_lost", + "attempt": None, + } + ] + assert summary["families"]["scripted-anthropic"]["reruns"] == 0 + + def test_run_summary_wall_time_includes_failed_attempts_backoff_and_grant_waits( tmp_path: Path, ) -> None: From 5cf69649e9524adae043a50e494779af058ba706 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 01:45:28 +0100 Subject: [PATCH 56/77] test(benchmarks): the Ref.tools template test checks only the claim it guards It asserted the note's full sentence too, which pins prose rather than behaviour. It now asserts only that "satisfied by construction" is gone. Co-Authored-By: Claude Opus 5.5 --- tests/benchmarks/test_competitor_eligibility.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/tests/benchmarks/test_competitor_eligibility.py b/tests/benchmarks/test_competitor_eligibility.py index ff877edd..64f4a79f 100644 --- a/tests/benchmarks/test_competitor_eligibility.py +++ b/tests/benchmarks/test_competitor_eligibility.py @@ -292,10 +292,6 @@ def test_template_states_the_ref_tools_session_requirement_for_round_2() -> None data = yaml.safe_load(_TEMPLATE_MANIFEST_PATH.read_text(encoding="utf-8")) (ref,) = [c for c in data["competitors"] if c["id"] == "ref-tools"] conditions = " ".join(ref["eligibility"]["conditions"]) - assert ( - "Requirement for round 2: the bridge must open a fresh MCP session per cell for " - "Ref.tools (today one session per job, reused across cells)." in conditions - ) assert "satisfied by construction" not in conditions From 79357caeed0a5775f739c6fa216fe69766773fa7 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 01:49:48 +0100 Subject: [PATCH 57/77] build(benchmarks): declare certifi, which the Gemini client now imports gemini_sdk builds its CA context from certifi.where(), so certifi is a direct import. It joins anthropic, openai and google-genai in the dev group with a lower bound the locked 2026.10.23 meets. uv.lock changes only the dev group's metadata; no package version moves. Co-Authored-By: Claude Opus 5.5 --- pyproject.toml | 1 + uv.lock | 2 ++ 2 files changed, 3 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 10808202..43e026b7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,6 +43,7 @@ dev = [ "anthropic==1.15.0", "openai==3.32.0", "google-genai==2.31.0", + "certifi>=2026.10.23", ] [project.scripts] diff --git a/uv.lock b/uv.lock index 086fbdde..430993d4 100644 --- a/uv.lock +++ b/uv.lock @@ -960,6 +960,7 @@ dependencies = [ [package.dev-dependencies] dev = [ { name = "anthropic" }, + { name = "certifi" }, { name = "google-genai" }, { name = "openai" }, { name = "pyright" }, @@ -984,6 +985,7 @@ requires-dist = [ [package.metadata.requires-dev] dev = [ { name = "anthropic", specifier = "==1.15.0" }, + { name = "certifi", specifier = ">=2026.10.23" }, { name = "google-genai", specifier = "==2.31.0" }, { name = "openai", specifier = "==3.32.0" }, { name = "pyright", specifier = ">=1.1" }, From b7e1055b85261141f214b1ee32591e4981944f52 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 02:02:54 +0100 Subject: [PATCH 58/77] fix(benchmarks): a system with no transport is screened for keys too system_spec_from_raw returned early for adapter: none before its env and pass_env checks, so a no-docs entry could carry a provider key, literal or passed, into the snapshotted manifest. The env, pass_env and key-shape checks now run before any transport-specific return. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/bridge.py | 11 ++++++----- tests/benchmarks/test_agentic_run.py | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/benchmarks/agentic/bridge.py b/benchmarks/agentic/bridge.py index fc6d0b1e..6be59889 100644 --- a/benchmarks/agentic/bridge.py +++ b/benchmarks/agentic/bridge.py @@ -83,11 +83,7 @@ def system_spec_from_raw(raw: Mapping[str, Any]) -> SystemSpec: f"system {system_id!r} has adapter {raw.get('adapter')!r}; " f"expected one of {sorted(_TRANSPORTS)}" ) - if transport == "none": - return SystemSpec(system_id, transport, (), {}, (), dict(raw)) - command = _strings(raw.get("command"), f"system {system_id!r} 'command'") - if not command: - raise BenchmarkValidationError(f"system {system_id!r} 'command' must not be empty") + # Keys first, whatever the transport: a manifest entry is snapshotted even if it spawns nothing. env = raw.get("env") or {} if not isinstance(env, Mapping) or not all( isinstance(k, str) and isinstance(v, str) for k, v in env.items() @@ -105,6 +101,11 @@ def system_spec_from_raw(raw: Mapping[str, Any]) -> SystemSpec: ) for name, value in env.items(): assert_no_key_shaped(value, where=f"system {system_id!r} env {name!r}") + if transport == "none": + return SystemSpec(system_id, transport, (), {}, (), dict(raw)) + command = _strings(raw.get("command"), f"system {system_id!r} 'command'") + if not command: + raise BenchmarkValidationError(f"system {system_id!r} 'command' must not be empty") return SystemSpec(system_id, transport, command, dict(env), pass_env, dict(raw)) diff --git a/tests/benchmarks/test_agentic_run.py b/tests/benchmarks/test_agentic_run.py index b077768d..31ea9bba 100644 --- a/tests/benchmarks/test_agentic_run.py +++ b/tests/benchmarks/test_agentic_run.py @@ -497,6 +497,25 @@ def test_a_competitor_key_reaches_its_system_only_through_pass_env(tmp_path: Pat assert summary["systems"] == ["ref-tools"] +@pytest.mark.parametrize( + "fields", + [ + {"env": {"REF_API_KEY": "ref_synthetic_secret_123"}}, + {"pass_env": ["ANTHROPIC_API_KEY"]}, + ], +) +def test_a_system_without_a_transport_is_screened_for_keys_too( + tmp_path: Path, fields: dict[str, Any] +) -> None: + manifest = tmp_path / "manifest.yml" + no_docs = {"id": "no-docs", "adapter": "none", **fields} + manifest.write_text(yaml.safe_dump({"competitors": [no_docs]}), encoding="utf-8") + with pytest.raises(BenchmarkValidationError, match="_API_KEY") as caught: + run_agentic(_config(tmp_path, manifest_path=manifest, dry_run=True)) + assert "ref_synthetic_secret_123" not in str(caught.value) + assert not (tmp_path / "run" / "snapshots").exists() + + def test_a_worker_error_costs_only_its_own_cells(tmp_path: Path) -> None: # Usage that cannot be bucketed (cached > input) raises BenchmarkValidationError in the # openai worker; the anthropic job still finishes and the summary lists the failure. From 769ba4f7ac42c18e1e2f1a693456ad7b5a841596 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 02:05:19 +0100 Subject: [PATCH 59/77] test(benchmarks): the second-abort teardown test orders its steps by signals The test relied on sleeps for its order. Now: - A's grandchild holds A's pipes and marks "entered" once A is killed, which happens only in A's teardown. - B waits for that mark before it sends its leak frame. B writes its stderr line first, in program order. - The test releases the grandchild only once A's supervisor has been cancelled, or has ended. Every wait is bounded at 10 s and fails loudly. It passed 10 runs in a row in about 0.5 s each. With the shield removed, A's log keeps the key and the test fails. Co-Authored-By: Claude Opus 5.5 --- tests/benchmarks/test_agentic_host.py | 62 ++++++++++++++++++++++----- 1 file changed, 52 insertions(+), 10 deletions(-) diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 8314e4dc..027e55de 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -5,6 +5,7 @@ from __future__ import annotations +import asyncio import json import os import subprocess @@ -596,15 +597,44 @@ async def test_every_worker_log_is_scrubbed_when_a_frame_leak_aborts_the_run( assert log.read_text() == "debug: [redacted]\n" +# Holds A's pipes, so A's teardown waits on it. Marks when A is killed, which happens only in +# A's teardown, then exits once the test releases it. Each wait is bounded and fails loudly. +_GRANDCHILD = ( + "import os, sys, time\n" + "from pathlib import Path\n" + "parent, entered, release = int(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3])\n" + "deadline = time.monotonic() + 10\n" + "while os.getppid() == parent:\n" + " if time.monotonic() > deadline:\n" + " sys.exit('grandchild: A was never killed')\n" + " time.sleep(0.01)\n" + "entered.touch()\n" + "while not release.exists():\n" + " if time.monotonic() > deadline + 10:\n" + " sys.exit('grandchild: never released')\n" + " time.sleep(0.01)\n" +) + + +def _supervisor(job_id: str) -> asyncio.Task[Any] | None: + """The running supervisor task of ``job_id``, found by its coroutine's frame.""" + for task in asyncio.all_tasks(): + frame = getattr(task.get_coro(), "cr_frame", None) + if frame is not None and frame.f_code.co_name == "_supervise": + if frame.f_locals["job"].job_id == job_id: + return task + return None + + async def test_a_teardown_cancelled_by_a_second_abort_still_scrubs_and_settles( host: Host, tmp_path: Path ) -> None: - # A holds a unit, then leaks a key. A grandchild keeps A's pipes open, so A's teardown - # waits for it. B leaks next, and its abort cancels A mid-teardown. + # A holds a unit, then leaks a key; its teardown waits on a grandchild holding its pipes. + # Only then does B leak, and B's abort cancels A mid-teardown. leaked = "sk-ant-api03-" + "z" * 90 - marker = str(tmp_path / "a-leaks") + entered, release = tmp_path / "a-in-teardown", tmp_path / "release" code = ( - "import json, subprocess, sys, time\n" + "import json, os, subprocess, sys, time\n" "from pathlib import Path\n" "inp, out = sys.stdin.buffer, sys.stdout.buffer\n" "def read():\n" @@ -619,18 +649,30 @@ async def test_a_teardown_cancelled_by_a_second_abort_still_scrubs_and_settles( "if job['job_id'] == 'a':\n" f" send({_reserve_frame(1024)!r})\n" " read()\n" - " subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(3)'])\n" - f" Path({marker!r}).touch()\n" + f" signals = [str(os.getpid()), {str(entered)!r}, {str(release)!r}]\n" + f" subprocess.Popen([sys.executable, '-c', {_GRANDCHILD!r}, *signals])\n" "else:\n" - f" while not Path({marker!r}).exists():\n" - " time.sleep(0.05)\n" - " time.sleep(0.3)\n" + " deadline = time.monotonic() + 10\n" + f" while not Path({str(entered)!r}).exists():\n" + " if time.monotonic() > deadline:\n" + " sys.exit('B: A never entered its teardown')\n" + " time.sleep(0.01)\n" f"send({{'type': 'system_info', 'note': '{leaked}'}})\n" "time.sleep(30)\n" ) jobs = [_job(tmp_path, [ANSWER], job_id=job_id) for job_id in ("a", "b")] + run = asyncio.create_task(host.run(jobs, launcher=KeyedLauncher(code, key=""))) + try: + async with asyncio.timeout(10): # bounded: a missed signal fails loudly + while (a := _supervisor("a")) is None: + await asyncio.sleep(0.01) + while not (a.done() or a.cancelling()): # B's abort has reached A + await asyncio.sleep(0.01) + finally: + release.touch() + await asyncio.wait([run], timeout=20) with pytest.raises(KeyLeakError): - await host.run(jobs, launcher=KeyedLauncher(code, key="")) + run.result() logs = sorted((tmp_path / "logs").iterdir()) assert [log.read_text() for log in logs] == ["debug: [redacted]\n"] * 2 settles = [e for e in host.ledger.events("host-test") if e["event"] == "settle"] From 16a105dce87ec4d4c68f9a22fe0d0feeecad0665 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 02:06:49 +0100 Subject: [PATCH 60/77] fix(benchmarks): a worker that never exits cannot hang its teardown Teardown awaited proc.wait() with no bound after the kill, so a worker that never exited (or a grandchild holding its pipes) could hang the run. It now waits at most _EXIT_WAIT_S (30 s), then scrubs the log and books the open unit anyway. The test drives _teardown with a fake process whose wait() never returns. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/host.py | 5 +++- tests/benchmarks/test_agentic_host.py | 34 +++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index d640de4a..1a0c1c90 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -37,6 +37,8 @@ #: What a local worker may see of the host's environment. Never a key, never the live flag. _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 @dataclass(frozen=True) @@ -86,7 +88,8 @@ async def _teardown( """Kill the worker, scrub its log and book its open unit; the log's key pattern, if any.""" if proc.returncode is None: proc.kill() - await proc.wait() + with suppress(TimeoutError): # a worker that never exits cannot hang the run + await asyncio.wait_for(proc.wait(), _EXIT_WAIT_S) # On every exit, a raise or a cancel included: the leaked bytes never stay on disk. redacted, pattern = redact_key_shaped(log_path.read_bytes()) if pattern: diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 027e55de..d352e66b 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -19,6 +19,7 @@ import pytest import yaml +import benchmarks.agentic.host as agentic_host 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 @@ -681,6 +682,39 @@ async def test_a_teardown_cancelled_by_a_second_abort_still_scrubs_and_settles( ] +class _Unending: + """A worker process that survives its kill: wait() never returns.""" + + returncode = None + + def kill(self) -> None: + pass + + async def wait(self) -> int: + await asyncio.Event().wait() + raise AssertionError("unreachable") + + +async def test_a_worker_that_never_exits_cannot_hang_its_teardown( + host: Host, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(agentic_host, "_EXIT_WAIT_S", 0.1, raising=False) + family = _job(tmp_path, [ANSWER]).family + service = host.service(family) + unit = await service.reserve( + 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") + async with asyncio.timeout(5): # the bound under test is 0.1 s + pattern = await agentic_host._teardown(_Unending(), log, service, unit) # type: ignore[arg-type] + assert pattern is not None and 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")) + ] + + async def test_host_aborts_the_run_when_a_worker_frame_holds_a_key_shaped_string( host: Host, tmp_path: Path ) -> None: From bf72d9e9e96300dbcdb4bf754f106049b0a93e0a Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 02:07:11 +0100 Subject: [PATCH 61/77] refactor(benchmarks): Gemini's async_client_args carries only the websocket context google-genai reads "verify" from client_args first, so the "verify" in async_client_args was never used. Only "ssl", the websocket context, stays. The CA test still passes, and it fails with "ssl" removed. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/clients.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/benchmarks/agentic/clients.py b/benchmarks/agentic/clients.py index 71d980da..dbe18556 100644 --- a/benchmarks/agentic/clients.py +++ b/benchmarks/agentic/clients.py @@ -329,7 +329,7 @@ def gemini_sdk( retry_options=genai_types.HttpRetryOptions(attempts=1), httpx_async_client=httpx.AsyncClient(**_client_args(transport)), client_args={"verify": ca}, - async_client_args={"verify": ca, "ssl": ca}, + async_client_args={"ssl": ca}, ), ) From db81196f3cbb57716280c32f56369966d6fa31a1 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 02:07:20 +0100 Subject: [PATCH 62/77] test(benchmarks): name the Ref.tools template test for what it checks Co-Authored-By: Claude Opus 5.5 --- tests/benchmarks/test_competitor_eligibility.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/benchmarks/test_competitor_eligibility.py b/tests/benchmarks/test_competitor_eligibility.py index 64f4a79f..63d83b88 100644 --- a/tests/benchmarks/test_competitor_eligibility.py +++ b/tests/benchmarks/test_competitor_eligibility.py @@ -288,7 +288,7 @@ def test_exclusions_block_passes_validation_and_survives_snapshot_byte_for_byte( # --- The committed template manifest ---------------------------------------- -def test_template_states_the_ref_tools_session_requirement_for_round_2() -> None: +def test_template_does_not_claim_the_ref_tools_session_requirement_is_met() -> None: data = yaml.safe_load(_TEMPLATE_MANIFEST_PATH.read_text(encoding="utf-8")) (ref,) = [c for c in data["competitors"] if c["id"] == "ref-tools"] conditions = " ".join(ref["eligibility"]["conditions"]) From 36f812e648972d70a002d8bb5da8b4a2913e0833 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 02:28:09 +0100 Subject: [PATCH 63/77] fix(benchmarks): no worker descendant can write a key into a published log After the bounded wait, a surviving descendant holding the worker's log descriptor could append a key after the final scrub. Two changes: - Each worker starts in its own session (start_new_session=True), and teardown kills the whole process group, even after the worker exited. A shortcut comment records the PR 4 requirement: the container launcher must give the same guarantee, which removing the container does. - Teardown always publishes the log as its scrubbed snapshot, through a temp file in the same directory and os.replace. A writer that still holds the old descriptor writes into an unlinked file. The regression test starts two late writers that share fd 2 and wait for a file signal. One stays in the worker's group and must be dead after the group kill. The other leaves the group with setsid, writes a key after the log is published, and the published log must not hold it. Each change, when removed, fails the test. The bounded-teardown test gives its fake process a real throwaway process group to kill, and its _EXIT_WAIT_S monkeypatch no longer passes raising=False (round 6 item 3). Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/host.py | 17 ++++-- tests/benchmarks/test_agentic_host.py | 83 ++++++++++++++++++++++++++- 2 files changed, 92 insertions(+), 8 deletions(-) diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index 1a0c1c90..a6c4dee9 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -11,6 +11,7 @@ import asyncio import json import os +import signal import sys from collections.abc import Awaitable, Callable, Mapping, Sequence from contextlib import suppress @@ -86,14 +87,19 @@ async def _teardown( proc: asyncio.subprocess.Process, log_path: Path, ledger: LedgerService, in_flight: str | None ) -> str | None: """Kill the worker, scrub its log and book its open unit; the log's key pattern, if any.""" - if proc.returncode is None: - proc.kill() + # The whole group, even after the worker exited: no descendant outlives it to write later. + # shortcut: reaches only this host's process tree; PR 4's container launcher must give the + # same guarantee, which removing the container does. + with suppress(ProcessLookupError): + os.killpg(proc.pid, signal.SIGKILL) with suppress(TimeoutError): # a worker that never exits cannot hang the run await asyncio.wait_for(proc.wait(), _EXIT_WAIT_S) - # On every exit, a raise or a cancel included: the leaked bytes never stay on disk. + # On every exit, a raise or a cancel included: the leaked bytes never stay on disk. The + # scrubbed copy replaces the log, so a writer still holding it writes into an unlinked file. redacted, pattern = redact_key_shaped(log_path.read_bytes()) - if pattern: - log_path.write_bytes(redacted) + scrubbed = log_path.with_name(log_path.name + ".tmp") + scrubbed.write_bytes(redacted) + os.replace(scrubbed, log_path) if in_flight is not None: # may have been billed: booked at twice its bound await ledger.settle(in_flight, outcome="worker_lost", buckets=None) return pattern @@ -119,6 +125,7 @@ async def _supervise( stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=log, + start_new_session=True, # its own process group, which teardown kills whole ) assert proc.stdin is not None and proc.stdout is not None in_flight: str | None = None diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index d352e66b..5376f567 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -8,6 +8,7 @@ import asyncio import json import os +import signal import subprocess import sys import time @@ -682,11 +683,83 @@ async def test_a_teardown_cancelled_by_a_second_abort_still_scrubs_and_settles( ] +# A worker's descendant that holds its log (fd 2) and writes a key once the log is published. +# "stay" remains in the worker's process group; "escape" leaves it with setsid. Bounded waits. +_LATE_WRITER = ( + "import os, sys, time\n" + "from pathlib import Path\n" + "mode, signals = sys.argv[1], Path(sys.argv[2])\n" + "if mode == 'escape':\n" + " os.setsid()\n" + " (signals / 'escaped').touch()\n" + "deadline = time.monotonic() + 10\n" + "while not (signals / 'published').exists():\n" + " if time.monotonic() > deadline:\n" + " sys.exit(mode + ': the log was never published')\n" + " time.sleep(0.01)\n" + "os.write(2, b'late: sk-ant-api03-' + b'z' * 90 + b'\\n')\n" + "(signals / (mode + '-wrote')).touch()\n" +) + + +def _alive(pid: int) -> bool: + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + stat = Path(f"/proc/{pid}/stat") # Linux: a zombie is dead, whoever has yet to reap it + return not (stat.exists() and stat.read_text().rsplit(")", 1)[1].split()[0] == "Z") + + +async def test_no_descendant_can_write_a_key_into_the_published_log( + host: Host, tmp_path: Path +) -> None: + # The worker skips protect_output, starts both late writers, then exits: a lost worker. + signals = tmp_path / "signals" + signals.mkdir() + code = ( + "import subprocess, sys, time\n" + "from pathlib import Path\n" + "sys.stdin.buffer.read(int.from_bytes(sys.stdin.buffer.read(8), 'big'))\n" + "sys.stderr.write('worker: started\\n')\n" + "sys.stderr.flush()\n" + f"signals = Path({str(signals)!r})\n" + "quiet = {'stdin': subprocess.DEVNULL, 'stdout': subprocess.DEVNULL} # fd 2 only\n" + f"argv = [sys.executable, '-c', {_LATE_WRITER!r}]\n" + "stay = subprocess.Popen([*argv, 'stay', str(signals)], **quiet)\n" + "(signals / 'stay.pid').write_text(str(stay.pid))\n" + "subprocess.Popen([*argv, 'escape', str(signals)], **quiet)\n" + "deadline = time.monotonic() + 10\n" + "while not (signals / 'escaped').exists():\n" + " if time.monotonic() > deadline:\n" + " sys.exit('worker: the escape never left the group')\n" + " time.sleep(0.01)\n" + "sys.exit(1)\n" + ) + await host.run([_job(tmp_path, [ANSWER])], launcher=KeyedLauncher(code, key="")) + stay = int((signals / "stay.pid").read_text()) + async with asyncio.timeout(5): # (a) the group kill took the descendant in the group + while _alive(stay): + await asyncio.sleep(0.01) + (signals / "published").touch() + async with asyncio.timeout(10): # (b) the escaped one writes into the unlinked old log + while not (signals / "escape-wrote").exists(): + await asyncio.sleep(0.01) + (log,) = (tmp_path / "logs").iterdir() + assert log.read_text() == "worker: started\n" + + class _Unending: - """A worker process that survives its kill: wait() never returns.""" + """A worker whose wait() never returns, as if it survived its kill. + + Its pid leads a real process group of its own, so the group kill hits only that group. + """ returncode = None + def __init__(self, pid: int) -> None: + self.pid = pid + def kill(self) -> None: pass @@ -698,7 +771,10 @@ async def wait(self) -> int: async def test_a_worker_that_never_exits_cannot_hang_its_teardown( host: Host, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - monkeypatch.setattr(agentic_host, "_EXIT_WAIT_S", 0.1, raising=False) + monkeypatch.setattr(agentic_host, "_EXIT_WAIT_S", 0.1) + group = subprocess.Popen( + [sys.executable, "-c", "import time; time.sleep(30)"], start_new_session=True + ) family = _job(tmp_path, [ANSWER]).family service = host.service(family) unit = await service.reserve( @@ -707,7 +783,8 @@ async def test_a_worker_that_never_exits_cannot_hang_its_teardown( log = tmp_path / "never-exits.stderr.log" log.write_text("debug: sk-ant-api03-" + "z" * 90 + "\n", encoding="utf-8") async with asyncio.timeout(5): # the bound under test is 0.1 s - pattern = await agentic_host._teardown(_Unending(), log, service, unit) # type: ignore[arg-type] + pattern = await agentic_host._teardown(_Unending(group.pid), log, service, unit) # type: ignore[arg-type] + assert group.wait(timeout=5) == -signal.SIGKILL assert pattern is not None and 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] == [ From 42a6a54ed488ab0b8d275a886ab3da55f6f5632d Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 02:39:21 +0100 Subject: [PATCH 64/77] test(benchmarks): the second-abort test fails unless A is cancelled mid-teardown The test released A's grandchild once A's supervisor was cancelling or done, so a teardown that ended before any second abort passed silently. After the group kill it did: the grandchild died with A's group, A's teardown finished, and the test passed without exercising the shield. The loop now waits only for cancelling(), and fails at its 10 s bound otherwise. The grandchild leaves A's group with setsid, and A waits for that before it leaks, so the grandchild keeps A's pipes open as intended. With the shield removed, the test still fails. Co-Authored-By: Claude Opus 5.5 --- tests/benchmarks/test_agentic_host.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 5376f567..8ab5166a 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -599,12 +599,15 @@ async def test_every_worker_log_is_scrubbed_when_a_frame_leak_aborts_the_run( assert log.read_text() == "debug: [redacted]\n" -# Holds A's pipes, so A's teardown waits on it. Marks when A is killed, which happens only in -# A's teardown, then exits once the test releases it. Each wait is bounded and fails loudly. +# Holds A's pipes, so A's teardown waits on it; it leaves A's process group first, so the +# group kill spares it. Marks when A is killed, which happens only in A's teardown, then exits +# once the test releases it. Each wait is bounded and fails loudly. _GRANDCHILD = ( "import os, sys, time\n" "from pathlib import Path\n" "parent, entered, release = int(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3])\n" + "os.setsid()\n" + "(entered.parent / 'escaped').touch()\n" "deadline = time.monotonic() + 10\n" "while os.getppid() == parent:\n" " if time.monotonic() > deadline:\n" @@ -632,7 +635,8 @@ async def test_a_teardown_cancelled_by_a_second_abort_still_scrubs_and_settles( host: Host, tmp_path: Path ) -> None: # A holds a unit, then leaks a key; its teardown waits on a grandchild holding its pipes. - # Only then does B leak, and B's abort cancels A mid-teardown. + # Only then does B leak, and B's abort cancels A mid-teardown. If A's teardown ends before + # that, A is never cancelled and the bounded wait fails. leaked = "sk-ant-api03-" + "z" * 90 entered, release = tmp_path / "a-in-teardown", tmp_path / "release" code = ( @@ -653,6 +657,11 @@ async def test_a_teardown_cancelled_by_a_second_abort_still_scrubs_and_settles( " read()\n" f" signals = [str(os.getpid()), {str(entered)!r}, {str(release)!r}]\n" f" subprocess.Popen([sys.executable, '-c', {_GRANDCHILD!r}, *signals])\n" + " deadline = time.monotonic() + 10\n" + f" while not Path({str(tmp_path / 'escaped')!r}).exists():\n" + " if time.monotonic() > deadline:\n" + " sys.exit('A: the grandchild never left the group')\n" + " time.sleep(0.01)\n" "else:\n" " deadline = time.monotonic() + 10\n" f" while not Path({str(entered)!r}).exists():\n" @@ -668,7 +677,7 @@ async def test_a_teardown_cancelled_by_a_second_abort_still_scrubs_and_settles( async with asyncio.timeout(10): # bounded: a missed signal fails loudly while (a := _supervisor("a")) is None: await asyncio.sleep(0.01) - while not (a.done() or a.cancelling()): # B's abort has reached A + while not a.cancelling(): # B's abort has reached A, mid-teardown await asyncio.sleep(0.01) finally: release.touch() From e843f4102b2701c924a2d60420652a385c0b6a85 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 02:42:15 +0100 Subject: [PATCH 65/77] fix(benchmarks): the group kill tolerates macOS's EPERM for a zombie group The full gate failed twice, intermittently, with PermissionError from os.killpg. A worker that has exited but is not yet reaped leaves a group that holds only a zombie, and macOS answers a kill on such a group with EPERM, not ESRCH. Teardown now suppresses PermissionError as well. The regression test leaves an exited child unreaped with os.waitid(WNOWAIT), then tears it down. Linux signals zombies without error, so the test passes trivially there. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/host.py | 3 ++- tests/benchmarks/test_agentic_host.py | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index a6c4dee9..8cdcd03c 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -90,7 +90,8 @@ async def _teardown( # The whole group, even after the worker exited: no descendant outlives it to write later. # shortcut: reaches only this host's process tree; PR 4's container launcher must give the # same guarantee, which removing the container does. - with suppress(ProcessLookupError): + # ESRCH: the group is gone. EPERM: macOS's answer for a group that holds only zombies. + with suppress(ProcessLookupError, PermissionError): os.killpg(proc.pid, signal.SIGKILL) with suppress(TimeoutError): # a worker that never exits cannot hang the run await asyncio.wait_for(proc.wait(), _EXIT_WAIT_S) diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 8ab5166a..a0abb977 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -758,6 +758,32 @@ async def test_no_descendant_can_write_a_key_into_the_published_log( assert log.read_text() == "worker: started\n" +class _Exited: + """A worker that has exited but is not yet reaped: its group holds only a zombie.""" + + returncode = None + + def __init__(self, pid: int) -> None: + self.pid = pid + + async def wait(self) -> int: + return 0 + + +async def test_teardown_of_an_exited_worker_not_yet_reaped(host: Host, tmp_path: Path) -> None: + # macOS answers a group kill with EPERM when the group holds only a zombie. + zombie = subprocess.Popen([sys.executable, "-c", "pass"], start_new_session=True) + os.waitid(os.P_PID, zombie.pid, os.WEXITED | os.WNOWAIT) # exited, left unreaped + try: + log = tmp_path / "exited.stderr.log" + log.write_text("worker: done\n", encoding="utf-8") + service = host.service(_job(tmp_path, [ANSWER]).family) + pattern = await agentic_host._teardown(_Exited(zombie.pid), log, service, None) # type: ignore[arg-type] + assert pattern is None and log.read_text() == "worker: done\n" + finally: + zombie.wait() + + class _Unending: """A worker whose wait() never returns, as if it survived its kill. From 207685f7c3b923757f079b9f4605cff84f4d7c1f Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 03:09:53 +0100 Subject: [PATCH 66/77] fix(benchmarks): a worker's open unit is booked even if its log cannot be published Teardown settled the open unit only after publishing the scrubbed log, so an OSError from the temp copy or os.replace (ENOSPC, EROFS) left the unit unbooked. The settle now runs in its own finally. On a failed publish, the original log is emptied, the partial temp copy is removed, and the error is re-raised. The test fills the "disk" after 10 bytes of the copy: the unit is booked worker_lost at 2x, no .tmp remains, and the log holds no key. Removing either the emptying or the cleanup fails it. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/host.py | 43 ++++++++++++++++++--------- tests/benchmarks/test_agentic_host.py | 34 +++++++++++++++++++++ 2 files changed, 63 insertions(+), 14 deletions(-) diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index 8cdcd03c..b8cb5db6 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -87,22 +87,37 @@ async def _teardown( proc: asyncio.subprocess.Process, log_path: Path, ledger: LedgerService, in_flight: str | None ) -> str | None: """Kill the worker, scrub its log and book its open unit; the log's key pattern, if any.""" - # The whole group, even after the worker exited: no descendant outlives it to write later. - # shortcut: reaches only this host's process tree; PR 4's container launcher must give the - # same guarantee, which removing the container does. - # ESRCH: the group is gone. EPERM: macOS's answer for a group that holds only zombies. - with suppress(ProcessLookupError, PermissionError): - os.killpg(proc.pid, signal.SIGKILL) - with suppress(TimeoutError): # a worker that never exits cannot hang the run - await asyncio.wait_for(proc.wait(), _EXIT_WAIT_S) - # On every exit, a raise or a cancel included: the leaked bytes never stay on disk. The - # scrubbed copy replaces the log, so a writer still holding it writes into an unlinked file. + try: + # The whole group, even after the worker exited: no descendant outlives it to write. + # shortcut: reaches only this host's process tree; PR 4's container launcher must give + # the same guarantee, which removing the container does. + # ESRCH: the group is gone. EPERM: macOS's answer for a group that holds only zombies. + with suppress(ProcessLookupError, PermissionError): + os.killpg(proc.pid, signal.SIGKILL) + with suppress(TimeoutError): # a worker that never exits cannot hang the run + await asyncio.wait_for(proc.wait(), _EXIT_WAIT_S) + 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 + 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 written, the log is emptied instead. + """ redacted, pattern = redact_key_shaped(log_path.read_bytes()) scrubbed = log_path.with_name(log_path.name + ".tmp") - scrubbed.write_bytes(redacted) - os.replace(scrubbed, log_path) - if in_flight is not None: # may have been billed: booked at twice its bound - await ledger.settle(in_flight, outcome="worker_lost", buckets=None) + try: + scrubbed.write_bytes(redacted) + os.replace(scrubbed, log_path) + except OSError: # a full or read-only disk, say + log_path.write_bytes(b"") + scrubbed.unlink(missing_ok=True) + raise return pattern diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index a0abb977..62359f11 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -827,6 +827,40 @@ async def test_a_worker_that_never_exits_cannot_hang_its_teardown( ] +async def test_a_failed_log_publish_still_settles_and_leaves_no_key( + host: Host, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> 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) + 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") + try: + with pytest.raises(OSError, match="No space left"): + await agentic_host._teardown(_Exited(group.pid), log, service, unit) # type: ignore[arg-type] + finally: + group.wait(timeout=5) + 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")) + ] + assert [path.name for path in tmp_path.glob("*.tmp")] == [] + assert "sk-ant-api03-" not in log.read_text() + + async def test_host_aborts_the_run_when_a_worker_frame_holds_a_key_shaped_string( host: Host, tmp_path: Path ) -> None: From 84a2cc875fcbec53913dfc23132b0301b8b264fc Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 03:18:02 +0100 Subject: [PATCH 67/77] fix(benchmarks): teardown kills an anchor's live group, never a reused id Codex's case: a worker starts a setsid descendant that holds the host's pipe, then exits and is reaped. The host reads on until its deadline, and the worker's pgid can be reused in that time, so killpg could hit an unrelated group. The host now starts a tiny anchor (python -c "signal.pause()") in a process group of its own, then starts the worker in the anchor's group (process_group=anchor.pid). The anchor lives until teardown, so the group id cannot be reused while the host may still signal it. Teardown kills the anchor's group, then waits for and reaps both the worker and the anchor, each within the 30 s bound. The EPERM/ESRCH suppression stays for an anchor that died early. If the worker fails to start, the anchor is killed and reaped at once. The anchor takes process_group=0, not start_new_session: setpgid refuses to join a group in another session (EPERM, checked on macOS). The shortcut comment adds the PR 4 requirement to signal only what the launcher holds. Tests: - A killpg spy records the target. Against the reaped worker's descendant case it saw a dead group before the fix; it now sees the anchor's live group, and calls through only for that anchor. - No anchor outlives its job, including a worker that never starts. The direct teardown tests give every fake process a pid of a throwaway process the test created, never 0, since os.killpg(0) is the caller's own group. _Unending.kill is gone (round 7 item 5). Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/host.py | 60 +++++++++---- tests/benchmarks/test_agentic_host.py | 124 +++++++++++++++++++++----- 2 files changed, 145 insertions(+), 39 deletions(-) diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index b8cb5db6..f3adc23d 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -40,6 +40,9 @@ _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 +#: Leads each worker's process group and lives until teardown, so the group id that teardown +#: kills is never reused meanwhile, even once the worker itself has exited and been reaped. +_ANCHOR = (sys.executable, "-c", "import signal; signal.pause()") @dataclass(frozen=True) @@ -84,18 +87,24 @@ def refuse_host_keys(environ: Mapping[str, str]) -> None: async def _teardown( - proc: asyncio.subprocess.Process, log_path: Path, ledger: LedgerService, in_flight: str | None + proc: asyncio.subprocess.Process, + anchor: asyncio.subprocess.Process, + log_path: Path, + ledger: LedgerService, + in_flight: str | None, ) -> str | None: - """Kill the worker, scrub its log and book its open unit; the log's key pattern, if any.""" + """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. + # The anchor's whole group, even after the worker exited: no descendant outlives it to + # write. The anchor is alive until here, 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. - # ESRCH: the group is gone. EPERM: macOS's answer for a group that holds only zombies. + # the same guarantee, which removing the container does, and signal only what it holds. + # ESRCH or EPERM (macOS, a group of zombies): the anchor died early, and its group too. with suppress(ProcessLookupError, PermissionError): - os.killpg(proc.pid, signal.SIGKILL) - with suppress(TimeoutError): # a worker that never exits cannot hang the run - await asyncio.wait_for(proc.wait(), _EXIT_WAIT_S) + os.killpg(anchor.pid, signal.SIGKILL) + for process in (proc, anchor): # reaped, so neither pid is signalled again + with suppress(TimeoutError): # a process that never exits cannot hang the run + await asyncio.wait_for(process.wait(), _EXIT_WAIT_S) 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 @@ -133,16 +142,29 @@ async def _supervise( ) -> None: argv, env = launcher.command(job) log_path = log_dir / f"{job.job_id}.stderr.log" - 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, - start_new_session=True, # its own process group, which teardown kills whole - ) + # A group of its own in this session: the worker cannot join a group of another session. + anchor = await asyncio.create_subprocess_exec( + *_ANCHOR, + stdin=asyncio.subprocess.DEVNULL, + stdout=asyncio.subprocess.DEVNULL, + stderr=asyncio.subprocess.DEVNULL, + process_group=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: + anchor.kill() + await anchor.wait() + raise assert proc.stdin is not None and proc.stdout is not None in_flight: str | None = None reported: set[tuple[str, int]] = set() @@ -232,7 +254,7 @@ async def _supervise( pass # the worker died or stalled; handled as a lost worker below finally: # Runs to its end even when a second abort cancels this task meanwhile; then re-raise. - teardown = asyncio.ensure_future(_teardown(proc, log_path, ledger, in_flight)) + teardown = asyncio.ensure_future(_teardown(proc, anchor, log_path, ledger, in_flight)) cancelled: asyncio.CancelledError | None = None while not teardown.done(): try: diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 62359f11..c1e9eea9 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -758,10 +758,102 @@ async def test_no_descendant_can_write_a_key_into_the_published_log( assert log.read_text() == "worker: started\n" +@pytest.fixture +def spawned(monkeypatch: pytest.MonkeyPatch) -> list[Any]: + """Every process the host spawns, in order.""" + real = asyncio.create_subprocess_exec + processes: list[Any] = [] + + async def spy(*args: Any, **kwargs: Any) -> Any: + process = await real(*args, **kwargs) + processes.append(process) + return process + + monkeypatch.setattr(agentic_host.asyncio, "create_subprocess_exec", spy) + return processes + + +async def test_teardown_kills_the_anchors_live_group_after_the_worker_is_reaped( + host: Host, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, spawned: list[Any] +) -> None: + # Codex's case: an escaped descendant holds the host's pipe, so the host reads on after + # the worker exited and was reaped. The group it then kills must still be the anchor's. + signals = tmp_path / "signals" + signals.mkdir() + holder = ( + "import os, sys, time\n" + "from pathlib import Path\n" + "signals = Path(sys.argv[1])\n" + "os.setsid()\n" + "(signals / 'escaped').touch()\n" + "deadline = time.monotonic() + 10\n" + "while not (signals / 'done').exists() and time.monotonic() < deadline:\n" + " time.sleep(0.01)\n" + ) + code = ( + "import os, subprocess, sys, time\n" + "from pathlib import Path\n" + "sys.stdin.buffer.read(int.from_bytes(sys.stdin.buffer.read(8), 'big'))\n" + f"signals = Path({str(signals)!r})\n" + "(signals / 'worker').write_text(f'{os.getpid()} {os.getpgid(0)}')\n" + "quiet = {'stdin': subprocess.DEVNULL, 'stderr': subprocess.DEVNULL} # keeps fd 1\n" + f"subprocess.Popen([sys.executable, '-c', {holder!r}, str(signals)], **quiet)\n" + "deadline = time.monotonic() + 10\n" + "while not (signals / 'escaped').exists():\n" + " if time.monotonic() > deadline:\n" + " sys.exit('worker: the holder never left the group')\n" + " time.sleep(0.01)\n" + "sys.exit(1)\n" + ) + real_killpg, calls = os.killpg, [] + + def killpg(pgid: int, sig: int) -> None: + worker_pid = int((signals / "worker").read_text().split()[0]) + calls.append((pgid, _alive(pgid), _alive(worker_pid))) + # Never a group this test did not see the host create and not yet reap. + if len(spawned) == 2 and pgid == spawned[0].pid and spawned[0].returncode is None: + real_killpg(pgid, sig) + + monkeypatch.setattr(os, "killpg", killpg) + monkeypatch.setattr(agentic_host, "_EXIT_WAIT_S", 0.5) # the held pipe delays wait() + job = replace(_job(tmp_path, [ANSWER]), caps=Caps(trajectory_s=0.2, model_call_timeout_s=0.3)) + try: + await host.run([job], launcher=KeyedLauncher(code, key="")) + finally: + (signals / "done").touch() + ((pgid, group_alive, worker_alive),) = calls + assert (group_alive, worker_alive) == (True, False), "a live group; the worker reaped" + anchor, worker = spawned + assert pgid == anchor.pid and (signals / "worker").read_text() == f"{worker.pid} {pgid}" + assert anchor.returncode == -signal.SIGKILL and worker.returncode is not None + + +async def test_no_anchor_outlives_its_job( + host: Host, tmp_path: Path, spawned: list[Any] +) -> None: + await host.run([_job(tmp_path, [ANSWER])]) + assert len(spawned) == 2 and all(p.returncode is not None for p in spawned) + + +class _Missing(LocalLauncher): + def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: + return [str(Path(job.family.raw["script"]).parent / "missing-worker")], {} + + +async def test_no_anchor_outlives_a_worker_that_never_started( + host: Host, tmp_path: Path, spawned: list[Any] +) -> None: + with pytest.raises(FileNotFoundError): + await host.run([_job(tmp_path, [ANSWER])], launcher=_Missing()) + assert len(spawned) == 1 and spawned[0].returncode is not None + + class _Exited: - """A worker that has exited but is not yet reaped: its group holds only a zombie.""" + """A worker or anchor that has exited: wait() returns at once. - returncode = None + Its pid is always a throwaway process the test created, never 0 (os.killpg(0) is the + caller's own group), so nothing else can be signalled through it, even by a bug. + """ def __init__(self, pid: int) -> None: self.pid = pid @@ -770,33 +862,23 @@ async def wait(self) -> int: return 0 -async def test_teardown_of_an_exited_worker_not_yet_reaped(host: Host, tmp_path: Path) -> None: - # macOS answers a group kill with EPERM when the group holds only a zombie. +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) os.waitid(os.P_PID, zombie.pid, os.WEXITED | os.WNOWAIT) # exited, left unreaped try: log = tmp_path / "exited.stderr.log" log.write_text("worker: done\n", encoding="utf-8") service = host.service(_job(tmp_path, [ANSWER]).family) - pattern = await agentic_host._teardown(_Exited(zombie.pid), log, service, None) # type: ignore[arg-type] + worker = anchor = _Exited(zombie.pid) + pattern = await agentic_host._teardown(worker, anchor, log, service, None) # type: ignore[arg-type] assert pattern is None and log.read_text() == "worker: done\n" finally: zombie.wait() -class _Unending: - """A worker whose wait() never returns, as if it survived its kill. - - Its pid leads a real process group of its own, so the group kill hits only that group. - """ - - returncode = None - - def __init__(self, pid: int) -> None: - self.pid = pid - - def kill(self) -> None: - pass +class _Unending(_Exited): + """A worker whose wait() never returns, as if it survived its kill.""" async def wait(self) -> int: await asyncio.Event().wait() @@ -818,7 +900,8 @@ async def test_a_worker_that_never_exits_cannot_hang_its_teardown( log = tmp_path / "never-exits.stderr.log" log.write_text("debug: sk-ant-api03-" + "z" * 90 + "\n", encoding="utf-8") async with asyncio.timeout(5): # the bound under test is 0.1 s - pattern = await agentic_host._teardown(_Unending(group.pid), log, service, unit) # type: ignore[arg-type] + worker, anchor = _Unending(group.pid), _Exited(group.pid) + pattern = await agentic_host._teardown(worker, anchor, log, service, unit) # type: ignore[arg-type] assert group.wait(timeout=5) == -signal.SIGKILL assert pattern is not None and log.read_text() == "debug: [redacted]\n" settles = [e for e in host.ledger.events("host-test") if e["event"] == "settle"] @@ -850,7 +933,8 @@ def full_disk(self: Path, data: bytes) -> int: log.write_text("debug: sk-ant-api03-" + "z" * 90 + "\n", encoding="utf-8") try: with pytest.raises(OSError, match="No space left"): - await agentic_host._teardown(_Exited(group.pid), log, service, unit) # type: ignore[arg-type] + worker = anchor = _Exited(group.pid) + await agentic_host._teardown(worker, anchor, log, service, unit) # type: ignore[arg-type] finally: group.wait(timeout=5) settles = [e for e in host.ledger.events("host-test") if e["event"] == "settle"] From d863eaa96c1306d94836acefcf7024cff8b0be32 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 03:20:01 +0100 Subject: [PATCH 68/77] fix(benchmarks): SIGTERM and SIGHUP tear an agentic run down like Ctrl-C Workers run in process groups of their own, so a signal sent to the host's group no longer reaches them, and SIGTERM ended the host without any teardown. That left the worker alive, its unit unbooked and no run summary. run.py now registers loop.add_signal_handler for SIGTERM and SIGHUP around run_jobs; each cancels the run task with a message naming the signal, so it takes the same teardown path as Ctrl-C. The test runs the host in a subprocess it creates and signals only that process. Its worker holds a unit and sleeps. After the signal, the worker is dead and reaped, the unit is settled worker_lost at 2x, and run-summary.json reports aborted with the signal's name. Before the fix, the worker outlived its host. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/run.py | 36 +++++++++--- tests/benchmarks/test_agentic_run.py | 85 ++++++++++++++++++++++++++++ 2 files changed, 113 insertions(+), 8 deletions(-) diff --git a/benchmarks/agentic/run.py b/benchmarks/agentic/run.py index 393c174b..4a359b5e 100644 --- a/benchmarks/agentic/run.py +++ b/benchmarks/agentic/run.py @@ -13,9 +13,10 @@ import json import os import random +import signal import sys from collections import Counter -from collections.abc import Mapping, Sequence +from collections.abc import Coroutine, Mapping, Sequence from dataclasses import dataclass, field, replace from datetime import UTC, date, datetime from decimal import Decimal @@ -92,6 +93,23 @@ class AgenticConfig: acknowledge_overrun: tuple[str, ...] = () +async def _until_signalled(run: Coroutine[Any, Any, None]) -> None: + """Await ``run``; SIGTERM or SIGHUP cancels it, so every worker is torn down as on Ctrl-C. + + Workers run in process groups of their own, so no signal sent to the host's group reaches + them: only the host's teardown can end them. + """ + task = asyncio.ensure_future(run) + loop = asyncio.get_running_loop() + for signum in (signal.SIGTERM, signal.SIGHUP): + loop.add_signal_handler(signum, task.cancel, f"signal {signum.name}") + try: + await task + finally: + for signum in (signal.SIGTERM, signal.SIGHUP): + loop.remove_signal_handler(signum) + + def cell_id(system_id: str, family_id: str, repeat: int) -> str: return f"{system_id}--{family_id}--r{repeat}" @@ -525,13 +543,15 @@ def write_outcome() -> None: 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( - run_jobs( - jobs, - launcher=launcher, - ledger=service, - on_message=collector.on_message, - log_dir=out / "logs", - cwd=_REPO_ROOT, + _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 diff --git a/tests/benchmarks/test_agentic_run.py b/tests/benchmarks/test_agentic_run.py index 31ea9bba..fb5dbc96 100644 --- a/tests/benchmarks/test_agentic_run.py +++ b/tests/benchmarks/test_agentic_run.py @@ -7,8 +7,12 @@ import hashlib import json +import os import random +import signal +import subprocess import sys +import time from datetime import date from decimal import Decimal from pathlib import Path @@ -299,6 +303,87 @@ def command(self, job: Any) -> tuple[list[str], dict[str, str]]: return [sys.executable, "-c", code], env +@pytest.mark.parametrize("signum", [signal.SIGTERM, signal.SIGHUP]) +def test_a_termination_signal_tears_the_run_down_like_ctrl_c( + tmp_path: Path, signum: signal.Signals +) -> None: + # The host runs in a subprocess this test creates, and only it is signalled. Its worker + # holds a unit, marks that it is ready, and sleeps; workers have process groups of their + # own, so only the host's teardown can end it. + ready = tmp_path / "worker.pid" + reserve = {"type": "reserve", "input_bound": 1000, "output_bound": 100, "kind": "model_call"} + worker = ( + "import json, os, sys, time\n" + "inp, out = sys.stdin.buffer, sys.stdout.buffer\n" + "inp.read(int.from_bytes(inp.read(8), 'big'))\n" + f"body = json.dumps({reserve!r}).encode()\n" + "out.write(len(body).to_bytes(8, 'big') + body)\n" + "out.flush()\n" + "inp.read(int.from_bytes(inp.read(8), 'big'))\n" + f"open({str(ready)!r}, 'w').write(str(os.getpid()))\n" + "time.sleep(20)\n" + ) + host_code = ( + "import sys\n" + "from pathlib import Path\n" + "from benchmarks.agentic.host import LocalLauncher\n" + "from benchmarks.agentic.run import AgenticConfig, run_agentic\n" + "class Launcher(LocalLauncher):\n" + " def command(self, job):\n" + f" return [sys.executable, '-c', {worker!r}], super().command(job)[1]\n" + "config = AgenticConfig(\n" + f" corpus_path=Path({str(SAMPLE_CORPUS)!r}),\n" + f" matrix_path=Path({str(FIX / 'model-matrix.yml')!r}),\n" + f" manifest_path=Path({str(COMMITTED_MANIFEST)!r}),\n" + f" prices_path=Path({str(FIX / 'prices.yml')!r}),\n" + f" ledger_dir=Path({str(tmp_path / 'ledger')!r}),\n" + f" out_dir=Path({str(tmp_path / 'run')!r}),\n" + " models=('scripted-anthropic',),\n" + " systems=('no-docs',),\n" + " questions=('SYN-EX-001',),\n" + " repeats=1,\n" + " seed=7,\n" + ")\n" + "run_agentic(config, launcher=Launcher())\n" + ) + host = subprocess.Popen( + [sys.executable, "-c", host_code], + cwd=REPO_ROOT, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + try: + deadline = time.monotonic() + 20 + while not ready.exists(): # bounded: a worker that never holds its unit fails loudly + assert host.poll() is None, "the host ended before its worker got ready" + assert time.monotonic() < deadline, "the worker never got ready" + time.sleep(0.01) + host.send_signal(signum) + host.wait(timeout=20) + finally: + if host.poll() is None: + host.kill() + host.wait() + pid = int(ready.read_text()) + deadline = time.monotonic() + 5 + while True: # the worker is dead, and its host reaped it + try: + os.kill(pid, 0) + except ProcessLookupError: + break + assert time.monotonic() < deadline, "the worker outlived its host" + time.sleep(0.01) + lines = (tmp_path / "ledger" / "anthropic.jsonl").read_text(encoding="utf-8").splitlines() + events = [json.loads(line) for line in lines] + assert [(e["event"], e.get("outcome")) for e in events] == [ + ("reserve", None), + ("settle", "worker_lost"), + ] + assert Decimal(events[1]["booked"]) == 2 * Decimal(events[0]["bound"]) + summary = json.loads((tmp_path / "run" / "run-summary.json").read_text()) + assert summary["status"] == "aborted" and signum.name in summary["abort_reason"] + + def test_a_rerun_that_never_ran_is_not_counted(tmp_path: Path) -> None: config = _config( tmp_path, From 07262cbd0a8583370268817c94fc51b478c320df Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 03:22:00 +0100 Subject: [PATCH 69/77] fix(benchmarks): an anchor ends with its host, even one killed outright A signal.pause() anchor outlived a host killed with SIGKILL forever: item 3's RED run left one behind. The anchor now reads its stdin, a pipe only the host holds, so it exits on EOF once the host is gone. In a normal teardown it is still killed with its group. Once the host is dead nothing signals the group, so an anchor that exits early cannot let a reused id be hit. The test kills a host subprocess outright with SIGKILL, once its worker holds a unit. The worker's process group, its anchor, must be gone within 5 s. Before the fix it was alive, and the test kills a leftover anchor itself. The signal test now shares the host helpers. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/host.py | 5 +- tests/benchmarks/test_agentic_run.py | 85 ++++++++++++++++++++-------- 2 files changed, 63 insertions(+), 27 deletions(-) diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index f3adc23d..30dee096 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -42,7 +42,8 @@ _EXIT_WAIT_S = 30.0 #: Leads each worker's process group and lives until teardown, so the group id that teardown #: kills is never reused meanwhile, even once the worker itself has exited and been reaped. -_ANCHOR = (sys.executable, "-c", "import signal; signal.pause()") +#: It reads its stdin, a pipe only the host holds, so it also ends with a host killed outright. +_ANCHOR = (sys.executable, "-c", "import sys; sys.stdin.buffer.read()") @dataclass(frozen=True) @@ -145,7 +146,7 @@ async def _supervise( # A group of its own in this session: the worker cannot join a group of another session. anchor = await asyncio.create_subprocess_exec( *_ANCHOR, - stdin=asyncio.subprocess.DEVNULL, + stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL, process_group=0, diff --git a/tests/benchmarks/test_agentic_run.py b/tests/benchmarks/test_agentic_run.py index fb5dbc96..22b6a598 100644 --- a/tests/benchmarks/test_agentic_run.py +++ b/tests/benchmarks/test_agentic_run.py @@ -303,25 +303,22 @@ def command(self, job: Any) -> tuple[list[str], dict[str, str]]: return [sys.executable, "-c", code], env -@pytest.mark.parametrize("signum", [signal.SIGTERM, signal.SIGHUP]) -def test_a_termination_signal_tears_the_run_down_like_ctrl_c( - tmp_path: Path, signum: signal.Signals -) -> None: - # The host runs in a subprocess this test creates, and only it is signalled. Its worker - # holds a unit, marks that it is ready, and sleeps; workers have process groups of their - # own, so only the host's teardown can end it. - ready = tmp_path / "worker.pid" +def _start_host(tmp_path: Path) -> tuple[subprocess.Popen[bytes], Path]: + """A host in a subprocess this test creates. Its one worker holds a unit, reports its pid + and process group, then waits until its host closes its stdin.""" + ready = tmp_path / "worker.ids" reserve = {"type": "reserve", "input_bound": 1000, "output_bound": 100, "kind": "model_call"} worker = ( - "import json, os, sys, time\n" + "import json, os, sys\n" "inp, out = sys.stdin.buffer, sys.stdout.buffer\n" "inp.read(int.from_bytes(inp.read(8), 'big'))\n" f"body = json.dumps({reserve!r}).encode()\n" "out.write(len(body).to_bytes(8, 'big') + body)\n" "out.flush()\n" "inp.read(int.from_bytes(inp.read(8), 'big'))\n" - f"open({str(ready)!r}, 'w').write(str(os.getpid()))\n" - "time.sleep(20)\n" + f"open({str(ready) + '.tmp'!r}, 'w').write(f'{{os.getpid()}} {{os.getpgid(0)}}')\n" + f"os.replace({str(ready) + '.tmp'!r}, {str(ready)!r})\n" + "inp.read()\n" ) host_code = ( "import sys\n" @@ -352,27 +349,48 @@ def test_a_termination_signal_tears_the_run_down_like_ctrl_c( stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) + return host, ready + + +def _when_ready(host: subprocess.Popen[bytes], ready: Path) -> tuple[int, int]: + """The worker's pid and process group (its anchor's pid), once it holds its unit.""" + deadline = time.monotonic() + 20 + while not ready.exists(): # bounded: a worker that never holds its unit fails loudly + assert host.poll() is None, "the host ended before its worker got ready" + assert time.monotonic() < deadline, "the worker never got ready" + time.sleep(0.01) + worker, group = map(int, ready.read_text().split()) + return worker, group + + +def _gone(pid: int) -> bool: + """Whether ``pid`` is gone within 5 s (reaped: an orphan's new parent reaps it at once).""" + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + try: + os.kill(pid, 0) + except ProcessLookupError: + return True + time.sleep(0.01) + return False + + +@pytest.mark.parametrize("signum", [signal.SIGTERM, signal.SIGHUP]) +def test_a_termination_signal_tears_the_run_down_like_ctrl_c( + tmp_path: Path, signum: signal.Signals +) -> None: + # Only the host is signalled. Workers have process groups of their own, so only the + # host's teardown can end its worker. + host, ready = _start_host(tmp_path) try: - deadline = time.monotonic() + 20 - while not ready.exists(): # bounded: a worker that never holds its unit fails loudly - assert host.poll() is None, "the host ended before its worker got ready" - assert time.monotonic() < deadline, "the worker never got ready" - time.sleep(0.01) + worker, _ = _when_ready(host, ready) host.send_signal(signum) host.wait(timeout=20) finally: if host.poll() is None: host.kill() host.wait() - pid = int(ready.read_text()) - deadline = time.monotonic() + 5 - while True: # the worker is dead, and its host reaped it - try: - os.kill(pid, 0) - except ProcessLookupError: - break - assert time.monotonic() < deadline, "the worker outlived its host" - time.sleep(0.01) + assert _gone(worker), "the worker outlived its host" lines = (tmp_path / "ledger" / "anthropic.jsonl").read_text(encoding="utf-8").splitlines() events = [json.loads(line) for line in lines] assert [(e["event"], e.get("outcome")) for e in events] == [ @@ -384,6 +402,23 @@ def test_a_termination_signal_tears_the_run_down_like_ctrl_c( assert summary["status"] == "aborted" and signum.name in summary["abort_reason"] +def test_no_anchor_outlives_a_host_killed_outright(tmp_path: Path) -> None: + # SIGKILL leaves no teardown: the anchor must end once its host's pipe closes. + host, ready = _start_host(tmp_path) + try: + _, anchor = _when_ready(host, ready) + host.kill() + host.wait(timeout=20) + finally: + if host.poll() is None: + host.kill() + host.wait() + gone = _gone(anchor) + if not gone: # alive throughout the wait, so still the anchor this test's host started + os.kill(anchor, signal.SIGKILL) + assert gone, "the anchor outlived its host" + + def test_a_rerun_that_never_ran_is_not_counted(tmp_path: Path) -> None: config = _config( tmp_path, From 65a863424517a1302232ee45979981fa7a194454 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 03:22:31 +0100 Subject: [PATCH 70/77] test(benchmarks): _alive treats a /proc entry gone mid-read as not alive On Linux a process can be reaped between os.kill(pid, 0) and the read of /proc//stat; the FileNotFoundError now means "not alive". Without /proc (macOS), a process that answers kill is alive. Co-Authored-By: Claude Opus 5.5 --- tests/benchmarks/test_agentic_host.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index c1e9eea9..4f91e74b 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -716,8 +716,12 @@ def _alive(pid: int) -> bool: os.kill(pid, 0) except ProcessLookupError: return False - stat = Path(f"/proc/{pid}/stat") # Linux: a zombie is dead, whoever has yet to reap it - return not (stat.exists() and stat.read_text().rsplit(")", 1)[1].split()[0] == "Z") + if not Path("/proc").is_dir(): # macOS: launchd reaps an orphan at once + return True + try: # Linux: a zombie is dead, whoever has yet to reap it + return Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[0] != "Z" + except FileNotFoundError: # reaped between the two reads + return False async def test_no_descendant_can_write_a_key_into_the_published_log( From 783ca3a121ca71f5944d83d708872810a299518f Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 03:49:03 +0100 Subject: [PATCH 71/77] fix(benchmarks): a failed log publish unlinks the log instead of truncating it Truncation left the published path open to a writer that kept its descriptor: its next write landed back in the log. On a failed publish the log is now unlinked, so such a writer writes into an unlinked file. The temp copy is still removed, and the unit is still settled once. The test keeps a writer open through the teardown and writes a key after the failed publish. Afterwards the published path either does not exist or holds no key; before the fix it held the key. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/host.py | 4 ++-- tests/benchmarks/test_agentic_host.py | 5 ++++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index 30dee096..8771e071 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -117,7 +117,7 @@ def _publish_scrubbed(log_path: Path) -> str | None: 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 written, the log is emptied instead. + 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") @@ -125,7 +125,7 @@ def _publish_scrubbed(log_path: Path) -> str | None: scrubbed.write_bytes(redacted) os.replace(scrubbed, log_path) except OSError: # a full or read-only disk, say - log_path.write_bytes(b"") + log_path.unlink(missing_ok=True) scrubbed.unlink(missing_ok=True) raise return pattern diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 4f91e74b..787c09e6 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -935,18 +935,21 @@ def full_disk(self: Path, data: bytes) -> int: ) 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 try: with pytest.raises(OSError, match="No space left"): worker = anchor = _Exited(group.pid) await agentic_host._teardown(worker, anchor, log, service, unit) # type: ignore[arg-type] + retained.write(b"late: sk-ant-api03-" + b"z" * 90 + b"\n") finally: + retained.close() group.wait(timeout=5) 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")) ] assert [path.name for path in tmp_path.glob("*.tmp")] == [] - assert "sk-ant-api03-" not in log.read_text() + assert not log.exists() or "sk-ant-api03-" not in log.read_text() async def test_host_aborts_the_run_when_a_worker_frame_holds_a_key_shaped_string( From c95eed80b98ca53141ff32b0de19f7ae1e2e573b Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 03:54:04 +0100 Subject: [PATCH 72/77] fix(benchmarks): an anchor reserves its group id until the final group kill The round-7 anchor ran under asyncio, whose child watcher reaps it the moment it dies. An anchor killed from outside was reaped at once, so its pid, the group id, could be reused before teardown signalled it. The anchor is now plain subprocess.Popen(["cat"], process_group=0), with a stdin pipe only the host holds. No child watcher reaps it, and the host never polls or waits on it before the final killpg. Even an anchor killed early stays a zombie, holding its pid and group id until teardown. After the kill, the host closes its stdin and reaps it in a thread, within the 30 s bound. The EPERM/ESRCH suppression stays: a group that holds only the zombie anchor answers EPERM on macOS. If the worker fails to start, the same kill-and-reap runs and its errors are suppressed, so the real start error reaches the summary. The shortcut comment notes that cat must be on PATH: it is on the ubuntu-latest and macos-latest runners CI uses, and PR 4's worker image must provide it. The tests now find the anchor's handle among the Popen objects the run creates (asyncio's own included). A killpg spy passes a kill on only for an unreaped child of the test process, checked with waitid(WNOHANG | WNOWAIT), whose pid cannot have been reused. - New, Codex's case: the test kills the anchor through its handle, the worker exits and is reaped, and an escaped descendant holds the pipe. At teardown the target is the anchor's pid, still a zombie. Before the fix it was already reaped. A mutation that polls the anchor before the kill fails the test. - The live-group and no-anchor-outlives tests now use the same handles. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/host.py | 77 +++++++++----- tests/benchmarks/test_agentic_host.py | 144 ++++++++++++++++++-------- 2 files changed, 154 insertions(+), 67 deletions(-) diff --git a/benchmarks/agentic/host.py b/benchmarks/agentic/host.py index 8771e071..d9a9c477 100644 --- a/benchmarks/agentic/host.py +++ b/benchmarks/agentic/host.py @@ -12,6 +12,7 @@ import json import os import signal +import subprocess import sys from collections.abc import Awaitable, Callable, Mapping, Sequence from contextlib import suppress @@ -40,10 +41,6 @@ _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 -#: Leads each worker's process group and lives until teardown, so the group id that teardown -#: kills is never reused meanwhile, even once the worker itself has exited and been reaped. -#: It reads its stdin, a pipe only the host holds, so it also ends with a host killed outright. -_ANCHOR = (sys.executable, "-c", "import sys; sys.stdin.buffer.read()") @dataclass(frozen=True) @@ -87,25 +84,60 @@ def refuse_host_keys(environ: Mapping[str, str]) -> None: ) +def _start_anchor() -> subprocess.Popen[bytes]: + """The leader of a worker's process group, in a group of its own in this session. + + Plain Popen, not asyncio: no child watcher ever reaps it, and nothing here waits on it + before the final group kill. So even an anchor killed from outside stays a zombie, and + 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 + return subprocess.Popen( + ["cat"], + stdin=subprocess.PIPE, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + process_group=0, # a worker cannot join a group of another session + ) + + +def _kill_group(anchor: subprocess.Popen[bytes]) -> None: + """Kill the anchor's whole group: the worker and every descendant still in it. + + 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. + # ESRCH, or EPERM (macOS, when the group holds only zombies, the anchor included). + with suppress(ProcessLookupError, PermissionError): + os.killpg(anchor.pid, signal.SIGKILL) + + +async def _reap(anchor: subprocess.Popen[bytes]) -> None: + """After the group kill only: close the anchor's stdin and reap it, within the bound.""" + if anchor.stdin is not None: + anchor.stdin.close() + with suppress(subprocess.TimeoutExpired): # an anchor that never exits cannot hang the run + await asyncio.to_thread(anchor.wait, _EXIT_WAIT_S) + + async def _teardown( proc: asyncio.subprocess.Process, - anchor: asyncio.subprocess.Process, + 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 anchor's whole group, even after the worker exited: no descendant outlives it to - # write. The anchor is alive until here, 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. - # ESRCH or EPERM (macOS, a group of zombies): the anchor died early, and its group too. - with suppress(ProcessLookupError, PermissionError): - os.killpg(anchor.pid, signal.SIGKILL) - for process in (proc, anchor): # reaped, so neither pid is signalled again - with suppress(TimeoutError): # a process that never exits cannot hang the run - await asyncio.wait_for(process.wait(), _EXIT_WAIT_S) + # The whole group, even after the worker exited: no descendant outlives it to write. + try: + _kill_group(anchor) + with suppress(TimeoutError): # a worker that never exits cannot hang the run + 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 @@ -143,14 +175,7 @@ async def _supervise( ) -> None: argv, env = launcher.command(job) log_path = log_dir / f"{job.job_id}.stderr.log" - # A group of its own in this session: the worker cannot join a group of another session. - anchor = await asyncio.create_subprocess_exec( - *_ANCHOR, - stdin=asyncio.subprocess.PIPE, - stdout=asyncio.subprocess.DEVNULL, - stderr=asyncio.subprocess.DEVNULL, - process_group=0, - ) + anchor = _start_anchor() try: with log_path.open("wb") as log: proc = await asyncio.create_subprocess_exec( @@ -162,9 +187,9 @@ async def _supervise( stderr=log, process_group=anchor.pid, # the anchor's group, which teardown kills whole ) - except BaseException: - anchor.kill() - await anchor.wait() + except BaseException: # the start error, never a kill error, reaches the summary + _kill_group(anchor) + await _reap(anchor) raise assert proc.stdin is not None and proc.stdout is not None in_flight: str | None = None diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 787c09e6..36812ee8 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -763,27 +763,31 @@ async def test_no_descendant_can_write_a_key_into_the_published_log( @pytest.fixture -def spawned(monkeypatch: pytest.MonkeyPatch) -> list[Any]: - """Every process the host spawns, in order.""" - real = asyncio.create_subprocess_exec - processes: list[Any] = [] +def popens(monkeypatch: pytest.MonkeyPatch) -> list[subprocess.Popen[bytes]]: + """Every subprocess.Popen started during the test, in order, asyncio's own included.""" + created: list[subprocess.Popen[bytes]] = [] - async def spy(*args: Any, **kwargs: Any) -> Any: - process = await real(*args, **kwargs) - processes.append(process) - return process + class Recorded(subprocess.Popen): # type: ignore[type-arg] + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + created.append(self) - monkeypatch.setattr(agentic_host.asyncio, "create_subprocess_exec", spy) - return processes + monkeypatch.setattr(subprocess, "Popen", Recorded) + return created -async def test_teardown_kills_the_anchors_live_group_after_the_worker_is_reaped( - host: Host, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, spawned: list[Any] -) -> None: - # Codex's case: an escaped descendant holds the host's pipe, so the host reads on after - # the worker exited and was reaped. The group it then kills must still be the anchor's. - signals = tmp_path / "signals" - signals.mkdir() +def _child_state(pid: int) -> str: + """'running', 'zombie' or 'reaped', for a child of this process; nothing is reaped here.""" + try: + exited = os.waitid(os.P_PID, pid, os.WEXITED | os.WNOHANG | os.WNOWAIT) + except ChildProcessError: + return "reaped" + return "running" if exited is None else "zombie" + + +def _holding_worker(signals: Path, *, exit_after: str | None = None) -> str: + """A worker that reports its pid and group, starts a descendant that leaves the group but + keeps the host's pipe (fd 1), waits for ``exit_after`` if given, then exits.""" holder = ( "import os, sys, time\n" "from pathlib import Path\n" @@ -794,49 +798,107 @@ async def test_teardown_kills_the_anchors_live_group_after_the_worker_is_reaped( "while not (signals / 'done').exists() and time.monotonic() < deadline:\n" " time.sleep(0.01)\n" ) - code = ( + wait_for = [] if exit_after is None else ["escaped", exit_after] + return ( "import os, subprocess, sys, time\n" "from pathlib import Path\n" "sys.stdin.buffer.read(int.from_bytes(sys.stdin.buffer.read(8), 'big'))\n" f"signals = Path({str(signals)!r})\n" - "(signals / 'worker').write_text(f'{os.getpid()} {os.getpgid(0)}')\n" "quiet = {'stdin': subprocess.DEVNULL, 'stderr': subprocess.DEVNULL} # keeps fd 1\n" f"subprocess.Popen([sys.executable, '-c', {holder!r}, str(signals)], **quiet)\n" - "deadline = time.monotonic() + 10\n" - "while not (signals / 'escaped').exists():\n" - " if time.monotonic() > deadline:\n" - " sys.exit('worker: the holder never left the group')\n" - " time.sleep(0.01)\n" + "(signals / 'ids.tmp').write_text(f'{os.getpid()} {os.getpgid(0)}')\n" + "os.replace(signals / 'ids.tmp', signals / 'ids')\n" + f"for name in {wait_for or ['escaped']!r}:\n" + " deadline = time.monotonic() + 10\n" + " while not (signals / name).exists():\n" + " if time.monotonic() > deadline:\n" + " sys.exit('worker: no ' + name)\n" + " time.sleep(0.01)\n" "sys.exit(1)\n" ) + + +def _guarded_killpg( + monkeypatch: pytest.MonkeyPatch, signals: Path +) -> list[tuple[int, str, str]]: + """Record each group kill as (pgid, its leader's state, the worker's state). It is passed + on only for an unreaped child of this process, whose pid cannot have been reused.""" real_killpg, calls = os.killpg, [] def killpg(pgid: int, sig: int) -> None: - worker_pid = int((signals / "worker").read_text().split()[0]) - calls.append((pgid, _alive(pgid), _alive(worker_pid))) - # Never a group this test did not see the host create and not yet reap. - if len(spawned) == 2 and pgid == spawned[0].pid and spawned[0].returncode is None: + worker = int((signals / "ids").read_text().split()[0]) + state = _child_state(pgid) + calls.append((pgid, state, _child_state(worker))) + if pgid > 0 and state != "reaped": real_killpg(pgid, sig) monkeypatch.setattr(os, "killpg", killpg) monkeypatch.setattr(agentic_host, "_EXIT_WAIT_S", 0.5) # the held pipe delays wait() + return calls + + +async def test_teardown_kills_the_anchors_live_group_after_the_worker_is_reaped( + host: Host, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + popens: list[subprocess.Popen[bytes]], +) -> None: + # Codex's case: an escaped descendant holds the host's pipe, so the host reads on after + # the worker exited and was reaped. The group it then kills must still be the anchor's. + signals = tmp_path / "signals" + signals.mkdir() + calls = _guarded_killpg(monkeypatch, signals) job = replace(_job(tmp_path, [ANSWER]), caps=Caps(trajectory_s=0.2, model_call_timeout_s=0.3)) try: - await host.run([job], launcher=KeyedLauncher(code, key="")) + await host.run([job], launcher=KeyedLauncher(_holding_worker(signals), key="")) + finally: + (signals / "done").touch() + worker, group = map(int, (signals / "ids").read_text().split()) + assert calls == [(group, "running", "reaped")], "the anchor's live group; the worker reaped" + (anchor,) = [p for p in popens if p.pid == group] + assert anchor.returncode == -signal.SIGKILL and worker != group + + +async def test_an_anchor_killed_early_keeps_its_group_id_until_teardown( + host: Host, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + popens: list[subprocess.Popen[bytes]], +) -> None: + # Codex's case: the anchor dies early (the test kills the anchor its host started, through + # its handle), the worker exits and is reaped, and an escaped descendant holds the pipe. + # Unreaped, the anchor still reserves its pid and group id when teardown kills the group. + signals = tmp_path / "signals" + signals.mkdir() + calls = _guarded_killpg(monkeypatch, signals) + code = _holding_worker(signals, exit_after="anchor-killed") + job = replace(_job(tmp_path, [ANSWER]), caps=Caps(trajectory_s=1.0, model_call_timeout_s=0.5)) + run = asyncio.create_task(host.run([job], launcher=KeyedLauncher(code, key=""))) + try: + async with asyncio.timeout(10): # bounded: a missed signal fails loudly + while not (signals / "ids").exists(): + await asyncio.sleep(0.01) + _, group = map(int, (signals / "ids").read_text().split()) + (anchor,) = [p for p in popens if p.pid == group] + anchor.send_signal(signal.SIGKILL) + while _child_state(group) == "running": + await asyncio.sleep(0.01) + (signals / "anchor-killed").touch() + await asyncio.wait_for(run, 20) finally: (signals / "done").touch() - ((pgid, group_alive, worker_alive),) = calls - assert (group_alive, worker_alive) == (True, False), "a live group; the worker reaped" - anchor, worker = spawned - assert pgid == anchor.pid and (signals / "worker").read_text() == f"{worker.pid} {pgid}" - assert anchor.returncode == -signal.SIGKILL and worker.returncode is not None + if not run.done(): + run.cancel() + await asyncio.gather(run, return_exceptions=True) + assert calls == [(group, "zombie", "reaped")], "an unreaped anchor; the worker reaped" + assert anchor.returncode == -signal.SIGKILL # reaped by the teardown, after its kill async def test_no_anchor_outlives_its_job( - host: Host, tmp_path: Path, spawned: list[Any] + host: Host, tmp_path: Path, popens: list[subprocess.Popen[bytes]] ) -> None: await host.run([_job(tmp_path, [ANSWER])]) - assert len(spawned) == 2 and all(p.returncode is not None for p in spawned) + assert len(popens) == 2 and all(p.returncode is not None for p in popens) class _Missing(LocalLauncher): @@ -845,11 +907,11 @@ def command(self, job: WorkerJob) -> tuple[list[str], dict[str, str]]: async def test_no_anchor_outlives_a_worker_that_never_started( - host: Host, tmp_path: Path, spawned: list[Any] + host: Host, tmp_path: Path, popens: list[subprocess.Popen[bytes]] ) -> None: with pytest.raises(FileNotFoundError): await host.run([_job(tmp_path, [ANSWER])], launcher=_Missing()) - assert len(spawned) == 1 and spawned[0].returncode is not None + assert len(popens) == 1 and popens[0].returncode is not None class _Exited: @@ -874,7 +936,7 @@ async def test_teardown_of_an_anchor_that_died_early(host: Host, tmp_path: Path) log = tmp_path / "exited.stderr.log" log.write_text("worker: done\n", encoding="utf-8") service = host.service(_job(tmp_path, [ANSWER]).family) - worker = anchor = _Exited(zombie.pid) + worker, anchor = _Exited(zombie.pid), zombie # the anchor died early pattern = await agentic_host._teardown(worker, anchor, log, service, None) # type: ignore[arg-type] assert pattern is None and log.read_text() == "worker: done\n" finally: @@ -904,7 +966,7 @@ async def test_a_worker_that_never_exits_cannot_hang_its_teardown( log = tmp_path / "never-exits.stderr.log" log.write_text("debug: sk-ant-api03-" + "z" * 90 + "\n", encoding="utf-8") async with asyncio.timeout(5): # the bound under test is 0.1 s - worker, anchor = _Unending(group.pid), _Exited(group.pid) + worker, anchor = _Unending(group.pid), group pattern = await agentic_host._teardown(worker, anchor, log, service, unit) # type: ignore[arg-type] assert group.wait(timeout=5) == -signal.SIGKILL assert pattern is not None and log.read_text() == "debug: [redacted]\n" @@ -938,7 +1000,7 @@ def full_disk(self: Path, data: bytes) -> int: retained = log.open("ab") # a writer that kept its descriptor through the teardown try: with pytest.raises(OSError, match="No space left"): - worker = anchor = _Exited(group.pid) + worker, anchor = _Exited(group.pid), group await agentic_host._teardown(worker, anchor, log, service, unit) # type: ignore[arg-type] retained.write(b"late: sk-ant-api03-" + b"z" * 90 + b"\n") finally: From 40481a11357cff184bc77ca3030255a250869ac9 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 03:55:31 +0100 Subject: [PATCH 73/77] test(benchmarks): the host-death test cleans up by handle only and counts a zombie as gone The killed-outright test killed a leftover anchor by its raw pid, which the test never held a handle to. That fallback is gone: the test cleans up only through the host Popen it created, and the failure names the pid instead. _gone now uses _alive, so a Linux zombie counts as exited. Co-Authored-By: Claude Opus 5.5 --- tests/benchmarks/test_agentic_run.py | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/tests/benchmarks/test_agentic_run.py b/tests/benchmarks/test_agentic_run.py index 22b6a598..841d4883 100644 --- a/tests/benchmarks/test_agentic_run.py +++ b/tests/benchmarks/test_agentic_run.py @@ -7,7 +7,6 @@ import hashlib import json -import os import random import signal import subprocess @@ -41,6 +40,7 @@ from benchmarks.report import generate_report from benchmarks.runner import BenchmarkValidationError, _load_questions, _load_yaml_mapping from benchmarks.scoring import score_run +from tests.benchmarks.test_agentic_host import _alive from tests.test_mcp_get_docs_cache_smoke import _create_contentful_json_index from tests.test_stdio_smoke import _isolated_cache_env @@ -364,15 +364,13 @@ def _when_ready(host: subprocess.Popen[bytes], ready: Path) -> tuple[int, int]: def _gone(pid: int) -> bool: - """Whether ``pid`` is gone within 5 s (reaped: an orphan's new parent reaps it at once).""" + """Whether ``pid`` has exited within 5 s; a zombie has, whoever has yet to reap it.""" deadline = time.monotonic() + 5 - while time.monotonic() < deadline: - try: - os.kill(pid, 0) - except ProcessLookupError: - return True + while _alive(pid): + if time.monotonic() > deadline: + return False time.sleep(0.01) - return False + return True @pytest.mark.parametrize("signum", [signal.SIGTERM, signal.SIGHUP]) @@ -413,10 +411,8 @@ def test_no_anchor_outlives_a_host_killed_outright(tmp_path: Path) -> None: if host.poll() is None: host.kill() host.wait() - gone = _gone(anchor) - if not gone: # alive throughout the wait, so still the anchor this test's host started - os.kill(anchor, signal.SIGKILL) - assert gone, "the anchor outlived its host" + # No cleanup by raw pid: the test holds no handle to its host's anchor. + assert _gone(anchor), f"the anchor (pid {anchor}) outlived its host" def test_a_rerun_that_never_ran_is_not_counted(tmp_path: Path) -> None: From 7246c4b9f2931bd4dcdfa40a115567daefea5c36 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 03:57:13 +0100 Subject: [PATCH 74/77] fix(benchmarks): signal handlers respect nohup, other threads and prior handlers Round 7's handlers overrode an ignored SIGHUP, so a nohup run was cancelled when the terminal closed. They also aborted any run outside the main thread (set_wakeup_fd), and left SIG_DFL behind on removal. Now: - a handler is installed only where signal.getsignal() is not SIG_IGN; - a RuntimeError, NotImplementedError or ValueError at registration means the run goes on without handlers; - removal restores the disposition each handler replaced, for those that were installed only. Tests: - A host started with SIGHUP ignored survives SIGHUP. It must not exit within a 1 s window, then ends on SIGTERM with its worker torn down. The test signals only the host subprocess it created. - run_agentic called through a ThreadPoolExecutor completes a scripted run. - After a run, a prior Python handler for SIGTERM and an ignored SIGHUP are both as before. All three failed before the fix. Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/run.py | 21 +++++++--- tests/benchmarks/test_agentic_run.py | 63 ++++++++++++++++++++++++++-- 2 files changed, 75 insertions(+), 9 deletions(-) diff --git a/benchmarks/agentic/run.py b/benchmarks/agentic/run.py index 4a359b5e..436c6fe7 100644 --- a/benchmarks/agentic/run.py +++ b/benchmarks/agentic/run.py @@ -97,17 +97,28 @@ async def _until_signalled(run: Coroutine[Any, Any, None]) -> None: """Await ``run``; SIGTERM or SIGHUP cancels it, so every worker is torn down as on Ctrl-C. Workers run in process groups of their own, so no signal sent to the host's group reaches - them: only the host's teardown can end them. + them: only the host's teardown can end them. An ignored signal stays ignored, a thread + that cannot take signals runs without the handlers, and each disposition the handlers + replaced is restored afterwards. """ task = asyncio.ensure_future(run) loop = asyncio.get_running_loop() - for signum in (signal.SIGTERM, signal.SIGHUP): - loop.add_signal_handler(signum, task.cancel, f"signal {signum.name}") + installed: list[tuple[signal.Signals, Any]] = [] # each with the disposition it replaced + try: + for signum in (signal.SIGTERM, signal.SIGHUP): + previous = signal.getsignal(signum) + if previous is signal.SIG_IGN: # as under nohup: it stays ignored + continue + loop.add_signal_handler(signum, task.cancel, f"signal {signum.name}") + installed.append((signum, previous)) + except (RuntimeError, NotImplementedError, ValueError): + pass # not the main thread, or a loop without signal support: run without handlers try: await task finally: - for signum in (signal.SIGTERM, signal.SIGHUP): - loop.remove_signal_handler(signum) + for signum, previous in installed: + loop.remove_signal_handler(signum) # leaves SIG_DFL behind + signal.signal(signum, signal.SIG_DFL if previous is None else previous) def cell_id(system_id: str, family_id: str, repeat: int) -> str: diff --git a/tests/benchmarks/test_agentic_run.py b/tests/benchmarks/test_agentic_run.py index 841d4883..fdd47978 100644 --- a/tests/benchmarks/test_agentic_run.py +++ b/tests/benchmarks/test_agentic_run.py @@ -12,6 +12,7 @@ import subprocess import sys import time +from concurrent.futures import ThreadPoolExecutor from datetime import date from decimal import Decimal from pathlib import Path @@ -303,9 +304,9 @@ def command(self, job: Any) -> tuple[list[str], dict[str, str]]: return [sys.executable, "-c", code], env -def _start_host(tmp_path: Path) -> tuple[subprocess.Popen[bytes], Path]: - """A host in a subprocess this test creates. Its one worker holds a unit, reports its pid - and process group, then waits until its host closes its stdin.""" +def _start_host(tmp_path: Path, prelude: str = "") -> tuple[subprocess.Popen[bytes], Path]: + """A host in a subprocess this test creates, running ``prelude`` first. Its one worker + holds a unit, reports its pid and process group, then waits until its host closes stdin.""" ready = tmp_path / "worker.ids" reserve = {"type": "reserve", "input_bound": 1000, "output_bound": 100, "kind": "model_call"} worker = ( @@ -321,7 +322,7 @@ def _start_host(tmp_path: Path) -> tuple[subprocess.Popen[bytes], Path]: "inp.read()\n" ) host_code = ( - "import sys\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" @@ -415,6 +416,60 @@ def test_no_anchor_outlives_a_host_killed_outright(tmp_path: Path) -> None: assert _gone(anchor), f"the anchor (pid {anchor}) outlived its host" +def test_a_host_started_with_sighup_ignored_survives_sighup(tmp_path: Path) -> None: + # As under nohup. Only the host is signalled; it must ignore SIGHUP, then end on SIGTERM. + ignore = "import signal\nsignal.signal(signal.SIGHUP, signal.SIG_IGN)\n" + host, ready = _start_host(tmp_path, prelude=ignore) + try: + worker, _ = _when_ready(host, ready) + host.send_signal(signal.SIGHUP) + with pytest.raises(subprocess.TimeoutExpired): # 1 s for an effect that must not come + host.wait(timeout=1) + host.send_signal(signal.SIGTERM) + host.wait(timeout=20) + finally: + if host.poll() is None: + host.kill() + host.wait() + assert _gone(worker), "the worker outlived its host" + summary = json.loads((tmp_path / "run" / "run-summary.json").read_text()) + assert summary["status"] == "aborted" and "SIGTERM" in summary["abort_reason"] + + +def _scripted_config(tmp_path: Path) -> AgenticConfig: + return _config( + tmp_path, + models=("scripted-anthropic",), + systems=("no-docs",), + questions=("SYN-EX-001",), + repeats=1, + ) + + +def test_run_agentic_completes_off_the_main_thread(tmp_path: Path) -> None: + # No signal handler can be installed off the main thread: the run goes on without one. + with ThreadPoolExecutor(1) as pool: + summary = pool.submit(run_agentic, _scripted_config(tmp_path)).result(timeout=60) + assert summary["status"] == "completed" and summary["succeeded_cells"] == 1 + + +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") + + saved = {signum: signal.getsignal(signum) for signum in (signal.SIGTERM, signal.SIGHUP)} + try: + signal.signal(signal.SIGTERM, previous) + signal.signal(signal.SIGHUP, signal.SIG_IGN) + summary = run_agentic(_scripted_config(tmp_path)) + after = {signum: signal.getsignal(signum) for signum in saved} + finally: + for signum, handler in saved.items(): + signal.signal(signum, handler) + assert summary["status"] == "completed" + assert after == {signal.SIGTERM: previous, signal.SIGHUP: signal.SIG_IGN} + + def test_a_rerun_that_never_ran_is_not_counted(tmp_path: Path) -> None: config = _config( tmp_path, From f945f98e383487405837f7e9b8bedcd18b4aaffc Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 04:09:59 +0100 Subject: [PATCH 75/77] test(benchmarks): portable child-state checks and a version-proof second-abort order CI on 7246c4b failed on 5 of 6 test jobs. Two causes: - os.waitid does not exist on macOS before Python 3.13. _child_state now asks ps for the pid's parent and state. A pid whose parent is not the test process counts as reaped, so a reused pid is never taken for the child. The anchor-died-early test waits for its throwaway child's zombie state through the same check, bounded. Production code never used waitid. - The second-abort test kept A inside its teardown by having a grandchild hold A's pipes, relying on asyncio's Process.wait() to wait for pipe EOF. It timed out on 3.13.18 and 3.14.10 (Linux and macOS) but passed on 3.12.16 and on the local 3.13.10 and 3.14.5. So the newer patch releases' Process.wait() appears to return at process exit: A's teardown ended before B's abort, and the test's cancelling() check rightly failed. Inferred from that version split; the newer CPython source was not checked. The test now holds A in its teardown with A itself. A leaves a sentinel child in its process group, leaves the group with setsid, then leaks. The group kill takes only the sentinel and the anchor, so teardown waits for A's own exit, which no Python version cuts short. A sees its sentinel die (its teardown has begun), and only then signals B to leak. Every step waits for a file or a child's exit within a bound. It passed 10 runs locally; with the shield removed it still fails. Co-Authored-By: Claude Opus 5.5 --- tests/benchmarks/test_agentic_host.py | 84 +++++++++++++-------------- 1 file changed, 39 insertions(+), 45 deletions(-) diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 36812ee8..05f8fdb5 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -599,28 +599,6 @@ async def test_every_worker_log_is_scrubbed_when_a_frame_leak_aborts_the_run( assert log.read_text() == "debug: [redacted]\n" -# Holds A's pipes, so A's teardown waits on it; it leaves A's process group first, so the -# group kill spares it. Marks when A is killed, which happens only in A's teardown, then exits -# once the test releases it. Each wait is bounded and fails loudly. -_GRANDCHILD = ( - "import os, sys, time\n" - "from pathlib import Path\n" - "parent, entered, release = int(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3])\n" - "os.setsid()\n" - "(entered.parent / 'escaped').touch()\n" - "deadline = time.monotonic() + 10\n" - "while os.getppid() == parent:\n" - " if time.monotonic() > deadline:\n" - " sys.exit('grandchild: A was never killed')\n" - " time.sleep(0.01)\n" - "entered.touch()\n" - "while not release.exists():\n" - " if time.monotonic() > deadline + 10:\n" - " sys.exit('grandchild: never released')\n" - " time.sleep(0.01)\n" -) - - def _supervisor(job_id: str) -> asyncio.Task[Any] | None: """The running supervisor task of ``job_id``, found by its coroutine's frame.""" for task in asyncio.all_tasks(): @@ -634,9 +612,13 @@ def _supervisor(job_id: str) -> asyncio.Task[Any] | None: async def test_a_teardown_cancelled_by_a_second_abort_still_scrubs_and_settles( host: Host, tmp_path: Path ) -> None: - # A holds a unit, then leaks a key; its teardown waits on a grandchild holding its pipes. - # Only then does B leak, and B's abort cancels A mid-teardown. If A's teardown ends before - # that, A is never cancelled and the bounded wait fails. + # A holds a unit, leaves its process group (as a misbehaving worker may), then leaks a key. + # The group kill then takes only A's sentinel, a child A left in the group, and A's + # teardown waits for A itself to exit. A sees its sentinel die, so its teardown has begun, + # and only then does B leak; B's abort cancels A mid-teardown. If A's teardown ended first, + # A would never be cancelled and the bounded wait would fail. Every step waits for a + # signal (a file, or a child's exit) within a bound: no step relies on timing, on how + # asyncio's Process.wait() treats pipes, or on the platform's child watcher. leaked = "sk-ant-api03-" + "z" * 90 entered, release = tmp_path / "a-in-teardown", tmp_path / "release" code = ( @@ -652,24 +634,28 @@ async def test_a_teardown_cancelled_by_a_second_abort_still_scrubs_and_settles( "job = read()\n" f"sys.stderr.write('debug: {leaked}\\n')\n" "sys.stderr.flush()\n" - "if job['job_id'] == 'a':\n" - f" send({_reserve_frame(1024)!r})\n" - " read()\n" - f" signals = [str(os.getpid()), {str(entered)!r}, {str(release)!r}]\n" - f" subprocess.Popen([sys.executable, '-c', {_GRANDCHILD!r}, *signals])\n" + f"leak = {{'type': 'system_info', 'note': '{leaked}'}}\n" + "def until(done, failure):\n" " deadline = time.monotonic() + 10\n" - f" while not Path({str(tmp_path / 'escaped')!r}).exists():\n" + " while not done():\n" " if time.monotonic() > deadline:\n" - " sys.exit('A: the grandchild never left the group')\n" + " sys.exit(failure)\n" " time.sleep(0.01)\n" + "if job['job_id'] == 'a':\n" + f" send({_reserve_frame(1024)!r})\n" + " read()\n" + " quiet = {'stdin': subprocess.DEVNULL, 'stdout': subprocess.DEVNULL}\n" + " sentinel = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)']," + " **quiet)\n" + " os.setsid()\n" + " send(leak)\n" + " until(lambda: sentinel.poll() is not None, 'A: its group was never killed')\n" + f" Path({str(entered)!r}).touch()\n" + f" until(Path({str(release)!r}).exists, 'A: never released')\n" "else:\n" - " deadline = time.monotonic() + 10\n" - f" while not Path({str(entered)!r}).exists():\n" - " if time.monotonic() > deadline:\n" - " sys.exit('B: A never entered its teardown')\n" - " time.sleep(0.01)\n" - f"send({{'type': 'system_info', 'note': '{leaked}'}})\n" - "time.sleep(30)\n" + f" until(Path({str(entered)!r}).exists, 'B: A never entered its teardown')\n" + " send(leak)\n" + " time.sleep(30)\n" ) jobs = [_job(tmp_path, [ANSWER], job_id=job_id) for job_id in ("a", "b")] run = asyncio.create_task(host.run(jobs, launcher=KeyedLauncher(code, key=""))) @@ -777,12 +763,17 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: def _child_state(pid: int) -> str: - """'running', 'zombie' or 'reaped', for a child of this process; nothing is reaped here.""" - try: - exited = os.waitid(os.P_PID, pid, os.WEXITED | os.WNOHANG | os.WNOWAIT) - except ChildProcessError: + """'running', 'zombie' or 'reaped' (or not this process's child); nothing is reaped here. + + ps, not os.waitid(WNOWAIT): macOS has no waitid before Python 3.13. A pid whose parent + is not this process counts as reaped, so a reused pid is never taken for the child. + """ + shown = subprocess.run( + ["ps", "-o", "ppid=,stat=", "-p", str(pid)], capture_output=True, text=True + ).stdout.split() + if len(shown) < 2 or int(shown[0]) != os.getpid(): return "reaped" - return "running" if exited is None else "zombie" + return "zombie" if shown[1].startswith("Z") else "running" def _holding_worker(signals: Path, *, exit_after: str | None = None) -> str: @@ -931,7 +922,10 @@ async def wait(self) -> int: 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) - os.waitid(os.P_PID, zombie.pid, os.WEXITED | os.WNOWAIT) # exited, left unreaped + deadline = time.monotonic() + 10 + while _child_state(zombie.pid) != "zombie": # exited, left unreaped + assert time.monotonic() < deadline, "the throwaway child never exited" + time.sleep(0.01) try: log = tmp_path / "exited.stderr.log" log.write_text("worker: done\n", encoding="utf-8") From 6ced7eda04ed5f60b3928cd3f4199e3df5846227 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 04:26:23 +0100 Subject: [PATCH 76/77] test(benchmarks): a held, unreaped zombie counts as exited on Linux and macOS New test, skipped where os.waitid is missing (macOS before Python 3.13). It holds the test's own exited child unreaped with waitid(WEXITED | WNOWAIT), asserts that _alive treats it as exited, then reaps it. It failed on macOS 3.13: _alive assumed that launchd reaps every zombie at once, which is not true for a child the caller still holds. _alive now reads the state from ps on both platforms. ps shows a zombie as such, sends no signal, and has no /proc read race. Co-Authored-By: Claude Opus 5.5 --- tests/benchmarks/test_agentic_host.py | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/tests/benchmarks/test_agentic_host.py b/tests/benchmarks/test_agentic_host.py index 05f8fdb5..0ee0cfdc 100644 --- a/tests/benchmarks/test_agentic_host.py +++ b/tests/benchmarks/test_agentic_host.py @@ -698,16 +698,24 @@ async def test_a_teardown_cancelled_by_a_second_abort_still_scrubs_and_settles( def _alive(pid: int) -> bool: + """Whether ``pid`` is a live process; a zombie is dead, whoever has yet to reap it. + + ps on Linux and macOS alike: it shows a zombie as such, and sends no signal at all. + """ + state = subprocess.run( + ["ps", "-o", "stat=", "-p", str(pid)], capture_output=True, text=True + ).stdout.strip() + return bool(state) and not state.startswith("Z") + + +@pytest.mark.skipif(not hasattr(os, "waitid"), reason="waitid: Linux; macOS from Python 3.13") +def test_alive_counts_an_unreaped_zombie_as_exited() -> None: + child = subprocess.Popen([sys.executable, "-c", "pass"]) # this test's own child try: - os.kill(pid, 0) - except ProcessLookupError: - return False - if not Path("/proc").is_dir(): # macOS: launchd reaps an orphan at once - return True - try: # Linux: a zombie is dead, whoever has yet to reap it - return Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[0] != "Z" - except FileNotFoundError: # reaped between the two reads - return False + os.waitid(os.P_PID, child.pid, os.WEXITED | os.WNOWAIT) # exited, held unreaped + assert not _alive(child.pid) + finally: + child.wait() # reaped here, by its parent async def test_no_descendant_can_write_a_key_into_the_published_log( From 817f9c2c10f386531c2105cb61b605cb7256fe66 Mon Sep 17 00:00:00 2001 From: Aymen Hammouda Date: Wed, 4 Nov 2026 04:28:19 +0100 Subject: [PATCH 77/77] fix(benchmarks): a run that cannot install its signal handlers says so When registration raises (not the main thread, or a loop without signal support), run.py now prints one stderr line. It names the signals whose handlers were skipped, and the exception type and message, so a main-thread registration failure is no longer silent. The threaded test asserts that line; it failed before. New test: a loop whose add_signal_handler raises NotImplementedError still runs the coroutine to the end. remove_signal_handler is never called, both signal dispositions are as before, and the stderr line names NotImplementedError. NotImplementedError is a subclass of RuntimeError, so dropping only it from the except changes nothing and fails no test. Catching only ValueError fails this test (with NotImplementedError) and the threaded one (with RuntimeError). Co-Authored-By: Claude Opus 5.5 --- benchmarks/agentic/run.py | 20 +++++++++----- tests/benchmarks/test_agentic_run.py | 40 ++++++++++++++++++++++++++-- 2 files changed, 52 insertions(+), 8 deletions(-) diff --git a/benchmarks/agentic/run.py b/benchmarks/agentic/run.py index 436c6fe7..1f464ee7 100644 --- a/benchmarks/agentic/run.py +++ b/benchmarks/agentic/run.py @@ -103,16 +103,24 @@ async def _until_signalled(run: Coroutine[Any, Any, None]) -> None: """ task = asyncio.ensure_future(run) loop = asyncio.get_running_loop() + wanted = [ # an ignored signal stays ignored, as under nohup + (signum, previous) + for signum in (signal.SIGTERM, signal.SIGHUP) + if (previous := signal.getsignal(signum)) is not signal.SIG_IGN + ] installed: list[tuple[signal.Signals, Any]] = [] # each with the disposition it replaced try: - for signum in (signal.SIGTERM, signal.SIGHUP): - previous = signal.getsignal(signum) - if previous is signal.SIG_IGN: # as under nohup: it stays ignored - continue + for signum, previous in wanted: loop.add_signal_handler(signum, task.cancel, f"signal {signum.name}") installed.append((signum, previous)) - except (RuntimeError, NotImplementedError, ValueError): - pass # not the main thread, or a loop without signal support: run without handlers + except (RuntimeError, NotImplementedError, ValueError) as exc: + # Not the main thread, or a loop without signal support: run without those handlers. + skipped = ", ".join(signum.name for signum, _ in wanted[len(installed) :]) + print( + f"agentic run: signal handlers not installed for {skipped} " + f"({type(exc).__name__}: {exc}); no teardown on those signals", + file=sys.stderr, + ) try: await task finally: diff --git a/tests/benchmarks/test_agentic_run.py b/tests/benchmarks/test_agentic_run.py index fdd47978..451f6696 100644 --- a/tests/benchmarks/test_agentic_run.py +++ b/tests/benchmarks/test_agentic_run.py @@ -5,6 +5,7 @@ from __future__ import annotations +import asyncio import hashlib import json import random @@ -31,6 +32,7 @@ from benchmarks.agentic.run import ( OUTPUT_CAP_STOPS, AgenticConfig, + _until_signalled, cell_id, plan_jobs, run_agentic, @@ -446,11 +448,45 @@ def _scripted_config(tmp_path: Path) -> AgenticConfig: ) -def test_run_agentic_completes_off_the_main_thread(tmp_path: Path) -> None: - # No signal handler can be installed off the main thread: the run goes on without one. +def test_run_agentic_completes_off_the_main_thread( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + # No signal handler can be installed off the main thread: the run goes on without one, + # and says so. with ThreadPoolExecutor(1) as pool: summary = pool.submit(run_agentic, _scripted_config(tmp_path)).result(timeout=60) assert summary["status"] == "completed" and summary["succeeded_cells"] == 1 + skipped = [line for line in capsys.readouterr().err.splitlines() if "handler" in line] + assert len(skipped) == 1 and "SIGTERM, SIGHUP" in skipped[0] and "RuntimeError" in skipped[0] + + +def test_a_loop_without_signal_support_runs_without_handlers( + capsys: pytest.CaptureFixture[str], +) -> None: + before = {signum: signal.getsignal(signum) for signum in (signal.SIGTERM, signal.SIGHUP)} + removed: list[int] = [] + + async def scenario() -> list[str]: + loop = asyncio.get_running_loop() + + def unsupported(*args: Any) -> None: + raise NotImplementedError + + loop.add_signal_handler = unsupported # type: ignore[method-assign] + loop.remove_signal_handler = removed.append # type: ignore[method-assign,assignment] + ran: list[str] = [] + + async def run() -> None: + ran.append("ran") + + await _until_signalled(run()) + return ran + + assert asyncio.run(scenario()) == ["ran"] + assert removed == [] # nothing was installed, so nothing is removed + assert {signum: signal.getsignal(signum) for signum in before} == before + err = capsys.readouterr().err + assert "SIGTERM, SIGHUP" in err and "NotImplementedError" in err def test_run_agentic_restores_the_previous_signal_dispositions(tmp_path: Path) -> None: