From 8601fab965d929848eac4dea637b70994c5d6345 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 24 Nov 2026 18:36:08 -0800 Subject: [PATCH 1/2] refactor(verifiers): pull the judge deploy and sample fan-out out of _judged, and share the run's sample overrides - `_judge_agent_of` finds or deploys the agent judge. - `_judge_agents` holds the judges for the grade and terminates the ones the step deployed. - `_side_by_side` and `_merged_samples` run and merge samples and batches. - `_JudgeOutcome` names the judge call's four results. - `judge_samples.overrides` builds the run overrides that bundle runs, `task run` and `eval run` each built by hand. - `splits` and `disagreement` share one tally. One judge and one batch still run in the caller's task, as before. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/bundle/run.py | 6 +- src/agent_env/cli/eval/run.py | 7 +- src/agent_env/cli/task/run.py | 7 +- .../verifiers/judge_utils/judge_samples.py | 28 ++- .../task_steps/verifiers/rubrics_verifier.py | 230 ++++++++++-------- .../test_rubrics_verifier_judge_samples.py | 2 + 6 files changed, 158 insertions(+), 122 deletions(-) diff --git a/src/agent_env/bundle/run.py b/src/agent_env/bundle/run.py index d9fab0601..1f68b1102 100644 --- a/src/agent_env/bundle/run.py +++ b/src/agent_env/bundle/run.py @@ -577,10 +577,8 @@ def _overrides(sandbox: str | None, user_model: str | None, judge_model: str | N """The run's ``user_overrides``: where everything deploys, the models the user simulator and judges run on, how many samples the judges take and how many of them must agree.""" overrides = sandbox_overrides(sandbox) if sandbox else {} - overrides.update({key: value for key, value in (("user_model", user_model), ("judge_model", judge_model), - ("judge_samples", judge_samples)) if value}) - if min_judge_agreement is not None: - overrides["min_judge_agreement"] = min_judge_agreement + overrides.update({key: value for key, value in (("user_model", user_model), ("judge_model", judge_model)) if value}) + overrides.update(judge_samples_rule.overrides(judge_samples, min_judge_agreement)) return overrides diff --git a/src/agent_env/cli/eval/run.py b/src/agent_env/cli/eval/run.py index 8220f0843..a82c01f8e 100644 --- a/src/agent_env/cli/eval/run.py +++ b/src/agent_env/cli/eval/run.py @@ -9,6 +9,7 @@ from agent_env.cli import submitted_runs from agent_env.cli.utils import judge_samples_option, min_judge_agreement_option +from agent_env.task_step.task_steps.verifiers.judge_utils import judge_samples as judge_samples_rule from agent_env.cli.banner import print_banner from agent_env.cli.identity import get_agent_env_client_id from agent_env.cli.usage_output import cost_line, sources_line @@ -87,10 +88,8 @@ def run(eval_id: str, eval_version: int | None, output_dir: str | None, k: int, client_id = get_agent_env_client_id() base_metadata = {"agent_env_hub": {"caller": client_id}} if client_id else {} - overrides = {key: value for key, value in (("user_model", user_model), ("judge_model", judge_model), - ("judge_samples", judge_samples)) if value} - if min_judge_agreement is not None: - overrides["min_judge_agreement"] = min_judge_agreement + overrides = {key: value for key, value in (("user_model", user_model), ("judge_model", judge_model)) if value} + overrides.update(judge_samples_rule.overrides(judge_samples, min_judge_agreement)) if overrides: base_metadata["user_overrides"] = overrides diff --git a/src/agent_env/cli/task/run.py b/src/agent_env/cli/task/run.py index 994c48057..e30b18cc5 100644 --- a/src/agent_env/cli/task/run.py +++ b/src/agent_env/cli/task/run.py @@ -18,6 +18,7 @@ from agent_env.config.runtime import GATEWAY_OVERRIDE, SERVICE_DB_OVERRIDE, WEBSITE_BROWSER_OVERRIDE from agent_env.cli import submitted_runs from agent_env.cli.utils import judge_samples_option, min_judge_agreement_option +from agent_env.task_step.task_steps.verifiers.judge_utils import judge_samples as judge_samples_rule from agent_env.cli.identity import get_agent_env_client_id from agent_env.cli.teardown_output import echo_finish_teardown, echo_teardown, gone from agent_env.cli.usage_output import cost_line, sources_line @@ -429,10 +430,8 @@ def run(task_id: str, task_version: int | None, output_dir: str | None, k: int, initial_context.metadata.setdefault("user_overrides", {})["user_model"] = user_model if judge_model: initial_context.metadata.setdefault("user_overrides", {})["judge_model"] = judge_model - if judge_samples: - initial_context.metadata.setdefault("user_overrides", {})["judge_samples"] = judge_samples - if min_judge_agreement is not None: - initial_context.metadata.setdefault("user_overrides", {})["min_judge_agreement"] = min_judge_agreement + if sampled := judge_samples_rule.overrides(judge_samples, min_judge_agreement): + initial_context.metadata.setdefault("user_overrides", {}).update(sampled) if agent_sandbox: initial_context.metadata.setdefault("user_overrides", {})["agent_sandbox"] = agent_sandbox if env_sandbox: diff --git a/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_samples.py b/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_samples.py index bd8bad36b..c0c30768e 100644 --- a/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_samples.py +++ b/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_samples.py @@ -66,24 +66,36 @@ def median_rows(sampled: list[list[dict[str, Any]]]) -> list[dict[str, Any]]: return merged +def overrides(samples: Optional[int], bar: Optional[float]) -> dict[str, Any]: + """The ``user_overrides`` a run's sample count and agreement bar make: each one given, a bar of 0 included.""" + return {**({"judge_samples": samples} if samples is not None else {}), + **({"min_judge_agreement": bar} if bar is not None else {})} + + +def _sampled(row: dict[str, Any]) -> bool: + """Whether ``median_rows`` made ``row``, so it carries its ``samples`` and ``agreement``.""" + return "samples" in row + + +def _tally(row: dict[str, Any]) -> str: + """How a sampled row's samples split, as `` of ``.""" + return f"{sum(1 for sample in row['samples'] if sample['passed'])} of {len(row['samples'])}" + + def disagreeing(rows: list[dict[str, Any]], bar: float) -> list[dict[str, Any]]: """The sampled rows whose ``agreement`` is under ``bar``.""" - return [row for row in rows if "agreement" in row and row["agreement"] < bar] + return [row for row in rows if _sampled(row) and row["agreement"] < bar] def splits(rows: list[dict[str, Any]]) -> list[str]: """Each sampled row its samples didn't all agree on, as `` ( of pass)``.""" - return [f"{row.get('id')} ({sum(1 for s in row['samples'] if s.get('passed'))} of {len(row['samples'])} pass)" - for row in rows if row.get("samples") and row.get("agreement", 1.0) < 1.0] + return [f"{row.get('id')} ({_tally(row)} pass)" for row in rows if _sampled(row) and row["agreement"] < 1.0] def disagreement(verifier_id: str, rows: list[dict[str, Any]], bar: float) -> str: """Why a grade whose samples split on ``rows`` failed, naming how each split.""" - splits = [] - for row in rows: - passes = sum(1 for sample in row["samples"] if sample["passed"]) - splits.append(f"{row.get('id')} ({passes} of {len(row['samples'])} samples pass it)") + named = ", ".join(f"{row.get('id')} ({_tally(row)} samples pass it)" for row in rows) which = "a criterion" if len(rows) == 1 else f"{len(rows)} criteria" return (f"Verifier '{verifier_id}': its judge samples split on {which}, under min_judge_agreement {bar:g}: " - f"{', '.join(splits)}. Each sample's verdict and justification are on the grade's rows; a lower " + f"{named}. Each sample's verdict and justification are on the grade's rows; a lower " "min_judge_agreement keeps the median instead.") diff --git a/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py b/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py index 113ef3cfe..acf24ca53 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 @@ -3,13 +3,14 @@ from __future__ import annotations import asyncio +import contextlib import json import logging import re import uuid -from collections.abc import Mapping, Sequence +from collections.abc import AsyncIterator, Callable, Coroutine, Mapping, Sequence from dataclasses import dataclass, field, replace -from typing import Any, ClassVar, Optional +from typing import Any, ClassVar, NamedTuple, Optional, TypeVar from agentenv_protocol.a2a_agent import Usage @@ -459,6 +460,64 @@ async def _terminate_auto_deployed_judge(judge: Any) -> None: logger.warning(f"Failed to terminate auto-deployed judge sandbox: {e}") +_T = TypeVar("_T") + + +class _JudgeOutcome(NamedTuple): + """What grading a batch gave, as ``_run_judge_with_output_retries`` returns it: its rows, the output retries it + took, the discrepancies they corrected and the judge's trajectory; for a sampled batch, its samples merged.""" + + rows: list[dict] + retries: int + discrepancies: list[dict] + trajectory_url: Optional[str] + + +async def _side_by_side(calls: Sequence[Coroutine[Any, Any, _T]]) -> list[_T]: + """Each of ``calls`` run at once, their results in order. The first to fail is raised as itself, as a lone call + would raise it, and the rest are cancelled.""" + try: + async with asyncio.TaskGroup() as group: + tasks = [group.create_task(call) for call in calls] + except ExceptionGroup as failed: + raise failed.exceptions[0] from failed + return [task.result() for task in tasks] + + +def _merged_samples(outcomes: Sequence[_JudgeOutcome]) -> _JudgeOutcome: + """A batch's samples as one outcome: each criterion's median row (``judge_samples.median_rows``), every sample's + retries, each discrepancy named by its sample, and the first trajectory a sample left.""" + return _JudgeOutcome(judge_samples_rule.median_rows([o.rows for o in outcomes]), sum(o.retries for o in outcomes), + [{**d, "sample": n} for n, o in enumerate(outcomes, 1) for d in o.discrepancies], + next((o.trajectory_url for o in outcomes if o.trajectory_url), None)) + + +@contextlib.asynccontextmanager +async def _judge_agents(make: Callable[[], Coroutine[Any, Any, _JudgeAgent]], count: int + ) -> AsyncIterator[list[_JudgeAgent]]: + """``count`` agent judges from ``make``, none for a direct judge, each one this step deployed terminated on the way + out. One is made in the caller's task, as before sampling; several are made at once, and when one can't be, those + that were are terminated and its error is raised as itself.""" + if count <= 1: + judges = [await make()] if count else [] + else: + made: list[asyncio.Task] = [] + try: + async with asyncio.TaskGroup() as group: + made = [group.create_task(make()) for _ in range(count)] + except BaseException as failed: + await asyncio.gather(*(_terminate_auto_deployed_judge(task.result().deployed) for task in made + if task.done() and not task.cancelled() and task.exception() is None)) + if isinstance(failed, ExceptionGroup): + raise failed.exceptions[0] from failed + raise + judges = [task.result() for task in made] + try: + yield judges + finally: + await asyncio.gather(*(_terminate_auto_deployed_judge(one.deployed) for one in judges)) + + def _image_count(blocks: list[dict]) -> int: """Images among judge message blocks (per-criterion frames interleave a ``FRAME:`` text block before each).""" return sum(1 for b in blocks if b.get("type") == "image_url") @@ -986,6 +1045,50 @@ def _gated(self, verdict: RubricsVerdict) -> RubricsVerdict: return replace(verdict, raise_after=VerifierNotPassingError( f"Verifier '{self.verifier_id}' isn't passing (score {verdict.score}); rows not met: {unmet}")) + async def _judge_agent_of(self, context: TaskStepContext, run: dict[str, Any]) -> _JudgeAgent: + """The agent judge to grade with, nothing staged in it yet: the task's agent ``agent_name`` names, or one this + step deploys (``judge_a2a_agent_id``, else the configured default) with the run's model key and endpoint.""" + if self.agent_name is not None: + agent = next((a for a in context.deployed_agents if a.agent_name == self.agent_name), None) + if agent is None: + raise StepContextError(f"Agent '{self.agent_name}' not found in context.deployed_agents") + if not agent.sandbox_id: + raise RuntimeError(f"Agent '{self.agent_name}' has no sandbox_id") + return _JudgeAgent(a2a_url=agent.a2a_url or agent.api_url, sandbox_id=agent.sandbox_id, + sandbox_type=agent.sandbox_type, card=agent.a2a_card or {}, agent=agent, + container=agent.installed_container) + from agent_env.a2a_agent import A2AAgent + from agent_env.config import get_config + + overrides = context.metadata.get("user_overrides", {}) + config = get_config() + api_key = config.resolve_reference(overrides.get("judge_litellm_api_key") or overrides.get("litellm_api_key")) + litellm_base_url = ( + overrides.get("judge_litellm_base_url") + or overrides.get("litellm_base_url") + or config.get_litellm_base_url() + ) + if not api_key: + if not config.is_model_endpoint(litellm_base_url): + raise ConfigError(f"{self.type} '{self.id}': its judge agent: " + f"{no_key_for(litellm_base_url, _JUDGE_KEY_HOW)}") + api_key = config.get_litellm_api_key() + env_vars = {"LITELLM_API_KEY": api_key, "LITELLM_BASE_URL": litellm_base_url} + resolved_judge_id = self.judge_a2a_agent_id or config.get_default_a2a_agent_id() + try: + a2a_agent = A2AAgent.get(resolved_judge_id) + except NotFoundError: + if not is_local_id(resolved_judge_id): + raise + raise NotFoundError(unwritten_local_agent(resolved_judge_id, "judge_a2a_agent_id")) from None + deploy_kwargs = {"env_vars": env_vars} + if run["judge_sandbox_type"]: + deploy_kwargs["sandbox_type"] = run["judge_sandbox_type"] + deployed = await a2a_agent.deploy(**deploy_kwargs) + logger.info(f"Auto-deployed judge A2A agent '{resolved_judge_id}' at {deployed.a2a_url}") + return _JudgeAgent(a2a_url=deployed.a2a_url, sandbox_id=deployed.sandbox_id, sandbox_type=deployed.sandbox_type, + card=deployed.agent_card, agent=deployed, container=None, deployed=deployed) + async def _judged(self, context: TaskStepContext) -> RubricsVerdict: """What the judge found in this run, written by nothing: an override point, whose result ``verify`` gates.""" prompt_response = next((pr for pr in context.prompt_responses if pr.prompt_id == self.prompt_id), None) @@ -1025,7 +1128,6 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: judge.read(_trajectory_sources(prompt_response)) documents = AtifDocuments() - overrides = context.metadata.get("user_overrides", {}) use_agent_judge = run["use_agent_judge"] criteria = self._resolved_criteria(context) # The judge sees/echoes short keys (c1..cN), not UUIDs; frame labels use them too, hence before compaction. @@ -1108,50 +1210,9 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: bar = judge_samples_rule.DEFAULT_MIN_AGREEMENT if bar is None else bar async def judge_agent() -> _JudgeAgent: - """An agent judge for the run, the trajectory staged in its sandbox: the task's agent, or one this step - deploys, which is terminated here too when staging fails.""" - if self.agent_name is not None: - agent = next((a for a in context.deployed_agents if a.agent_name == self.agent_name), None) - if agent is None: - raise StepContextError(f"Agent '{self.agent_name}' not found in context.deployed_agents") - if not agent.sandbox_id: - raise RuntimeError(f"Agent '{self.agent_name}' has no sandbox_id") - one = _JudgeAgent(a2a_url=agent.a2a_url or agent.api_url, sandbox_id=agent.sandbox_id, - sandbox_type=agent.sandbox_type, card=agent.a2a_card or {}, agent=agent, - container=agent.installed_container) - else: - from agent_env.a2a_agent import A2AAgent - from agent_env.config import get_config - - config = get_config() - api_key = config.resolve_reference( - overrides.get("judge_litellm_api_key") or overrides.get("litellm_api_key")) - litellm_base_url = ( - overrides.get("judge_litellm_base_url") - or overrides.get("litellm_base_url") - or config.get_litellm_base_url() - ) - if not api_key: - if not config.is_model_endpoint(litellm_base_url): - raise ConfigError(f"{self.type} '{self.id}': its judge agent: " - f"{no_key_for(litellm_base_url, _JUDGE_KEY_HOW)}") - api_key = config.get_litellm_api_key() - env_vars = {"LITELLM_API_KEY": api_key, "LITELLM_BASE_URL": litellm_base_url} - resolved_judge_id = self.judge_a2a_agent_id or config.get_default_a2a_agent_id() - try: - a2a_agent = A2AAgent.get(resolved_judge_id) - except NotFoundError: - if not is_local_id(resolved_judge_id): - raise - raise NotFoundError(unwritten_local_agent(resolved_judge_id, "judge_a2a_agent_id")) from None - deploy_kwargs = {"env_vars": env_vars} - if run["judge_sandbox_type"]: - deploy_kwargs["sandbox_type"] = run["judge_sandbox_type"] - deployed = await a2a_agent.deploy(**deploy_kwargs) - one = _JudgeAgent(a2a_url=deployed.a2a_url, sandbox_id=deployed.sandbox_id, - sandbox_type=deployed.sandbox_type, card=deployed.agent_card, agent=deployed, - container=None, deployed=deployed) - logger.info(f"Auto-deployed judge A2A agent '{resolved_judge_id}' at {one.a2a_url}") + """An agent judge for the run with the trajectory staged in its sandbox; one this step deployed is + terminated here too when staging fails.""" + one = await self._judge_agent_of(context, run) # Loading the trajectory can fail (an override's staging, a transfer): the judge this step deployed is # released then too, not only after grading. try: @@ -1180,25 +1241,10 @@ async def judge_agent() -> _JudgeAgent: # A judge this step deploys gets a deployment of its own per sample, so no sample sees another's files; the # task's own judge is the one agent the task deployed, which its samples share. - judges: list[_JudgeAgent] = [] - if use_agent_judge: - if self.agent_name is not None or samples == 1: - judges = [await judge_agent()] - else: - deploying: list[asyncio.Task] = [] - try: - async with asyncio.TaskGroup() as group: - deploying = [group.create_task(judge_agent()) for _ in range(samples)] - except BaseException as failed: - await asyncio.gather(*(_terminate_auto_deployed_judge(task.result().deployed) for task in deploying - if task.done() and not task.cancelled() and task.exception() is None)) - if isinstance(failed, ExceptionGroup): - raise failed.exceptions[0] from failed - raise - judges = [task.result() for task in deploying] - compacted.tool_result_files = [] - - try: + agents = 0 if not use_agent_judge else 1 if self.agent_name is not None or samples == 1 else samples + async with _judge_agents(judge_agent, agents) as judges: + if use_agent_judge: + compacted.tool_result_files = [] model = self._judge_model(context) context.record_model(ModelRole.JUDGE.record_key, self.id, model) agent_prompt_text = prompt_response.prompt_text or "" @@ -1312,10 +1358,9 @@ def judge_for(sample_number: Optional[int]) -> Optional[_JudgeAgent]: return judges[(sample_number or 1) - 1] return judges[0] if judges else None - async def call(batch: list[dict], prompt: str, one: Optional[_JudgeAgent] - ) -> tuple[list[dict], int, list[dict], Optional[str]]: + async def call(batch: list[dict], prompt: str, one: Optional[_JudgeAgent]) -> _JudgeOutcome: async with concurrency: - return await self._run_judge_with_output_retries( + return _JudgeOutcome(*await self._run_judge_with_output_retries( eval_prompt=prompt, context=context, model=model, @@ -1329,10 +1374,9 @@ async def call(batch: list[dict], prompt: str, one: Optional[_JudgeAgent] image_blocks=image_blocks, reject_bulk_verdicts=batch_size is not None and self._spec().checks_bulk_verdicts, usage=usage, - ) + )) - async def grade(batch: list[dict], number: Optional[int] = None - ) -> tuple[list[dict], int, list[dict], Optional[str]]: + async def grade(batch: list[dict], number: Optional[int] = None) -> _JudgeOutcome: judge_usage.batch(number) def prompt_for(one: Optional[_JudgeAgent]) -> str: @@ -1346,50 +1390,32 @@ def prompt_for(one: Optional[_JudgeAgent]) -> str: if samples == 1: return await call(batch, prompt_for(judge_for(None)), judge_for(None)) - async def sample(n: int) -> tuple[list[dict], int, list[dict], Optional[str]]: + async def sample(n: int) -> _JudgeOutcome: judge_usage.sample(n) return await call(batch, prompt_for(judge_for(n)), judge_for(n)) - try: - async with asyncio.TaskGroup() as group: - sampled = [group.create_task(sample(n)) for n in range(1, samples + 1)] - except ExceptionGroup as failed: - # A sample that fails fails the grade, as a batch does; the group cancels the others. - raise failed.exceptions[0] from failed - outcomes = [task.result() for task in sampled] - sample_trajectory_urls[number] = [url for _, _, _, url in outcomes] - return (judge_samples_rule.median_rows([rows for rows, _, _, _ in outcomes]), - sum(retries for _, retries, _, _ in outcomes), - [{**d, "sample": n} for n, (_, _, ds, _) in enumerate(outcomes, 1) for d in ds], - next((url for _, _, _, url in outcomes if url), None)) - - if len(batches) == 1: - outcomes = [await grade(batches[0])] - else: - try: - async with asyncio.TaskGroup() as group: - graded = [group.create_task(grade(batch, number)) for number, batch in enumerate(batches, 1)] - except ExceptionGroup as failed: - # The first batch's error, as an unbatched judge would raise it; the group cancels the rest. - raise failed.exceptions[0] from failed - outcomes = [task.result() for task in graded] + # A sample that fails fails the grade, as a batch does. + outcomes = await _side_by_side([sample(n) for n in range(1, samples + 1)]) + sample_trajectory_urls[number] = [o.trajectory_url for o in outcomes] + return _merged_samples(outcomes) + + outcomes = ([await grade(batches[0])] if len(batches) == 1 + else await _side_by_side([grade(batch, number) for number, batch in enumerate(batches, 1)])) if len(outcomes) == 1: verification_results, judge_output_retries, judge_output_discrepancies, judge_trajectory_url = ( outcomes[0]) else: - verification_results = [row for rows, _, _, _ in outcomes for row in rows] - judge_output_retries = sum(retries for _, retries, _, _ in outcomes) + verification_results = [row for o in outcomes for row in o.rows] + judge_output_retries = sum(o.retries for o in outcomes) judge_output_discrepancies = [ - {**d, "batch": i} for i, (_, _, ds, _) in enumerate(outcomes, 1) for d in ds] - batch_trajectory_urls = [url for _, _, _, url in outcomes] + {**d, "batch": i} for i, o in enumerate(outcomes, 1) for d in o.discrepancies] + batch_trajectory_urls = [o.trajectory_url for o in outcomes] judge_trajectory_url = next((url for url in batch_trajectory_urls if url), None) # Rows come back keyed by c1..cN; restore the real criterion ids, in the cited frame labels too. _restore_criterion_ids(verification_results, real_by_short) if isinstance(verification_results, ResultRows): _restore_frame_labels(verification_results, real_by_short) _restore_frame_labels(verification_results.checks, real_by_short) - finally: - await asyncio.gather(*(_terminate_auto_deployed_judge(one.deployed) for one in judges)) judge_call_fields: dict = { **dual_keyed("compact_trajectory_s3_uri", "compact_trajectory_object_url", compacted.compact_object_url), diff --git a/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_samples.py b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_samples.py index 45c3ff7ea..c678d3b38 100644 --- a/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_samples.py +++ b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_samples.py @@ -296,6 +296,8 @@ def test_the_run_flags_set_the_runs_count_and_bar_and_refuse_bad_ones(tmp_path): assert _overrides(None, None, None, 2) == {"judge_samples": 2} assert _overrides(None, None, None, 3, 0.0) == {"judge_samples": 3, "min_judge_agreement": 0.0} assert _overrides(None, None, None, None) == {} + assert judge_samples.overrides(None, 1.0) == {"min_judge_agreement": 1.0} + assert judge_samples.overrides(5, None) == {"judge_samples": 5} for bad in (0, -1): with pytest.raises(ValueError, match="judge_samples must be a positive integer"): run_bundle(tmp_path, judge_samples=bad) From c39ba7cddfcf55ab33e2f90bd912e9c43efd67fb Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Wed, 25 Nov 2026 12:15:44 -0800 Subject: [PATCH 2/2] fix(verifiers): a judge the verifier deploys leaves no sandbox folder behind A run's teardown removes the work folders of the sandboxes it records. A judge the verifier deploys isn't recorded, so `_terminate_auto_deployed_judge` stopped its container and left its folder in the local sandbox directory: one per grade, and since judge samples, one per sample. Once the sandbox is terminated, it now removes the folder when the sandbox ran on this machine, as the gateway provider does after a failed deploy. It keeps the folder of a sandbox it couldn't terminate. Co-Authored-By: Claude Opus 5.5 --- .../task_steps/verifiers/rubrics_verifier.py | 11 +++++- .../test_always_on_agent_verifier.py | 2 + .../test_rubrics_verifier_judge_samples.py | 2 + .../test_rubrics_verifier_judge_teardown.py | 38 ++++++++++++++++--- .../test_rubrics_verifier_staging_cleanup.py | 2 + 5 files changed, 48 insertions(+), 7 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 acf24ca53..2159664d7 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 @@ -26,6 +26,7 @@ from agent_env.config import model_call from agent_env.config.model import ModelRole, no_key_for from agent_env.config.model_pricing import Cost, ReportedBy +from agent_env.providers.sandbox_providers.local_docker.provider import remove_local_work_dir from agent_env.providers.sandbox_providers.sandbox import into_container from agent_env.task_step.context import ( PromptResponse, @@ -447,7 +448,9 @@ class JudgeSettingRefused(RuntimeError): async def _terminate_auto_deployed_judge(judge: Any) -> None: - """Terminate the judge sandbox a verifier deployed itself; None (it used a task's agent) has nothing to release.""" + """Terminate the judge sandbox a verifier deployed itself and, on this machine, remove its work folder, as a run's + teardown does for the sandboxes it records, which this one isn't; None (it used a task's agent) has nothing to + release.""" if judge is None: return from agent_env.providers.sandbox_providers.sandbox_provider import build_sandbox_provider, get_agent_sandbox_provider @@ -458,6 +461,12 @@ async def _terminate_auto_deployed_judge(judge: Any) -> None: logger.info(f"Terminated auto-deployed judge sandbox {judge.sandbox_id}") except Exception as e: logger.warning(f"Failed to terminate auto-deployed judge sandbox: {e}") + return + if sandbox.ON_THIS_MACHINE: + try: + await asyncio.to_thread(remove_local_work_dir, judge.sandbox_id) + except OSError as e: + logger.warning(f"Judge sandbox {judge.sandbox_id}'s work folder was not removed: {e}") _T = TypeVar("_T") diff --git a/tst/unit/task_step/test_always_on_agent_verifier.py b/tst/unit/task_step/test_always_on_agent_verifier.py index 1e5a1bf34..5668be941 100644 --- a/tst/unit/task_step/test_always_on_agent_verifier.py +++ b/tst/unit/task_step/test_always_on_agent_verifier.py @@ -257,6 +257,8 @@ def test_is_rubrics_verifier_recognises_the_subclass_as_a_step_and_as_a_stored_d class _Sandbox: + ON_THIS_MACHINE = False + def __init__(self): self.files: dict[str, str] = {} diff --git a/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_samples.py b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_samples.py index c678d3b38..e4591ba43 100644 --- a/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_samples.py +++ b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_samples.py @@ -429,6 +429,8 @@ def __init__(self, failing=None): fleet = self class Sandbox: + ON_THIS_MACHINE = False + def __init__(self, sandbox_id): self.sandbox_id = sandbox_id diff --git a/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_teardown.py b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_teardown.py index d0c00767c..cee8b5e6c 100644 --- a/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_teardown.py +++ b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_teardown.py @@ -1,4 +1,5 @@ -"""An auto-deployed judge is torn down on the provider it was deployed on, not the configured agent default.""" +"""An auto-deployed judge is torn down on the provider it was deployed on, not the configured agent default, and its +work folder goes with it on this machine.""" from __future__ import annotations from types import SimpleNamespace @@ -8,6 +9,7 @@ from agent_env.a2a_agent import A2AAgent from agent_env.task_step.context import PromptResponse, TaskStepContext +from agent_env.task_step.task_steps.verifiers import rubrics_verifier from agent_env.task_step.task_steps.verifiers.judge_utils.judge_output_format import ResultRows from agent_env.task_step.task_steps.verifiers.rubrics_verifier import RubricsVerifierTaskStep @@ -19,9 +21,8 @@ def _judged(*, eval_prompt, context, model, criteria, **kw): return ResultRows(rows, reasoning="", checks=[]), 0, [], None -@pytest.mark.asyncio -@pytest.mark.parametrize("sandbox_type, built", [("modal", "modal"), (None, None)], ids=["recorded", "unrecorded"]) -async def test_the_judge_is_torn_down_where_it_was_deployed(monkeypatch, sandbox_type, built): +async def _grade_with(monkeypatch, sandbox, sandbox_type=None): + """Grade once with a judge the verifier deploys onto ``sandbox``; the provider and its lookups, to check.""" step = RubricsVerifierTaskStep(id="judge", version=1, criteria=CRITERIA, prompt_id="p1", verifier_id="v", use_agent_judge=True, use_trajectory=False, judge_a2a_agent_id="judge-agent") judge = SimpleNamespace(a2a_url="http://judge", sandbox_id="sb-judge", agent_card={}, sandbox_type=sandbox_type) @@ -33,17 +34,24 @@ async def run_judge(**kw): return _judged(**kw) monkeypatch.setattr(step, "_run_judge_with_output_retries", run_judge) - sandbox = AsyncMock() provider = MagicMock() provider.get_sandbox = AsyncMock(return_value=sandbox) context = TaskStepContext( prompt_responses=[PromptResponse(prompt_id="p1", response="done", prompt_text="do it")], metadata={"user_overrides": {"judge_litellm_api_key": "k", "judge_litellm_base_url": "http://litellm"}}, ) - with patch("agent_env.providers.sandbox_providers.sandbox_provider.build_sandbox_provider", return_value=provider) as build, \ patch("agent_env.providers.sandbox_providers.sandbox_provider.get_agent_sandbox_provider", return_value=provider) as default: await step.execute(context) + return provider, build, default + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sandbox_type, built", [("modal", "modal"), (None, None)], ids=["recorded", "unrecorded"]) +async def test_the_judge_is_torn_down_where_it_was_deployed(monkeypatch, sandbox_type, built): + sandbox = AsyncMock(ON_THIS_MACHINE=False) + + provider, build, default = await _grade_with(monkeypatch, sandbox, sandbox_type) provider.get_sandbox.assert_awaited_once_with("sb-judge") sandbox.terminate.assert_awaited_once() @@ -53,3 +61,21 @@ async def run_judge(**kw): else: build.assert_not_called() default.assert_called_once_with() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("here, terminates, removed", [(True, True, ["sb-judge"]), (False, True, []), (True, False, [])], + ids=["on-this-machine", "elsewhere", "terminate-failed"]) +async def test_a_judge_on_this_machine_leaves_no_work_folder(monkeypatch, here, terminates, removed): + """A run's teardown removes the folders of the sandboxes it records, which a judge the verifier deploys isn't: the + verifier removes the folder once the sandbox is terminated, and keeps one it couldn't terminate.""" + sandbox = AsyncMock(ON_THIS_MACHINE=here) + if not terminates: + sandbox.terminate.side_effect = RuntimeError("Local sandbox teardown incomplete") + gone: list[str] = [] + monkeypatch.setattr(rubrics_verifier, "remove_local_work_dir", gone.append) + + await _grade_with(monkeypatch, sandbox) + + sandbox.terminate.assert_awaited_once() + assert gone == removed diff --git a/tst/unit/task_step/verifiers/test_rubrics_verifier_staging_cleanup.py b/tst/unit/task_step/verifiers/test_rubrics_verifier_staging_cleanup.py index 08898332d..19c50ba5e 100644 --- a/tst/unit/task_step/verifiers/test_rubrics_verifier_staging_cleanup.py +++ b/tst/unit/task_step/verifiers/test_rubrics_verifier_staging_cleanup.py @@ -24,6 +24,8 @@ async def test_a_failed_staging_terminates_the_judge_the_verifier_deployed(monke terminated: list[str] = [] class Sandbox: + ON_THIS_MACHINE = False + def __init__(self, sandbox_id): self.sandbox_id = sandbox_id