From d8697d1fa8cbd0826f69126b3cab439c9327c0f0 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 13:08:18 -0800 Subject: [PATCH 1/8] feat(verifiers): each judge call's record names exactly what it was sent, and a judge's settings name the trajectory source it read for each turn A direct judge call's input is its messages, response format and settings; an agent judge call's is its message and a manifest of every file put in its sandbox, each one written as text stored too. Each is stored by its sha256 under judge-inputs/, so identical content is stored once, and the call's record in judge_calls names it as input, or as input_error when the store refused it, which never fails the grade. verifier_settings.trajectory_sources lists each turn the judge read with its format, an ATIF copy's adapter version beside it; the always-on judge lists the formats its staged trajectories read as. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- .../verifiers/always_on_agent_verifier.py | 5 + .../verifiers/judge_utils/judge_usage.py | 106 +++++++++-- .../task_steps/verifiers/rubrics_verifier.py | 60 +++++-- .../task_step/judge_settings_wire_test.py | 7 +- .../verifiers/test_judge_inputs_stored.py | 170 ++++++++++++++++++ 6 files changed, 319 insertions(+), 31 deletions(-) create mode 100644 tst/unit/task_step/verifiers/test_judge_inputs_stored.py diff --git a/AGENTS.md b/AGENTS.md index 5ac13f531..880c82038 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -155,7 +155,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`), and its `verifier_settings` hold 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 and every file put in its sandbox, stored by sha256 under `judge-inputs/`), 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`). | | `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/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 1b29396f3..c981bcd38 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 @@ -68,6 +68,7 @@ TurnEvents, turn_events, ) +from agent_env.task_step.task_steps.verifiers.judge_utils import judge_usage from agent_env.task_step.task_steps.verifiers.rubrics_verifier import ( RUN_CONTEXT_PARTS, RubricsVerdict, @@ -405,6 +406,10 @@ async def stage_trajectory(self, context: TaskStepContext, prompt_response: Prom 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) + if (judge := judge_usage.current()) is not None: + # 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()), record=staged.record) 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 6d9c9ac38..988503069 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 @@ -1,22 +1,35 @@ -"""A judge step's record of its run, beside its usage: each model call the judge made and the settings those calls -carried, for its grade (``judge_calls``, ``verifier_settings``). The record of the run in progress is held per task, -since a step is shared by every run of its task: a judge step's ``execute`` scopes it (``scope``) and its judging starts -it (``start``).""" +"""A judge step's record of its run, beside its usage: each model call the judge made, with a reference to exactly what +it was sent, and the settings and trajectory sources those calls carried, for its grade (``judge_calls``, +``verifier_settings``). The record of the run in progress is held per task, since a step is shared by every run of its +task: a judge step's ``execute`` scopes it (``scope``) and its judging starts it (``start``). + +What a call was sent is stored by its sha256 under ``judge-inputs/`` in the object store (``store_input``), so a retried +request's input or a file another run staged is stored once, and a reader checks it against the key it's stored under.""" from __future__ import annotations import contextlib +import functools +import hashlib +import json +import logging from collections.abc import Iterator, Mapping from contextvars import ContextVar from typing import Any, Optional from agentenv_protocol.a2a_agent import Usage +from agent_env.config import get_config from agent_env.config.model import ModelRole from agent_env.config.model_pricing import ReportedBy, Tokens, price from agent_env.task_step.context import TaskStepContext +from agent_env.task_step.thread_work import finish_on_thread from agent_env.task_step.usage import StepUsage +logger = logging.getLogger(__name__) + +INPUTS_PREFIX = "judge-inputs" + class JudgeUsage(StepUsage): """A judge step's usage, written as every step's is, and its own record of the run: each model call it made @@ -29,23 +42,33 @@ def __init__(self, context: TaskStepContext, step_id: str) -> None: self.sent: Optional[dict[str, Any]] = None self.not_sent: dict[str, Any] = {} self.endpoint_host: Optional[str] = None + self.staged: list[dict[str, Any]] = [] + self.sources: Optional[list[dict[str, Any]]] = None def call(self, role: ModelRole, usage: Optional[Usage], *, model: Optional[str], endpoint_host: Optional[str], - reported_by: ReportedBy = ReportedBy.HARNESS, cost: Optional[Mapping[str, Any]] = None) -> None: + reported_by: ReportedBy = ReportedBy.HARNESS, cost: Optional[Mapping[str, Any]] = None, + sent: Optional[Mapping[str, Any]] = None) -> None: """The base's, and the answered call in the record: ``cost``, the cost keys the call itself carried (a direct - call's, from ``model_call``), else its price from LiteLLM's map.""" + call's, from ``model_call``), else its price from LiteLLM's map; ``sent``, the reference to what it was sent + (``store_input``).""" super().call(role, usage, model=model, endpoint_host=endpoint_host, reported_by=reported_by) - self._record("answered", usage, model, endpoint_host, reported_by, cost=cost) + self._record("answered", usage, model, endpoint_host, reported_by, cost=cost, sent=sent) def cut_off_call(self, role: ModelRole, *, model: Optional[str], endpoint_host: Optional[str], - reported_by: ReportedBy = ReportedBy.HARNESS) -> None: + reported_by: ReportedBy = ReportedBy.HARNESS, sent: Optional[Mapping[str, Any]] = None) -> None: super().cut_off_call(role, model=model, endpoint_host=endpoint_host, reported_by=reported_by) - self._record("cut_off", None, model, endpoint_host, reported_by) + self._record("cut_off", None, model, endpoint_host, reported_by, sent=sent) - def refused_call(self, *, model: Optional[str], endpoint_host: Optional[str], error: str) -> None: + def refused_call(self, *, model: Optional[str], endpoint_host: Optional[str], error: str, + sent: Optional[Mapping[str, Any]] = None) -> None: """A call that got no answer and cost nothing, as one LiteLLM refused before sending it or one the endpoint refused: in the record, not in the step's usage.""" - self._record("refused", None, model, endpoint_host, ReportedBy.PROVIDER, error=error) + self._record("refused", None, model, endpoint_host, ReportedBy.PROVIDER, error=error, sent=sent) + + def read(self, sources: list[dict[str, Any]]) -> None: + """The trajectory sources the run's judge read: one per turn, with its format and, for an ATIF copy, the + adapter version that made it.""" + self.sources = list(sources) def carried(self, sent: dict[str, Any], not_sent: dict[str, Any], endpoint_host: Optional[str]) -> None: """The settings the run's calls carried, kept from its first call, since every call of a run carries the same.""" @@ -53,18 +76,73 @@ def carried(self, sent: dict[str, Any], not_sent: dict[str, Any], endpoint_host: self.sent, self.not_sent, self.endpoint_host = dict(sent), dict(not_sent), endpoint_host def _record(self, outcome: str, usage: Optional[Usage], model: Optional[str], endpoint_host: Optional[str], - reported_by: ReportedBy, *, error: Optional[str] = None, - cost: Optional[Mapping[str, Any]] = None) -> None: + reported_by: ReportedBy, *, error: Optional[str] = None, cost: Optional[Mapping[str, Any]] = None, + sent: Optional[Mapping[str, Any]] = None) -> None: if cost is None: cost = price(Tokens.of(usage.to_dict()) if usage is not None else None, usage.cost_usd if usage is not None else None, model=model, prices=self._prices, reported_by=reported_by).fields() self.calls.append({"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(), "attempt": _ATTEMPT.get(), **(sent or {}), **({"error": error} if error is not None else {})}) +async def store_input(body: Any) -> dict[str, Any]: + """``body`` as the JSON a judge call was sent, stored by its sha256 (``store_bytes``): ``{"input": reference}``, or + ``{"input_error": why}`` when the store refused it, which never fails the grade.""" + data = json.dumps(body, ensure_ascii=False, sort_keys=True).encode() + try: + return {"input": await store_bytes(data, "application/json")} + except Exception as exc: + logger.warning("a judge call's input wasn't stored: %s", exc) + return {"input_error": f"{type(exc).__name__}: {exc}"[:300]} + + +async def store_bytes(data: bytes, content_type: str) -> dict[str, Any]: + """``data`` in the object store under ``judge-inputs/``, once whatever writes it: its ``object_url``, + ``bytes`` and ``sha256``.""" + digest = hashlib.sha256(data).hexdigest() + url = await finish_on_thread(functools.partial(_put_once, digest, data, content_type), + "Storing a judge call's input") + return {"object_url": url, "bytes": len(data), "sha256": digest} + + +def _put_once(digest: str, data: bytes, content_type: str) -> str: + config = get_config() + store, key = config.get_object_store(), f"{config.get_artifact_key_prefix()}{INPUTS_PREFIX}/{digest}" + return store.object_url(key) if store.exists(key) else store.put(key, data, content_type=content_type, + allow_overwrite=True) + + +class StagingRecorder: + """The judge's sandbox, every file written into it kept in its run's manifest (``JudgeUsage.staged``): a file + written as text stored by its sha256 too, one copied from a stored object named by that object's URL.""" + + def __init__(self, sandbox: Any, judge: JudgeUsage) -> None: + self._sandbox, self._judge = sandbox, judge + + 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) + data = text.encode() + try: + stored = await store_bytes(data, "text/plain; charset=utf-8") + except Exception as exc: + logger.warning("a judge's staged file %s wasn't stored: %s", path, exc) + stored = {"bytes": len(data), "sha256": hashlib.sha256(data).hexdigest(), + "input_error": f"{type(exc).__name__}: {exc}"[:300]} + self._judge.staged.append({"path": path, **stored}) + 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._judge.staged.append({"path": path, "object_url": object_url}) + return written + + _RUN: ContextVar[Optional[JudgeUsage]] = ContextVar("judge_run", default=None) _BATCH: ContextVar[Optional[int]] = ContextVar("judge_batch", default=None) _ATTEMPT: ContextVar[Optional[int]] = ContextVar("judge_attempt", default=None) 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 5b6aca762..8bf26db81 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 @@ -64,6 +64,7 @@ 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 ( + ATIF, AtifDocuments, TurnSource, atif_turns, @@ -322,13 +323,28 @@ def _direct_settings(route: model_call.ModelRoute, run: Mapping[str, Any] return params, {key: value for key, value in sent.items() if value is not None}, not_sent -def _record_failed_call(judge: JudgeUsage, exc: BaseException, *, model: str, endpoint_host: Optional[str]) -> None: - """A direct judge request that got no answer, in the run's record: cut off by a time limit (maybe billed, so a call - of unknown usage in the step's usage too), or refused, costing nothing.""" +def _record_failed_call(judge: JudgeUsage, exc: BaseException, *, model: str, endpoint_host: Optional[str], + sent: Mapping[str, Any]) -> None: + """A direct judge request that got no answer, in the run's record with what it was sent: cut off by a time limit + (maybe billed, so a call of unknown usage in the step's usage too), or refused, costing nothing.""" if model_call.cut_off(exc): - judge.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=endpoint_host, reported_by=ReportedBy.PROVIDER) + judge.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=endpoint_host, reported_by=ReportedBy.PROVIDER, + sent=sent) else: - judge.refused_call(model=model, endpoint_host=endpoint_host, error=f"{type(exc).__name__}: {exc}") + judge.refused_call(model=model, endpoint_host=endpoint_host, error=f"{type(exc).__name__}: {exc}", sent=sent) + + +def _trajectory_sources(prompt_response: PromptResponse) -> list[dict[str, Any]]: + """Each turn of ``prompt_response`` the judge reads, by its stored label: the turn, its format, and an ATIF copy's + adapter version.""" + sources = [] + for turn, record in enumerate(prompt_response.target_agent_per_turn_trajectories or [], 1): + record = record or {} + fmt = record.get("format") + atif = (record.get("atif") or {}) if fmt == ATIF else None + sources.append({"turn": turn, "format": fmt, + **({"adapter_version": atif.get("adapter_version")} if atif is not None else {})}) + return sources def _image_url_block(frame: ImageFrame) -> dict: @@ -874,6 +890,8 @@ def verifier_settings(self, context: TaskStepContext) -> dict[str, Any]: settings["not_sent"] = dict(judge.not_sent) if judge.endpoint_host: settings["judge_endpoint_host"] = judge.endpoint_host + if judge is not None and judge.sources: + settings["trajectory_sources"] = list(judge.sources) return {**settings, "overridden": overridden} def grade_fields(self, context: TaskStepContext) -> dict[str, Any]: @@ -909,6 +927,7 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: if prompt_response is None: raise StepContextError(f"PromptResponse with prompt_id='{self.prompt_id}' not found in context") run = self._run_values(context) + judge = judge_usage.start(context, self.id) grade_up_to_turn = _validated_turn(run["grade_up_to_turn"]) as_of = _as_of_turn(prompt_response, grade_up_to_turn) if as_of is not prompt_response and not self.use_trajectory: @@ -935,6 +954,8 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: raise RuntimeError(f"No trajectory available for prompt_id='{self.prompt_id}'") # A run whose turns are atif/1 copies reads each turn by its label; one with none keeps the native path. atif = atif_turns(prompt_response) if self.use_trajectory else None + if self.use_trajectory: + judge.read(_trajectory_sources(prompt_response)) documents = AtifDocuments() overrides = context.metadata.get("user_overrides", {}) @@ -1072,7 +1093,7 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: 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 = await provider.get_sandbox(judge_sandbox_id) + sandbox = judge_usage.StagingRecorder(await provider.get_sandbox(judge_sandbox_id), judge) staged = await self.stage_trajectory(context, stored_response, run_context, sandbox, judge_container) if staged is None and atif is not None: media = await self._stage_atif_turns( @@ -1193,7 +1214,7 @@ def eval_prompt_for(batch: list[dict]) -> str: 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.") concurrency = asyncio.Semaphore(batch_concurrency or self.DEFAULT_JUDGE_BATCH_CONCURRENCY) - usage = judge_usage.start(context, self.id) + usage = judge async def grade(batch: list[dict], number: Optional[int] = None ) -> tuple[list[dict], int, list[dict], Optional[str]]: @@ -1618,21 +1639,28 @@ async def _prompt_llm_judge( judge = judge_usage.current() if judge is not None: judge.carried(sent, not_sent, route.endpoint_host) + inputs: dict[bool, dict[str, Any]] = {} # Some endpoints reject json_schema with images. Fall back once on that exact # error shape; malformed JSON is handled by the outer output-retry loop. use_response_format = True last_exc: Exception | None = None for attempt in range(1, self.DEFAULT_MAX_RETRIES + 1): + if judge is not None and use_response_format not in inputs: + inputs[use_response_format] = await judge_usage.store_input({ + "messages": messages, "response_format": response_format if use_response_format else None, + "settings": params}) + judge_input = inputs.get(use_response_format, {}) try: reply = await model_call.complete(route, messages, timeout=self.judge_timeout_seconds, response_format=response_format if use_response_format else None, settings=params) - return {"response": reply.content, "trajectory_object_url": None, **reply.fields()} + return {"response": reply.content, "trajectory_object_url": None, "judge_input": judge_input, + **reply.fields()} except Exception as exc: last_exc = exc if judge is not None: - _record_failed_call(judge, exc, model=model, endpoint_host=route.endpoint_host) + _record_failed_call(judge, exc, model=model, endpoint_host=route.endpoint_host, sent=judge_input) if params and model_call.refused_setting(exc): raise JudgeSettingRefused(f"{model} refused the judge's " f"{sorted(key for key in _JUDGE_SETTINGS if key in sent)}: {exc}") from exc @@ -1720,6 +1748,8 @@ async def _invoke_judge_a2a( from agent_env.a2a_agent import protocol host = getattr(judge_agent, "model_endpoint_host", None) + sent = ({"sent": await judge_usage.store_input({"message": eval_prompt, "files": list(usage.staged)})} + if isinstance(usage, JudgeUsage) else {}) try: task_id, _ = await protocol.send_a2a_message( judge_a2a_url, @@ -1730,7 +1760,7 @@ async def _invoke_judge_a2a( ) except (TimeoutError, asyncio.CancelledError): # The judge may have taken the message before its task id came back; with no id, it can't be cancelled. - usage.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=host) + usage.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=host, **sent) raise try: result = await protocol.poll_a2a_task( @@ -1741,22 +1771,22 @@ async def _invoke_judge_a2a( sandbox_id=getattr(judge_agent, "sandbox_id", None), ) except asyncio.CancelledError: - usage.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=host) + usage.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=host, **sent) # A sibling batch failed: stop this judge too, or it keeps working on a reused judge sandbox. await asyncio.shield(protocol.cancel_a2a_task(judge_a2a_url, task_id)) raise except protocol.AgentUnreachableError: - usage.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=host) + usage.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=host, **sent) raise except TimeoutError as e: - usage.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=host) + usage.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=host, **sent) if self.judge_timeout_retries is None: raise raise await self._judge_timed_out(str(e), judge_a2a_url, judge_agent_card, task_id, judge_agent) from e state = result["status"]["state"] status_msg = (result.get("status") or {}).get("message") or {} tr = protocol.TerminalResponse.from_message(status_msg) - usage.call(ModelRole.JUDGE, tr.usage, model=model, endpoint_host=host) + usage.call(ModelRole.JUDGE, tr.usage, model=model, endpoint_host=host, **sent) if state == "failed": sandbox_id = getattr(judge_agent, "sandbox_id", None) logger.error( @@ -1913,7 +1943,7 @@ def _record_direct_call(usage: StepUsage, data: dict, *, model: str) -> None: read = Usage.from_model_response(data["usage"]) if data.get("usage") else None if data.get("reported_cost_usd") is not None: read = replace(read or Usage(), cost_usd=data["reported_cost_usd"]) - extra = ({"cost": {key: data[key] for key in Cost.KEYS if key in data}} + extra = ({"cost": {key: data[key] for key in Cost.KEYS if key in data}, "sent": data.get("judge_input")} if isinstance(usage, JudgeUsage) else {}) usage.call(ModelRole.JUDGE, read, model=data.get("model") or model, endpoint_host=data.get("endpoint_host"), reported_by=ReportedBy.PROVIDER, **extra) diff --git a/tst/integration/task_step/judge_settings_wire_test.py b/tst/integration/task_step/judge_settings_wire_test.py index b0dd1fedc..0a3743623 100644 --- a/tst/integration/task_step/judge_settings_wire_test.py +++ b/tst/integration/task_step/judge_settings_wire_test.py @@ -1,15 +1,17 @@ -"""A direct judge's settings on the wire: through LiteLLM's real client to a fake OpenAI-compatible endpoint, the run's +"""A direct judge's settings and stored input on the wire: through LiteLLM's real client to a fake OpenAI-compatible endpoint, the run's effort goes out as ``reasoning_effort`` where LiteLLM takes it, a thinking budget the route doesn't take stays out and the grade says so, a value LiteLLM refuses never reaches the endpoint, and the grade keeps each call with the usage the endpoint reported.""" from __future__ import annotations +import hashlib import json import re import pytest +from agent_env.config import get_config from agent_env.task_step.context import PromptResponse, TaskStepContext, VerifierNotPassingError from agent_env.task_step.task_steps.verifiers.rubrics_verifier import JudgeSettingRefused, RubricsVerifierTaskStep from tst.util.config import install_model_config @@ -66,6 +68,9 @@ async def test_gpt_5_gets_the_effort_on_the_wire_and_the_thinking_budget_is_reco assert (call["outcome"], call["model"], call["usage"]["input_tokens"], call["usage"]["output_tokens"]) == ( "answered", "gpt-5", USAGE["prompt_tokens"], USAGE["completion_tokens"]) assert grade["verifier_status"] == "graded" and grade["score"] == 1.0 + stored = get_config().get_object_store().get(call["input"]["object_url"]) + assert hashlib.sha256(stored).hexdigest() == call["input"]["sha256"] + assert json.loads(stored)["messages"] == request.body["messages"] @pytest.mark.asyncio diff --git a/tst/unit/task_step/verifiers/test_judge_inputs_stored.py b/tst/unit/task_step/verifiers/test_judge_inputs_stored.py new file mode 100644 index 000000000..03c495d79 --- /dev/null +++ b/tst/unit/task_step/verifiers/test_judge_inputs_stored.py @@ -0,0 +1,170 @@ +"""Each judge call's record names exactly what it was sent, stored by its sha256: a direct judge's messages, response +format and settings, an agent judge's message and every file put in its sandbox. A judge's settings say which +trajectory source it read for each turn.""" + +from __future__ import annotations + +import hashlib +import json +from types import SimpleNamespace + +import pytest + +from agent_env.a2a_agent import protocol +from agent_env.task_step.context import PromptResponse, TaskStepContext +from agent_env.task_step.task_steps.verifiers.judge_utils import judge_usage +from tst.unit.task_step.verifiers.test_rubrics_verifier_golden import _binary, _context, _direct_judge, _step +from tst.unit.task_step.verifiers.test_rubrics_verifier_judge_settings import _grade, _llm + +ANSWER = json.dumps({"results": [{"id": "c1", "score": 1.0, "justification": "it asked"}]}) + + +class _Store: + def __init__(self, fail: bool = False): + self.fail, self.objects, self.puts = fail, {}, 0 + + def exists(self, key): + return key in self.objects + + def object_url(self, key): + return f"mem://{key}" + + def put(self, key, data, content_type=None, allow_overwrite=False): + if self.fail: + raise ConnectionError("store unreachable") + self.puts += 1 + self.objects[key] = data + return f"mem://{key}" + + +@pytest.fixture +def store(monkeypatch): + store = _Store() + monkeypatch.setattr(judge_usage, "get_config", lambda: SimpleNamespace( + get_artifact_key_prefix=lambda: "pfx/", get_object_store=lambda: store)) + return store + + +def _opened(store: _Store, ref: dict) -> dict: + data = store.objects[ref["object_url"].removeprefix("mem://")] + assert (hashlib.sha256(data).hexdigest(), len(data)) == (ref["sha256"], ref["bytes"]) + assert ref["object_url"] == f"mem://pfx/judge-inputs/{ref['sha256']}" + return json.loads(data) + + +@pytest.mark.asyncio +async def test_a_direct_calls_record_opens_to_exactly_the_messages_format_and_settings_it_sent(monkeypatch, store): + requests = _llm(monkeypatch) + + grade = await _grade(_step(default_model="claude-sonnet-4-6", effort="high"), _context()) + + [call] = grade["judge_calls"] + sent = _opened(store, call["input"]) + assert sent["messages"] == requests[0]["messages"] + assert sent["response_format"] == requests[0]["response_format"] + assert sent["settings"] == {"reasoning_effort": "high"} + + +@pytest.mark.asyncio +async def test_a_request_retried_with_the_same_input_shares_one_stored_object(monkeypatch, store): + import litellm + + _llm(monkeypatch, failures=[litellm.RateLimitError("slow down", llm_provider="openai", model="gpt-4o-mini")]) + + grade = await _grade(_step(default_model="gpt-4o-mini"), _context()) + + refused, answered = grade["judge_calls"] + assert (refused["outcome"], answered["outcome"]) == ("refused", "answered") + assert refused["input"] == answered["input"] and store.puts == 1 + + +@pytest.mark.asyncio +async def test_an_input_the_store_refuses_is_recorded_and_the_judge_still_grades(monkeypatch): + _llm(monkeypatch) + monkeypatch.setattr(judge_usage, "get_config", lambda: SimpleNamespace( + get_artifact_key_prefix=lambda: "pfx/", get_object_store=lambda: _Store(fail=True))) + + grade = await _grade(_step(default_model="gpt-4o-mini"), _context()) + + [call] = grade["judge_calls"] + assert "input" not in call and call["input_error"] == "ConnectionError: store unreachable" + assert grade["verifier_status"] == "graded" + + +class _Sandbox: + def __init__(self): + self.files = {} + + async def write_file_from_text(self, text, path, **kwargs): + self.files[path] = text + + async def write_file_from_object(self, object_url, path, **kwargs): + self.files[path] = object_url + + async def terminate(self): + pass + + +@pytest.mark.asyncio +async def test_the_staging_recorder_keeps_each_file_put_in_the_judges_sandbox(store): + judge = judge_usage.JudgeUsage(TaskStepContext(), "verify") + sandbox = _Sandbox() + recorder = judge_usage.StagingRecorder(sandbox, judge) + + await recorder.write_file_from_text("turn one", "/tmp/run/turn_01.json") + await recorder.write_file_from_object("mem://trajectories/2.json", "/tmp/run/turn_02.json") + await recorder.terminate() + + text = "turn one".encode() + assert sandbox.files == {"/tmp/run/turn_01.json": "turn one", "/tmp/run/turn_02.json": "mem://trajectories/2.json"} + assert judge.staged == [ + {"path": "/tmp/run/turn_01.json", "object_url": f"mem://pfx/judge-inputs/{hashlib.sha256(text).hexdigest()}", + "bytes": len(text), "sha256": hashlib.sha256(text).hexdigest()}, + {"path": "/tmp/run/turn_02.json", "object_url": "mem://trajectories/2.json"}] + + +@pytest.mark.asyncio +async def test_an_agent_calls_record_opens_to_its_message_and_the_files_staged_for_it(monkeypatch, store): + async def send(url, **kwargs): + return "task-1", None + + async def poll(url, task_id, **kwargs): + return {"status": {"state": "completed", "message": {"parts": [{"kind": "text", "text": ANSWER}]}}} + + monkeypatch.setattr(protocol, "send_a2a_message", send) + monkeypatch.setattr(protocol, "poll_a2a_task", poll) + context = TaskStepContext() + with judge_usage.scope(): + judge = judge_usage.start(context, "verify") + judge.staged.append({"path": "/tmp/run/turn_01.json", "object_url": "mem://trajectories/1.json"}) + verifier = _step(use_agent_judge=True, criteria=[{"id": "c1", "title": "asked"}]) + await verifier._invoke_judge_a2a(eval_prompt="grade it", judge_a2a_url="http://judge.test", + judge_agent_card={}, judge_agent=SimpleNamespace(sandbox_id=None, control_headers={}), + model="m", usage=judge) + + [call] = judge.calls + assert _opened(store, call["input"]) == { + "message": "grade it", "files": [{"path": "/tmp/run/turn_01.json", "object_url": "mem://trajectories/1.json"}]} + + +def test_the_trajectory_sources_name_each_turns_format_and_an_atif_copys_adapter_version(): + from agent_env.task_step.task_steps.verifiers.rubrics_verifier import _trajectory_sources + + response = PromptResponse(prompt_id="p1", response="done", target_agent_per_turn_trajectories=[ + {"format": "claude-code-stream-json", "atif": None}, + {"format": "atif/1", "atif": {"adapter_version": "claude-code@0.3", "status": "ok"}}]) + + assert _trajectory_sources(response) == [ + {"turn": 1, "format": "claude-code-stream-json"}, + {"turn": 2, "format": "atif/1", "adapter_version": "claude-code@0.3"}] + + +@pytest.mark.asyncio +async def test_a_judge_that_reads_the_trajectory_records_its_sources_in_its_settings(store): + context = _context(target_agent_per_turn_trajectories=[{"format": "claude-code-stream-json", "atif": None}], + target_agent_per_turn_trajectory_object_urls=["mem://traj/1.json"]) + step = _direct_judge(_step(use_trajectory=True), lambda ids, n: _binary(ids)) + + grade = await _grade(step, context) + + assert grade["verifier_settings"]["trajectory_sources"] == [{"turn": 1, "format": "claude-code-stream-json"}] From fa1994899ee4c6e0e63978bd402ecc553275dbb5 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 13:23:52 -0800 Subject: [PATCH 2/8] fix(verifiers): a direct judge's stored input holds the config's params it sent, credentials left out Co-Authored-By: Claude Opus 5.5 --- src/agent_env/config/model_call.py | 13 +++++++++++++ .../task_steps/verifiers/rubrics_verifier.py | 4 ++-- .../task_step/verifiers/test_judge_inputs_stored.py | 11 ++++++++--- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/agent_env/config/model_call.py b/src/agent_env/config/model_call.py index 1b3e714eb..63e9873c5 100644 --- a/src/agent_env/config/model_call.py +++ b/src/agent_env/config/model_call.py @@ -13,6 +13,7 @@ from agentenv_protocol.a2a_agent import Usage +from agent_env.config.describe import is_secret_key from agent_env.config.errors import ConfigError from agent_env.config.model import ModelCallConfig, ModelParam, api_root, endpoint_host, no_key_for from agent_env.config.model_pricing import Cost, ReportedBy, Tokens, litellm_prices, price @@ -108,6 +109,18 @@ async def complete(route: ModelRoute, messages: list[dict], *, timeout: Optional return ModelReply(response.choices[0].message.content or "", route.model, route.endpoint_host, usage, cost) +def sent_params(route: ModelRoute, settings: Optional[dict[str, Any]] = None) -> dict[str, Any]: + """The params a call by ``route`` with ``settings`` sends (``complete``), the config's ``[model.params]`` with + ``settings`` over them, as a record of the call keeps them: a value under a secret-shaped key (``config show``'s + rule, which takes in ``extra_headers``) is left out at any depth unless it's a number, as ``max_tokens`` is.""" + return _without_secrets({**route.call.params, **(settings or {})}) + + +def _without_secrets(params: dict[str, Any]) -> dict[str, Any]: + return {key: _without_secrets(value) if isinstance(value, dict) else value for key, value in params.items() + if not is_secret_key(key) or isinstance(value, (int, float))} + + def takes(route: ModelRoute, param: str) -> bool: """Whether LiteLLM sends ``param`` (``reasoning_effort``, ``thinking``) on ``route``: one of the params it takes for the route's provider and model, as LiteLLM's own table says. A route it can't place takes none.""" 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 8bf26db81..5e3d43fe4 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 @@ -315,7 +315,7 @@ def _direct_settings(route: model_call.ModelRoute, run: Mapping[str, Any] params[param] = value if param == "reasoning_effort" else {"type": "enabled", "budget_tokens": value} if not_sent: logger.warning("%s takes no %s; the judge grades without them", route.model, sorted(not_sent)) - request = {**route.call.params, **params} + request = model_call.sent_params(route, params) thinking = request.get("thinking") sent = {"effort": request.get("reasoning_effort"), "max_thinking_tokens": thinking.get("budget_tokens") if isinstance(thinking, Mapping) else None, @@ -1649,7 +1649,7 @@ async def _prompt_llm_judge( if judge is not None and use_response_format not in inputs: inputs[use_response_format] = await judge_usage.store_input({ "messages": messages, "response_format": response_format if use_response_format else None, - "settings": params}) + "settings": model_call.sent_params(route, params)}) judge_input = inputs.get(use_response_format, {}) try: reply = await model_call.complete(route, messages, timeout=self.judge_timeout_seconds, diff --git a/tst/unit/task_step/verifiers/test_judge_inputs_stored.py b/tst/unit/task_step/verifiers/test_judge_inputs_stored.py index 03c495d79..248c4d2de 100644 --- a/tst/unit/task_step/verifiers/test_judge_inputs_stored.py +++ b/tst/unit/task_step/verifiers/test_judge_inputs_stored.py @@ -1,5 +1,6 @@ """Each judge call's record names exactly what it was sent, stored by its sha256: a direct judge's messages, response -format and settings, an agent judge's message and every file put in its sandbox. A judge's settings say which +format and settings (the config's with the run's over them, credentials left out), an agent judge's message and every +file put in its sandbox. A judge's settings say which trajectory source it read for each turn.""" from __future__ import annotations @@ -54,7 +55,9 @@ def _opened(store: _Store, ref: dict) -> dict: @pytest.mark.asyncio async def test_a_direct_calls_record_opens_to_exactly_the_messages_format_and_settings_it_sent(monkeypatch, store): - requests = _llm(monkeypatch) + requests = _llm(monkeypatch, params={"temperature": 0, "max_tokens": 512, "aws_secret_access_key": "hush", + "extra_body": {"top_k": 5, "auth": "hush"}}, + headers={"X-Team-Key": "team-secret"}) grade = await _grade(_step(default_model="claude-sonnet-4-6", effort="high"), _context()) @@ -62,7 +65,9 @@ async def test_a_direct_calls_record_opens_to_exactly_the_messages_format_and_se sent = _opened(store, call["input"]) assert sent["messages"] == requests[0]["messages"] assert sent["response_format"] == requests[0]["response_format"] - assert sent["settings"] == {"reasoning_effort": "high"} + assert sent["settings"] == {"temperature": 0, "max_tokens": 512, "extra_body": {"top_k": 5}, + "reasoning_effort": "high"} + assert (requests[0]["extra_headers"], requests[0]["aws_secret_access_key"]) == ({"X-Team-Key": "team-secret"}, "hush") @pytest.mark.asyncio From 55b339b211c3c1d3ffae009362340934f90aad5f Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 13:26:21 -0800 Subject: [PATCH 3/8] fix(verifiers): a direct judge call cancelled mid-request keeps what it was sent and the host it reached Co-Authored-By: Claude Opus 5.5 --- .../task_steps/verifiers/rubrics_verifier.py | 11 ++++--- .../verifiers/test_judge_inputs_stored.py | 29 +++++++++++++++++-- 2 files changed, 34 insertions(+), 6 deletions(-) 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 5e3d43fe4..92548f0ea 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 @@ -1657,6 +1657,10 @@ async def _prompt_llm_judge( settings=params) return {"response": reply.content, "trajectory_object_url": None, "judge_input": judge_input, **reply.fields()} + except asyncio.CancelledError as exc: + if judge is not None: + _record_failed_call(judge, exc, model=model, endpoint_host=route.endpoint_host, sent=judge_input) + raise except Exception as exc: last_exc = exc if judge is not None: @@ -1921,16 +1925,15 @@ async def _fetch_judge_trajectory( async def _judge_directly(self, prompt: str, *, model: str, context: TaskStepContext, image_blocks: Optional[list[dict]], usage: StepUsage) -> dict: """One direct judge call, its usage in ``usage``: what it answered, or, when a cancel or a time limit stopped - it, a call of unknown usage. Under a judge's record (``JudgeUsage``), each request that failed is already in - it, from ``_prompt_llm_judge``'s own retries; a cancel, which those don't see, is recorded here.""" + it, a call of unknown usage. Under a judge's record (``JudgeUsage``), each request that failed or was cancelled + is already in it, with what it was sent, from ``_prompt_llm_judge`` itself.""" try: if image_blocks: data = await self._prompt_llm_judge(prompt, model=model, context=context, image_blocks=image_blocks) else: data = await self._prompt_llm_judge(prompt, model=model, context=context) except BaseException as exc: - recorded = isinstance(exc, Exception) and isinstance(usage, JudgeUsage) - if not recorded and model_call.cut_off(exc): + if not isinstance(usage, JudgeUsage) and model_call.cut_off(exc): usage.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=None, reported_by=ReportedBy.PROVIDER) raise self._record_direct_call(usage, data, model=model) diff --git a/tst/unit/task_step/verifiers/test_judge_inputs_stored.py b/tst/unit/task_step/verifiers/test_judge_inputs_stored.py index 248c4d2de..d2466f2f9 100644 --- a/tst/unit/task_step/verifiers/test_judge_inputs_stored.py +++ b/tst/unit/task_step/verifiers/test_judge_inputs_stored.py @@ -5,10 +5,12 @@ from __future__ import annotations +import asyncio import hashlib import json from types import SimpleNamespace +import litellm import pytest from agent_env.a2a_agent import protocol @@ -71,9 +73,32 @@ async def test_a_direct_calls_record_opens_to_exactly_the_messages_format_and_se @pytest.mark.asyncio -async def test_a_request_retried_with_the_same_input_shares_one_stored_object(monkeypatch, store): - import litellm +async def test_a_request_cancelled_mid_call_keeps_what_it_was_sent(monkeypatch, store): + _llm(monkeypatch) + calling = asyncio.Event() + + async def hangs(**kwargs): + calling.set() + await asyncio.sleep(3600) + + monkeypatch.setattr(litellm, "acompletion", hangs) + context, step = _context(), _step(default_model="gpt-4o-mini") + with judge_usage.scope(): + judge = judge_usage.start(context, step.id) + judging = asyncio.create_task(step._judge_directly("grade it", model="gpt-4o-mini", context=context, + image_blocks=None, usage=judge)) + await calling.wait() + judging.cancel() + with pytest.raises(asyncio.CancelledError): + await judging + [call] = judge.calls + assert (call["outcome"], call["endpoint_host"]) == ("cut_off", "gw.test") + assert _opened(store, call["input"])["messages"] == [{"role": "user", "content": "grade it"}] + + +@pytest.mark.asyncio +async def test_a_request_retried_with_the_same_input_shares_one_stored_object(monkeypatch, store): _llm(monkeypatch, failures=[litellm.RateLimitError("slow down", llm_provider="openai", model="gpt-4o-mini")]) grade = await _grade(_step(default_model="gpt-4o-mini"), _context()) From 7149467bcb5c92df9a648a873077931424887627 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 13:39:17 -0800 Subject: [PATCH 4/8] fix(config): a call record's params leave out credentials inside lists and a URL's userinfo too Co-Authored-By: Claude Opus 5.5 --- src/agent_env/config/model_call.py | 15 ++++++++++----- .../verifiers/test_judge_inputs_stored.py | 9 ++++++--- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/src/agent_env/config/model_call.py b/src/agent_env/config/model_call.py index 63e9873c5..73ead0be3 100644 --- a/src/agent_env/config/model_call.py +++ b/src/agent_env/config/model_call.py @@ -13,7 +13,7 @@ from agentenv_protocol.a2a_agent import Usage -from agent_env.config.describe import is_secret_key +from agent_env.config.describe import is_secret_key, mask_value from agent_env.config.errors import ConfigError from agent_env.config.model import ModelCallConfig, ModelParam, api_root, endpoint_host, no_key_for from agent_env.config.model_pricing import Cost, ReportedBy, Tokens, litellm_prices, price @@ -112,13 +112,18 @@ async def complete(route: ModelRoute, messages: list[dict], *, timeout: Optional def sent_params(route: ModelRoute, settings: Optional[dict[str, Any]] = None) -> dict[str, Any]: """The params a call by ``route`` with ``settings`` sends (``complete``), the config's ``[model.params]`` with ``settings`` over them, as a record of the call keeps them: a value under a secret-shaped key (``config show``'s - rule, which takes in ``extra_headers``) is left out at any depth unless it's a number, as ``max_tokens`` is.""" + rule, which takes in ``extra_headers``) is left out, through tables and lists, unless it's a number, as + ``max_tokens`` is, and a URL's userinfo is masked.""" return _without_secrets({**route.call.params, **(settings or {})}) -def _without_secrets(params: dict[str, Any]) -> dict[str, Any]: - return {key: _without_secrets(value) if isinstance(value, dict) else value for key, value in params.items() - if not is_secret_key(key) or isinstance(value, (int, float))} +def _without_secrets(value: Any) -> Any: + if isinstance(value, dict): + return {key: _without_secrets(item) for key, item in value.items() + if not is_secret_key(key) or isinstance(item, (int, float))} + if isinstance(value, list): + return [_without_secrets(item) for item in value] + return mask_value("", value) def takes(route: ModelRoute, param: str) -> bool: diff --git a/tst/unit/task_step/verifiers/test_judge_inputs_stored.py b/tst/unit/task_step/verifiers/test_judge_inputs_stored.py index d2466f2f9..d60b15ef6 100644 --- a/tst/unit/task_step/verifiers/test_judge_inputs_stored.py +++ b/tst/unit/task_step/verifiers/test_judge_inputs_stored.py @@ -58,7 +58,9 @@ def _opened(store: _Store, ref: dict) -> dict: @pytest.mark.asyncio async def test_a_direct_calls_record_opens_to_exactly_the_messages_format_and_settings_it_sent(monkeypatch, store): requests = _llm(monkeypatch, params={"temperature": 0, "max_tokens": 512, "aws_secret_access_key": "hush", - "extra_body": {"top_k": 5, "auth": "hush"}}, + "extra_body": {"top_k": 5, "auth": "hush", + "providers": [{"api_key": "hush", "order": 1}], + "relay": "https://user:hush@relay.test/v1"}}, headers={"X-Team-Key": "team-secret"}) grade = await _grade(_step(default_model="claude-sonnet-4-6", effort="high"), _context()) @@ -67,8 +69,9 @@ async def test_a_direct_calls_record_opens_to_exactly_the_messages_format_and_se sent = _opened(store, call["input"]) assert sent["messages"] == requests[0]["messages"] assert sent["response_format"] == requests[0]["response_format"] - assert sent["settings"] == {"temperature": 0, "max_tokens": 512, "extra_body": {"top_k": 5}, - "reasoning_effort": "high"} + assert sent["settings"] == {"temperature": 0, "max_tokens": 512, "reasoning_effort": "high", "extra_body": { + "top_k": 5, "providers": [{"order": 1}], "relay": "https://***@relay.test/v1"}} + assert not any(secret in data for data in store.objects.values() for secret in (b"hush", b"team-secret")) assert (requests[0]["extra_headers"], requests[0]["aws_secret_access_key"]) == ({"X-Team-Key": "team-secret"}, "hush") From 635d13ec4049c6e1d1b5c7c968d05bb29dc280c1 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 14:15:36 -0800 Subject: [PATCH 5/8] feat(verifiers): an agent judge's stored input lists what the task's own steps loaded into its sandbox A judge the task deployed (agent_name) grades from what load_artifact put in its sandbox; the input now names those loads as the run recorded them. A file a step wrote by running a command there is recorded nowhere, so isn't listed. Also tests the always-on judge's staged files and guessed trajectory sources. Co-Authored-By: Claude Opus 5.5 --- .../verifiers/judge_utils/judge_usage.py | 15 +++- .../task_steps/verifiers/rubrics_verifier.py | 5 +- .../verifiers/test_judge_inputs_stored.py | 90 +++++++++++++++++-- 3 files changed, 103 insertions(+), 7 deletions(-) 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 988503069..927dacbb2 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 @@ -4,7 +4,10 @@ task: a judge step's ``execute`` scopes it (``scope``) and its judging starts it (``start``). What a call was sent is stored by its sha256 under ``judge-inputs/`` in the object store (``store_input``), so a retried -request's input or a file another run staged is stored once, and a reader checks it against the key it's stored under.""" +request's input or a file another run staged is stored once, and a reader checks it against the key it's stored under. +An agent call's input names the files the judge step staged in the judge's sandbox and, for a judge the task deployed, +what the task's own steps loaded there as the run recorded them (``loads_into``): best effort, since a file a step wrote +by running a command there is recorded nowhere.""" from __future__ import annotations @@ -29,6 +32,8 @@ logger = logging.getLogger(__name__) INPUTS_PREFIX = "judge-inputs" +#: The run's records of what its steps loaded into an agent's sandbox (``load_artifact``), each entry naming the agent. +LOAD_RECORDS = ("loaded_file_artifact_universes", "loaded_environment_artifacts", "loaded_urls") class JudgeUsage(StepUsage): @@ -43,6 +48,7 @@ def __init__(self, context: TaskStepContext, step_id: str) -> None: self.not_sent: dict[str, Any] = {} self.endpoint_host: Optional[str] = None self.staged: list[dict[str, Any]] = [] + self.loaded: list[dict[str, Any]] = [] self.sources: Optional[list[dict[str, Any]]] = None def call(self, role: ModelRole, usage: Optional[Usage], *, model: Optional[str], endpoint_host: Optional[str], @@ -88,6 +94,13 @@ def _record(self, outcome: str, usage: Optional[Usage], model: Optional[str], en **({"error": error} if error is not None else {})}) +def loads_into(context: TaskStepContext, agent_name: str) -> list[dict[str, Any]]: + """What the run's own steps loaded into ``agent_name``'s sandbox, each entry as its load recorded it, under the key + it's recorded under (``record``).""" + return [{"record": key, **entry} for key in LOAD_RECORDS for entry in context.metadata.get(key) or [] + if isinstance(entry, Mapping) and entry.get("agent_name") == agent_name] + + async def store_input(body: Any) -> dict[str, Any]: """``body`` as the JSON a judge call was sent, stored by its sha256 (``store_bytes``): ``{"input": reference}``, or ``{"input_error": why}`` when the store refused it, which never fails the grade.""" 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 92548f0ea..5d4c14cc4 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 @@ -928,6 +928,8 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: raise StepContextError(f"PromptResponse with prompt_id='{self.prompt_id}' not found in context") run = self._run_values(context) judge = judge_usage.start(context, self.id) + if run["use_agent_judge"] and self.agent_name: + judge.loaded = judge_usage.loads_into(context, self.agent_name) grade_up_to_turn = _validated_turn(run["grade_up_to_turn"]) as_of = _as_of_turn(prompt_response, grade_up_to_turn) if as_of is not prompt_response and not self.use_trajectory: @@ -1752,7 +1754,8 @@ async def _invoke_judge_a2a( from agent_env.a2a_agent import protocol host = getattr(judge_agent, "model_endpoint_host", None) - sent = ({"sent": await judge_usage.store_input({"message": eval_prompt, "files": list(usage.staged)})} + sent = ({"sent": await judge_usage.store_input({"message": eval_prompt, "files": list(usage.staged), + "loaded": list(usage.loaded)})} if isinstance(usage, JudgeUsage) else {}) try: task_id, _ = await protocol.send_a2a_message( diff --git a/tst/unit/task_step/verifiers/test_judge_inputs_stored.py b/tst/unit/task_step/verifiers/test_judge_inputs_stored.py index d60b15ef6..442a95df2 100644 --- a/tst/unit/task_step/verifiers/test_judge_inputs_stored.py +++ b/tst/unit/task_step/verifiers/test_judge_inputs_stored.py @@ -1,7 +1,7 @@ """Each judge call's record names exactly what it was sent, stored by its sha256: a direct judge's messages, response -format and settings (the config's with the run's over them, credentials left out), an agent judge's message and every -file put in its sandbox. A judge's settings say which -trajectory source it read for each turn.""" +format and settings (the config's with the run's over them, credentials left out); an agent judge's message, every file +its step staged in its sandbox and, for a judge the task deployed, what the task's steps loaded there as the run recorded +it. A judge's settings say which trajectory source it read for each turn.""" from __future__ import annotations @@ -14,8 +14,9 @@ import pytest from agent_env.a2a_agent import protocol -from agent_env.task_step.context import PromptResponse, TaskStepContext +from agent_env.task_step.context import DeployedAgent, PromptResponse, TaskStepContext from agent_env.task_step.task_steps.verifiers.judge_utils import judge_usage +from tst.unit.task_step import test_always_on_agent_verifier as A from tst.unit.task_step.verifiers.test_rubrics_verifier_golden import _binary, _context, _direct_judge, _step from tst.unit.task_step.verifiers.test_rubrics_verifier_judge_settings import _grade, _llm @@ -177,7 +178,8 @@ async def poll(url, task_id, **kwargs): [call] = judge.calls assert _opened(store, call["input"]) == { - "message": "grade it", "files": [{"path": "/tmp/run/turn_01.json", "object_url": "mem://trajectories/1.json"}]} + "message": "grade it", "files": [{"path": "/tmp/run/turn_01.json", "object_url": "mem://trajectories/1.json"}], + "loaded": []} def test_the_trajectory_sources_name_each_turns_format_and_an_atif_copys_adapter_version(): @@ -201,3 +203,81 @@ async def test_a_judge_that_reads_the_trajectory_records_its_sources_in_its_sett grade = await _grade(step, context) assert grade["verifier_settings"]["trajectory_sources"] == [{"turn": 1, "format": "claude-code-stream-json"}] + + +def _answering_judge(monkeypatch) -> list[str]: + """The judge agent's A2A calls answered passing for every criterion asked about; each message it was sent kept.""" + sent: list[str] = [] + + async def send(url, **kwargs): + sent.append(kwargs["message"] if "message" in kwargs else str(kwargs)) + return "task-1", None + + async def poll(url, task_id, **kwargs): + return {"status": {"state": "completed", "message": {"parts": [{"kind": "text", "text": _binary(["c1", "c2"])}]}}} + + monkeypatch.setattr(protocol, "send_a2a_message", send) + monkeypatch.setattr(protocol, "poll_a2a_task", poll) + return sent + + +@pytest.mark.asyncio +async def test_a_judge_the_task_deployed_lists_what_the_runs_steps_loaded_into_it(monkeypatch, store): + _answering_judge(monkeypatch) + context = _context() + context.deployed_agents.append(DeployedAgent(agent_name="judge", api_url="http://judge.test", + a2a_url="http://judge.test", sandbox_id="sb-judge")) + outputs = {"id": "outputs", "version": 3, "artifact_type": "file_artifact_universe", "agent_name": "judge", + "destination_path": "/tmp/outputs", "files": {"report.md": "/tmp/outputs/report.md"}} + context.metadata.update( + loaded_file_artifact_universes=[outputs, {**outputs, "agent_name": "default-agent", "destination_path": "/app"}], + loaded_environment_artifacts=[{"id": "inbox", "version": 1, "agent_name": "judge", + "destination_path": "/data/env_after", "files": ["mail/inbox.json"]}], + loaded_urls=[{"step_id": "load-sheet", "agent_name": "judge", "destination_path": "/tmp/inputs", + "files": ["sheet.xlsx"]}]) + step = _step(use_agent_judge=True, agent_name="judge") + + async def configured(**kwargs): + return None + + step._configure_judge_a2a = configured + grade = await _grade(step, context) + + [call] = grade["judge_calls"] + sent = _opened(store, call["input"]) + assert sent["files"] == [] + assert sent["loaded"] == [ + {"record": "loaded_file_artifact_universes", **outputs}, + {"record": "loaded_environment_artifacts", "id": "inbox", "version": 1, "agent_name": "judge", + "destination_path": "/data/env_after", "files": ["mail/inbox.json"]}, + {"record": "loaded_urls", "step_id": "load-sheet", "agent_name": "judge", "destination_path": "/tmp/inputs", + "files": ["sheet.xlsx"]}] + + +@pytest.mark.asyncio +@pytest.mark.usefixtures("local_stores") +async def test_an_always_on_judge_keeps_each_file_it_staged_and_names_the_formats_it_guessed(monkeypatch, store): + run, sandbox, sources = A._staged_run(monkeypatch) + verifier = A._verifier(use_agent_judge=True, use_trajectory=True, agent_name="judge") + seen: dict = {} + + async def judge(*, eval_prompt, **kwargs): + record = judge_usage.current() + seen.update(staged=list(record.staged), sources=list(record.sources or [])) + return ([{**verifier.criteria[0], "score": 1.0, "result": True}], 0, [], None) + + def read(url): + if url not in sources: + raise FileNotFoundError(url) + return sources[url] + + monkeypatch.setattr(verifier, "_run_judge_with_output_retries", judge) + monkeypatch.setattr(verifier, "_read_trajectory_text", read) + grade = await _grade(verifier, run) + + assert sandbox.files and {entry["path"] for entry in seen["staged"]} == set(sandbox.files) + for entry in seen["staged"]: + assert store.objects[f"pfx/judge-inputs/{entry['sha256']}"] == sandbox.files[entry["path"]].encode() + assert seen["sources"] and all(source["guessed"] for source in seen["sources"]) + assert grade["verifier_settings"]["trajectory_sources"] == seen["sources"] + assert {source["format"] for source in seen["sources"]} >= {"claude-code-stream-json"} From 5db8657d817d03d938df495fcdf150b7eb75b2e8 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 14:44:46 -0800 Subject: [PATCH 6/8] perf(verifiers): a judge's inputs upload in the background, and its grade waits for them once Each upload's reference is known at once (its sha256 and key), the puts run beside the judging on their own concurrency, and the step waits for those still running before it writes its grade (VerifierTaskStep.settle, at most 120 s), marking any that failed or hadn't finished input_error. An agent call's input is stored then, after the files staged for it. Staging no longer waits on the object store. Co-Authored-By: Claude Opus 5.5 --- .../verifiers/judge_utils/judge_usage.py | 153 +++++++++++++----- .../task_steps/verifiers/rubrics_verifier.py | 12 +- .../task_steps/verifiers/verifier.py | 6 + .../verifiers/test_judge_inputs_stored.py | 97 +++++++++-- 4 files changed, 212 insertions(+), 56 deletions(-) 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 927dacbb2..1ec5301fb 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 @@ -3,14 +3,17 @@ ``verifier_settings``). The record of the run in progress is held per task, since a step is shared by every run of its task: a judge step's ``execute`` scopes it (``scope``) and its judging starts it (``start``). -What a call was sent is stored by its sha256 under ``judge-inputs/`` in the object store (``store_input``), so a retried -request's input or a file another run staged is stored once, and a reader checks it against the key it's stored under. +What a call was sent is stored by its sha256 under ``judge-inputs/`` in the object store, so a retried request's input or +a file another run staged is stored once, and a reader checks it against the key it's stored under. Uploads run in the +background, off the judging's path (``JudgeUsage.upload``); the step waits for them once, before it writes its grade +(``JudgeUsage.settle``), when an upload that failed or didn't finish is marked ``input_error``, which never fails the grade. An agent call's input names the files the judge step staged in the judge's sandbox and, for a judge the task deployed, what the task's own steps loaded there as the run recorded them (``loads_into``): best effort, since a file a step wrote by running a command there is recorded nowhere.""" from __future__ import annotations +import asyncio import contextlib import functools import hashlib @@ -18,7 +21,8 @@ import logging from collections.abc import Iterator, Mapping from contextvars import ContextVar -from typing import Any, Optional +from dataclasses import dataclass +from typing import Any, Optional, Union from agentenv_protocol.a2a_agent import Usage @@ -34,6 +38,21 @@ INPUTS_PREFIX = "judge-inputs" #: The run's records of what its steps loaded into an agent's sandbox (``load_artifact``), each entry naming the agent. LOAD_RECORDS = ("loaded_file_artifact_universes", "loaded_environment_artifacts", "loaded_urls") +#: How many of a judge run's uploads run at once, and how long its grade waits for those still running. +UPLOAD_CONCURRENCY = 16 +SETTLE_SECONDS = 120.0 + + +@dataclass(frozen=True) +class AgentInput: + """What an agent call was sent, stored when the run settles, after the files staged for it.""" + + message: str + files: list[dict[str, Any]] + loaded: list[dict[str, Any]] + + +Sent = Union[Mapping[str, Any], AgentInput, None] class JudgeUsage(StepUsage): @@ -50,23 +69,26 @@ def __init__(self, context: TaskStepContext, step_id: str) -> None: self.staged: list[dict[str, Any]] = [] self.loaded: list[dict[str, Any]] = [] self.sources: Optional[list[dict[str, Any]]] = None + self._uploads: dict[str, asyncio.Task] = {} + self._gate = asyncio.Semaphore(UPLOAD_CONCURRENCY) + self._deferred: list[tuple[dict[str, Any], AgentInput]] = [] def call(self, role: ModelRole, usage: Optional[Usage], *, model: Optional[str], endpoint_host: Optional[str], reported_by: ReportedBy = ReportedBy.HARNESS, cost: Optional[Mapping[str, Any]] = None, - sent: Optional[Mapping[str, Any]] = None) -> None: + sent: Sent = None) -> None: """The base's, and the answered call in the record: ``cost``, the cost keys the call itself carried (a direct - call's, from ``model_call``), else its price from LiteLLM's map; ``sent``, the reference to what it was sent - (``store_input``).""" + call's, from ``model_call``), else its price from LiteLLM's map; ``sent``, what it was sent (``input``, or + ``agent_input``, stored when the run settles).""" super().call(role, usage, model=model, endpoint_host=endpoint_host, reported_by=reported_by) self._record("answered", usage, model, endpoint_host, reported_by, cost=cost, sent=sent) def cut_off_call(self, role: ModelRole, *, model: Optional[str], endpoint_host: Optional[str], - reported_by: ReportedBy = ReportedBy.HARNESS, sent: Optional[Mapping[str, Any]] = None) -> None: + reported_by: ReportedBy = ReportedBy.HARNESS, sent: Sent = None) -> None: super().cut_off_call(role, model=model, endpoint_host=endpoint_host, reported_by=reported_by) self._record("cut_off", None, model, endpoint_host, reported_by, sent=sent) def refused_call(self, *, model: Optional[str], endpoint_host: Optional[str], error: str, - sent: Optional[Mapping[str, Any]] = None) -> None: + sent: Sent = None) -> None: """A call that got no answer and cost nothing, as one LiteLLM refused before sending it or one the endpoint refused: in the record, not in the step's usage.""" self._record("refused", None, model, endpoint_host, ReportedBy.PROVIDER, error=error, sent=sent) @@ -76,6 +98,67 @@ def read(self, sources: list[dict[str, Any]]) -> None: adapter version that made it.""" self.sources = list(sources) + def upload(self, data: bytes, content_type: str) -> dict[str, Any]: + """``data`` stored under ``judge-inputs/`` in the background, once however often the run sends it: its + reference (``object_url``, ``bytes``, ``sha256``) at once; ``settle`` marks it if it wasn't stored.""" + digest = hashlib.sha256(data).hexdigest() + config = get_config() + store, key = config.get_object_store(), f"{config.get_artifact_key_prefix()}{INPUTS_PREFIX}/{digest}" + if digest not in self._uploads: + task = asyncio.ensure_future(self._put(store, key, data, content_type)) + task.add_done_callback(_logged) + self._uploads[digest] = task + return {"object_url": store.object_url(key), "bytes": len(data), "sha256": digest} + + async def input(self, body: Any) -> dict[str, Any]: + """``body`` as the JSON a call was sent, uploaded (``upload``): ``{"input": reference}``.""" + return {"input": self.upload(await asyncio.to_thread(_encoded, body), "application/json")} + + 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)) + + 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 + staged files are; and marks each staged file and call whose upload failed or hadn't finished ``input_error``.""" + deadline = asyncio.get_running_loop().time() + SETTLE_SECONDS + await self._wait(deadline) + for entry in self.staged: + if error := self._failed(entry.get("sha256")): + entry.pop("object_url", None) + entry["input_error"] = error + deferred, self._deferred = self._deferred, [] + for record, sent in deferred: + record.update(await self.input({"message": sent.message, "files": sent.files, "loaded": sent.loaded})) + await self._wait(deadline) + for record in self.calls: + if error := self._failed((record.get("input") or {}).get("sha256")): + del record["input"] + record["input_error"] = error + + async def _put(self, store: Any, key: str, data: bytes, content_type: str) -> None: + async with self._gate: + await finish_on_thread(functools.partial(_put_once, store, key, data, content_type), + "Storing a judge's input") + + async def _wait(self, deadline: float) -> None: + pending = [task for task in self._uploads.values() if not task.done()] + if pending: + await asyncio.wait(pending, timeout=max(0.0, deadline - asyncio.get_running_loop().time())) + + def _failed(self, digest: Optional[str]) -> Optional[str]: + """Why the run's upload of ``digest`` didn't store it; None when it did, or the run uploaded no such thing.""" + task = self._uploads.get(digest) if digest else None + if task is None: + return None + if not task.done(): + task.cancel() + return f"TimeoutError: still uploading after {SETTLE_SECONDS:.0f}s" + if task.cancelled(): + return "CancelledError: the upload was cancelled" + exc = task.exception() + return f"{type(exc).__name__}: {exc}"[:300] if exc is not None else None + def carried(self, sent: dict[str, Any], not_sent: dict[str, Any], endpoint_host: Optional[str]) -> None: """The settings the run's calls carried, kept from its first call, since every call of a run carries the same.""" if self.sent is None: @@ -83,15 +166,18 @@ def carried(self, sent: dict[str, Any], not_sent: dict[str, Any], endpoint_host: def _record(self, outcome: str, usage: Optional[Usage], model: Optional[str], endpoint_host: Optional[str], reported_by: ReportedBy, *, error: Optional[str] = None, cost: Optional[Mapping[str, Any]] = None, - sent: Optional[Mapping[str, Any]] = None) -> None: + sent: Sent = None) -> None: if cost is None: cost = price(Tokens.of(usage.to_dict()) if usage is not None else None, usage.cost_usd if usage is not None else None, model=model, prices=self._prices, reported_by=reported_by).fields() - self.calls.append({"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(), **(sent or {}), - **({"error": error} if error is not None else {})}) + 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(), + **(sent if isinstance(sent, Mapping) else {}), **({"error": error} if error is not None else {})} + self.calls.append(record) + if isinstance(sent, AgentInput): + self._deferred.append((record, sent)) def loads_into(context: TaskStepContext, agent_name: str) -> list[dict[str, Any]]: @@ -101,36 +187,24 @@ def loads_into(context: TaskStepContext, agent_name: str) -> list[dict[str, Any] if isinstance(entry, Mapping) and entry.get("agent_name") == agent_name] -async def store_input(body: Any) -> dict[str, Any]: - """``body`` as the JSON a judge call was sent, stored by its sha256 (``store_bytes``): ``{"input": reference}``, or - ``{"input_error": why}`` when the store refused it, which never fails the grade.""" - data = json.dumps(body, ensure_ascii=False, sort_keys=True).encode() - try: - return {"input": await store_bytes(data, "application/json")} - except Exception as exc: - logger.warning("a judge call's input wasn't stored: %s", exc) - return {"input_error": f"{type(exc).__name__}: {exc}"[:300]} +def _encoded(body: Any) -> bytes: + return json.dumps(body, ensure_ascii=False, sort_keys=True).encode() -async def store_bytes(data: bytes, content_type: str) -> dict[str, Any]: - """``data`` in the object store under ``judge-inputs/``, once whatever writes it: its ``object_url``, - ``bytes`` and ``sha256``.""" - digest = hashlib.sha256(data).hexdigest() - url = await finish_on_thread(functools.partial(_put_once, digest, data, content_type), - "Storing a judge call's input") - return {"object_url": url, "bytes": len(data), "sha256": digest} +def _put_once(store: Any, key: str, data: bytes, content_type: str) -> None: + if not store.exists(key): + store.put(key, data, content_type=content_type, allow_overwrite=True) -def _put_once(digest: str, data: bytes, content_type: str) -> str: - config = get_config() - store, key = config.get_object_store(), f"{config.get_artifact_key_prefix()}{INPUTS_PREFIX}/{digest}" - return store.object_url(key) if store.exists(key) else store.put(key, data, content_type=content_type, - allow_overwrite=True) +def _logged(task: asyncio.Task) -> None: + if not task.cancelled() and (exc := task.exception()) is not None: + logger.warning("a judge's input wasn't stored: %s: %s", type(exc).__name__, exc) class StagingRecorder: """The judge's sandbox, every file written into it kept in its run's manifest (``JudgeUsage.staged``): a file - written as text stored by its sha256 too, one copied from a stored object named by that object's URL.""" + written as text stored by its sha256 too, in the background (``JudgeUsage.upload``), one copied from a stored object + named by that object's URL.""" def __init__(self, sandbox: Any, judge: JudgeUsage) -> None: self._sandbox, self._judge = sandbox, judge @@ -140,14 +214,7 @@ def __getattr__(self, name: str) -> Any: 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) - data = text.encode() - try: - stored = await store_bytes(data, "text/plain; charset=utf-8") - except Exception as exc: - logger.warning("a judge's staged file %s wasn't stored: %s", path, exc) - stored = {"bytes": len(data), "sha256": hashlib.sha256(data).hexdigest(), - "input_error": f"{type(exc).__name__}: {exc}"[:300]} - self._judge.staged.append({"path": path, **stored}) + self._judge.staged.append({"path": path, **self._judge.upload(text.encode(), "text/plain; charset=utf-8")}) return written async def write_file_from_object(self, object_url: str, path: str, **kwargs: Any) -> Any: 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 5d4c14cc4..c3f851c52 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 @@ -904,6 +904,12 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: with judge_usage.scope(): return await super().execute(context) + async def settle(self, context: TaskStepContext) -> None: + """The run's judge inputs stored before the grade says what each call was sent (``JudgeUsage.settle``).""" + judge = judge_usage.current() + if judge is not None: + await judge.settle() + async def verify(self, context: TaskStepContext) -> Verification: verdict = self._gated(await self._judged(context)) if verdict.mistakes_entry is not None: @@ -1649,7 +1655,7 @@ async def _prompt_llm_judge( last_exc: Exception | None = None for attempt in range(1, self.DEFAULT_MAX_RETRIES + 1): if judge is not None and use_response_format not in inputs: - inputs[use_response_format] = await judge_usage.store_input({ + inputs[use_response_format] = await judge.input({ "messages": messages, "response_format": response_format if use_response_format else None, "settings": model_call.sent_params(route, params)}) judge_input = inputs.get(use_response_format, {}) @@ -1754,9 +1760,7 @@ async def _invoke_judge_a2a( from agent_env.a2a_agent import protocol host = getattr(judge_agent, "model_endpoint_host", None) - sent = ({"sent": await judge_usage.store_input({"message": eval_prompt, "files": list(usage.staged), - "loaded": list(usage.loaded)})} - if isinstance(usage, JudgeUsage) else {}) + sent = {"sent": usage.agent_input(eval_prompt)} 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/verifier.py b/src/agent_env/task_step/task_steps/verifiers/verifier.py index 544219bab..11a21e3a9 100644 --- a/src/agent_env/task_step/task_steps/verifiers/verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/verifier.py @@ -131,6 +131,7 @@ async def verify(self, context: TaskStepContext) -> Verification: async def execute(self, context: TaskStepContext) -> TaskStepContext: try: verification = await self.verify(context) + await self.settle(context) score = self._score(verification) status = (VerifierStatus.SKIPPED if verification.skipped is not None else VerifierStatus.FAILED if verification.error is not None else VerifierStatus.GRADED) @@ -139,6 +140,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: skip=verification.skipped) grade.update(await self._output(context, verification.output)) except Exception as exc: + await self.settle(context) self._write_grade(context, self._grade(context, VerifierStatus.FAILED, None, [], error=_capped(f"{type(exc).__name__}: {exc}"))) raise @@ -166,6 +168,10 @@ def grade_fields(self, context: TaskStepContext) -> dict[str, Any]: a failed run did too, as a judge's ``judge_calls``. None by default.""" return {} + async def settle(self, context: TaskStepContext) -> None: + """Work ``verify`` left running that ``grade_fields`` reports, as a judge's uploads, finished before the grade is + written, whether the step graded or failed. Nothing by default; it must not raise.""" + def criterion_rows(self) -> Optional[int]: """How many criterion rows a run of this verifier grades, when its config alone says, for lint to weigh a pooled aggregate's sources; None when only a run can tell, as for a script's or a test run's rows.""" diff --git a/tst/unit/task_step/verifiers/test_judge_inputs_stored.py b/tst/unit/task_step/verifiers/test_judge_inputs_stored.py index 442a95df2..e237153a3 100644 --- a/tst/unit/task_step/verifiers/test_judge_inputs_stored.py +++ b/tst/unit/task_step/verifiers/test_judge_inputs_stored.py @@ -1,13 +1,15 @@ """Each judge call's record names exactly what it was sent, stored by its sha256: a direct judge's messages, response format and settings (the config's with the run's over them, credentials left out); an agent judge's message, every file its step staged in its sandbox and, for a judge the task deployed, what the task's steps loaded there as the run recorded -it. A judge's settings say which trajectory source it read for each turn.""" +it. The uploads run in the background and the grade waits for them, marking any that failed or hadn't finished. A +judge's settings say which trajectory source it read for each turn.""" from __future__ import annotations import asyncio import hashlib import json +import threading from types import SimpleNamespace import litellm @@ -24,8 +26,11 @@ class _Store: - def __init__(self, fail: bool = False): - self.fail, self.objects, self.puts = fail, {}, 0 + """An object store in memory; ``fail`` refuses every put, or only those of bytes holding it; ``gate`` holds each put + until it's set.""" + + def __init__(self, fail=False, gate: threading.Event | None = None): + self.fail, self.gate, self.objects, self.puts = fail, gate, {}, 0 def exists(self, key): return key in self.objects @@ -34,21 +39,26 @@ def object_url(self, key): return f"mem://{key}" def put(self, key, data, content_type=None, allow_overwrite=False): - if self.fail: + if self.gate is not None: + assert self.gate.wait(10) + if self.fail is True or (isinstance(self.fail, bytes) and self.fail in data): raise ConnectionError("store unreachable") self.puts += 1 self.objects[key] = data return f"mem://{key}" -@pytest.fixture -def store(monkeypatch): - store = _Store() +def _using(monkeypatch, store: _Store) -> _Store: monkeypatch.setattr(judge_usage, "get_config", lambda: SimpleNamespace( get_artifact_key_prefix=lambda: "pfx/", get_object_store=lambda: store)) return store +@pytest.fixture +def store(monkeypatch): + return _using(monkeypatch, _Store()) + + def _opened(store: _Store, ref: dict) -> dict: data = store.objects[ref["object_url"].removeprefix("mem://")] assert (hashlib.sha256(data).hexdigest(), len(data)) == (ref["sha256"], ref["bytes"]) @@ -95,6 +105,7 @@ async def hangs(**kwargs): judging.cancel() with pytest.raises(asyncio.CancelledError): await judging + await judge.settle() [call] = judge.calls assert (call["outcome"], call["endpoint_host"]) == ("cut_off", "gw.test") @@ -115,8 +126,7 @@ async def test_a_request_retried_with_the_same_input_shares_one_stored_object(mo @pytest.mark.asyncio async def test_an_input_the_store_refuses_is_recorded_and_the_judge_still_grades(monkeypatch): _llm(monkeypatch) - monkeypatch.setattr(judge_usage, "get_config", lambda: SimpleNamespace( - get_artifact_key_prefix=lambda: "pfx/", get_object_store=lambda: _Store(fail=True))) + _using(monkeypatch, _Store(fail=True)) grade = await _grade(_step(default_model="gpt-4o-mini"), _context()) @@ -148,6 +158,7 @@ async def test_the_staging_recorder_keeps_each_file_put_in_the_judges_sandbox(st await recorder.write_file_from_text("turn one", "/tmp/run/turn_01.json") await recorder.write_file_from_object("mem://trajectories/2.json", "/tmp/run/turn_02.json") await recorder.terminate() + await judge.settle() text = "turn one".encode() assert sandbox.files == {"/tmp/run/turn_01.json": "turn one", "/tmp/run/turn_02.json": "mem://trajectories/2.json"} @@ -175,6 +186,7 @@ async def poll(url, task_id, **kwargs): await verifier._invoke_judge_a2a(eval_prompt="grade it", judge_a2a_url="http://judge.test", judge_agent_card={}, judge_agent=SimpleNamespace(sandbox_id=None, control_headers={}), model="m", usage=judge) + await judge.settle() [call] = judge.calls assert _opened(store, call["input"]) == { @@ -281,3 +293,70 @@ def read(url): assert seen["sources"] and all(source["guessed"] for source in seen["sources"]) assert grade["verifier_settings"]["trajectory_sources"] == seen["sources"] assert {source["format"] for source in seen["sources"]} >= {"claude-code-stream-json"} + + +@pytest.mark.asyncio +async def test_the_judge_is_sent_its_message_while_its_staged_files_are_still_uploading(monkeypatch): + released = threading.Event() + store = _using(monkeypatch, _Store(gate=released)) + sent_while_uploading: list[bool] = [] + + async def send(url, **kwargs): + sent_while_uploading.append(not store.objects) + released.set() + return "task-1", None + + async def poll(url, task_id, **kwargs): + return {"status": {"state": "completed", "message": {"parts": [{"kind": "text", "text": ANSWER}]}}} + + monkeypatch.setattr(protocol, "send_a2a_message", send) + monkeypatch.setattr(protocol, "poll_a2a_task", poll) + with judge_usage.scope(): + judge = judge_usage.start(TaskStepContext(), "verify") + await judge_usage.StagingRecorder(_Sandbox(), judge).write_file_from_text("turn one", "/tmp/run/turn_01.json") + verifier = _step(use_agent_judge=True, criteria=[{"id": "c1", "title": "asked"}]) + await verifier._invoke_judge_a2a(eval_prompt="grade it", judge_a2a_url="http://judge.test", + judge_agent_card={}, judge_agent=SimpleNamespace(sandbox_id=None, control_headers={}), + model="m", usage=judge) + await judge.settle() + + assert sent_while_uploading == [True] + [call] = judge.calls + assert _opened(store, call["input"])["files"][0]["sha256"] == hashlib.sha256(b"turn one").hexdigest() + + +@pytest.mark.asyncio +async def test_an_upload_still_running_when_the_grade_is_written_is_marked_and_the_grade_goes_on(monkeypatch): + released = threading.Event() + _using(monkeypatch, _Store(gate=released)) + monkeypatch.setattr(judge_usage, "SETTLE_SECONDS", 0.2) + _llm(monkeypatch) + + grade = await _grade(_step(default_model="gpt-4o-mini"), _context()) + released.set() + + [call] = grade["judge_calls"] + assert "input" not in call and call["input_error"] == "TimeoutError: still uploading after 0s" + assert grade["verifier_status"] == "graded" + + +@pytest.mark.asyncio +async def test_a_staged_file_that_wasnt_stored_is_marked_in_the_manifest_and_in_the_calls_input(monkeypatch): + store = _using(monkeypatch, _Store(fail=b"secret turn")) + _answering_judge(monkeypatch) + with judge_usage.scope(): + judge = judge_usage.start(TaskStepContext(), "verify") + recorder = judge_usage.StagingRecorder(_Sandbox(), judge) + await recorder.write_file_from_text("secret turn", "/tmp/run/turn_01.json") + await recorder.write_file_from_text("turn two", "/tmp/run/turn_02.json") + verifier = _step(use_agent_judge=True) + await verifier._invoke_judge_a2a(eval_prompt="grade it", judge_a2a_url="http://judge.test", + judge_agent_card={}, judge_agent=SimpleNamespace(sandbox_id=None, control_headers={}), + model="m", usage=judge) + await judge.settle() + + failed, stored = judge.staged + assert "object_url" not in failed and failed["input_error"] == "ConnectionError: store unreachable" + assert stored["object_url"] == f"mem://pfx/judge-inputs/{stored['sha256']}" + [call] = judge.calls + assert _opened(store, call["input"])["files"] == [failed, stored] From 50e43c8915ababd1ac076cac4d11f55c2a65c88f Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 15:08:39 -0800 Subject: [PATCH 7/8] refactor(verifiers): a judge's uploads in a module of their own, its record's input one type, load records' keys from load_artifact judge_inputs.py holds the background uploads (Uploads, StagingRecorder) and judge_usage the record; a direct call's record takes its input's reference itself; the direct judge drops its per-variant cache, since an upload dedupes by sha256; Uploads.wait cancels what's late, so failed only reads; load_artifact names the keys its loads are recorded under and gives loads_into, which the judge, its prompt and add_skills read; calls() says a record is final once the run settles; AGENTS.md says how the uploads run. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- .../task_step/task_steps/add_skills.py | 3 +- .../task_step/task_steps/load_artifact.py | 24 ++- .../verifiers/judge_utils/judge_inputs.py | 119 +++++++++++++++ .../verifiers/judge_utils/judge_usage.py | 139 ++++-------------- .../task_steps/verifiers/rubrics_verifier.py | 30 ++-- .../verifiers/test_judge_inputs_stored.py | 12 +- 7 files changed, 187 insertions(+), 142 deletions(-) create mode 100644 src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_inputs.py diff --git a/AGENTS.md b/AGENTS.md index 880c82038..e529229b5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -155,7 +155,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 and every file put in its sandbox, stored by sha256 under `judge-inputs/`), 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`) 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/task_step/task_steps/add_skills.py b/src/agent_env/task_step/task_steps/add_skills.py index 019b02a27..463c92eae 100644 --- a/src/agent_env/task_step/task_steps/add_skills.py +++ b/src/agent_env/task_step/task_steps/add_skills.py @@ -19,6 +19,7 @@ from agent_env.entity.refs import EntityRef from agent_env.entity.scopes import FieldScope from agent_env.task_step.task_step import TaskStep, TaskStepDependency +from agent_env.task_step.task_steps.load_artifact import LOADED_FILE_UNIVERSES logger = logging.getLogger(__name__) @@ -278,7 +279,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: loaded_universes_by_id: dict[str, dict] = { e["id"]: e - for e in (context.metadata.get("loaded_file_artifact_universes") or []) + for e in (context.metadata.get(LOADED_FILE_UNIVERSES) or []) if e.get("agent_name") == self.agent_name } for fau_id in self.file_artifact_universe_ids: diff --git a/src/agent_env/task_step/task_steps/load_artifact.py b/src/agent_env/task_step/task_steps/load_artifact.py index 96657cbb1..7c20d3099 100644 --- a/src/agent_env/task_step/task_steps/load_artifact.py +++ b/src/agent_env/task_step/task_steps/load_artifact.py @@ -10,7 +10,7 @@ import shlex import uuid from dataclasses import dataclass -from typing import Callable, ClassVar, Optional +from typing import Any, Callable, ClassVar, Optional from urllib.parse import unquote, urlparse from agent_env.artifact import Artifact, EnvironmentArtifact, EnvironmentUniverseArtifact @@ -27,6 +27,18 @@ from agent_env.task_step.task_steps.deploy_agent import bound_deployment from agent_env.utils.paths import validate_relative_filename +#: What each load records in ``context.metadata``, one entry per load naming its target (``agent_name``, ``env_id``, ...). +LOADED_FILE_UNIVERSES = "loaded_file_artifact_universes" +LOADED_ENVIRONMENT_ARTIFACTS = "loaded_environment_artifacts" +LOADED_URLS = "loaded_urls" + + +def loads_into(context: TaskStepContext, agent_name: str) -> list[dict[str, Any]]: + """Each load the run recorded into ``agent_name``'s sandbox, as recorded, with the key it's recorded under as + ``record``.""" + return [{"record": key, **entry} for key in (LOADED_FILE_UNIVERSES, LOADED_ENVIRONMENT_ARTIFACTS, LOADED_URLS) + for entry in context.metadata.get(key) or [] if entry.get("agent_name") == agent_name] + logger = logging.getLogger(__name__) # Where producer steps record what they made, keyed by their own step id. Resolving @@ -487,7 +499,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: files = await _load_universe_onto_vm(target_sandbox, artifact, destination) else: files = await _load_universe_into_sandbox_container(target_sandbox, artifact, destination) - context.metadata.setdefault("loaded_file_artifact_universes", []).append({ + context.metadata.setdefault(LOADED_FILE_UNIVERSES, []).append({ "id": artifact.id, "version": artifact.version, "artifact_type": artifact.type, @@ -510,7 +522,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: env_obj = Env.get(deployed.env_id, deployed.env_version) env = await type(env_obj).from_deployed_env(deployed) result = await env.load_file_artifact_universe(artifact, destination_path=destination_path) - context.metadata.setdefault("loaded_file_artifact_universes", []).append({ + context.metadata.setdefault(LOADED_FILE_UNIVERSES, []).append({ "id": artifact.id, "version": artifact.version, "artifact_type": artifact.type, @@ -527,7 +539,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: destination = (destination_path or "/tmp/file_artifacts").rstrip("/") or "/" files = await A2AAgent.load_file_artifact_universe( deployed_agent, artifact, destination, **_agent_files(agent)) - context.metadata.setdefault("loaded_file_artifact_universes", []).append({ + context.metadata.setdefault(LOADED_FILE_UNIVERSES, []).append({ "id": artifact.id, "version": artifact.version, "artifact_type": artifact.type, @@ -574,7 +586,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: files = await _stage_environment_payload_into_container( sandbox, container, artifact, destination, ) - context.metadata.setdefault("loaded_environment_artifacts", []).append({ + context.metadata.setdefault(LOADED_ENVIRONMENT_ARTIFACTS, []).append({ "id": artifact.id, "version": artifact.version, "service_name": artifact.environment_name, @@ -671,7 +683,7 @@ async def _load_one(url: str, filename: str) -> None: logger.info(f"Loaded URL into {target_desc}: {url} -> {dest}") await asyncio.gather(*(_load_one(u, f) for u, f in downloads)) - context.metadata.setdefault("loaded_urls", []).append({ + context.metadata.setdefault(LOADED_URLS, []).append({ "step_id": self.id, "agent_name": None if self.sandbox_name is not None else self.agent_name, "sandbox_name": self.sandbox_name, 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 new file mode 100644 index 000000000..3095ec1c4 --- /dev/null +++ b/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_inputs.py @@ -0,0 +1,119 @@ +"""What a judge was sent, stored by its sha256 under ``judge-inputs/`` in the object store, so a retried request's input +or a file another run staged is stored once and a reader checks it against the key it's stored under. A judge run's +uploads run in the background, off its judging's path (``Uploads``); its record waits for them once, before its grade is +written (``JudgeUsage.settle``), when an upload that failed or hadn't finished is marked ``input_error``, which never +fails the grade.""" + +from __future__ import annotations + +import asyncio +import functools +import hashlib +import json +import logging +from typing import Any, Optional + +from agent_env.config import get_config +from agent_env.task_step.thread_work import finish_on_thread + +logger = logging.getLogger(__name__) + +INPUTS_PREFIX = "judge-inputs" +#: How many of a judge run's uploads run at once, and how long its grade waits for those still running. +UPLOAD_CONCURRENCY = 16 +SETTLE_SECONDS = 120.0 + + +class Uploads: + """A judge run's uploads: each distinct body put once, in the background, ``UPLOAD_CONCURRENCY`` at a time.""" + + def __init__(self) -> None: + self._tasks: dict[str, asyncio.Task] = {} + self._late: set[str] = set() + self._gate = asyncio.Semaphore(UPLOAD_CONCURRENCY) + + def put(self, data: bytes, content_type: str, digest: Optional[str] = None) -> dict[str, Any]: + """``data`` stored under ``judge-inputs/``, in the background and once however often the run sends it: + its reference (``object_url``, ``bytes``, ``sha256``) at once.""" + digest = digest or hashlib.sha256(data).hexdigest() + config = get_config() + store, key = config.get_object_store(), f"{config.get_artifact_key_prefix()}{INPUTS_PREFIX}/{digest}" + if digest not in self._tasks: + task = asyncio.ensure_future(self._put(store, key, data, content_type)) + task.add_done_callback(_logged) + self._tasks[digest] = task + return {"object_url": store.object_url(key), "bytes": len(data), "sha256": digest} + + async def put_json(self, body: Any) -> dict[str, Any]: + """``body`` as JSON (``put``), encoded and hashed off the event loop, since a call's input may be tens of MB.""" + data, digest = await asyncio.to_thread(_encoded, body) + return self.put(data, "application/json", digest) + + @staticmethod + def deadline() -> float: + """When a run that settles now stops waiting for its uploads.""" + return asyncio.get_running_loop().time() + SETTLE_SECONDS + + async def wait(self, deadline: float) -> None: + """Waits for the uploads still running until ``deadline``, then cancels those that haven't finished.""" + pending = {digest: task for digest, task in self._tasks.items() if not task.done()} + if pending: + await asyncio.wait(pending.values(), timeout=max(0.0, deadline - asyncio.get_running_loop().time())) + for digest, task in pending.items(): + if not task.done(): + task.cancel() + self._late.add(digest) + + def failed(self, digest: Optional[str]) -> Optional[str]: + """Why the upload of ``digest`` didn't store it, once ``wait`` has returned; None when it did, or the run + uploaded no such thing.""" + task = self._tasks.get(digest) if digest else None + if task is None: + return None + if digest in self._late: + return f"TimeoutError: still uploading after {SETTLE_SECONDS:.0f}s" + if task.cancelled(): + return "CancelledError: the upload was cancelled" + exc = task.exception() + return f"{type(exc).__name__}: {exc}"[:300] if exc is not None else None + + async def _put(self, store: Any, key: str, data: bytes, content_type: str) -> None: + async with self._gate: + await finish_on_thread(functools.partial(_put_once, store, key, data, content_type), + "Storing a judge's input") + + +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.""" + + def __init__(self, sandbox: Any, staged: list[dict[str, Any]], uploads: Uploads) -> None: + self._sandbox, self._staged, self._uploads = sandbox, staged, 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")}) + 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}) + return written + + +def _encoded(body: Any) -> tuple[bytes, str]: + data = json.dumps(body, ensure_ascii=False, sort_keys=True).encode() + return data, hashlib.sha256(data).hexdigest() + + +def _put_once(store: Any, key: str, data: bytes, content_type: str) -> None: + if not store.exists(key): + store.put(key, data, content_type=content_type, allow_overwrite=True) + + +def _logged(task: asyncio.Task) -> None: + if not task.cancelled() and (exc := task.exception()) is not None: + logger.warning("a judge's input wasn't stored: %s: %s", type(exc).__name__, exc) 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 1ec5301fb..dfab62b0c 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 @@ -3,22 +3,15 @@ ``verifier_settings``). The record of the run in progress is held per task, since a step is shared by every run of its task: a judge step's ``execute`` scopes it (``scope``) and its judging starts it (``start``). -What a call was sent is stored by its sha256 under ``judge-inputs/`` in the object store, so a retried request's input or -a file another run staged is stored once, and a reader checks it against the key it's stored under. Uploads run in the -background, off the judging's path (``JudgeUsage.upload``); the step waits for them once, before it writes its grade -(``JudgeUsage.settle``), when an upload that failed or didn't finish is marked ``input_error``, which never fails the grade. -An agent call's input names the files the judge step staged in the judge's sandbox and, for a judge the task deployed, -what the task's own steps loaded there as the run recorded them (``loads_into``): best effort, since a file a step wrote -by running a command there is recorded nowhere.""" +What each call was sent is uploaded in the background (``judge_inputs``) and its reference filled into the call's record +when the run settles (``JudgeUsage.settle``), before the grade is written. An agent call's input names the files the +judge step staged in the judge's sandbox and, for a judge the task deployed, what the task's own steps loaded there as +the run recorded them (``load_artifact.loads_into``): best effort, since a file a step wrote by running a command there +is recorded nowhere.""" from __future__ import annotations -import asyncio import contextlib -import functools -import hashlib -import json -import logging from collections.abc import Iterator, Mapping from contextvars import ContextVar from dataclasses import dataclass @@ -26,22 +19,12 @@ from agentenv_protocol.a2a_agent import Usage -from agent_env.config import get_config from agent_env.config.model import ModelRole from agent_env.config.model_pricing import ReportedBy, Tokens, price from agent_env.task_step.context import TaskStepContext -from agent_env.task_step.thread_work import finish_on_thread +from agent_env.task_step.task_steps.verifiers.judge_utils.judge_inputs import StagingRecorder, Uploads from agent_env.task_step.usage import StepUsage -logger = logging.getLogger(__name__) - -INPUTS_PREFIX = "judge-inputs" -#: The run's records of what its steps loaded into an agent's sandbox (``load_artifact``), each entry naming the agent. -LOAD_RECORDS = ("loaded_file_artifact_universes", "loaded_environment_artifacts", "loaded_urls") -#: How many of a judge run's uploads run at once, and how long its grade waits for those still running. -UPLOAD_CONCURRENCY = 16 -SETTLE_SECONDS = 120.0 - @dataclass(frozen=True) class AgentInput: @@ -52,6 +35,8 @@ class AgentInput: loaded: list[dict[str, Any]] +#: What a call was sent: a direct call's input as uploaded (``Uploads.put``'s reference), or an agent call's, uploaded +#: when the run settles. Sent = Union[Mapping[str, Any], AgentInput, None] @@ -69,8 +54,7 @@ def __init__(self, context: TaskStepContext, step_id: str) -> None: self.staged: list[dict[str, Any]] = [] self.loaded: list[dict[str, Any]] = [] self.sources: Optional[list[dict[str, Any]]] = None - self._uploads: dict[str, asyncio.Task] = {} - self._gate = asyncio.Semaphore(UPLOAD_CONCURRENCY) + self.uploads = Uploads() self._deferred: list[tuple[dict[str, Any], AgentInput]] = [] def call(self, role: ModelRole, usage: Optional[Usage], *, model: Optional[str], endpoint_host: Optional[str], @@ -98,67 +82,37 @@ def read(self, sources: list[dict[str, Any]]) -> None: adapter version that made it.""" self.sources = list(sources) - def upload(self, data: bytes, content_type: str) -> dict[str, Any]: - """``data`` stored under ``judge-inputs/`` in the background, once however often the run sends it: its - reference (``object_url``, ``bytes``, ``sha256``) at once; ``settle`` marks it if it wasn't stored.""" - digest = hashlib.sha256(data).hexdigest() - config = get_config() - store, key = config.get_object_store(), f"{config.get_artifact_key_prefix()}{INPUTS_PREFIX}/{digest}" - if digest not in self._uploads: - task = asyncio.ensure_future(self._put(store, key, data, content_type)) - task.add_done_callback(_logged) - self._uploads[digest] = task - return {"object_url": store.object_url(key), "bytes": len(data), "sha256": digest} - async def input(self, body: Any) -> dict[str, Any]: - """``body`` as the JSON a call was sent, uploaded (``upload``): ``{"input": reference}``.""" - return {"input": self.upload(await asyncio.to_thread(_encoded, body), "application/json")} + """``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 recording(self, sandbox: Any) -> StagingRecorder: + """``sandbox``, every file written into it kept in ``staged``.""" + return StagingRecorder(sandbox, self.staged, 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 staged files are; and marks each staged file and call whose upload failed or hadn't finished ``input_error``.""" - deadline = asyncio.get_running_loop().time() + SETTLE_SECONDS - await self._wait(deadline) + deadline = self.uploads.deadline() + await self.uploads.wait(deadline) for entry in self.staged: - if error := self._failed(entry.get("sha256")): + if error := self.uploads.failed(entry.get("sha256")): entry.pop("object_url", None) entry["input_error"] = error deferred, self._deferred = self._deferred, [] for record, sent in deferred: - record.update(await self.input({"message": sent.message, "files": sent.files, "loaded": sent.loaded})) - await self._wait(deadline) + record["input"] = await self.uploads.put_json( + {"message": sent.message, "files": sent.files, "loaded": sent.loaded}) + await self.uploads.wait(deadline) for record in self.calls: - if error := self._failed((record.get("input") or {}).get("sha256")): + if error := self.uploads.failed((record.get("input") or {}).get("sha256")): del record["input"] record["input_error"] = error - async def _put(self, store: Any, key: str, data: bytes, content_type: str) -> None: - async with self._gate: - await finish_on_thread(functools.partial(_put_once, store, key, data, content_type), - "Storing a judge's input") - - async def _wait(self, deadline: float) -> None: - pending = [task for task in self._uploads.values() if not task.done()] - if pending: - await asyncio.wait(pending, timeout=max(0.0, deadline - asyncio.get_running_loop().time())) - - def _failed(self, digest: Optional[str]) -> Optional[str]: - """Why the run's upload of ``digest`` didn't store it; None when it did, or the run uploaded no such thing.""" - task = self._uploads.get(digest) if digest else None - if task is None: - return None - if not task.done(): - task.cancel() - return f"TimeoutError: still uploading after {SETTLE_SECONDS:.0f}s" - if task.cancelled(): - return "CancelledError: the upload was cancelled" - exc = task.exception() - return f"{type(exc).__name__}: {exc}"[:300] if exc is not None else None - def carried(self, sent: dict[str, Any], not_sent: dict[str, Any], endpoint_host: Optional[str]) -> None: """The settings the run's calls carried, kept from its first call, since every call of a run carries the same.""" if self.sent is None: @@ -174,55 +128,13 @@ def _record(self, outcome: str, usage: Optional[Usage], model: Optional[str], en 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(), - **(sent if isinstance(sent, Mapping) else {}), **({"error": error} if error is not None else {})} + **({"input": dict(sent)} if isinstance(sent, Mapping) else {}), + **({"error": error} if error is not None else {})} self.calls.append(record) if isinstance(sent, AgentInput): self._deferred.append((record, sent)) -def loads_into(context: TaskStepContext, agent_name: str) -> list[dict[str, Any]]: - """What the run's own steps loaded into ``agent_name``'s sandbox, each entry as its load recorded it, under the key - it's recorded under (``record``).""" - return [{"record": key, **entry} for key in LOAD_RECORDS for entry in context.metadata.get(key) or [] - if isinstance(entry, Mapping) and entry.get("agent_name") == agent_name] - - -def _encoded(body: Any) -> bytes: - return json.dumps(body, ensure_ascii=False, sort_keys=True).encode() - - -def _put_once(store: Any, key: str, data: bytes, content_type: str) -> None: - if not store.exists(key): - store.put(key, data, content_type=content_type, allow_overwrite=True) - - -def _logged(task: asyncio.Task) -> None: - if not task.cancelled() and (exc := task.exception()) is not None: - logger.warning("a judge's input wasn't stored: %s: %s", type(exc).__name__, exc) - - -class StagingRecorder: - """The judge's sandbox, every file written into it kept in its run's manifest (``JudgeUsage.staged``): a file - written as text stored by its sha256 too, in the background (``JudgeUsage.upload``), one copied from a stored object - named by that object's URL.""" - - def __init__(self, sandbox: Any, judge: JudgeUsage) -> None: - self._sandbox, self._judge = sandbox, judge - - 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._judge.staged.append({"path": path, **self._judge.upload(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._judge.staged.append({"path": path, "object_url": object_url}) - return written - - _RUN: ContextVar[Optional[JudgeUsage]] = ContextVar("judge_run", default=None) _BATCH: ContextVar[Optional[int]] = ContextVar("judge_batch", default=None) _ATTEMPT: ContextVar[Optional[int]] = ContextVar("judge_attempt", default=None) @@ -251,7 +163,8 @@ def current() -> Optional[JudgeUsage]: def calls() -> list[dict[str, Any]]: - """The record of each model call the judge run this task is in has made so far.""" + """The record of each model call the judge run this task is in has made so far. A record is final once the run + settles (``JudgeUsage.settle``), which fills in its ``input`` or marks it ``input_error``.""" judge = _RUN.get() return list(judge.calls) if judge is not None else [] 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 c3f851c52..c60a1619b 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 @@ -61,6 +61,7 @@ agent_error_text, 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_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 ( @@ -324,7 +325,7 @@ def _direct_settings(route: model_call.ModelRoute, run: Mapping[str, Any] def _record_failed_call(judge: JudgeUsage, exc: BaseException, *, model: str, endpoint_host: Optional[str], - sent: Mapping[str, Any]) -> None: + sent: Optional[Mapping[str, Any]]) -> None: """A direct judge request that got no answer, in the run's record with what it was sent: cut off by a time limit (maybe billed, so a call of unknown usage in the step's usage too), or refused, costing nothing.""" if model_call.cut_off(exc): @@ -935,7 +936,7 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: run = self._run_values(context) judge = judge_usage.start(context, self.id) if run["use_agent_judge"] and self.agent_name: - judge.loaded = judge_usage.loads_into(context, self.agent_name) + judge.loaded = loads_into(context, self.agent_name) grade_up_to_turn = _validated_turn(run["grade_up_to_turn"]) as_of = _as_of_turn(prompt_response, grade_up_to_turn) if as_of is not prompt_response and not self.use_trajectory: @@ -1101,7 +1102,7 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: 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_usage.StagingRecorder(await provider.get_sandbox(judge_sandbox_id), judge) + 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: media = await self._stage_atif_turns( @@ -1132,7 +1133,7 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: loaded_for_judge: list[dict] = [] if use_agent_judge and self.agent_name is not None: loaded_for_judge = [ - e for e in (context.metadata.get("loaded_file_artifact_universes") or []) + e for e in (context.metadata.get(LOADED_FILE_UNIVERSES) or []) if e.get("agent_name") == self.agent_name ] context_facts = (resolve_context_facts(self.context_facts_for_judge, context.metadata) @@ -1610,10 +1611,12 @@ async def _prompt_llm_judge( cached_prefix: Optional[str] = None, ) -> dict: """Direct judge — no agent boot, no tools — through core's one model call (``config.model_call``). Returns - ``response`` and ``trajectory_object_url`` (None), and the call's record, which the step keeps in its usage - (``_record_direct_call``): its ``usage`` as the response carried it, the ``model`` called, the - ``endpoint_host`` it reached, and its cost's keys, ``cost_usd`` what the endpoint billed or else LiteLLM's - price map's figure. + ``response`` and ``trajectory_object_url`` (None), and the call's record: its ``usage`` as the response carried + it, the ``model`` called, the ``endpoint_host`` it reached, its cost's keys, ``cost_usd`` what the endpoint + billed or else LiteLLM's price map's figure, and under the run's judge record ``judge_input``, the reference to + what it was sent. A request that got no answer goes in that record here (``_record_failed_call``); the answered + one the step records from what this returns (``_record_direct_call``), so an override that answers itself + is recorded too. When ``image_blocks`` are provided the user message becomes multimodal (text + images); otherwise it stays a plain string. ``system`` is sent as a system message first. ``cached_prefix`` is the start of @@ -1647,18 +1650,15 @@ async def _prompt_llm_judge( judge = judge_usage.current() if judge is not None: judge.carried(sent, not_sent, route.endpoint_host) - inputs: dict[bool, dict[str, Any]] = {} # Some endpoints reject json_schema with images. Fall back once on that exact # error shape; malformed JSON is handled by the outer output-retry loop. use_response_format = True last_exc: Exception | None = None for attempt in range(1, self.DEFAULT_MAX_RETRIES + 1): - if judge is not None and use_response_format not in inputs: - inputs[use_response_format] = await judge.input({ - "messages": messages, "response_format": response_format if use_response_format else None, - "settings": model_call.sent_params(route, params)}) - judge_input = inputs.get(use_response_format, {}) + judge_input = None if judge is None else await judge.input({ + "messages": messages, "response_format": response_format if use_response_format else None, + "settings": model_call.sent_params(route, params)}) try: reply = await model_call.complete(route, messages, timeout=self.judge_timeout_seconds, response_format=response_format if use_response_format else None, @@ -1949,7 +1949,7 @@ async def _judge_directly(self, prompt: str, *, model: str, context: TaskStepCon @staticmethod def _record_direct_call(usage: StepUsage, data: dict, *, model: str) -> None: """One direct judge call's usage in the step's ``judge`` entry, as the response carried it, the endpoint's - bill its cost when it sent one, with or without token counts.""" + bill its cost when it sent one, with or without token counts; in a judge's record, with what it was sent.""" read = Usage.from_model_response(data["usage"]) if data.get("usage") else None if data.get("reported_cost_usd") is not None: read = replace(read or Usage(), cost_usd=data["reported_cost_usd"]) diff --git a/tst/unit/task_step/verifiers/test_judge_inputs_stored.py b/tst/unit/task_step/verifiers/test_judge_inputs_stored.py index e237153a3..e716f1eea 100644 --- a/tst/unit/task_step/verifiers/test_judge_inputs_stored.py +++ b/tst/unit/task_step/verifiers/test_judge_inputs_stored.py @@ -17,7 +17,7 @@ from agent_env.a2a_agent import protocol from agent_env.task_step.context import DeployedAgent, PromptResponse, TaskStepContext -from agent_env.task_step.task_steps.verifiers.judge_utils import judge_usage +from agent_env.task_step.task_steps.verifiers.judge_utils import judge_inputs, judge_usage from tst.unit.task_step import test_always_on_agent_verifier as A from tst.unit.task_step.verifiers.test_rubrics_verifier_golden import _binary, _context, _direct_judge, _step from tst.unit.task_step.verifiers.test_rubrics_verifier_judge_settings import _grade, _llm @@ -49,7 +49,7 @@ def put(self, key, data, content_type=None, allow_overwrite=False): def _using(monkeypatch, store: _Store) -> _Store: - monkeypatch.setattr(judge_usage, "get_config", lambda: SimpleNamespace( + monkeypatch.setattr(judge_inputs, "get_config", lambda: SimpleNamespace( get_artifact_key_prefix=lambda: "pfx/", get_object_store=lambda: store)) return store @@ -153,7 +153,7 @@ async def terminate(self): async def test_the_staging_recorder_keeps_each_file_put_in_the_judges_sandbox(store): judge = judge_usage.JudgeUsage(TaskStepContext(), "verify") sandbox = _Sandbox() - recorder = judge_usage.StagingRecorder(sandbox, judge) + recorder = judge.recording(sandbox) await recorder.write_file_from_text("turn one", "/tmp/run/turn_01.json") await recorder.write_file_from_object("mem://trajectories/2.json", "/tmp/run/turn_02.json") @@ -313,7 +313,7 @@ async def poll(url, task_id, **kwargs): monkeypatch.setattr(protocol, "poll_a2a_task", poll) with judge_usage.scope(): judge = judge_usage.start(TaskStepContext(), "verify") - await judge_usage.StagingRecorder(_Sandbox(), judge).write_file_from_text("turn one", "/tmp/run/turn_01.json") + await judge.recording(_Sandbox()).write_file_from_text("turn one", "/tmp/run/turn_01.json") verifier = _step(use_agent_judge=True, criteria=[{"id": "c1", "title": "asked"}]) await verifier._invoke_judge_a2a(eval_prompt="grade it", judge_a2a_url="http://judge.test", judge_agent_card={}, judge_agent=SimpleNamespace(sandbox_id=None, control_headers={}), @@ -329,7 +329,7 @@ async def poll(url, task_id, **kwargs): async def test_an_upload_still_running_when_the_grade_is_written_is_marked_and_the_grade_goes_on(monkeypatch): released = threading.Event() _using(monkeypatch, _Store(gate=released)) - monkeypatch.setattr(judge_usage, "SETTLE_SECONDS", 0.2) + monkeypatch.setattr(judge_inputs, "SETTLE_SECONDS", 0.2) _llm(monkeypatch) grade = await _grade(_step(default_model="gpt-4o-mini"), _context()) @@ -346,7 +346,7 @@ async def test_a_staged_file_that_wasnt_stored_is_marked_in_the_manifest_and_in_ _answering_judge(monkeypatch) with judge_usage.scope(): judge = judge_usage.start(TaskStepContext(), "verify") - recorder = judge_usage.StagingRecorder(_Sandbox(), judge) + recorder = judge.recording(_Sandbox()) await recorder.write_file_from_text("secret turn", "/tmp/run/turn_01.json") await recorder.write_file_from_text("turn two", "/tmp/run/turn_02.json") verifier = _step(use_agent_judge=True) From e0ed679afda1913da12a2bde32cd63ff9a168cbc Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 15:23:42 -0800 Subject: [PATCH 8/8] fix(verifiers): judge uploads run on threads of their own, a store that can't be had is input_error, and settling keeps its deadline On the event loop's default pool, slow uploads could take every worker and stall the process's other thread work. Building the store is inside the guard now, so a store without credentials marks the input instead of failing the grade; and an agent call's input encoded at settle waits only until the deadline. Co-Authored-By: Claude Opus 5.5 --- .../verifiers/judge_utils/judge_inputs.py | 54 ++++++++++++------- .../verifiers/judge_utils/judge_usage.py | 11 ++-- .../verifiers/test_judge_inputs_stored.py | 51 ++++++++++++++++++ 3 files changed, 94 insertions(+), 22 deletions(-) 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 3095ec1c4..d732bc932 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 @@ -1,8 +1,8 @@ """What a judge was sent, stored by its sha256 under ``judge-inputs/`` in the object store, so a retried request's input or a file another run staged is stored once and a reader checks it against the key it's stored under. A judge run's uploads run in the background, off its judging's path (``Uploads``); its record waits for them once, before its grade is -written (``JudgeUsage.settle``), when an upload that failed or hadn't finished is marked ``input_error``, which never -fails the grade.""" +written (``JudgeUsage.settle``), when an upload that failed or hadn't finished, or a store that couldn't be had, is marked +``input_error``, which never fails the grade.""" from __future__ import annotations @@ -11,38 +11,47 @@ import hashlib import json import logging +from concurrent.futures import ThreadPoolExecutor from typing import Any, Optional from agent_env.config import get_config -from agent_env.task_step.thread_work import finish_on_thread logger = logging.getLogger(__name__) INPUTS_PREFIX = "judge-inputs" -#: How many of a judge run's uploads run at once, and how long its grade waits for those still running. +#: How many judge uploads run at once in the process, and how long a grade waits for its run's still running. UPLOAD_CONCURRENCY = 16 SETTLE_SECONDS = 120.0 +#: The process's judge uploads run on threads of their own, not the event loop's default pool, so a slow store holds up +#: only other judge uploads. +_POOL = ThreadPoolExecutor(max_workers=UPLOAD_CONCURRENCY, thread_name_prefix="judge-input") class Uploads: - """A judge run's uploads: each distinct body put once, in the background, ``UPLOAD_CONCURRENCY`` at a time.""" + """A judge run's uploads: each distinct body put once, in the background.""" def __init__(self) -> None: - self._tasks: dict[str, asyncio.Task] = {} + self._tasks: dict[str, asyncio.Future] = {} self._late: set[str] = set() - self._gate = asyncio.Semaphore(UPLOAD_CONCURRENCY) def put(self, data: bytes, content_type: str, digest: Optional[str] = None) -> dict[str, Any]: """``data`` stored under ``judge-inputs/``, in the background and once however often the run sends it: - its reference (``object_url``, ``bytes``, ``sha256``) at once.""" + its reference (``object_url``, ``bytes``, ``sha256``) at once; without ``object_url`` when the store can't be + had, which ``failed`` then says.""" digest = digest or hashlib.sha256(data).hexdigest() - config = get_config() - store, key = config.get_object_store(), f"{config.get_artifact_key_prefix()}{INPUTS_PREFIX}/{digest}" + try: + config = get_config() + store, key = config.get_object_store(), f"{config.get_artifact_key_prefix()}{INPUTS_PREFIX}/{digest}" + url = store.object_url(key) + except Exception as exc: + self._tasks.setdefault(digest, _failed_with(exc)) + return {"bytes": len(data), "sha256": digest} if digest not in self._tasks: - task = asyncio.ensure_future(self._put(store, key, data, content_type)) + task = asyncio.ensure_future(asyncio.get_running_loop().run_in_executor( + _POOL, functools.partial(_put_once, store, key, data, content_type))) task.add_done_callback(_logged) self._tasks[digest] = task - return {"object_url": store.object_url(key), "bytes": len(data), "sha256": digest} + return {"object_url": url, "bytes": len(data), "sha256": digest} async def put_json(self, body: Any) -> dict[str, Any]: """``body`` as JSON (``put``), encoded and hashed off the event loop, since a call's input may be tens of MB.""" @@ -54,11 +63,16 @@ def deadline() -> float: """When a run that settles now stops waiting for its uploads.""" return asyncio.get_running_loop().time() + SETTLE_SECONDS + @staticmethod + def left(deadline: float) -> float: + """The seconds left until ``deadline``, none once it's passed.""" + return max(0.0, deadline - asyncio.get_running_loop().time()) + async def wait(self, deadline: float) -> None: """Waits for the uploads still running until ``deadline``, then cancels those that haven't finished.""" pending = {digest: task for digest, task in self._tasks.items() if not task.done()} if pending: - await asyncio.wait(pending.values(), timeout=max(0.0, deadline - asyncio.get_running_loop().time())) + await asyncio.wait(pending.values(), timeout=self.left(deadline)) for digest, task in pending.items(): if not task.done(): task.cancel() @@ -77,11 +91,6 @@ def failed(self, digest: Optional[str]) -> Optional[str]: exc = task.exception() return f"{type(exc).__name__}: {exc}"[:300] if exc is not None else None - async def _put(self, store: Any, key: str, data: bytes, content_type: str) -> None: - async with self._gate: - await finish_on_thread(functools.partial(_put_once, store, key, data, content_type), - "Storing a judge's input") - class StagingRecorder: """A judge's sandbox, every file written into it kept in its run's manifest (``staged``): a file written as text @@ -114,6 +123,13 @@ def _put_once(store: Any, key: str, data: bytes, content_type: str) -> None: store.put(key, data, content_type=content_type, allow_overwrite=True) -def _logged(task: asyncio.Task) -> None: +def _logged(task: asyncio.Future) -> None: if not task.cancelled() and (exc := task.exception()) is not None: logger.warning("a judge's input wasn't stored: %s: %s", type(exc).__name__, exc) + + +def _failed_with(exc: Exception) -> asyncio.Future: + failed = asyncio.get_running_loop().create_future() + failed.set_exception(exc) + _logged(failed) + return failed 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 dfab62b0c..976d1ca46 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 @@ -11,6 +11,7 @@ from __future__ import annotations +import asyncio import contextlib from collections.abc import Iterator, Mapping from contextvars import ContextVar @@ -22,6 +23,7 @@ from agent_env.config.model import ModelRole from agent_env.config.model_pricing import ReportedBy, Tokens, price from agent_env.task_step.context import TaskStepContext +from agent_env.task_step.task_steps.verifiers.judge_utils import judge_inputs from agent_env.task_step.task_steps.verifiers.judge_utils.judge_inputs import StagingRecorder, Uploads from agent_env.task_step.usage import StepUsage @@ -96,7 +98,7 @@ def recording(self, sandbox: Any) -> StagingRecorder: 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 - staged files are; and marks each staged file and call whose upload failed or hadn't finished ``input_error``.""" + staged files are; and marks each staged file and call whose input wasn't stored by then ``input_error``.""" deadline = self.uploads.deadline() await self.uploads.wait(deadline) for entry in self.staged: @@ -105,8 +107,11 @@ async def settle(self) -> None: entry["input_error"] = error deferred, self._deferred = self._deferred, [] for record, sent in deferred: - record["input"] = await self.uploads.put_json( - {"message": sent.message, "files": sent.files, "loaded": sent.loaded}) + body = {"message": sent.message, "files": sent.files, "loaded": sent.loaded} + try: + record["input"] = await asyncio.wait_for(self.uploads.put_json(body), self.uploads.left(deadline)) + except TimeoutError: + record["input_error"] = f"TimeoutError: not encoded within {judge_inputs.SETTLE_SECONDS:.0f}s" await self.uploads.wait(deadline) for record in self.calls: if error := self.uploads.failed((record.get("input") or {}).get("sha256")): diff --git a/tst/unit/task_step/verifiers/test_judge_inputs_stored.py b/tst/unit/task_step/verifiers/test_judge_inputs_stored.py index e716f1eea..55c8e5a5c 100644 --- a/tst/unit/task_step/verifiers/test_judge_inputs_stored.py +++ b/tst/unit/task_step/verifiers/test_judge_inputs_stored.py @@ -10,6 +10,7 @@ import hashlib import json import threading +import time from types import SimpleNamespace import litellm @@ -360,3 +361,53 @@ async def test_a_staged_file_that_wasnt_stored_is_marked_in_the_manifest_and_in_ assert stored["object_url"] == f"mem://pfx/judge-inputs/{stored['sha256']}" [call] = judge.calls assert _opened(store, call["input"])["files"] == [failed, stored] + + +@pytest.mark.asyncio +async def test_a_store_that_cant_be_had_leaves_input_error_and_the_judge_still_grades(monkeypatch): + def no_store(): + raise PermissionError("no credentials for the bucket") + + monkeypatch.setattr(judge_inputs, "get_config", lambda: SimpleNamespace( + get_artifact_key_prefix=lambda: "pfx/", get_object_store=no_store)) + _llm(monkeypatch) + + grade = await _grade(_step(default_model="gpt-4o-mini"), _context()) + + [call] = grade["judge_calls"] + assert "input" not in call and call["input_error"] == "PermissionError: no credentials for the bucket" + assert grade["verifier_status"] == "graded" + + +@pytest.mark.asyncio +async def test_settling_stops_at_its_deadline_even_when_an_input_is_slow_to_encode(monkeypatch, store): + _answering_judge(monkeypatch) + monkeypatch.setattr(judge_inputs, "SETTLE_SECONDS", 0.2) + encode = judge_inputs._encoded + monkeypatch.setattr(judge_inputs, "_encoded", lambda body: (time.sleep(1), encode(body))[1]) + with judge_usage.scope(): + judge = judge_usage.start(TaskStepContext(), "verify") + verifier = _step(use_agent_judge=True) + await verifier._invoke_judge_a2a(eval_prompt="grade it", judge_a2a_url="http://judge.test", + judge_agent_card={}, judge_agent=SimpleNamespace(sandbox_id=None, control_headers={}), + model="m", usage=judge) + started = time.monotonic() + await judge.settle() + + assert time.monotonic() - started < 0.8 + [call] = judge.calls + assert "input" not in call and call["input_error"] == "TimeoutError: not encoded within 0s" + + +@pytest.mark.asyncio +async def test_uploads_held_up_by_a_slow_store_leave_the_event_loops_threads_free(monkeypatch): + released = threading.Event() + _using(monkeypatch, _Store(gate=released)) + uploads = judge_inputs.Uploads() + try: + for n in range(judge_inputs.UPLOAD_CONCURRENCY + 8): + uploads.put(f"file {n}".encode(), "text/plain") + assert await asyncio.wait_for(asyncio.gather(*(asyncio.to_thread(lambda: 1) for _ in range(64))), 5) == [1] * 64 + finally: + released.set() + await uploads.wait(uploads.deadline())