diff --git a/AGENTS.md b/AGENTS.md index d2356bb3d..50a83bd3b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -164,7 +164,7 @@ and deserialized through a registry. |---|---| | `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | | `artifact/` | Immutable versioned artifacts; every `put()` creates a new version. The document goes to the document store, binary payloads to the object store. Every artifact but an environment universe, whose `metadata` key holds its legacy metadata file ids, carries a `metadata` dict outside its versioned fields, changed by compare-and-swap (`merge_metadata`). Built-ins: `CliArtifact` (`cli`), `ComputerArtifact` (`computer`, a base computer: its architectures, OS, session user, settings and container form, whose image `put` reads from its registry into `metadata.validated_images`), `FileArtifact` (`file`), `FileArtifactUniverse` (`file_artifact_universe`), `DockerImageArtifact` (`docker_image`), `EnvironmentArtifact` (`environment`: its environment's files by path, stored as the one wrapped `file_artifact_ref` every environment artifact had when it has one file at its filename, else as `file_artifact_refs`; `get_file_artifacts()` reads either, and a load hands each file to the env's `data/add` with its path, which a pre-v1 load, taking one file, refuses), `EnvironmentUniverseArtifact` (`environment_universe`), `SkillArtifact` (`skill`); `[artifacts] type_aliases` maps another stored spelling of a type onto one of them. A `DockerImageArtifact` holds a tar.gz of its image, or, written by `put_ref` (`--image-ref` on `env mcp-server put` and `a2a-agent put`), only a registry reference with its tag pinned to a digest, which sandboxes pull, or a published image's tag with its `image_digest` and its build context, which sandboxes pull by the digest and build from the context when they can't (the infra images, and a bundle agent built from a shipped agent's sources, `Plan.published`), or, written by `put_context`, only its build context, which a VM sandbox builds before running it (`VmSandbox.load_docker_images`) and Modal builds before creating its container (`ModalSandboxProvider.prepare_image`, outside a fallback chain's deadline); anything else that runs images by name (a container on the local provider, a lone server on any provider but Modal) refuses such an image. A build context (`utils/docker/context.py`) is what `docker build` would send, `.dockerignore` applied, written so equal files give equal bytes and an equal `source_digest`. | -| `task/`, `task_step/` | A `Task` holds its `TaskStep`s inline; `Task.run()` executes them as a DAG. Its `headline_verifiers`, step ids saved only when set, name the grades that are its reward: one is the reward, several a multi-reward over them, none a multi-reward over every grade; it refuses one that names no step of the task, or one named twice. `depends_on` (None means all prior steps) gates a step, independent steps run concurrently, `fail_task_on_error` makes a failure fatal or tolerated, `retry_config` rolls a failed span back through the step journal and re-dispatches it. `task/lint.py` is `agent-env task lint` (a bundle folder, a task file or a stored task): an error is what a task gets wrong before it runs (a field its step doesn't read, a step's own `config_problems`, a headline that grades nothing, an aggregate source no verifier writes) and refuses `agent-env run`, `bundle register`, `task create`, `task validate` and `eval run`, and the bundle plans `openenv`'s `build_app` and the trainers make (`run`, `register`, `build_app`, `prepare_bundle` and the trainers take `--skip-lint`/`skip_lint`, which lifts lint's own rules but not a step's `config_problems`, which refused a bundle before lint; `eval run`'s lifts every error, since it checked none before); a warning is what may be wrong (a step's `config_warnings`, a store entity read with no version, no verifier, several and no headline, a judge that runs in the solver's own agent, which training refuses) and is only printed, each kind once by a run (`task.lint.said`), an eval run's unpinned references as one count (`unpinned_summary`), every one by `task lint`. `aggregate_verifiers` names its sources by step id (`sources`, `gates`) and reads their named grades: `combine` `pooled` (the default) pools their rows, `weighted_mean` weighs their scores, equally unless `weights` gives every source one, and a failing gate scores it 0; a failed or missing source fails it, and its older `verifier_ids` pools legacy entries as it always has. Built-in steps live in `task_step/task_steps/` (`deploy_env`, `deploy_agent`, `prompt_agent`, the verifiers under `verifiers/`, among them `start_computer_recording` (its driver draws each input over the frames in its caller's colour, and a pointer per role where the frames lack one, unless `annotation_settings` says `is_enabled: false`; a driver whose card lists no `annotate` records it plain, with a warning, and the run's recording entry says `annotated`) and `end_computer_recording`, `start_browser_recording` and `end_browser_recording` (`browser-recording/v1`: one recording per context, a lease's or the default one's, with a video of the tab its agent is on, its context's log, the browser's network log as HAR and opt-in frames keyed to the action log, the contexts its agents make recorded with it, one universe per recording, anything missing failing the run), and more). Every built-in verifier is on the `VerifierTaskStep` base (`verifiers/verifier.py`): it implements `verify` and returns a `Verification`, and the base writes the step's named grade to `context.metadata["grades"][]` (score, `min_passing_score`, `passed`, `verifier_status` graded, skipped or failed, criteria rows, type, version, and `verifier_settings`, the values the run graded with, its overrides applied and named in `overridden`, with `scoring_rules`) beside the legacy `verifications` entries every reader still takes; a judge's grade also has `judge_calls`, a record of each model call it made (`JudgeUsage`), each naming exactly what it was sent (`input`: a direct call's messages, response format and settings, an agent call's message, every file its step staged in the judge's sandbox and, for a judge the task deployed, what the task's own `load_artifact` steps put there as the run recorded it, stored by sha256 under `judge-inputs/` in the background, `judge_utils/judge_inputs.py`; the step waits for those uploads, at most 120 s, before it writes its grade, `VerifierTaskStep.settle`, and one that failed or hadn't finished is the call's `input_error`, never a failed grade), and its `verifier_settings` hold the trajectory source of each turn it read (`trajectory_sources`) and the effort and thinking budget its calls carried, with `not_sent` for those its route or agent card doesn't take (a value the model refuses fails the grade); an exception from `verify` or a `Verification` with an `error`, as a timed-out `run_container_unit_tests_verifier`, is a failed grade, and `rubrics_verifier` still writes its `-trajectory-mistakes` entry itself. On an env whose card serves computer-exec/v1 (a computer), `run_code` with `env_id` and `run_container_unit_tests_verifier` with `env_id` run inside it as its session user through the driver: files staged with `data/add` and read with `data/get`, commands run with `run`; `computer_exec` runs one command there through `run` (a program and its arguments, or a string through `sh -c`; in a multi env, the computer it names), recorded under `computer_exec` in the run's metadata, a non-zero exit or a timeout failing it unless `check` is off, or with `background` starts it and leaves it running, as an app launched for the agent, a program that isn't there exiting 127; with `scope: "system"` it runs as root instead, through the computer's sandbox (`RootChannel`, `docker exec -u 0`), in the session user's folder and `HOME`, its output capped in the computer, never with `background` and not on a computer booted from a disk; on a Windows computer, which has no `sh`, a string or `background` command is refused; on a multi env, `load_artifact` with `env_id` puts an environment artifact named after one of its computers, or after an app of one, into that computer, the computer's own as files at their paths under the session user's home; `env_outcome_verifier` hands a `verify` that takes an `env_url` keyword the env's address. A computer's framework-only routes (everything but MCP and the card) take the per-deploy control token its provider boots it with (`DeployedEnv.control_token`, `AGENTENV_CONTROL_TOKEN`), a multi env's computers the multi env's own, which its gateway passes on only on their `/svc` routes and its clock watch (`CONTROL_TOKEN_CHILDREN`); framework calls send `deployed.control_headers`, `Task.run` runs every step under `protocol_v1.authorized` with each deployed env's (a `verify` included), and a `run_code` script inside the computer gets `input["env"]["headers"]`. `teardown_run` and the `teardown_sandboxes` step share one core (`task/teardown.py` `tear_down`): the recordings the run left open end with fresh grants, each env still up closes (`Env.close`; a computer env ends any recording still open), what stayed open is registered from its namespace, then every sandbox is terminated by id. A run whose teardown leaves sandboxes up, stopped by a second signal or failing, keeps on its instance the context it ended with (`record_teardown`), and `agent-env run` and `task run --keep` name `agent-env task teardown --instance `, which tears down what that context still records up, a running one only with `--force`. `task/episode/` runs a task with some of its agents played from outside, as a training loop does (`EpisodeSpec`). | +| `task/`, `task_step/` | A `Task` holds its `TaskStep`s inline; `Task.run()` executes them as a DAG. Its `headline_verifiers`, step ids saved only when set, name the grades that are its reward: one is the reward, several a multi-reward over them, none a multi-reward over every grade; it refuses one that names no step of the task, or one named twice. `depends_on` (None means all prior steps) gates a step, independent steps run concurrently, `fail_task_on_error` makes a failure fatal or tolerated, `retry_config` rolls a failed span back through the step journal and re-dispatches it. `task/lint.py` is `agent-env task lint` (a bundle folder, a task file or a stored task): an error is what a task gets wrong before it runs (a field its step doesn't read, a step's own `config_problems`, a headline that grades nothing, an aggregate source no verifier writes) and refuses `agent-env run`, `bundle register`, `task create`, `task validate` and `eval run`, and the bundle plans `openenv`'s `build_app` and the trainers make (`run`, `register`, `build_app`, `prepare_bundle` and the trainers take `--skip-lint`/`skip_lint`, which lifts lint's own rules but not a step's `config_problems`, which refused a bundle before lint; `eval run`'s lifts every error, since it checked none before); a warning is what may be wrong (a step's `config_warnings`, a store entity read with no version, no verifier, several and no headline, a judge that runs in the solver's own agent, which training refuses) and is only printed, each kind once by a run (`task.lint.said`), an eval run's unpinned references as one count (`unpinned_summary`), every one by `task lint`. `aggregate_verifiers` names its sources by step id (`sources`, `gates`) and reads their named grades: `combine` `pooled` (the default) pools their rows, `weighted_mean` weighs their scores, equally unless `weights` gives every source one, and a failing gate scores it 0; a failed or missing source fails it, and its older `verifier_ids` pools legacy entries as it always has. Built-in steps live in `task_step/task_steps/` (`deploy_env`, `deploy_agent`, `prompt_agent`, the verifiers under `verifiers/`, among them `start_computer_recording` (its driver draws each input over the frames in its caller's colour, and a pointer per role where the frames lack one, unless `annotation_settings` says `is_enabled: false`; a driver whose card lists no `annotate` records it plain, with a warning, and the run's recording entry says `annotated`) and `end_computer_recording`, `start_browser_recording` and `end_browser_recording` (`browser-recording/v1`: one recording per context, a lease's or the default one's, with a video of the tab its agent is on, its context's log, the browser's network log as HAR and opt-in frames keyed to the action log, the contexts its agents make recorded with it, one universe per recording, anything missing failing the run), and more). Every built-in verifier is on the `VerifierTaskStep` base (`verifiers/verifier.py`): it implements `verify` and returns a `Verification`, and the base writes the step's named grade to `context.metadata["grades"][]` (score, `min_passing_score`, `passed`, `verifier_status` graded, skipped or failed, criteria rows, type, version, and `verifier_settings`, the values the run graded with, its overrides applied and named in `overridden`, with `scoring_rules`) beside the legacy `verifications` entries every reader still takes; a judge's grade also has `judge_calls`, a record of each model call it made (`JudgeUsage`), each naming exactly what it was sent (`input`: a direct call's messages, response format and settings, an agent call's message, every file its step staged in the judge's sandbox and, for a judge the task deployed, what the task's own `load_artifact` steps put there as the run recorded it, stored by sha256 under `judge-inputs/` in the background, `judge_utils/judge_inputs.py`; the step waits for those uploads, at most 120 s, before it writes its grade, `VerifierTaskStep.settle`, and one that failed or hadn't finished is the call's `input_error`, never a failed grade), and its `verifier_settings` hold the trajectory source of each turn it read (`trajectory_sources`); with `judge_samples` (a count, as a step field, a run override or `--judge-samples` on `run`, `task run` and `eval run`), a rubric_binary or rubric_partial judge grades each criterion that many times, each a call of its own under `judge_batch_concurrency` (an agent judge the verifier deploys gets a deployment of its own per sample, its trajectory staged in each; the task's own judge takes every sample), and keeps its median, the lower middle score on a tie, which fails it, the row the first sample that scored it gave with every sample's score, verdict and justification in its `samples` and its `agreement`, the share of samples giving its verdict; a row under `min_judge_agreement` (0.5 by default, which never fails, so the median decides; 1.0 fails any split; set where `judge_samples` is, `--min-judge-agreement`) fails the grade, its rows kept, and then the step (`JudgeDisagreementError`), and `agent-env run` names the criteria a grade that stood split on (`samples split:`), and one failed sample fails the grade (a run's count or agreement a judge of another format can't take is recorded in `not_sent`) and the effort and thinking budget its calls carried, with `not_sent` for those its route or agent card doesn't take (a value the model refuses fails the grade); an exception from `verify` or a `Verification` with an `error`, as a timed-out `run_container_unit_tests_verifier`, is a failed grade, and `rubrics_verifier` still writes its `-trajectory-mistakes` entry itself. On an env whose card serves computer-exec/v1 (a computer), `run_code` with `env_id` and `run_container_unit_tests_verifier` with `env_id` run inside it as its session user through the driver: files staged with `data/add` and read with `data/get`, commands run with `run`; `computer_exec` runs one command there through `run` (a program and its arguments, or a string through `sh -c`; in a multi env, the computer it names), recorded under `computer_exec` in the run's metadata, a non-zero exit or a timeout failing it unless `check` is off, or with `background` starts it and leaves it running, as an app launched for the agent, a program that isn't there exiting 127; with `scope: "system"` it runs as root instead, through the computer's sandbox (`RootChannel`, `docker exec -u 0`), in the session user's folder and `HOME`, its output capped in the computer, never with `background` and not on a computer booted from a disk; on a Windows computer, which has no `sh`, a string or `background` command is refused; on a multi env, `load_artifact` with `env_id` puts an environment artifact named after one of its computers, or after an app of one, into that computer, the computer's own as files at their paths under the session user's home; `env_outcome_verifier` hands a `verify` that takes an `env_url` keyword the env's address. A computer's framework-only routes (everything but MCP and the card) take the per-deploy control token its provider boots it with (`DeployedEnv.control_token`, `AGENTENV_CONTROL_TOKEN`), a multi env's computers the multi env's own, which its gateway passes on only on their `/svc` routes and its clock watch (`CONTROL_TOKEN_CHILDREN`); framework calls send `deployed.control_headers`, `Task.run` runs every step under `protocol_v1.authorized` with each deployed env's (a `verify` included), and a `run_code` script inside the computer gets `input["env"]["headers"]`. `teardown_run` and the `teardown_sandboxes` step share one core (`task/teardown.py` `tear_down`): the recordings the run left open end with fresh grants, each env still up closes (`Env.close`; a computer env ends any recording still open), what stayed open is registered from its namespace, then every sandbox is terminated by id. A run whose teardown leaves sandboxes up, stopped by a second signal or failing, keeps on its instance the context it ended with (`record_teardown`), and `agent-env run` and `task run --keep` name `agent-env task teardown --instance `, which tears down what that context still records up, a running one only with `--force`. `task/episode/` runs a task with some of its agents played from outside, as a training loop does (`EpisodeSpec`). | | `store/` | Four store ABCs with local and cloud implementations: `DocumentStore` (SQLite, MongoDB, DynamoDB, Firestore with MongoDB compatibility), `ObjectStore` (filesystem, S3, Cloud Storage), `ImageStore` (local OCI registry, ECR), `SecretStore` (env vars or file, AWS Secrets Manager, Google Cloud Secret Manager). `VersionedEntityStore` implements the shared versioned get/put logic, `QueryBuilder` is the immutable chained query API, `store/base.py` holds the error types. `store/routing.py` is the local namespaces, `@local` and `@hf` (`is_local_id`), each with a documents file of its own: while the CLI or a `build_app` server runs, a local id and what a local task's run records go to local stores beside the configured ones, and that run's writes to the configured stores are refused. A new backend must pass the conformance kits in `tst/store/`. | | `config/` | The `Config` singleton (`get_config`, `configure`, `reset_config`) in `config/runtime.py`, file discovery in `config/loader.py`, and `load_impl`, which resolves `module:Class` pointers. `agent_env.store` re-exports the config names for compatibility. | | `providers/` | `providers/sandbox_providers/` holds the sandbox providers `local`, `modal`, `modal_vm`, `e2b`, `sail_vm` (the `sail` extra), `smol_vm` (the `smol` extra), `tensorlake` (the `tensorlake` extra), `tenki` (the `tenki` extra), `vercel` (the `vercel` extra), `boxd` (the `boxd` extra), `coreweave` (the `coreweave` extra), `daytona` (the `daytona` extra), `boat` (the `boat` extra), `agent37` (no extra), `kosa8` (no extra); `[sandbox] default` and `agent_default` accept a comma-separated fallback chain, whose deploys skip a provider that can't run them. A sandbox provider declares what it runs (`ON_THIS_MACHINE`, and for VMs on this machine the address their requests to it arrive at, `REACHES_HOST_AT`; `CONTAINER_ACCEPTS`, `PRIVATE_NETWORK`, `WEBSOCKETS`; `SUPPORTED_SANDBOX_MODES`, derived from whether it implements `create_sandbox` and `create_vm`; and `SANDBOX_ACCEPTS`, the images an agent's sandbox runs, which defaults to those a VM loads when it implements `create_vm` and to `CONTAINER_ACCEPTS` otherwise, so only a provider that implements `create_vm` yet gives an agent a container, like the local one, declares it), each sandbox carries the `platform` of the images it runs (linux/amd64 unless its provider sets another when it creates it; None, any, unchecked, for a local sandbox), and code outside `providers/sandbox_providers/` reads those, never which provider it has. `providers/env_providers/` holds the environment providers: `EnvironmentProvider` (an env's containers and state store), `EnvironmentGatewayProvider` (`gateway`, an env's default), which renders a docker-compose for the gateway and its MCP servers inside the sandbox, and `EnvironmentServerProvider` (`server`), one MCP server in its own container with no gateway in front and no state store; `providers/env_state/` holds env-state providers (`local_postgres` built in). | diff --git a/src/agent_env/bundle/run.py b/src/agent_env/bundle/run.py index d6c88008b..d9fab0601 100644 --- a/src/agent_env/bundle/run.py +++ b/src/agent_env/bundle/run.py @@ -23,11 +23,14 @@ from dataclasses import dataclass, replace from enum import Enum from pathlib import Path +from typing import Any from agent_env.artifact.artifacts.docker_image import DockerImageArtifact from agent_env.env.bootstrap import InfraSetup, ensure_default_envs from agent_env.env.envs.computer.utils.composer import Composing from agent_env.providers import build_sandbox_provider +from agent_env.task_step.task_steps.verifiers.judge_utils import judge_samples as judge_samples_rule +from agent_env.task_step.task_steps.verifiers.verifier import GRADES_KEY from agent_env.store.base import NotFoundError from agent_env.store.routing import namespace_routing, run_scope from agent_env.task.store import find_task_instance, record_task_cancelled @@ -94,6 +97,13 @@ def scores(self) -> dict[str, float]: when that isn't a step's verifier id.""" return recorded_scores(self.task.steps, self.context) + @property + def splits(self) -> dict[str, list[str]]: + """The criteria a sampled judge's samples split on in a grade that stood, by step id, each with its passes.""" + grades = self.context.metadata.get(GRADES_KEY) or {} + return {step_id: split for step_id, grade in grades.items() if grade.get("verifier_status") == "graded" + and (split := judge_samples_rule.splits(grade.get("verifier_criteria") or []))} + @property def models(self) -> dict[str, dict[str, str | None]]: """The model each step asked for, by role then step id; None leaves it to the agent.""" @@ -225,6 +235,8 @@ def run_bundle( model: str | None = None, user_model: str | None = None, judge_model: str | None = None, + judge_samples: int | None = None, + min_judge_agreement: float | None = None, agent: str | None = None, sandbox: str | None = None, on_progress: Callable[[str], None] | None = None, @@ -237,8 +249,8 @@ def run_bundle( ) -> BundleRun: """Write what the tasks and evals selected in ``root`` need, as ``plan_bundle`` selects them, then run each of their tasks once. ``model``, ``user_model`` and ``judge_model`` replace the models the solver, the - user simulator and the judges run on, and ``agent`` the agent the solver runs as (``Plan.agent``), leaving the - tasks as written; ``sandbox`` is the provider that envs, agents, sandboxes and the judge deploy on, whose deploys + user simulator and the judges run on, ``judge_samples`` how many times each judge that can grades each criterion and ``min_judge_agreement`` the share of those samples each criterion's verdict needs, + and ``agent`` the agent the solver runs as (``Plan.agent``), leaving the tasks as written; ``sandbox`` is the provider that envs, agents, sandboxes and the judge deploy on, whose deploys pick the forms a computer env composes, on the env's default provider, this machine unless the config names another; that compose emulates an arch no link of it runs natively unless ``emulate`` is False, which leaves it skipped. ``on_progress`` is given a line of text @@ -264,11 +276,13 @@ def run_bundle( ends. Before anything is written, raises RuntimeError when an event loop is already running, ValueError when - ``sandbox`` names no provider, and BundleError when the bundle can't be planned or a deploy can't run where + ``sandbox`` names no provider or ``judge_samples`` isn't a positive count or ``min_judge_agreement`` a number from 0 to 1, and BundleError when the bundle can't be planned or a deploy can't run where it would (``preflight``). A task that fails its preflight raises BundleError once the entities it reads are written, before any task is. Building an infra env the run needs raises what the build raises, before any task runs.""" _refuse_a_running_loop() + judge_samples = judge_samples_rule.validated(judge_samples) + min_judge_agreement = judge_samples_rule.validated_agreement(min_judge_agreement) composing = _composing(sandbox, emulate) say = _progress(on_progress) with namespace_routing(): @@ -277,7 +291,7 @@ def run_bundle( variant=variant, skip_lint=skip_lint) plan, entries = prepared.plan, [entry for entry, _ in prepared.tasks] with Interrupts() as interrupts: - overrides = _overrides(sandbox, user_model, judge_model) + overrides = _overrides(sandbox, user_model, judge_model, judge_samples, min_judge_agreement) runs = interrupts.run(_run_all(plan, list(prepared.tasks), model, overrides, solver_params(plan, prepared.materialization), keep, say, interrupts, source)) @@ -558,15 +572,20 @@ def solver_params(plan: Plan, materialization: Materialization) -> dict[str, dic return {task_id: {step_id: dict(choice) for step_id in steps} for task_id, steps in plan.agent.steps.items()} -def _overrides(sandbox: str | None, user_model: str | None, judge_model: str | None) -> dict[str, str]: - """The run's ``user_overrides``: where everything deploys, and the models the user simulator and judges run on.""" +def _overrides(sandbox: str | None, user_model: str | None, judge_model: str | None, + judge_samples: int | None = None, min_judge_agreement: float | None = None) -> dict[str, Any]: + """The run's ``user_overrides``: where everything deploys, the models the user simulator and judges run on, how + many samples the judges take and how many of them must agree.""" overrides = sandbox_overrides(sandbox) if sandbox else {} - return {**overrides, **{key: value for key, value in (("user_model", user_model), ("judge_model", judge_model)) - if value}} + overrides.update({key: value for key, value in (("user_model", user_model), ("judge_model", judge_model), + ("judge_samples", judge_samples)) if value}) + if min_judge_agreement is not None: + overrides["min_judge_agreement"] = min_judge_agreement + return overrides async def _run_all( - plan: Plan, to_run: list[tuple[BundleEntry, Task]], model: str | None, overrides: dict[str, str], + plan: Plan, to_run: list[tuple[BundleEntry, Task]], model: str | None, overrides: dict[str, Any], step_params: Mapping[str, dict], keep: bool, say: Callable[[str], None], interrupts: Interrupts, source: HubSource | None, ) -> tuple[TaskRun, ...]: diff --git a/src/agent_env/cli/eval/run.py b/src/agent_env/cli/eval/run.py index 3986fa7c0..8220f0843 100644 --- a/src/agent_env/cli/eval/run.py +++ b/src/agent_env/cli/eval/run.py @@ -8,6 +8,7 @@ import click from agent_env.cli import submitted_runs +from agent_env.cli.utils import judge_samples_option, min_judge_agreement_option from agent_env.cli.banner import print_banner from agent_env.cli.identity import get_agent_env_client_id from agent_env.cli.usage_output import cost_line, sources_line @@ -36,10 +37,12 @@ def _write_context(context, task_id, output_dir, prefix=""): @click.option("--agent-model", default=None, type=str, help="Override the model used by prompt_agent steps") @click.option("--user-model", default=None, type=str, help="Override the model the user simulator runs on") @click.option("--judge-model", default=None, type=str, help="Override the model rubrics_verifier judges grade with") +@judge_samples_option +@min_judge_agreement_option @click.option("--agent-artifact-id", default=None, type=str, help="Override the agent image artifact for deploy_agent steps") @click.option("--skip-lint", is_flag=True, help="Run tasks agent-env task lint finds errors in, saying them, as eval run did before it linted") -def run(eval_id: str, eval_version: int | None, output_dir: str | None, k: int, max_concurrency: int | None, agent_model: str | None, user_model: str | None, judge_model: str | None, agent_artifact_id: str | None, skip_lint: bool): +def run(eval_id: str, eval_version: int | None, output_dir: str | None, k: int, max_concurrency: int | None, agent_model: str | None, user_model: str | None, judge_model: str | None, judge_samples: int | None, min_judge_agreement: float | None, agent_artifact_id: str | None, skip_lint: bool): """Run all tasks in an eval through the configured [runner], concurrently.""" if k < 1: raise click.BadParameter("must be at least 1", param_hint="'--k'") @@ -84,7 +87,11 @@ def run(eval_id: str, eval_version: int | None, output_dir: str | None, k: int, client_id = get_agent_env_client_id() base_metadata = {"agent_env_hub": {"caller": client_id}} if client_id else {} - if overrides := {key: value for key, value in (("user_model", user_model), ("judge_model", judge_model)) if value}: + overrides = {key: value for key, value in (("user_model", user_model), ("judge_model", judge_model), + ("judge_samples", judge_samples)) if value} + if min_judge_agreement is not None: + overrides["min_judge_agreement"] = min_judge_agreement + if overrides: base_metadata["user_overrides"] = overrides submissions = [(f"[{task.id} run {i}]" if k > 1 else f"[{task.id}]", task, copy.deepcopy(base_metadata), None) diff --git a/src/agent_env/cli/run.py b/src/agent_env/cli/run.py index f3cd6db11..d223c8905 100644 --- a/src/agent_env/cli/run.py +++ b/src/agent_env/cli/run.py @@ -15,6 +15,7 @@ from agent_env.bundle.installed import InstalledBundle, checked, installed_bundles, locate_bundle, run_name from agent_env.bundle.plan import NotInStore from agent_env.bundle.requires import UnmetRequirements +from agent_env.cli.utils import judge_samples_option, min_judge_agreement_option from agent_env.cli._install_prompt import offer_to_install from agent_env.cli.teardown_output import echo_finish_teardown, gone from agent_env.cli.usage_output import cost_line, sources_line @@ -40,6 +41,8 @@ @click.option("--model", default=None, help="The model the solver agent runs on, whatever the tasks name.") @click.option("--user-model", default=None, help="The model the user simulator runs on, whatever the tasks name.") @click.option("--judge-model", default=None, help="The model the judges grade with, whatever the tasks name.") +@judge_samples_option +@min_judge_agreement_option @click.option("--agent", default=None, help="The agent the solver runs as, whatever the tasks name: an alias such as pi, an agent of this " "bundle or an installed one, or the store's.") @@ -62,7 +65,8 @@ help="Run tasks agent-env task lint refuses for its own rules (a field no step reads, a headline or aggregate source that grades nothing), saying them; a step's own config problems still refuse it.") @click.pass_context def run(ctx: click.Context, bundle: str | None, tasks: tuple[str, ...], evals: tuple[str, ...], model: str | None, - user_model: str | None, judge_model: str | None, agent: str | None, settings: tuple[str, ...], + user_model: str | None, judge_model: str | None, judge_samples: int | None, min_judge_agreement: float | None, agent: str | None, + settings: tuple[str, ...], sandbox: str | None, keep: bool, dry_run: bool, no_emulate: bool, skip_lint: bool): """Run a bundle's tasks and evals, or list the installed bundles. @@ -106,10 +110,11 @@ def run(ctx: click.Context, bundle: str | None, tasks: tuple[str, ...], evals: t exits 130 (143 for SIGTERM); a second one stops the teardown and prints what is still up. """ if bundle is None: - if tasks or evals or model or user_model or judge_model or agent or settings or sandbox or keep or dry_run \ - or no_emulate or skip_lint: - raise click.UsageError("--task, --eval, --model, --user-model, --judge-model, --agent, --set, --sandbox, " - "--keep, --dry-run, --no-emulate and --skip-lint need a BUNDLE to run") + if tasks or evals or model or user_model or judge_model or judge_samples or min_judge_agreement is not None \ + or agent or settings or sandbox or keep or dry_run or no_emulate or skip_lint: + raise click.UsageError("--task, --eval, --model, --user-model, --judge-model, --judge-samples, " + "--min-judge-agreement, --agent, --set, --sandbox, --keep, --dry-run, --no-emulate " + "and --skip-lint need a BUNDLE to run") _list_installed() return verbose = ctx.find_root().params.get("verbose") @@ -124,7 +129,9 @@ def run(ctx: click.Context, bundle: str | None, tasks: tuple[str, ...], evals: t variant=variant, skip_lint=skip_lint)) return result = run_bundle(root, tasks=tasks, evals=evals, model=model, user_model=user_model, - judge_model=judge_model, agent=agent, sandbox=sandbox, on_progress=click.echo, + judge_model=judge_model, judge_samples=judge_samples, + min_judge_agreement=min_judge_agreement, agent=agent, sandbox=sandbox, + on_progress=click.echo, id_root=id_root, keep=keep, emulate=not no_emulate, source=hub.source if hub else None, variant=variant, skip_lint=skip_lint) except BundleError as e: @@ -206,6 +213,9 @@ def _summarize(result: BundleRun, verbose: bool) -> None: click.echo(f" models: {models}") if cost := cost_line(run.usage_summary): click.echo(f" {cost}") + if run.splits: + click.echo(" samples split: " + "; ".join(f"{step_id} on {', '.join(rows)}" + for step_id, rows in run.splits.items())) if result.evals: click.echo("Evals:") for eval_run in result.evals: diff --git a/src/agent_env/cli/task/run.py b/src/agent_env/cli/task/run.py index e5b524223..994c48057 100644 --- a/src/agent_env/cli/task/run.py +++ b/src/agent_env/cli/task/run.py @@ -17,6 +17,7 @@ from agent_env.cli.task._checks import runnable_task from agent_env.config.runtime import GATEWAY_OVERRIDE, SERVICE_DB_OVERRIDE, WEBSITE_BROWSER_OVERRIDE from agent_env.cli import submitted_runs +from agent_env.cli.utils import judge_samples_option, min_judge_agreement_option from agent_env.cli.identity import get_agent_env_client_id from agent_env.cli.teardown_output import echo_finish_teardown, echo_teardown, gone from agent_env.cli.usage_output import cost_line, sources_line @@ -368,6 +369,8 @@ def _stored(task, context: TaskStepContext) -> str: @click.option("--agent-model", default=None, type=str, help="Override the model used by prompt_agent steps") @click.option("--user-model", default=None, type=str, help="Override the model the user simulator runs on") @click.option("--judge-model", default=None, type=str, help="Override the model rubrics_verifier judges grade with") +@judge_samples_option +@min_judge_agreement_option @click.option("--agent-artifact-id", default=None, type=str, help="Override the agent image artifact for deploy_agent steps") @click.option("--start-step", default=0, type=int, help="0-based step index to start execution from") @click.option("--context-json", default=None, type=click.Path(exists=True, dir_okay=False), help="Path to a JSON file to seed the TaskStepContext") @@ -394,7 +397,7 @@ def _stored(task, context: TaskStepContext) -> str: help="Keep what a run deployed up when it ends, print it, and tear it down on Ctrl-C; while it holds, " "another terminal can resume the run with --start-step and --context-json. Without it, each run " "is torn down as it ends, as Ctrl-C mid-run always does.") -def run(task_id: str, task_version: int | None, output_dir: str | None, k: int, agent_model: str | None, user_model: str | None, judge_model: str | None, agent_artifact_id: str | None, start_step: int, context_json: str | None, litellm_api_key: str | None, judge_litellm_api_key: str | None, apply_trajectory_filter: bool | None, a2a_agent_id: str | None, agent_sandbox: str | None, env_sandbox: str | None, gateway_env_id: str | None, service_db_env_id: str | None, website_browser_env_id: str | None, env_state_type: str | None, env_state_instance_id: str | None, keep: bool): +def run(task_id: str, task_version: int | None, output_dir: str | None, k: int, agent_model: str | None, user_model: str | None, judge_model: str | None, judge_samples: int | None, min_judge_agreement: float | None, agent_artifact_id: str | None, start_step: int, context_json: str | None, litellm_api_key: str | None, judge_litellm_api_key: str | None, apply_trajectory_filter: bool | None, a2a_agent_id: str | None, agent_sandbox: str | None, env_sandbox: str | None, gateway_env_id: str | None, service_db_env_id: str | None, website_browser_env_id: str | None, env_state_type: str | None, env_state_instance_id: str | None, keep: bool): """Run a task through the configured [runner] and follow it. Each run's sandboxes are torn down as it ends, passed or failed; its instance and context JSON stay. @@ -426,6 +429,10 @@ def run(task_id: str, task_version: int | None, output_dir: str | None, k: int, initial_context.metadata.setdefault("user_overrides", {})["user_model"] = user_model if judge_model: initial_context.metadata.setdefault("user_overrides", {})["judge_model"] = judge_model + if judge_samples: + initial_context.metadata.setdefault("user_overrides", {})["judge_samples"] = judge_samples + if min_judge_agreement is not None: + initial_context.metadata.setdefault("user_overrides", {})["min_judge_agreement"] = min_judge_agreement if agent_sandbox: initial_context.metadata.setdefault("user_overrides", {})["agent_sandbox"] = agent_sandbox if env_sandbox: @@ -531,6 +538,8 @@ def _seed_universe_id(task, seed: dict) -> str | None: @click.option("--agent-model", default=None, type=str, help="Override the model used by prompt_agent steps") @click.option("--user-model", default=None, type=str, help="Override the model the user simulator runs on") @click.option("--judge-model", default=None, type=str, help="Override the model rubrics_verifier judges grade with") +@judge_samples_option +@min_judge_agreement_option @click.option("--agent-artifact-id", default=None, type=str, help="Override the agent image artifact for deploy_agent steps") @click.option("--litellm-api-key", default=None, type=str, help="Override LITELLM_API_KEY for all runs; a secret:KEY or env:NAME reference is resolved where it is used") @click.option("--judge-litellm-api-key", default=None, type=str, help="Override LITELLM_API_KEY used by rubrics_verifier judge agents; a secret:KEY or env:NAME reference is resolved where it is used") @@ -546,7 +555,7 @@ def _seed_universe_id(task, seed: dict) -> str | None: @click.option("--keep", is_flag=True, help="Keep what each run deployed up when it ends, print it, and tear it down on Ctrl-C. Without it, " "each run is torn down as it ends, as Ctrl-C mid-batch always does.") -def run_batch(task_id: str, task_version: int | None, seeds: str, concurrency: int, output_dir: str | None, agent_model: str | None, user_model: str | None, judge_model: str | None, agent_artifact_id: str | None, litellm_api_key: str | None, judge_litellm_api_key: str | None, apply_trajectory_filter: bool | None, agent_sandbox: str | None, env_sandbox: str | None, env_state_type: str | None, env_state_instance_id: str | None, keep: bool): +def run_batch(task_id: str, task_version: int | None, seeds: str, concurrency: int, output_dir: str | None, agent_model: str | None, user_model: str | None, judge_model: str | None, judge_samples: int | None, min_judge_agreement: float | None, agent_artifact_id: str | None, litellm_api_key: str | None, judge_litellm_api_key: str | None, apply_trajectory_filter: bool | None, agent_sandbox: str | None, env_sandbox: str | None, env_state_type: str | None, env_state_instance_id: str | None, keep: bool): """Run a task through the configured [runner] once per seed in a CSV file, and follow the runs. Each run's sandboxes are torn down as it ends; --keep holds them up until Ctrl-C instead. Ctrl-C or @@ -573,6 +582,7 @@ def run_batch(task_id: str, task_version: int | None, seeds: str, concurrency: i _stamp_agent_env_client_metadata(metadata, get_agent_env_client_id()) given = {"litellm_api_key": litellm_api_key, "judge_litellm_api_key": judge_litellm_api_key, "apply_trajectory_filter": apply_trajectory_filter, "user_model": user_model, "judge_model": judge_model, + "judge_samples": judge_samples, "min_judge_agreement": min_judge_agreement, "agent_sandbox": agent_sandbox, "env_sandbox": env_sandbox, "env_state_type": env_state_type, "env_state_instance_id": env_state_instance_id} if overrides := {key: value for key, value in given.items() if value is not None and value != ""}: diff --git a/src/agent_env/cli/utils.py b/src/agent_env/cli/utils.py index 1f94e4f22..ecfdd4b95 100644 --- a/src/agent_env/cli/utils.py +++ b/src/agent_env/cli/utils.py @@ -12,6 +12,7 @@ from agent_env.providers.env_providers.env_provider import _env_provider_class from agent_env.providers.env_providers.env_server_provider import EnvironmentServerProvider from agent_env.store.base import NotFoundError +from agent_env.task_step.task_steps.verifiers.judge_utils import judge_samples from agent_env.utils.docker.metadata import detect_base_metadata, detect_env_metadata # noqa: F401 re-exported for the put commands from agent_env.utils.docker.build import DEFAULT_BUILD_PLATFORM @@ -60,6 +61,38 @@ def build_platform_option(f): )(f) +def _judge_samples(ctx: click.Context, param: click.Parameter, value: int | None) -> int | None: + try: + return judge_samples.validated(value) + except ValueError as e: + raise click.BadParameter(str(e)) from None + + +def judge_samples_option(f): + """``--judge-samples N``, the run's ``judge_samples``: a positive count, refused at once otherwise.""" + return click.option( + "--judge-samples", type=int, default=None, callback=_judge_samples, metavar="N", + help="Grade each criterion N times and keep its median, the lower middle score on a tie (so a tie " + "fails), in every judge that can (a rubric_binary or rubric_partial one), whatever the tasks say; " + "each sample's score is kept.")(f) + + +def _min_judge_agreement(ctx: click.Context, param: click.Parameter, value: float | None) -> float | None: + try: + return judge_samples.validated_agreement(value) + except ValueError as e: + raise click.BadParameter(str(e)) from None + + +def min_judge_agreement_option(f): + """``--min-judge-agreement SHARE``, the run's ``min_judge_agreement``: a number from 0 to 1.""" + return click.option( + "--min-judge-agreement", type=float, default=None, callback=_min_judge_agreement, metavar="SHARE", + help="The share of a sampled judge's samples that must give each criterion's kept verdict, else its grade " + "fails, in every judge that samples, whatever the tasks say: 1.0 fails any split, 0.67 is two of " + "three, and 0.5, the default, never fails, so the median decides.")(f) + + def refuse_unwritable_ids(*ids: str) -> None: """Refuse, before anything is built, an id the store a put writes it to wouldn't take, such as an @local id the image's suffix makes too long.""" diff --git a/src/agent_env/task/task.py b/src/agent_env/task/task.py index 8be4ba775..3b9fc3eb9 100644 --- a/src/agent_env/task/task.py +++ b/src/agent_env/task/task.py @@ -221,6 +221,7 @@ async def _roll_back_span( completed_ids: set[str], log_prefix: str, state: _SchedulerState, + error: BaseException | None = None, ) -> set[str] | None: """Roll back a failed span so the scheduler can re-dispatch it on a clean world. @@ -252,8 +253,10 @@ async def _roll_back_span( span_order = [s.id for s in steps if s.id in span_ids] rollback_ids = span_ids | cancelled_ids logger.warning( - "%sStep %s failed; rolling back span %s and re-dispatching from %s (attempt %d).", - log_prefix, failed_id, span_order, resume_from, attempt, + "%sStep %s failed%s; rolling back span %s and re-dispatching from %s (attempt %d).", + # The error's type alone: some steps put a response body in their messages, which the run record keeps. + log_prefix, failed_id, f" ({type(error).__name__})" if error is not None else "", span_order, + resume_from, attempt, ) if not instance_id: logger.error( @@ -826,7 +829,7 @@ async def _drain_in_flight() -> set[str]: failed_id=step_obj.id, resume_from=retry_cfg.retry_from_step_id, cancelled_ids=cancelled, attempt=retry_counts[step_obj.id] + 1, windows={sid: (t0, ended.get(sid, now_tick)) for sid, t0 in started.items()}, - completed_ids=set(state.completed), log_prefix=log_prefix, state=state, + completed_ids=set(state.completed), log_prefix=log_prefix, state=state, error=exc, ) if outcome is None: # Could not roll back (refused, unpersisted, or a concurrent survivor): diff --git a/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py b/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py index 411af5556..23086e09f 100644 --- a/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py @@ -174,9 +174,17 @@ # The per-criterion row fields a judge of such a run may add, and the formats whose rows take them. CONTEXT_LOSS_FIELDS = {"context_loss": {"type": "boolean"}, "context_loss_evidence": {"type": "string"}} _CONTEXT_LOSS_FORMATS = frozenset({JudgeOutputFormat.RUBRIC_BINARY, JudgeOutputFormat.RUBRIC_PARTIAL}) -# Whether the run being graded (this task's context) has the harness's agent labels and a per-criterion format, so its -# judge is asked for context loss: set by stage_trajectory, read by _spec, per run (one step serves concurrent runs). -_CONTEXT_LOSS_RUN: ContextVar[bool] = ContextVar("always_on_context_loss_run", default=False) + + +@dataclasses.dataclass +class _ContextLoss: + """Whether the run being graded has the harness's agent labels and a per-criterion format, so its judge is asked + for context loss: one per run (one step serves concurrent runs), set by stage_trajectory, read by _spec. A holder, + so staging in a task of its own, as each sample's judge is staged, sets it for the run.""" + asked: bool = False + + +_CONTEXT_LOSS_RUN: ContextVar[Optional[_ContextLoss]] = ContextVar("always_on_context_loss_run", default=None) class UngradableRunError(RuntimeError): @@ -218,6 +226,8 @@ def __init__( judge_sandbox_type: Optional[str] = None, judge_batch_size: Optional[int] = None, judge_batch_concurrency: Optional[int] = None, + judge_samples: Optional[int] = None, + min_judge_agreement: Optional[float] = None, judge_timeout_retries: Optional[int] = None, judge_max_turns: Optional[int] = None, full_app_changes: bool = False, @@ -245,7 +255,8 @@ def __init__( default_model=default_model, default_model_api_base=default_model_api_base, effort=effort, max_thinking_tokens=max_thinking_tokens, judge_a2a_agent_id=judge_a2a_agent_id, judge_sandbox_type=judge_sandbox_type, judge_batch_size=judge_batch_size, - judge_batch_concurrency=judge_batch_concurrency, + judge_batch_concurrency=judge_batch_concurrency, judge_samples=judge_samples, + min_judge_agreement=min_judge_agreement, judge_timeout_retries=(self.DEFAULT_JUDGE_TIMEOUT_RETRIES if judge_timeout_retries is None else judge_timeout_retries), judge_max_turns=self.DEFAULT_JUDGE_MAX_TURNS if judge_max_turns is None else judge_max_turns, @@ -301,16 +312,16 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: if self.use_trajectory and (context.metadata.get("user_overrides") or {}).get("use_agent_judge") is False: raise RuntimeError(f"Verifier '{self.verifier_id}': use_trajectory needs the agent judge; this run's " "use_agent_judge=False would grade without the wakes it was set to read.") - token = _CONTEXT_LOSS_RUN.set(False) + loss = _ContextLoss() + token = _CONTEXT_LOSS_RUN.set(loss) try: verdict = await super()._judged(context) - asked = _CONTEXT_LOSS_RUN.get() finally: _CONTEXT_LOSS_RUN.reset(token) output = dict(verdict.output) if "trajectory_staging" in output: output["trajectory_staging"]["judge_reads"] = await self._judge_reads(output) - if asked: + if loss.asked: output["context_loss"] = context_loss(verdict.criteria) if harness := await self._assistant_harness(context, staged="trajectory_staging" in output): output["assistant_harness"] = harness @@ -320,7 +331,8 @@ def _spec(self) -> JudgeOutputFormatSpec: """rubrics_verifier's format; for a run with agent labels (``_CONTEXT_LOSS_RUN``), its rows also take ``context_loss`` and ``context_loss_evidence``.""" spec = super()._spec() - return _with_context_loss(spec) if _CONTEXT_LOSS_RUN.get() else spec + loss = _CONTEXT_LOSS_RUN.get() + return _with_context_loss(spec) if loss is not None and loss.asked else spec async def _assistant_harness(self, context: TaskStepContext, *, staged: bool) -> dict: """The graded assistant's harness as the run records it: its agent name, its A2A card's name and version, and, @@ -408,8 +420,9 @@ async def stage_trajectory(self, context: TaskStepContext, prompt_response: Prom values = await self._change_values(context) if self.full_app_changes and not by_position else None staged = await asyncio.to_thread(stage_run, timeline, turns, firings=run.firings_read(), unavailable=run.unavailable, by_position=by_position, change_values=values) - _CONTEXT_LOSS_RUN.set(bool(staged.record.get("agent_labeled_trajectories")) - and self.output_format in _CONTEXT_LOSS_FORMATS) + asked = bool(staged.record.get("agent_labeled_trajectories")) and self.output_format in _CONTEXT_LOSS_FORMATS + if (loss := _CONTEXT_LOSS_RUN.get()) is not None: + loss.asked = asked path = f"{STAGING_DIR}/{uuid.uuid4().hex[:12]}" await self._write_files(sandbox, {f"{path}/{name}": text for name, text in staged.files.items()}, container) self._log_staging(staged) @@ -417,7 +430,7 @@ async def stage_trajectory(self, context: TaskStepContext, prompt_response: Prom # Its turns carry no labels: each trajectory's format is the one its shape reads as. judge.read([{"format": fmt, "trajectories": count, "guessed": True} for fmt, count in (staged.record.get("formats") or {}).items()]) - return StagedTrajectory(path=path, prompt_note=_files_note(path, staged, context_loss=_CONTEXT_LOSS_RUN.get()), + return StagedTrajectory(path=path, prompt_note=_files_note(path, staged, context_loss=asked), record=staged.record) async def _read_turns(self, urls: list[str], names: dict[str, str], diff --git a/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_inputs.py b/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_inputs.py index d732bc932..77b607d7c 100644 --- a/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_inputs.py +++ b/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_inputs.py @@ -93,25 +93,30 @@ def failed(self, digest: Optional[str]) -> Optional[str]: class StagingRecorder: - """A judge's sandbox, every file written into it kept in its run's manifest (``staged``): a file written as text - stored by its sha256 too (``Uploads.put``), one copied from a stored object named by that object's URL.""" + """A judge's sandbox, every file written into it kept in its run's manifests (``manifests``, each entry the same + in each): a file written as text stored by its sha256 too (``Uploads.put``), one copied from a stored object named + by that object's URL.""" - def __init__(self, sandbox: Any, staged: list[dict[str, Any]], uploads: Uploads) -> None: - self._sandbox, self._staged, self._uploads = sandbox, staged, uploads + def __init__(self, sandbox: Any, manifests: tuple[list[dict[str, Any]], ...], uploads: Uploads) -> None: + self._sandbox, self._manifests, self._uploads = sandbox, manifests, uploads def __getattr__(self, name: str) -> Any: return getattr(self._sandbox, name) async def write_file_from_text(self, text: str, path: str, **kwargs: Any) -> Any: written = await self._sandbox.write_file_from_text(text, path, **kwargs) - self._staged.append({"path": path, **self._uploads.put(text.encode(), "text/plain; charset=utf-8")}) + self._record({"path": path, **self._uploads.put(text.encode(), "text/plain; charset=utf-8")}) return written async def write_file_from_object(self, object_url: str, path: str, **kwargs: Any) -> Any: written = await self._sandbox.write_file_from_object(object_url, path, **kwargs) - self._staged.append({"path": path, "object_url": object_url}) + self._record({"path": path, "object_url": object_url}) return written + def _record(self, entry: dict[str, Any]) -> None: + for manifest in self._manifests: + manifest.append(entry) + def _encoded(body: Any) -> tuple[bytes, str]: data = json.dumps(body, ensure_ascii=False, sort_keys=True).encode() diff --git a/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_output_format.py b/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_output_format.py index 961fd6f7d..b5e6bf669 100644 --- a/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_output_format.py +++ b/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_output_format.py @@ -1600,6 +1600,9 @@ class JudgeOutputFormatSpec: # Batched rows are checked for bulk verdicts (shared or short justifications) and retried with a correction. A # format whose rows may rightly share a short reason turns it off. checks_bulk_verdicts: bool = True + # Each row is one criterion's score and justification and nothing else, so judge_samples may grade it several + # times and keep its median (``judge_samples``); a format with frames, a per-call block or verdicts leaves it off. + samplable: bool = False JUDGE_OUTPUT_FORMAT_REGISTRY: dict[JudgeOutputFormat, JudgeOutputFormatSpec] = { @@ -1612,6 +1615,7 @@ class JudgeOutputFormatSpec: diagnose_response=diagnose_rubric_binary_response, format_correction_prompt=format_judge_correction_prompt, batchable=True, + samplable=True, ), JudgeOutputFormat.RUBRIC_PARTIAL: JudgeOutputFormatSpec( output_format=_rubric_score_output_format(), @@ -1622,6 +1626,7 @@ class JudgeOutputFormatSpec: diagnose_response=diagnose_rubric_partial_response, format_correction_prompt=format_partial_judge_correction_prompt, batchable=True, + samplable=True, ), JudgeOutputFormat.RUBRIC_EVIDENCE: JudgeOutputFormatSpec( output_format=_rubric_evidence_output_format(), diff --git a/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_samples.py b/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_samples.py new file mode 100644 index 000000000..bd8bad36b --- /dev/null +++ b/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_samples.py @@ -0,0 +1,89 @@ +"""A judge's samples: ``judge_samples`` grades each criterion that many times and keeps the median, the lower of the two +middle scores for an even count, so it is always a score a sample gave. A score of 1 is always the agent's pass (a +negative criterion's is inverted), so a tie fails: two samples pass only together, four need three. For a 0-or-1 +criterion an odd count is the majority vote. The row kept is that sample's (its justification, and its outcome on a +criterion with fixed outcomes), with every sample's score, verdict and justification beside it. + +``min_judge_agreement`` is how many of the samples must give the kept row's verdict, as a share, or the grade fails +(``JudgeDisagreementError``). It is 0.5 by default, which the kept verdict always meets, so the median decides every +row unless a task or run asks for more: 1.0 fails any split. The share is kept to two places, so 0.67 is two samples +of three, and is 1.0 only when every sample agrees.""" + +from __future__ import annotations + +import statistics +from typing import Any, Optional + +DEFAULT_MIN_AGREEMENT = 0.5 +# Agreement is kept to this many decimal places, so a bar of 0.67 is two samples of three. +AGREEMENT_PLACES = 2 +# The most a split's agreement reads, one step under 1.0 at those places, so only unanimous samples read 1.0. +SPLIT_AGREEMENT_MAX = round(1 - 10 ** -AGREEMENT_PLACES, AGREEMENT_PLACES) + + +class JudgeDisagreementError(RuntimeError): + """A sampled judge's samples split on a criterion more than ``min_judge_agreement`` allows.""" + + +def validated(value: Any) -> Optional[int]: + """``value`` as a judge_samples count: None, or a positive integer; anything else is a ValueError.""" + if value is None: + return None + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise ValueError(f"judge_samples must be a positive integer, got {value!r}") + return value + + +def validated_agreement(value: Any) -> Optional[float]: + """``value`` as a min_judge_agreement: None, or a number from 0 to 1; anything else is a ValueError.""" + if value is None: + return None + if isinstance(value, bool) or not isinstance(value, (int, float)) or not 0 <= value <= 1: + raise ValueError(f"min_judge_agreement must be a number from 0 to 1, got {value!r}") + return float(value) + + +def _share(agreeing: int, total: int) -> float: + """``agreeing`` of ``total`` to two places, 1.0 only when all agree, so no split reads as unanimous.""" + return 1.0 if agreeing == total else min(round(agreeing / total, AGREEMENT_PLACES), SPLIT_AGREEMENT_MAX) + + +def median_rows(sampled: list[list[dict[str, Any]]]) -> list[dict[str, Any]]: + """Each criterion's row across ``sampled``, one list of rows per sample, each with every criterion: the first + sample's row that scored the low median, with its ``agreement``, the share of samples whose verdict (``result``) + is that row's, and ``samples``, each sample's score, verdict and justification in order.""" + by_sample = [{row["id"]: row for row in rows} for rows in sampled] + merged = [] + for row in sampled[0]: + rows = [sample[row["id"]] for sample in by_sample] + median = statistics.median_low(each["score"] for each in rows) + chosen = next(each for each in rows if each["score"] == median) + verdict = chosen.get("result") is True + agreeing = sum(1 for each in rows if (each.get("result") is True) == verdict) + merged.append({**chosen, "agreement": _share(agreeing, len(rows)), + "samples": [{"score": each["score"], "passed": each.get("result") is True, + "justification": each.get("justification")} for each in rows]}) + return merged + + +def disagreeing(rows: list[dict[str, Any]], bar: float) -> list[dict[str, Any]]: + """The sampled rows whose ``agreement`` is under ``bar``.""" + return [row for row in rows if "agreement" in row and row["agreement"] < bar] + + +def splits(rows: list[dict[str, Any]]) -> list[str]: + """Each sampled row its samples didn't all agree on, as `` ( of pass)``.""" + return [f"{row.get('id')} ({sum(1 for s in row['samples'] if s.get('passed'))} of {len(row['samples'])} pass)" + for row in rows if row.get("samples") and row.get("agreement", 1.0) < 1.0] + + +def disagreement(verifier_id: str, rows: list[dict[str, Any]], bar: float) -> str: + """Why a grade whose samples split on ``rows`` failed, naming how each split.""" + splits = [] + for row in rows: + passes = sum(1 for sample in row["samples"] if sample["passed"]) + splits.append(f"{row.get('id')} ({passes} of {len(row['samples'])} samples pass it)") + which = "a criterion" if len(rows) == 1 else f"{len(rows)} criteria" + return (f"Verifier '{verifier_id}': its judge samples split on {which}, under min_judge_agreement {bar:g}: " + f"{', '.join(splits)}. Each sample's verdict and justification are on the grade's rows; a lower " + "min_judge_agreement keeps the median instead.") diff --git a/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_usage.py b/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_usage.py index 976d1ca46..1fa1e9f32 100644 --- a/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_usage.py +++ b/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_usage.py @@ -57,6 +57,7 @@ def __init__(self, context: TaskStepContext, step_id: str) -> None: self.loaded: list[dict[str, Any]] = [] self.sources: Optional[list[dict[str, Any]]] = None self.uploads = Uploads() + self._staged_in: dict[str, list[dict[str, Any]]] = {} self._deferred: list[tuple[dict[str, Any], AgentInput]] = [] def call(self, role: ModelRole, usage: Optional[Usage], *, model: Optional[str], endpoint_host: Optional[str], @@ -88,13 +89,17 @@ async def input(self, body: Any) -> dict[str, Any]: """``body`` as the JSON a direct call was sent, uploaded: its reference.""" return await self.uploads.put_json(body) - def agent_input(self, message: str) -> AgentInput: - """What an agent call is sent now: its message, the files staged so far and the task's loads into the judge.""" - return AgentInput(message, list(self.staged), list(self.loaded)) + def agent_input(self, message: str, sandbox_id: Optional[str] = None) -> AgentInput: + """What an agent call is sent now: its message, the files staged so far in its judge's sandbox + (``sandbox_id``; every one staged, without) and the task's loads into the judge.""" + files = self._staged_in[sandbox_id] if sandbox_id in self._staged_in else self.staged + return AgentInput(message, list(files), list(self.loaded)) - def recording(self, sandbox: Any) -> StagingRecorder: - """``sandbox``, every file written into it kept in ``staged``.""" - return StagingRecorder(sandbox, self.staged, self.uploads) + def recording(self, sandbox: Any, sandbox_id: Optional[str] = None) -> StagingRecorder: + """``sandbox``, every file written into it kept in ``staged`` and, when it's named, in its own sandbox's list, + which the calls to that sandbox's judge name, as when each sample has a judge of its own.""" + manifests = (self.staged,) if sandbox_id is None else (self.staged, self._staged_in.setdefault(sandbox_id, [])) + return StagingRecorder(sandbox, manifests, self.uploads) async def settle(self) -> None: """Waits, up to ``SETTLE_SECONDS`` all told, for the run's uploads; stores each agent call's input once its @@ -132,7 +137,7 @@ def _record(self, outcome: str, usage: Optional[Usage], model: Optional[str], en reported_by=reported_by).fields() record = {"outcome": outcome, "model": model, "endpoint_host": endpoint_host, "usage": usage.to_dict() if usage is not None else None, **cost, - "batch": _BATCH.get(), "attempt": _ATTEMPT.get(), + "batch": _BATCH.get(), "sample": _SAMPLE.get(), "attempt": _ATTEMPT.get(), **({"input": dict(sent)} if isinstance(sent, Mapping) else {}), **({"error": error} if error is not None else {})} self.calls.append(record) @@ -142,6 +147,7 @@ def _record(self, outcome: str, usage: Optional[Usage], model: Optional[str], en _RUN: ContextVar[Optional[JudgeUsage]] = ContextVar("judge_run", default=None) _BATCH: ContextVar[Optional[int]] = ContextVar("judge_batch", default=None) +_SAMPLE: ContextVar[Optional[int]] = ContextVar("judge_sample", default=None) _ATTEMPT: ContextVar[Optional[int]] = ContextVar("judge_attempt", default=None) @@ -179,6 +185,11 @@ def batch(number: Optional[int]) -> None: _BATCH.set(number) +def sample(number: Optional[int]) -> None: + """The judge sample the calls made from here in this task belong to (None for a run that takes one).""" + _SAMPLE.set(number) + + def attempt(number: int) -> None: """The output attempt the calls made from here in this task belong to.""" _ATTEMPT.set(number) diff --git a/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py b/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py index c60a1619b..113ef3cfe 100644 --- a/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py @@ -62,6 +62,7 @@ fetch_container_logs, ) from agent_env.task_step.task_steps.load_artifact import LOADED_FILE_UNIVERSES, loads_into +from agent_env.task_step.task_steps.verifiers.judge_utils import judge_samples as judge_samples_rule from agent_env.task_step.task_steps.verifiers.judge_utils import judge_usage from agent_env.task_step.task_steps.verifiers.judge_utils.judge_usage import JudgeUsage from agent_env.task_step.task_steps.verifiers.judge_utils.atif_turns import ( @@ -356,6 +357,22 @@ def _image_url_block(frame: ImageFrame) -> dict: } +@dataclass +class _JudgeAgent: + """An agent judge the run grades with: where it's reached, its card and record, the container its files go in, the + deployment this step made of it (None for the task's own agent), and what was staged in its sandbox.""" + + a2a_url: Optional[str] + sandbox_id: Optional[str] + sandbox_type: Optional[str] + card: dict + agent: Any + container: Optional[str] + deployed: Any = None + staged: Optional[StagedTrajectory] = None + atif_note: str = "" + + @dataclass class _CompactedTrajectory: """Every representation the filter produced; the caller picks what its judge consumes.""" @@ -482,6 +499,11 @@ def _unbatchable_format_message(output_format: JudgeOutputFormat) -> str: return f"judge_batch_size does not apply to output_format={output_format.value}." +def _unsamplable_format_message(output_format: JudgeOutputFormat, field: str = "judge_samples") -> str: + return (f"{field} does not apply to output_format={output_format.value}: only a rubric_binary or " + "rubric_partial judge's rows have one score each to take the median of.") + + def _override_or(overrides: dict, key: str, stored: Optional[int]) -> Optional[int]: """The run's override when present (even an invalid one, so validation reports it), else the stored value.""" return overrides[key] if overrides.get(key) is not None else stored @@ -531,7 +553,8 @@ class RubricsVerifierTaskStep(VerifierTaskStep): context_paths = ("context_facts_for_judge{}",) field_scopes = {**TaskStep.field_scopes, **dict.fromkeys( ("judge_a2a_agent_id", "default_model", "default_model_api_base", "effort", "max_thinking_tokens", - "judge_sandbox_type", "judge_batch_size", "judge_batch_concurrency"), FieldScope.USER)} + "judge_sandbox_type", "judge_batch_size", "judge_batch_concurrency", "judge_samples", "min_judge_agreement"), + FieldScope.USER)} DEFAULT_JUDGE_TIMEOUT_SECONDS: ClassVar[int] = 1000 DEFAULT_JUDGE_BATCH_CONCURRENCY: ClassVar[int] = 4 _PER_ROW_EVIDENCE_NOTE: ClassVar[str] = ( @@ -588,6 +611,8 @@ def __init__( run_context_for_judge: Optional[list[str]] = None, judge_batch_size: Optional[int] = None, judge_batch_concurrency: Optional[int] = None, + judge_samples: Optional[int] = None, + min_judge_agreement: Optional[float] = None, judge_timeout_retries: Optional[int] = None, judge_max_turns: Optional[int] = None, depends_on: Optional[list[TaskStepDependency]] = None, @@ -611,6 +636,12 @@ def __init__( # judge_batch_concurrency at once), and retry a batch whose rows read as bulk verdicts. self.judge_batch_size = _validated_batch_option("judge_batch_size", judge_batch_size) self.judge_batch_concurrency = _validated_batch_option("judge_batch_concurrency", judge_batch_concurrency) + # Grade each criterion this many times and keep its median, the lower middle score on a tie, every sample's + # score kept. + self.judge_samples = judge_samples_rule.validated(judge_samples) + # The share of samples that must give each criterion's kept verdict, else the grade fails; None is the + # default, 0.5, which never fails, so the median decides; 1.0 fails any split. + self.min_judge_agreement = judge_samples_rule.validated_agreement(min_judge_agreement) # An agent judge call (a batch's, with batches) that runs out of judge_timeout_seconds is tried again this many # times, and the timed-out attempt's trajectory is kept; None keeps the first timeout fatal, as it always was. if judge_timeout_retries is not None and (isinstance(judge_timeout_retries, bool) @@ -678,6 +709,10 @@ def __init__( ) if self.judge_batch_size is not None and not self._spec().batchable: raise ValueError(_unbatchable_format_message(self.output_format)) + if (self.judge_samples or 1) > 1 and not self._spec().samplable: + raise ValueError(_unsamplable_format_message(self.output_format)) + if self.min_judge_agreement is not None and not self._spec().samplable: + raise ValueError(_unsamplable_format_message(self.output_format, "min_judge_agreement")) def _spec(self) -> JudgeOutputFormatSpec: return get_judge_output_format_spec(self.output_format) @@ -747,6 +782,10 @@ def to_dict(self) -> dict: base["judge_batch_size"] = self.judge_batch_size if self.judge_batch_concurrency is not None: base["judge_batch_concurrency"] = self.judge_batch_concurrency + if self.judge_samples is not None: + base["judge_samples"] = self.judge_samples + if self.min_judge_agreement is not None: + base["min_judge_agreement"] = self.min_judge_agreement if self.judge_timeout_retries is not None: base["judge_timeout_retries"] = self.judge_timeout_retries if self.judge_max_turns is not None: @@ -779,6 +818,8 @@ def from_dict(cls, data: dict) -> RubricsVerifierTaskStep: grade_up_to_turn=data.get("grade_up_to_turn"), run_context_for_judge=data.get("run_context_for_judge"), judge_batch_size=data.get("judge_batch_size"), + judge_samples=data.get("judge_samples"), + min_judge_agreement=data.get("min_judge_agreement"), judge_batch_concurrency=data.get("judge_batch_concurrency"), judge_timeout_retries=data.get("judge_timeout_retries"), judge_max_turns=data.get("judge_max_turns"), @@ -853,6 +894,8 @@ def _run_values(self, context: TaskStepContext) -> dict[str, Any]: "max_thinking_tokens": overrides.get("judge_max_thinking_tokens") or self.max_thinking_tokens, "judge_batch_size": _override_or(overrides, "judge_batch_size", self.judge_batch_size), "judge_batch_concurrency": _override_or(overrides, "judge_batch_concurrency", self.judge_batch_concurrency), + "judge_samples": _override_or(overrides, "judge_samples", self.judge_samples), + "min_judge_agreement": _override_or(overrides, "min_judge_agreement", self.min_judge_agreement), "judge_sandbox_type": (overrides.get("agent_sandbox") or self.judge_sandbox_type) if use_agent_judge and self.agent_name is None else self.judge_sandbox_type, } @@ -869,7 +912,9 @@ def verifier_settings(self, context: TaskStepContext) -> dict[str, Any]: model the run recorded (else the one it resolves), the agent it deploys as its judge when it deploys one, and ``overridden``, the settings this run's overrides changed. Once the judge has called, its effort and thinking budget are those its calls carried, ``not_sent`` those it couldn't send, with ``judge_endpoint_host`` and any - ``temperature`` and ``seed`` the config gave a direct call. Never a key, header or base URL.""" + ``temperature`` and ``seed`` the config gave a direct call; a run's ``judge_samples`` or ``min_judge_agreement`` + its format can't take is in ``not_sent`` too, and a sampled judge's ``min_judge_agreement`` is the bar it + applied, the default included. Never a key, header or base URL.""" settings = super().verifier_settings(context) settings.pop("default_model_api_base", None) values, stored = self._recorded_values(context), self._recorded_values(TaskStepContext()) @@ -893,6 +938,18 @@ def verifier_settings(self, context: TaskStepContext) -> dict[str, Any]: settings["judge_endpoint_host"] = judge.endpoint_host if judge is not None and judge.sources: settings["trajectory_sources"] = list(judge.sources) + asked, bar = values.get("judge_samples"), values.get("min_judge_agreement") + if not self._spec().samplable: + # A run-wide judge_samples reaches every judge; one whose format can't take it grades once. + refused = {**({"judge_samples": asked} if isinstance(asked, int) and asked > 1 else {}), + **({"min_judge_agreement": bar} if bar is not None else {})} + if "judge_samples" in refused: + settings["judge_samples"] = 1 + settings.pop("min_judge_agreement", None) + if refused: + settings["not_sent"] = {**(settings.get("not_sent") or {}), **refused} + elif isinstance(asked, int) and asked > 1: + settings["min_judge_agreement"] = judge_samples_rule.DEFAULT_MIN_AGREEMENT if bar is None else bar return {**settings, "overridden": overridden} def grade_fields(self, context: TaskStepContext) -> dict[str, Any]: @@ -920,8 +977,9 @@ async def verify(self, context: TaskStepContext) -> Verification: def _gated(self, verdict: RubricsVerdict) -> RubricsVerdict: """``verdict``, failing its step once recorded when ``fail_task_when_not_passing`` and it scores under - ``min_passing_score``, naming the rows that weren't met.""" - if not self.fail_task_when_not_passing or verdict.score >= self.min_passing_score: + ``min_passing_score``, naming the rows that weren't met; one that failed already, as a judge whose samples + split, keeps its own error.""" + if verdict.error is not None or not self.fail_task_when_not_passing or verdict.score >= self.min_passing_score: return verdict unmet = [str(row.get("id")) for row in verdict.criteria if row.get("score", 1.0 if row.get("result") else 0.0) < 1] @@ -1041,26 +1099,26 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: raise RuntimeError(f"Verifier '{self.verifier_id}': unjudged_rows gave rows with a criterion's id: " f"{sorted(map(str, clashing))}") - auto_deployed_judge = None - staged: Optional[StagedTrajectory] = None - atif_note = "" - judge_agent = None - judge_a2a_url: Optional[str] = None - judge_sandbox_id: Optional[str] = None - judge_agent_card: dict = {} - judge_container: Optional[str] = None - if use_agent_judge: + samples = judge_samples_rule.validated(run["judge_samples"]) or 1 + bar = judge_samples_rule.validated_agreement(run["min_judge_agreement"]) + if samples > 1 and not self._spec().samplable: + logger.warning("Verifier '%s': %s It grades once.", self.verifier_id, + _unsamplable_format_message(self.output_format)) + samples = 1 + bar = judge_samples_rule.DEFAULT_MIN_AGREEMENT if bar is None else bar + + async def judge_agent() -> _JudgeAgent: + """An agent judge for the run, the trajectory staged in its sandbox: the task's agent, or one this step + deploys, which is terminated here too when staging fails.""" if self.agent_name is not None: agent = next((a for a in context.deployed_agents if a.agent_name == self.agent_name), None) if agent is None: raise StepContextError(f"Agent '{self.agent_name}' not found in context.deployed_agents") if not agent.sandbox_id: raise RuntimeError(f"Agent '{self.agent_name}' has no sandbox_id") - judge_a2a_url = agent.a2a_url or agent.api_url - judge_sandbox_id = agent.sandbox_id - judge_agent_card = agent.a2a_card or {} - judge_agent = agent - judge_container = agent.installed_container + one = _JudgeAgent(a2a_url=agent.a2a_url or agent.api_url, sandbox_id=agent.sandbox_id, + sandbox_type=agent.sandbox_type, card=agent.a2a_card or {}, agent=agent, + container=agent.installed_container) else: from agent_env.a2a_agent import A2AAgent from agent_env.config import get_config @@ -1089,37 +1147,56 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: deploy_kwargs = {"env_vars": env_vars} if run["judge_sandbox_type"]: deploy_kwargs["sandbox_type"] = run["judge_sandbox_type"] - auto_deployed_judge = await a2a_agent.deploy(**deploy_kwargs) - judge_a2a_url = auto_deployed_judge.a2a_url - judge_sandbox_id = auto_deployed_judge.sandbox_id - judge_agent_card = auto_deployed_judge.agent_card - judge_agent = auto_deployed_judge - logger.info(f"Auto-deployed judge A2A agent '{resolved_judge_id}' at {judge_a2a_url}") + deployed = await a2a_agent.deploy(**deploy_kwargs) + one = _JudgeAgent(a2a_url=deployed.a2a_url, sandbox_id=deployed.sandbox_id, + sandbox_type=deployed.sandbox_type, card=deployed.agent_card, agent=deployed, + container=None, deployed=deployed) + logger.info(f"Auto-deployed judge A2A agent '{resolved_judge_id}' at {one.a2a_url}") # Loading the trajectory can fail (an override's staging, a transfer): the judge this step deployed is # released then too, not only after grading. try: if self.use_trajectory: from agent_env.providers.sandbox_providers.sandbox_provider import build_sandbox_provider, get_agent_sandbox_provider - judge_sandbox_type = auto_deployed_judge.sandbox_type if auto_deployed_judge else (agent.sandbox_type if self.agent_name else None) - provider = build_sandbox_provider(judge_sandbox_type) if judge_sandbox_type else get_agent_sandbox_provider() - sandbox = judge.recording(await provider.get_sandbox(judge_sandbox_id)) - staged = await self.stage_trajectory(context, stored_response, run_context, sandbox, judge_container) - if staged is None and atif is not None: + provider = build_sandbox_provider(one.sandbox_type) if one.sandbox_type else get_agent_sandbox_provider() + sandbox = judge.recording(await provider.get_sandbox(one.sandbox_id), one.sandbox_id) + one.staged = await self.stage_trajectory(context, stored_response, run_context, sandbox, + one.container) + if one.staged is None and atif is not None: media = await self._stage_atif_turns( - sandbox, atif, multiturn_dir, filter_to_apply, judge_container, documents) - atif_note = self._atif_note(atif, filter_to_apply, media=media) - elif staged is None and multiturn: + sandbox, atif, multiturn_dir, filter_to_apply, one.container, documents) + one.atif_note = self._atif_note(atif, filter_to_apply, media=media) + elif one.staged is None and multiturn: await self._load_per_turn_trajectories( - sandbox, per_turn_uris, multiturn_dir, filter_to_apply, judge_container) - elif staged is None: + sandbox, per_turn_uris, multiturn_dir, filter_to_apply, one.container) + elif one.staged is None: await sandbox.write_file_from_object(compacted.container_object_url, self.TRAJECTORY_CONTAINER_PATH, - **into_container(judge_container)) + **into_container(one.container)) if compacted.tool_result_files: - await self._load_tool_result_files(sandbox, compacted.tool_result_files, judge_container) - compacted.tool_result_files = [] + await self._load_tool_result_files(sandbox, compacted.tool_result_files, one.container) except BaseException: - await _terminate_auto_deployed_judge(auto_deployed_judge) + await _terminate_auto_deployed_judge(one.deployed) raise + return one + + # A judge this step deploys gets a deployment of its own per sample, so no sample sees another's files; the + # task's own judge is the one agent the task deployed, which its samples share. + judges: list[_JudgeAgent] = [] + if use_agent_judge: + if self.agent_name is not None or samples == 1: + judges = [await judge_agent()] + else: + deploying: list[asyncio.Task] = [] + try: + async with asyncio.TaskGroup() as group: + deploying = [group.create_task(judge_agent()) for _ in range(samples)] + except BaseException as failed: + await asyncio.gather(*(_terminate_auto_deployed_judge(task.result().deployed) for task in deploying + if task.done() and not task.cancelled() and task.exception() is None)) + if isinstance(failed, ExceptionGroup): + raise failed.exceptions[0] from failed + raise + judges = [task.result() for task in deploying] + compacted.tool_result_files = [] try: model = self._judge_model(context) @@ -1139,7 +1216,6 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: context_facts = (resolve_context_facts(self.context_facts_for_judge, context.metadata) if self.context_facts_for_judge else []) image_blocks: list[dict] = [] - trajectory_path: Optional[str] = None trajectory_inline: Optional[str] = None if use_agent_judge: # Agent judge can't use inline screenshot frames; it loads the raw file. @@ -1149,10 +1225,6 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: f"verifier '{self.verifier_id}' uses an agent judge — raw trajectory " "passed through unchanged." ) - if staged is not None: - trajectory_path = staged.path - elif self.use_trajectory: - trajectory_path = multiturn_dir if multiturn or atif is not None else self.TRAJECTORY_CONTAINER_PATH else: image_blocks = compacted.image_blocks # Direct judge embeds the trajectory inline; DEFAULT has no pre-rendered text. @@ -1167,27 +1239,34 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: if trajectory_content is not None: trajectory_inline = trajectory_content - def eval_prompt_for(batch: list[dict]) -> str: + def trajectory_path_of(one: _JudgeAgent) -> Optional[str]: + if one.staged is not None: + return one.staged.path + if self.use_trajectory: + return multiturn_dir if multiturn or atif is not None else self.TRAJECTORY_CONTAINER_PATH + return None + + def eval_prompt_for(batch: list[dict], one: Optional[_JudgeAgent]) -> str: criteria_json = json.dumps([ {**c, "negative": True} if (c.get("weight") is not None and c["weight"] < 0) else c for c in batch ], indent=2) - if use_agent_judge: + if one is not None: prompt = self._build_eval_prompt( agent_prompt=agent_prompt_text, agent_response=prompt_response.response, criteria_json=criteria_json, - trajectory_path=trajectory_path, + trajectory_path=trajectory_path_of(one), trajectory_inline=trajectory_inline, loaded_artifacts=loaded_for_judge, context_facts=context_facts, run_context=run_context, extra_sections=extra_sections, ) - if staged is not None: - prompt += staged.prompt_note - elif atif_note: - prompt += atif_note + if one.staged is not None: + prompt += one.staged.prompt_note + elif one.atif_note: + prompt += one.atif_note elif self.use_trajectory and multiturn: prompt += self._MULTITURN_DIR_NOTE.format(n=len(per_turn_uris)) else: @@ -1222,25 +1301,27 @@ def eval_prompt_for(batch: list[dict]) -> str: # Batches merge by concatenating rows, which drops a format's one-per-call reasoning, checks and mistakes. raise RuntimeError(f"Verifier '{self.verifier_id}': _criteria_batches gave {len(batches)} batches, but " f"output_format={self.output_format.value} is graded in one judge call.") + # Every call, a batch's or a sample's, takes a place of this limit. concurrency = asyncio.Semaphore(batch_concurrency or self.DEFAULT_JUDGE_BATCH_CONCURRENCY) usage = judge + sample_trajectory_urls: dict[Optional[int], list[Optional[str]]] = {} - async def grade(batch: list[dict], number: Optional[int] = None - ) -> tuple[list[dict], int, list[dict], Optional[str]]: - judge_usage.batch(number) - prompt = eval_prompt_for(batch) - if len(batches) > 1: - prompt += self._BATCH_NOTE.format( - first=position[batch[0]["id"]], last=position[batch[-1]["id"]], - total=len(criteria_for_judge), count=len(batch)) + def judge_for(sample_number: Optional[int]) -> Optional[_JudgeAgent]: + """The agent judge a sample's calls go to: its own when each sample has one; None for a direct one.""" + if len(judges) > 1: + return judges[(sample_number or 1) - 1] + return judges[0] if judges else None + + async def call(batch: list[dict], prompt: str, one: Optional[_JudgeAgent] + ) -> tuple[list[dict], int, list[dict], Optional[str]]: async with concurrency: return await self._run_judge_with_output_retries( eval_prompt=prompt, context=context, model=model, - judge_a2a_url=judge_a2a_url, - judge_agent_card=judge_agent_card, - judge_agent=judge_agent, + judge_a2a_url=one.a2a_url if one is not None else None, + judge_agent_card=one.card if one is not None else {}, + judge_agent=one.agent if one is not None else None, judge_effort=judge_effort, judge_max_thinking_tokens=judge_max_thinking_tokens, use_agent_judge=use_agent_judge, @@ -1250,6 +1331,38 @@ async def grade(batch: list[dict], number: Optional[int] = None usage=usage, ) + async def grade(batch: list[dict], number: Optional[int] = None + ) -> tuple[list[dict], int, list[dict], Optional[str]]: + judge_usage.batch(number) + + def prompt_for(one: Optional[_JudgeAgent]) -> str: + prompt = eval_prompt_for(batch, one) + if len(batches) > 1: + prompt += self._BATCH_NOTE.format( + first=position[batch[0]["id"]], last=position[batch[-1]["id"]], + total=len(criteria_for_judge), count=len(batch)) + return prompt + + if samples == 1: + return await call(batch, prompt_for(judge_for(None)), judge_for(None)) + + async def sample(n: int) -> tuple[list[dict], int, list[dict], Optional[str]]: + judge_usage.sample(n) + return await call(batch, prompt_for(judge_for(n)), judge_for(n)) + + try: + async with asyncio.TaskGroup() as group: + sampled = [group.create_task(sample(n)) for n in range(1, samples + 1)] + except ExceptionGroup as failed: + # A sample that fails fails the grade, as a batch does; the group cancels the others. + raise failed.exceptions[0] from failed + outcomes = [task.result() for task in sampled] + sample_trajectory_urls[number] = [url for _, _, _, url in outcomes] + return (judge_samples_rule.median_rows([rows for rows, _, _, _ in outcomes]), + sum(retries for _, retries, _, _ in outcomes), + [{**d, "sample": n} for n, (_, _, ds, _) in enumerate(outcomes, 1) for d in ds], + next((url for _, _, _, url in outcomes if url), None)) + if len(batches) == 1: outcomes = [await grade(batches[0])] else: @@ -1276,7 +1389,7 @@ async def grade(batch: list[dict], number: Optional[int] = None _restore_frame_labels(verification_results, real_by_short) _restore_frame_labels(verification_results.checks, real_by_short) finally: - await _terminate_auto_deployed_judge(auto_deployed_judge) + await asyncio.gather(*(_terminate_auto_deployed_judge(one.deployed) for one in judges)) judge_call_fields: dict = { **dual_keyed("compact_trajectory_s3_uri", "compact_trajectory_object_url", compacted.compact_object_url), @@ -1289,11 +1402,25 @@ async def grade(batch: list[dict], number: Optional[int] = None if len(batches) > 1: judge_call_fields["judge_batches"] = len(batches) judge_call_fields["judge_batch_trajectory_object_urls"] = batch_trajectory_urls + if samples > 1: + judge_call_fields["judge_samples"] = samples + urls = [url for number in (range(1, len(batches) + 1) if len(batches) > 1 else [None]) + for url in sample_trajectory_urls.get(number, [])] + if any(urls): + judge_call_fields["judge_sample_trajectory_object_urls"] = urls if grade_up_to_turn is not None: judge_call_fields["graded_up_to_turn"] = grade_up_to_turn - if staged is not None: - judge_call_fields["trajectory_staging"] = staged.record - return self._entries(verification_results, judge_call_fields, unjudged=unjudged) + if judges and judges[0].staged is not None: + judge_call_fields["trajectory_staging"] = judges[0].staged.record + verdict = self._entries(verification_results, judge_call_fields, unjudged=unjudged) + if samples > 1 and (split := judge_samples_rule.disagreeing(verdict.criteria, bar)): + # The rows stay on the failed grade, each with its samples, for whoever has to see why it split. + reason = judge_samples_rule.disagreement(self.verifier_id, split, bar) + verdict = replace(verdict, error=reason, raise_after=judge_samples_rule.JudgeDisagreementError(reason), + output={**verdict.output, "judge_disagreement": { + "min_judge_agreement": bar, + "criteria": [{"id": row.get("id"), "agreement": row["agreement"]} for row in split]}}) + return verdict def _entries(self, verification_results: list[dict], judge_call_fields: dict, *, unjudged: Sequence[dict] = ()) -> RubricsVerdict: @@ -1760,7 +1887,8 @@ async def _invoke_judge_a2a( from agent_env.a2a_agent import protocol host = getattr(judge_agent, "model_endpoint_host", None) - sent = {"sent": usage.agent_input(eval_prompt)} if isinstance(usage, JudgeUsage) else {} + sent = ({"sent": usage.agent_input(eval_prompt, getattr(judge_agent, "sandbox_id", None))} + if isinstance(usage, JudgeUsage) else {}) try: task_id, _ = await protocol.send_a2a_message( judge_a2a_url, diff --git a/src/agent_env/task_step/task_steps/verifiers/user_sim_judge.py b/src/agent_env/task_step/task_steps/verifiers/user_sim_judge.py index de3e3e2c5..65a265df8 100644 --- a/src/agent_env/task_step/task_steps/verifiers/user_sim_judge.py +++ b/src/agent_env/task_step/task_steps/verifiers/user_sim_judge.py @@ -181,8 +181,8 @@ **dict.fromkeys(("criteria", "prompt_id", "default_model", "default_model_api_base", "agent_name", "trajectory_filter", "max_thinking_tokens", "effort", "judge_a2a_agent_id", "judge_sandbox_type", "grading_policy_prompt", "context_facts_for_judge", "grade_up_to_turn", "run_context_for_judge", - "judge_batch_size", "judge_batch_concurrency", "judge_timeout_retries", "judge_max_turns", - "min_passing_score"))} + "judge_batch_size", "judge_batch_concurrency", "judge_samples", "min_judge_agreement", "judge_timeout_retries", + "judge_max_turns", "min_passing_score"))} NOT_FAILING_OFF = "fail_task_when_not_passing is off: verdicts are recorded only" NOT_FAILING_UNCONFIRMED = ("the judge's copy of the user sim's instructions isn't confirmed to be the one it ran with, " "so it doesn't fail the task") diff --git a/tst/unit/bundle/installed_test.py b/tst/unit/bundle/installed_test.py index ed5d3b8ba..52643cbc9 100644 --- a/tst/unit/bundle/installed_test.py +++ b/tst/unit/bundle/installed_test.py @@ -281,11 +281,13 @@ def test_the_cli_says_so_when_no_bundles_are_installed_and_needs_a_bundle_for_it assert CliRunner().invoke(cli, ["run"]).output == "No bundles are installed. agent-env run PATH runs a folder.\n" for option in (["--task", "t"], ["--keep"], ["--dry-run"], ["--user-model", "m"], ["--judge-model", "m"], - ["--agent", "pi"], ["--set", "envs/desktop.driver=reference"], ["--no-emulate"], ["--skip-lint"]): + ["--judge-samples", "3"], ["--min-judge-agreement", "0.5"], ["--agent", "pi"], ["--set", "envs/desktop.driver=reference"], + ["--no-emulate"], ["--skip-lint"]): usage = CliRunner().invoke(cli, ["run", *option]) assert usage.exit_code == 2 - assert ("--task, --eval, --model, --user-model, --judge-model, --agent, --set, --sandbox, --keep, --dry-run, " - "--no-emulate and --skip-lint need a BUNDLE to run") in " ".join(usage.output.split()) + assert ("--task, --eval, --model, --user-model, --judge-model, --judge-samples, --min-judge-agreement, --agent, " + "--set, --sandbox, --keep, --dry-run, --no-emulate and --skip-lint need a BUNDLE to run") in " ".join( + usage.output.split()) def test_the_cli_runs_an_installed_bundle_by_name_with_ids_rooted_at_its_package(site, monkeypatch, quiet_logs, diff --git a/tst/unit/bundle/run_test.py b/tst/unit/bundle/run_test.py index f8a5aa98b..2cdbe41c6 100644 --- a/tst/unit/bundle/run_test.py +++ b/tst/unit/bundle/run_test.py @@ -129,6 +129,20 @@ async def execute(self, context): return context +class _SplitGrade(_Scored): + """Records a grade whose judge took 3 samples and they split on one criterion, as a sampled rubrics judge does.""" + + type = "split_grade_run_test" + + async def execute(self, context): + samples = [{"score": 1.0, "passed": True}, {"score": 1.0, "passed": True}, {"score": 0.0, "passed": False}] + context.metadata.setdefault("grades", {})[self.id] = { + "verifier_status": "graded", "score": 1.0, + "verifier_criteria": [{"id": "c1", "score": 1.0, "agreement": 1.0, "samples": [samples[0]] * 3}, + {"id": "c2", "score": 1.0, "agreement": 0.67, "samples": samples}]} + return await super().execute(context) + + class _NamesAgent(_Scored): """Names an agent, so the agent and its image are written, without deploying it.""" @@ -174,7 +188,7 @@ def _scored(score): def registries(monkeypatch): steps = {**Config().task_step_registry(), **{cls.type: cls for cls in (_Scored, _Failing, _Cancelled, _NamesAgent, _RecordsModels, _Spends, - _ReadsCache)}} + _ReadsCache, _SplitGrade)}} monkeypatch.setattr(Config, "task_step_registry", lambda self: steps) fake_plugins(monkeypatch) # no installed package ships these classes monkeypatch.setattr(_Scored, "seen", []) @@ -520,6 +534,15 @@ def test_the_cli_runs_each_role_on_its_model_names_them_and_a_rerun_on_others_wr assert (bundle_dir / "tasks" / "models.json").read_text() == written +def test_the_cli_names_the_criteria_a_sampled_judges_samples_split_on_in_a_grade_that_stood(bundle_dir, quiet_logs): + layout(bundle_dir, {"tasks/split.json": json.dumps([{"id": "judge", "type": "split_grade_run_test"}])}) + + result = CliRunner().invoke(cli, ["run", str(bundle_dir), "--task", "split"]) + + assert result.exit_code == 0, result.output + assert " samples split: judge on c2 (2 of 3 pass)" in result.output.splitlines() + + @pytest.fixture def prices(monkeypatch): """gpt-4.1-mini at $0.40 and $1.60 per million input and output tokens, judge-1 at $3 and $15.""" diff --git a/tst/unit/env/envs/test_computer_site_proxy.py b/tst/unit/env/envs/test_computer_site_proxy.py index 18fd597d2..fee102daf 100644 --- a/tst/unit/env/envs/test_computer_site_proxy.py +++ b/tst/unit/env/envs/test_computer_site_proxy.py @@ -9,7 +9,6 @@ import contextlib import dataclasses import email.message -import gc import io import json import os @@ -41,6 +40,10 @@ pytestmark = pytest.mark.usefixtures("socket_enabled") +#: How long a test waits for answers that come back in under a second: generous, since the wait ends once every answer is +#: in, and a busy test worker's event loop can stall for seconds, as a full garbage collection of its heap does. +ANSWERS_WAIT_S = 5.0 + def _ok(body=b"hello", extra=()): async def respond(start, headers, request_body, reader, writer): @@ -885,12 +888,11 @@ def datagram_received(self, data, addr): local_addr=("127.0.0.1", 0)) client, _ = await loop.create_datagram_endpoint(Client, remote_addr=server.get_extra_info("sockname")) try: - deadline = loop.time() + 10 * nameserver_delay_s client.sendto(_query("eu.chat.test", 1)) for _ in range(passed_on): client.sendto(_query("example.org", 1)) + deadline = loop.time() + ANSWERS_WAIT_S while loop.time() < deadline and len(answered) < passed_on + 1: - gc.collect() await asyncio.sleep(0.05) finally: for transport in (client, server, upstream): diff --git a/tst/unit/task_step/retry_test.py b/tst/unit/task_step/retry_test.py index 14d93ec64..c1db0c915 100644 --- a/tst/unit/task_step/retry_test.py +++ b/tst/unit/task_step/retry_test.py @@ -244,14 +244,18 @@ async def execute(self, context): @pytest.mark.asyncio -async def test_self_retry_reruns_only_the_failed_step(store): +async def test_self_retry_reruns_only_the_failed_step_and_says_why(store, caplog): deploy = _FakeDeployEnv("s0") # retry_from = the step itself -> span is just {s1}, deploy is not rolled back. flaky = _FlakyPrompt("s1", retry_config=RetryConfig(retry_from_step_id="s1"), fail_times=1) task = Task(id="t", version=1, steps=[deploy, flaky]) ctx = TaskStepContext() - result = await task.run(context=ctx) + with caplog.at_level(logging.WARNING, logger="agent_env.task.task"): + result = await task.run(context=ctx) + + assert "Step s1 failed (RuntimeError); rolling back span ['s1']" in caplog.text + assert "flaky boom" not in caplog.text assert deploy.deploy_calls == ["s0"] # deploy NOT re-run assert flaky.attempts == 2 diff --git a/tst/unit/task_step/test_always_on_agent_verifier.py b/tst/unit/task_step/test_always_on_agent_verifier.py index d5d5b7f0c..1e5a1bf34 100644 --- a/tst/unit/task_step/test_always_on_agent_verifier.py +++ b/tst/unit/task_step/test_always_on_agent_verifier.py @@ -6,8 +6,10 @@ from __future__ import annotations +import asyncio import json from pathlib import Path +from types import SimpleNamespace from typing import Optional import pytest @@ -27,6 +29,7 @@ from agent_env.task_step.task_steps.verifiers.rubrics_verifier import RUN_CONTEXT_PARTS, RubricsVerifierTaskStep from tst.unit.task_step.always_on_harness import Rig from tst.util import atif_runs +from tst.util.config import install_model_config pytestmark = pytest.mark.usefixtures("local_stores") @@ -642,6 +645,47 @@ async def test_a_v7_run_s_failed_criterion_traced_to_a_compaction_is_labelled_an "id", "score", "justification"] +@pytest.mark.asyncio +async def test_a_judge_deployed_per_sample_is_still_asked_for_context_loss_and_the_entry_counts_it(monkeypatch): + install_model_config(monkeypatch, base_url="https://gw.test/v1", api_key="configured-key") + ctx, _, sources = _v7_staged_run(monkeypatch, summary_drops=" FACT: the gate code must never be shared. |") + sandboxes: dict[str, _Sandbox] = {} + + class Agent: + async def deploy(self, **kwargs): + sandbox_id = f"sb-{len(sandboxes) + 1}" + sandboxes[sandbox_id] = _Sandbox() + return SimpleNamespace(a2a_url=f"http://{sandbox_id}.test", sandbox_id=sandbox_id, agent_card={}, + sandbox_type=None, control_headers={}, model_endpoint_host=None) + + class Provider: + async def get_sandbox(self, sandbox_id): + return sandboxes[sandbox_id] + + async def configured(**kwargs): + return None + + monkeypatch.setattr(A2AAgent, "get", staticmethod(lambda agent_id: Agent())) + monkeypatch.setattr(sandbox_provider, "get_agent_sandbox_provider", lambda: Provider()) + monkeypatch.setattr(_Sandbox, "terminate", lambda self: asyncio.sleep(0), raising=False) + verifier = _verifier(use_agent_judge=True, use_trajectory=True, judge_a2a_agent_id="judge-agent", + judge_samples=3, criteria=[{"id": "gate", "description": "Never shares the gate code"}]) + verifier._configure_judge_a2a = configured + captured = _judging(monkeypatch, verifier, sources, { + "score": 0.0, "justification": "Gave the gate code to the courier.", "context_loss": True, + "context_loss_evidence": "wakes/wake_004.jsonl:7"}) + + await verifier.execute(ctx) + + assert sorted(sandboxes) == ["sb-1", "sb-2", "sb-3"] and all(sandbox.files for sandbox in sandboxes.values()) + entry = ctx.metadata["verifications"]["rubric"] + assert [sample["score"] for sample in entry["results"][0]["samples"]] == [0.0, 0.0, 0.0] + assert entry["results"][0]["context_loss"] is True + assert entry["context_loss"] == {"failed_criteria": 1, "caused_by_compaction": 1, "ids": ["gate"]} + assert 'For each criterion you fail, also return "context_loss"' in captured["prompt"] + assert "context_loss" in captured["schema"]["schema"]["properties"]["results"]["items"]["properties"] + + @pytest.mark.asyncio async def test_a_v7_judge_that_says_nothing_about_context_loss_is_counted_as_not_saying(monkeypatch): ctx, _, sources = _v7_staged_run(monkeypatch) diff --git a/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_samples.py b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_samples.py new file mode 100644 index 000000000..45c3ff7ea --- /dev/null +++ b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_samples.py @@ -0,0 +1,523 @@ +"""judge_samples: a rubric_binary or rubric_partial judge grades each criterion that many times and keeps its median, the +lower middle score on a tie, so a tie fails, the row of the first sample that scored it with every sample's score, +verdict and justification beside it and its agreement; a split under min_judge_agreement (0.5 by default, which never +fails) fails the grade, its rows kept, then the step, and so the task unless the step tolerates it; each +call's record names its sample; the samples share the judge's concurrency; one that fails fails the grade; a judge the +verifier deploys gets one of its own per sample, while the task's own judge takes every sample; a run's count reaches +every judge that can take it, and one that can't grades once and records it as not sent.""" + +from __future__ import annotations + +import asyncio +import json +from types import SimpleNamespace + +import litellm +import pytest +from click.testing import CliRunner + +from agent_env.a2a_agent import A2AAgent, protocol +from agent_env.bundle.run import _overrides, run_bundle +from agent_env.cli.run import run as run_command +from agent_env.config import get_config +from agent_env.providers.sandbox_providers import sandbox_provider +from agent_env.task.task import Task +from agent_env.task_step.context import DeployedAgent +from agent_env.task_step.task_steps.verifiers.judge_utils import judge_samples, judge_usage +from agent_env.task_step.task_steps.verifiers.judge_utils.judge_samples import JudgeDisagreementError +from agent_env.task_step.task_steps.verifiers import rubrics_verifier as rv +from agent_env.task_step.task_steps.verifiers.rubrics_verifier import RubricsVerifierTaskStep +from agent_env.task_step.task_steps.verifiers.user_sim_judge import UserSimJudge +from tst.unit.task_step.verifiers import test_rubrics_verifier_golden as G +from tst.unit.task_step.verifiers.test_rubrics_verifier_judge_settings import _grade +from tst.util.config import install_model_config + +TWO = G.TWO + + +def _verdicts(scores: dict[str, float], sample: int) -> str: + return json.dumps({"results": [{"id": i, "score": s, "justification": f"sample {sample} scored {i} {s}"} + for i, s in scores.items()]}) + + +def _sampled_llm(monkeypatch, by_sample, *, failing_sample=None, slow_s=0.0) -> dict: + """LiteLLM faked through the configured endpoint, each call answered by its sample's verdicts + (``by_sample(sample, ids)`` gives the scores), read from the call's own context; ``failing_sample`` is refused on + every attempt; the calls in flight at once are counted.""" + install_model_config(monkeypatch, base_url="https://gw.test/v1", api_key="configured-key") + seen = {"calls": [], "in_flight": 0, "most": 0} + + async def acompletion(**kwargs): + sample = judge_usage._SAMPLE.get() + prompt = kwargs["messages"][-1]["content"] + ids = G._ids(prompt if isinstance(prompt, str) else "".join(b.get("text", "") for b in prompt)) + seen["calls"].append((judge_usage._BATCH.get(), sample)) + seen["in_flight"] += 1 + seen["most"] = max(seen["most"], seen["in_flight"]) + try: + await asyncio.sleep(slow_s) + if sample is not None and sample == failing_sample: + raise litellm.RateLimitError("slow down", llm_provider="openai", model="gpt-4o-mini") + content = _verdicts(by_sample(sample, ids), sample or 1) + finally: + seen["in_flight"] -= 1 + return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=content))], + usage={"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}, + _hidden_params={}) + + monkeypatch.setattr(litellm, "acompletion", acompletion) + return seen + + +def _two_to_one(sample, ids) -> dict[str, float]: + """c1 passes on samples 1 and 3 and fails on 2; c2 fails on 1 and passes on 2 and 3.""" + return {"c1": 0.0 if sample == 2 else 1.0, "c2": 0.0 if sample == 1 else 1.0, **{i: 1.0 for i in ids[2:]}} + + +def test_a_count_is_any_positive_integer(): + assert [judge_samples.validated(n) for n in (None, 1, 2, 3, 4)] == [None, 1, 2, 3, 4] + for bad in (0, -3, True, 3.0, "3"): + with pytest.raises(ValueError, match="positive integer"): + judge_samples.validated(bad) + + +def test_each_criterion_keeps_the_first_row_that_scored_its_median_and_every_samples_score_verdict_and_reason(): + sampled = [[{"id": "a", "score": s, "result": s >= 0.5, "justification": f"{n}:{s}", "outcome": f"level {s}"} + for s in [score]] for n, score in enumerate([0.25, 0.75, 0.5], 1)] + + [row] = judge_samples.median_rows(sampled) + + assert (row["score"], row["justification"], row["outcome"], row["agreement"]) == (0.5, "3:0.5", "level 0.5", 0.67) + assert row["samples"] == [{"score": 0.25, "passed": False, "justification": "1:0.25"}, + {"score": 0.75, "passed": True, "justification": "2:0.75"}, + {"score": 0.5, "passed": True, "justification": "3:0.5"}] + + +def test_an_agreement_bar_is_a_number_from_0_to_1(): + assert [judge_samples.validated_agreement(v) for v in (None, 0, 0.5, 0.67, 1)] == [None, 0.0, 0.5, 0.67, 1.0] + for bad in (-0.1, 1.5, True, "1", float("nan")): + with pytest.raises(ValueError, match="min_judge_agreement must be a number from 0 to 1"): + judge_samples.validated_agreement(bad) + + +@pytest.mark.parametrize("scores, agreement", [([1.0, 1.0, 0.0], 0.67), ([1.0, 0.0], 0.5), ([0.75, 0.7], 1.0), + ([0.4, 0.6], 0.5), ([1.0, 1.0, 1.0, 0.0, 1.0], 0.8), + ([1.0] * 200 + [0.0], 0.99)]) +def test_a_rows_agreement_is_the_share_of_samples_giving_its_verdict_not_its_score(scores, agreement): + sampled = [[{"id": "a", "score": score, "result": score >= 0.5}] for score in scores] + + [row] = judge_samples.median_rows(sampled) + + assert row["agreement"] == agreement + assert judge_samples.disagreeing([row], 1.0) == ([] if agreement == 1.0 else [row]) + assert judge_samples.disagreeing([row], agreement) == [] + + +@pytest.mark.parametrize("scores, kept", [([1.0, 0.0], 0.0), ([0.0, 1.0], 0.0), ([1.0, 1.0, 0.0, 1.0], 1.0), + ([1.0, 0.0, 0.0, 1.0], 0.0), ([0.75, 0.25], 0.25)]) +def test_an_even_count_s_tie_keeps_the_lower_middle_score_and_the_first_sample_that_gave_it(scores, kept): + sampled = [[{"id": "a", "score": score, "justification": f"sample {n}"}] for n, score in enumerate(scores, 1)] + + [row] = judge_samples.median_rows(sampled) + + assert row["score"] == kept and row["justification"] == f"sample {scores.index(kept) + 1}" + assert [each["score"] for each in row["samples"]] == scores + + +def test_a_task_that_asks_no_samples_or_samples_a_format_without_one_score_a_row_fails_to_load(): + with pytest.raises(ValueError, match="judge_samples must be a positive integer, got 0"): + RubricsVerifierTaskStep.from_dict({**G._step().to_dict(), "judge_samples": 0}) + with pytest.raises(ValueError, match="min_judge_agreement must be a number from 0 to 1, got 2"): + RubricsVerifierTaskStep.from_dict({**G._step().to_dict(), "min_judge_agreement": 2}) + with pytest.raises(ValueError, match="min_judge_agreement does not apply to output_format=rubric_evidence"): + G._evidence_step("rubric_evidence", min_judge_agreement=0.67) + with pytest.raises(ValueError, match="min_judge_agreement"): + UserSimJudge.from_dict({"id": "sim", "version": 1, "type": "user_sim_judge", "run_step_id": "week", + "min_judge_agreement": 0.5}) + shared = G._step(judge_samples=3, min_judge_agreement=0.67) + assert RubricsVerifierTaskStep.from_dict(shared.to_dict()).min_judge_agreement == 0.67 + assert "min_judge_agreement" not in G._step(judge_samples=3).to_dict() + with pytest.raises(ValueError, match="judge_samples does not apply to output_format=rubric_evidence"): + G._evidence_step("rubric_evidence", judge_samples=3) + with pytest.raises(ValueError, match="judge_samples"): + UserSimJudge.from_dict({"id": "sim", "version": 1, "type": "user_sim_judge", "run_step_id": "week", + "judge_samples": 3}) + for count in (2, 3): + assert RubricsVerifierTaskStep.from_dict(G._step(judge_samples=count).to_dict()).judge_samples == count + assert "judge_samples" not in G._step().to_dict() + + +@pytest.mark.asyncio +async def test_a_direct_judge_grades_each_criterion_three_times_and_keeps_each_ones_median(monkeypatch): + seen = _sampled_llm(monkeypatch, _two_to_one) + context = G._context() + + grade = await _grade(G._step(default_model="gpt-4o-mini", judge_samples=3, min_judge_agreement=0.67), context) + + rows = {row["id"]: row for row in grade["verifier_criteria"]} + assert (rows["table-reserved"]["score"], rows["party-size"]["score"]) == (1.0, 1.0) + assert rows["table-reserved"]["agreement"] == rows["party-size"]["agreement"] == 0.67 + assert rows["table-reserved"]["justification"] == "sample 1 scored c1 1.0" + assert rows["party-size"]["justification"] == "sample 2 scored c2 1.0" + assert [s["score"] for s in rows["table-reserved"]["samples"]] == [1.0, 0.0, 1.0] + assert sorted(sample for _, sample in seen["calls"]) == [1, 2, 3] + assert sorted((c["sample"], c["outcome"]) for c in grade["judge_calls"]) == [(1, "answered"), (2, "answered"), + (3, "answered")] + assert grade["verifier_settings"]["judge_samples"] == 3 + assert grade["verifier_settings"]["min_judge_agreement"] == 0.67 + entry = context.metadata["verifications"]["vid"] + assert entry["judge_samples"] == 3 and all(len(row["samples"]) == 3 for row in entry["results"]) + + +@pytest.mark.asyncio +async def test_two_samples_that_split_fail_the_criterion_with_the_failing_samples_reason(monkeypatch): + _sampled_llm(monkeypatch, _two_to_one) + + grade = await _grade(G._step(default_model="gpt-4o-mini", judge_samples=2, min_judge_agreement=0.5), G._context()) + + rows = {row["id"]: row for row in grade["verifier_criteria"]} + assert (rows["table-reserved"]["score"], rows["party-size"]["score"]) == (0.0, 0.0) + assert rows["table-reserved"]["justification"] == "sample 2 scored c1 0.0" + assert rows["party-size"]["justification"] == "sample 1 scored c2 0.0" + assert grade["score"] == 0.0 and grade["verifier_settings"]["judge_samples"] == 2 + + +@pytest.mark.asyncio +async def test_a_judge_of_one_sample_grades_as_before(monkeypatch): + _sampled_llm(monkeypatch, lambda sample, ids: dict.fromkeys(ids, 1.0)) + context = G._context() + + grade = await _grade(G._step(default_model="gpt-4o-mini"), context) + + assert all("samples" not in row for row in grade["verifier_criteria"]) + assert [c["sample"] for c in grade["judge_calls"]] == [None] + assert "judge_samples" not in context.metadata["verifications"]["vid"] + + +@pytest.mark.asyncio +async def test_batches_times_samples_share_the_judges_concurrency(monkeypatch): + seen = _sampled_llm(monkeypatch, lambda sample, ids: dict.fromkeys(ids, 1.0), slow_s=0.05) + step = G._step(default_model="gpt-4o-mini", judge_samples=3, judge_batch_size=1, judge_batch_concurrency=2) + + grade = await _grade(step, G._context()) + + assert sorted(seen["calls"]) == [(b, s) for b in (1, 2) for s in (1, 2, 3)] + assert seen["most"] == 2 + assert sorted((c["batch"], c["sample"]) for c in grade["judge_calls"]) == sorted(seen["calls"]) + assert all(len(row["samples"]) == 3 for row in grade["verifier_criteria"]) + + +@pytest.mark.asyncio +async def test_a_sample_out_of_retries_fails_the_grade_with_every_call_recorded(monkeypatch): + _sampled_llm(monkeypatch, lambda sample, ids: dict.fromkeys(ids, 1.0), failing_sample=2, slow_s=0.01) + context = G._context() + + with pytest.raises(RuntimeError, match="failed after 3 attempts"): + await G._step(default_model="gpt-4o-mini", judge_samples=3).execute(context) + + grade = context.metadata["grades"]["verify"] + assert grade["verifier_status"] == "failed" + assert [c["outcome"] for c in grade["judge_calls"] if c["sample"] == 2] == ["refused"] * 3 + + +@pytest.mark.asyncio +async def test_a_runs_count_reaches_a_judge_that_can_take_it_and_says_it_was_overridden(monkeypatch): + seen = _sampled_llm(monkeypatch, _two_to_one) + + grade = await _grade(G._step(default_model="gpt-4o-mini"), + G._context({"judge_samples": 3, "min_judge_agreement": 0.67})) + + assert len(seen["calls"]) == 3 and grade["verifier_status"] == "graded" + settings = grade["verifier_settings"] + assert settings["judge_samples"] == 3 and settings["min_judge_agreement"] == 0.67 + assert {"judge_samples", "min_judge_agreement"} <= set(settings["overridden"]) + + +@pytest.mark.asyncio +async def test_a_runs_count_a_format_cant_take_grades_once_and_is_recorded_as_not_sent(): + calls: list[str] = [] + step = G._direct_judge(G._evidence_step("rubric_evidence"), + lambda ids, n: calls.append("call") or G._evidence(ids)) + + grade = await _grade(step, G._context({"judge_samples": 3, "min_judge_agreement": 0.67})) + + assert calls == ["call"] and grade["verifier_status"] == "graded" + assert grade["verifier_settings"]["judge_samples"] == 1 + assert grade["verifier_settings"]["not_sent"] == {"judge_samples": 3, "min_judge_agreement": 0.67} + assert "min_judge_agreement" not in grade["verifier_settings"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("overrides, why", [({"judge_samples": 0}, "judge_samples must be a positive integer, got 0"), + ({"judge_samples": 3, "min_judge_agreement": 1.5}, + "min_judge_agreement must be a number from 0 to 1, got 1.5")]) +async def test_a_runs_bad_count_or_bar_fails_the_grade_saying_why_before_any_call(monkeypatch, overrides, why): + seen = _sampled_llm(monkeypatch, lambda sample, ids: dict.fromkeys(ids, 1.0)) + context = G._context(overrides) + + with pytest.raises(ValueError, match=why): + await G._step(default_model="gpt-4o-mini").execute(context) + + assert context.metadata["grades"]["verify"]["verifier_status"] == "failed" and seen["calls"] == [] + + +@pytest.mark.asyncio +async def test_the_tasks_own_agent_judge_takes_every_sample_each_in_a_conversation_of_its_own(monkeypatch): + sent: list[dict] = [] + + async def send(url, **kwargs): + sent.append({"url": url, "context_id": kwargs.get("context_id"), "sample": judge_usage._SAMPLE.get()}) + return f"task-{len(sent)}", None + + async def poll(url, task_id, **kwargs): + text = _verdicts(_two_to_one(judge_usage._SAMPLE.get(), ["c1", "c2"]), judge_usage._SAMPLE.get()) + return {"status": {"state": "completed", "message": {"parts": [{"kind": "text", "text": text}]}}} + + monkeypatch.setattr(protocol, "send_a2a_message", send) + monkeypatch.setattr(protocol, "poll_a2a_task", poll) + context = G._context() + context.deployed_agents.append(DeployedAgent(agent_name="judge", api_url="http://judge.test", + a2a_url="http://judge.test", sandbox_id="sb-judge")) + step = G._step(use_agent_judge=True, agent_name="judge", judge_samples=3, min_judge_agreement=0.67) + + async def configured(**kwargs): + return None + + step._configure_judge_a2a = configured + grade = await _grade(step, context) + + assert sorted(s["sample"] for s in sent) == [1, 2, 3] and {s["context_id"] for s in sent} == {None} + assert {s["url"] for s in sent} == {"http://judge.test"} + assert [row["score"] for row in grade["verifier_criteria"]] == [1.0, 1.0] + assert sorted(c["sample"] for c in grade["judge_calls"]) == [1, 2, 3] + + +def test_the_run_flags_set_the_runs_count_and_bar_and_refuse_bad_ones(tmp_path): + assert _overrides(None, None, None, 2) == {"judge_samples": 2} + assert _overrides(None, None, None, 3, 0.0) == {"judge_samples": 3, "min_judge_agreement": 0.0} + assert _overrides(None, None, None, None) == {} + for bad in (0, -1): + with pytest.raises(ValueError, match="judge_samples must be a positive integer"): + run_bundle(tmp_path, judge_samples=bad) + with pytest.raises(ValueError, match="min_judge_agreement must be a number from 0 to 1"): + run_bundle(tmp_path, min_judge_agreement=1.5) + result = CliRunner().invoke(run_command, ["some-bundle", "--judge-samples", "0"]) + assert result.exit_code != 0 and "positive integer" in result.output + result = CliRunner().invoke(run_command, ["some-bundle", "--min-judge-agreement", "1.5"]) + assert result.exit_code != 0 and "number from 0 to 1" in result.output + + +@pytest.mark.asyncio +async def test_by_default_the_median_decides_a_split_and_each_row_says_how_much_its_samples_agreed(monkeypatch): + _sampled_llm(monkeypatch, _two_to_one) + + grade = await _grade(G._step(default_model="gpt-4o-mini", judge_samples=3), G._context()) + + assert (grade["verifier_status"], grade["score"]) == ("graded", 1.0) + assert [row["agreement"] for row in grade["verifier_criteria"]] == [0.67, 0.67] + assert grade["verifier_settings"]["min_judge_agreement"] == 0.5 + assert judge_samples.splits(grade["verifier_criteria"]) == ["table-reserved (2 of 3 pass)", "party-size (2 of 3 pass)"] + + +@pytest.mark.asyncio +async def test_a_bar_of_1_fails_a_split_grade_keeping_each_row_and_its_samples_then_fails_the_step(monkeypatch): + _sampled_llm(monkeypatch, _two_to_one) + context = G._context() + + with pytest.raises(JudgeDisagreementError) as raised: + await G._step(default_model="gpt-4o-mini", judge_samples=3, min_judge_agreement=1.0).execute(context) + + assert str(raised.value) == ( + "Verifier 'vid': its judge samples split on 2 criteria, under min_judge_agreement 1: table-reserved (2 of 3 " + "samples pass it), party-size (2 of 3 samples pass it). Each sample's verdict and justification are on the " + "grade's rows; a lower min_judge_agreement keeps the median instead.") + grade = context.metadata["grades"]["verify"] + assert (grade["verifier_status"], grade["score"], grade["passed"]) == ("failed", None, False) + assert grade["verifier_error_reasoning"] == str(raised.value) + assert grade["verifier_settings"]["min_judge_agreement"] == 1.0 + rows = {row["id"]: row for row in grade["verifier_criteria"]} + assert [s["passed"] for s in rows["table-reserved"]["samples"]] == [True, False, True] + assert rows["table-reserved"]["agreement"] == 0.67 and rows["table-reserved"]["score"] == 1.0 + entry = context.metadata["verifications"]["vid"] + assert entry["judge_disagreement"] == {"min_judge_agreement": 1.0, "criteria": [ + {"id": "table-reserved", "agreement": 0.67}, {"id": "party-size", "agreement": 0.67}]} + assert len(entry["results"]) == 2 + + +@pytest.mark.asyncio +async def test_samples_that_agree_grade_as_before_with_the_default_bar_recorded(monkeypatch): + _sampled_llm(monkeypatch, lambda sample, ids: dict.fromkeys(ids, 1.0)) + + grade = await _grade(G._step(default_model="gpt-4o-mini", judge_samples=3), G._context()) + + assert (grade["verifier_status"], grade["score"]) == ("graded", 1.0) + assert all(row["agreement"] == 1.0 for row in grade["verifier_criteria"]) + assert grade["verifier_settings"]["min_judge_agreement"] == 0.5 + assert judge_samples.splits(grade["verifier_criteria"]) == [] + + +@pytest.mark.asyncio +async def test_one_sample_records_no_bar_and_a_bar_without_samples_never_fails(monkeypatch): + _sampled_llm(monkeypatch, lambda sample, ids: {**dict.fromkeys(ids, 1.0), "c1": 0.0}) + + plain = await _grade(G._step(default_model="gpt-4o-mini"), G._context()) + barred = await _grade(G._step(default_model="gpt-4o-mini", min_judge_agreement=1.0), G._context()) + + assert plain["verifier_status"] == barred["verifier_status"] == "graded" + assert "min_judge_agreement" not in plain["verifier_settings"] + assert all("agreement" not in row for row in plain["verifier_criteria"] + barred["verifier_criteria"]) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("bar, graded", [(0.67, True), (0.7, False)]) +async def test_a_bar_two_of_three_meets_keeps_the_median_and_a_higher_one_fails(monkeypatch, bar, graded): + _sampled_llm(monkeypatch, _two_to_one) + context = G._context({"judge_samples": 3, "min_judge_agreement": bar}) + + if graded: + await G._step(default_model="gpt-4o-mini").execute(context) + else: + with pytest.raises(JudgeDisagreementError, match="under min_judge_agreement 0.7"): + await G._step(default_model="gpt-4o-mini").execute(context) + + assert context.metadata["grades"]["verify"]["verifier_status"] == ("graded" if graded else "failed") + + +@pytest.mark.asyncio +async def test_partial_scores_agree_on_their_verdict_so_close_scores_pass_and_a_split_verdict_fails(monkeypatch): + by_sample = {1: {"c1": 0.75, "c2": 0.9}, 2: {"c1": 0.7, "c2": 0.25}, 3: {"c1": 0.8, "c2": 0.9}} + _sampled_llm(monkeypatch, lambda sample, ids: by_sample[sample]) + context = G._context() + + with pytest.raises(JudgeDisagreementError, match=r"split on a criterion, .*: party-size \(2 of 3 samples pass it\)"): + await G._step(default_model="gpt-4o-mini", judge_samples=3, output_format="rubric_partial", + min_judge_agreement=1.0).execute(context) + + rows = {row["id"]: row for row in context.metadata["grades"]["verify"]["verifier_criteria"]} + assert (rows["table-reserved"]["score"], rows["table-reserved"]["agreement"]) == (0.75, 1.0) + assert rows["party-size"]["agreement"] == 0.67 + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("local_stores") +@pytest.mark.parametrize("fatal", [True, False]) +async def test_a_split_fails_the_task_or_is_tolerated_as_the_steps_fail_task_on_error_says(monkeypatch, fatal): + _sampled_llm(monkeypatch, _two_to_one) + task = Task(id="t", version=1, steps=[G._step(default_model="gpt-4o-mini", judge_samples=3, + min_judge_agreement=1.0, fail_task_on_error=fatal)]) + context = G._context() + + if fatal: + with pytest.raises(JudgeDisagreementError): + await task.run(context=context) + else: + context = await task.run(context=context) + + [failed] = context.metadata["failed_steps"] + assert (failed["step_id"], failed["error_type"], failed["is_fatal"]) == ("verify", "JudgeDisagreementError", fatal) + assert context.metadata["grades"]["verify"]["verifier_status"] == "failed" + + +class _Fleet: + """Judge agents the verifier deploys, each with a sandbox of its own: what each was sent, what was staged in each, + and which were terminated; the ``failing`` deploy (1-based) raises.""" + + def __init__(self, failing=None): + self.failing, self.deployed, self.files, self.terminated, self.sent = failing, [], {}, [], [] + fleet = self + + class Sandbox: + def __init__(self, sandbox_id): + self.sandbox_id = sandbox_id + + async def write_file_from_object(self, object_url, path, **kwargs): + fleet.files.setdefault(self.sandbox_id, []).append(path) + + async def write_file_from_text(self, text, path, **kwargs): + fleet.files.setdefault(self.sandbox_id, []).append(path) + + async def terminate(self): + fleet.terminated.append(self.sandbox_id) + + class Provider: + async def get_sandbox(self, sandbox_id): + return Sandbox(sandbox_id) + + class Agent: + async def deploy(self, **kwargs): + n = len(fleet.deployed) + 1 + fleet.deployed.append(f"sb-{n}") + if n == fleet.failing: + fleet.deployed.pop() + raise ConnectionError(f"deploy {n} dropped") + await asyncio.sleep(0) + return SimpleNamespace(a2a_url=f"http://judge-{n}.test", sandbox_id=f"sb-{n}", agent_card={}, + sandbox_type=None, control_headers={}, model_endpoint_host=None) + + self.provider, self.agent = Provider(), Agent() + + def install(self, monkeypatch) -> None: + monkeypatch.setattr(A2AAgent, "get", staticmethod(lambda agent_id: self.agent)) + monkeypatch.setattr(sandbox_provider, "get_agent_sandbox_provider", lambda: self.provider) + + async def send(url, **kwargs): + self.sent.append((judge_usage._SAMPLE.get(), url)) + return f"task-{len(self.sent)}", None + + async def poll(url, task_id, **kwargs): + sample = judge_usage._SAMPLE.get() + text = _verdicts(_two_to_one(sample, ["c1", "c2"]), sample) + return {"status": {"state": "completed", "message": {"parts": [{"kind": "text", "text": text}]}}} + + monkeypatch.setattr(protocol, "send_a2a_message", send) + monkeypatch.setattr(protocol, "poll_a2a_task", poll) + + +def _deployed_judge_step(**kw) -> RubricsVerifierTaskStep: + step = G._step(use_agent_judge=True, use_trajectory=True, judge_a2a_agent_id="judge-agent", judge_samples=3, **kw) + + async def configured(**kwargs): + return None + + step._configure_judge_a2a = configured + step._compact_trajectory = lambda *a, **k: rv._CompactedTrajectory.for_screenshot( + None, [], container_object_url="mem://traj/raw.json") + return step + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("local_stores") +async def test_a_judge_the_verifier_deploys_gets_one_of_its_own_per_sample_each_staged_and_terminated(monkeypatch): + install_model_config(monkeypatch, base_url="https://gw.test/v1", api_key="configured-key") + fleet = _Fleet() + fleet.install(monkeypatch) + + grade = await _grade(_deployed_judge_step(min_judge_agreement=0.67), G._context()) + + assert fleet.deployed == ["sb-1", "sb-2", "sb-3"] and sorted(fleet.terminated) == fleet.deployed + assert {sandbox: len(paths) for sandbox, paths in fleet.files.items()} == {"sb-1": 1, "sb-2": 1, "sb-3": 1} + by_sample = {} + for sample, url in fleet.sent: + by_sample.setdefault(sample, set()).add(url) + assert sorted(by_sample) == [1, 2, 3] and all(len(urls) == 1 for urls in by_sample.values()) + assert len(set().union(*by_sample.values())) == 3 + assert [row["score"] for row in grade["verifier_criteria"]] == [1.0, 1.0] + store = get_config().get_object_store() + for call in grade["judge_calls"]: + assert len(json.loads(store.get(call["input"]["object_url"]))["files"]) == 1 + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("local_stores") +async def test_a_judge_that_fails_to_deploy_for_one_sample_fails_the_grade_and_every_deployed_one_is_terminated( + monkeypatch): + install_model_config(monkeypatch, base_url="https://gw.test/v1", api_key="configured-key") + fleet = _Fleet(failing=2) + fleet.install(monkeypatch) + context = G._context() + + with pytest.raises(ConnectionError, match="deploy 2 dropped"): + await _deployed_judge_step().execute(context) + + assert sorted(fleet.terminated) == sorted(fleet.deployed) and fleet.sent == [] + assert context.metadata["grades"]["verify"]["verifier_status"] == "failed"