From ff5249c4856bd2bbc7eb4e33de19c2a9ae0698bb Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Sun, 22 Nov 2026 21:33:40 -0800 Subject: [PATCH 1/4] feat(verifiers): a judge call cut off by a time limit or a cancel marks its step's usage a lower bound As #868 marks a prompt step's cut-off turn: its calls may be billed but their usage never came back, so the judge entry counts it as a call of unknown usage (partial) rather than leaving it out. An agent judge's turn cut off waiting for the reply (a time limit, a cancel, a judge that stopped answering); a direct judge's call stopped by a cancel or a LiteLLM Timeout, an attempt that timed out before a retry answered included. StepUsage.cut_off_call records one, starting the role when it's the first call; model_call.cut_off says which errors are cut-offs. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/config/model_call.py | 10 ++ .../task_steps/verifiers/rubrics_verifier.py | 48 ++++-- src/agent_env/task_step/usage.py | 14 +- tst/unit/config/test_model_call.py | 11 ++ tst/unit/task_step/usage_test.py | 14 ++ .../test_rubrics_verifier_judge_usage.py | 141 ++++++++++++++++++ 6 files changed, 224 insertions(+), 14 deletions(-) diff --git a/src/agent_env/config/model_call.py b/src/agent_env/config/model_call.py index 10c0776be..57bf94f91 100644 --- a/src/agent_env/config/model_call.py +++ b/src/agent_env/config/model_call.py @@ -4,6 +4,7 @@ from __future__ import annotations +import asyncio import contextlib import io import math @@ -105,6 +106,15 @@ 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 cut_off(exc: BaseException) -> bool: + """Whether ``exc`` stopped a call that may have reached the model, so it may be billed with no answer: a cancel, or + LiteLLM's ``Timeout``, raised itself or as the cause of a failure after retries.""" + import litellm + + return isinstance(exc, asyncio.CancelledError) or any( + isinstance(e, litellm.Timeout) for e in (exc, exc.__cause__)) + + def setup_errors() -> tuple[type[BaseException], ...]: """What a call raises when it can't work as set up, as opposed to a flaky failure: agent-env's ConfigError (no key, missing config) and LiteLLM's AuthenticationError, PermissionDeniedError, NotFoundError (an unknown model), 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 c3840c256..aee2edd1d 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 @@ -1372,7 +1372,7 @@ async def _prompt_llm_judge( ``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. + price map's figure. ``cut_off_calls`` counts the attempts before the answer that ran out of time, when any did. 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 @@ -1407,13 +1407,16 @@ async def _prompt_llm_judge( use_response_format = True last_exc: Exception | None = None + cut_off = 0 for attempt in range(1, self.DEFAULT_MAX_RETRIES + 1): try: reply = await model_call.complete(route, messages, timeout=self.judge_timeout_seconds, response_format=response_format if use_response_format else None) - return {"response": reply.content, "trajectory_object_url": None, **reply.fields()} + return {"response": reply.content, "trajectory_object_url": None, **reply.fields(), + **({"cut_off_calls": cut_off} if cut_off else {})} except Exception as exc: last_exc = exc + cut_off += model_call.cut_off(exc) if image_blocks and use_response_format and _looks_like_response_format_error(exc): logger.warning( f"Multimodal judge call with json_schema failed for verifier " @@ -1484,7 +1487,8 @@ async def _invoke_judge_a2a( usage: StepUsage, ) -> dict: """Send one evaluation prompt to an A2A judge and return its response. The turn's reported usage goes into - ``usage`` as soon as the judge replies, a failed reply's too.""" + ``usage`` as soon as the judge replies, a failed reply's too; a turn cut off waiting for the reply (a time + limit, a cancel, a judge that stopped answering) goes in as a call of unknown usage.""" from agent_env.a2a_agent import protocol task_id, _ = await protocol.send_a2a_message( @@ -1494,6 +1498,7 @@ async def _invoke_judge_a2a( context_id=None, timeout_seconds=self.judge_timeout_seconds, ) + host = getattr(judge_agent, "model_endpoint_host", None) try: result = await protocol.poll_a2a_task( judge_a2a_url, @@ -1503,20 +1508,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) # 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) raise except TimeoutError as e: + usage.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=host) 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=getattr(judge_agent, "model_endpoint_host", None)) + usage.call(ModelRole.JUDGE, tr.usage, model=model, endpoint_host=host) if state == "failed": sandbox_id = getattr(judge_agent, "sandbox_id", None) logger.error( @@ -1648,15 +1655,35 @@ async def _fetch_judge_trajectory( ) return None + 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.""" + 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: + if 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) + return data + @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; and each attempt before it that ran out of time, + as a call of unknown usage.""" 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"]) usage.call(ModelRole.JUDGE, read, model=data.get("model") or model, endpoint_host=data.get("endpoint_host"), reported_by=ReportedBy.PROVIDER) + for _ in range(data.get("cut_off_calls", 0)): + usage.cut_off_call(ModelRole.JUDGE, model=data.get("model") or model, + endpoint_host=data.get("endpoint_host"), reported_by=ReportedBy.PROVIDER) async def _run_judge_with_output_retries( self, @@ -1711,14 +1738,9 @@ async def _run_judge_with_output_retries( model=agent_model, usage=usage, ) - elif 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) - if not use_agent_judge: - self._record_direct_call(usage, data, model=model) + data = await self._judge_directly(prompt, model=model, context=context, image_blocks=image_blocks, + usage=usage) logger.info(f"Judge response: {data['response'][:200]}...") judge_trajectory_url = data.get("trajectory_object_url") diff --git a/src/agent_env/task_step/usage.py b/src/agent_env/task_step/usage.py index 2e4845694..0710d0b92 100644 --- a/src/agent_env/task_step/usage.py +++ b/src/agent_env/task_step/usage.py @@ -125,6 +125,11 @@ def _reported(self, summed: Optional[float]) -> Optional[float]: return summed +def _unreported() -> Usage: + """A turn or call whose usage never came back.""" + return Usage(provider_details={"unreported": True}) + + def _unreported_calls(usage: Usage) -> int: """The calls a turn's usage says reported none, as the shipped agents put it in ``provider_details``.""" value = usage.provider_details.get("unreported_calls") @@ -175,9 +180,16 @@ def cut_off(self, role: ModelRole) -> None: started, a human peer's, is skipped.""" usage = self._roles.get(role) if usage is not None: - usage.add(Usage(provider_details={"unreported": True})) + usage.add(_unreported()) self.entries() + def cut_off_call(self, role: ModelRole, *, model: Optional[str], endpoint_host: Optional[str], + reported_by: ReportedBy = ReportedBy.HARNESS) -> None: + """A model call of ``role`` that was sent but never answered, cut off by a time limit or a cancel: a call of + unknown usage, marking the role's entry a lower bound as ``cut_off`` marks a turn's, recorded as ``call`` + records one, so it starts the role when it's the first.""" + self.call(role, _unreported(), model=model, endpoint_host=endpoint_host, reported_by=reported_by) + def entries(self) -> Optional[list[UsageEntry]]: """The entries of the roles that ran turns, written to ``metadata["step_usage"]``; None, and nothing written, when none did.""" diff --git a/tst/unit/config/test_model_call.py b/tst/unit/config/test_model_call.py index 4168233c9..3ce789879 100644 --- a/tst/unit/config/test_model_call.py +++ b/tst/unit/config/test_model_call.py @@ -4,6 +4,7 @@ from __future__ import annotations +import asyncio import json import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer @@ -227,3 +228,13 @@ def test_setup_errors_are_the_ones_no_retry_fixes(): assert ConfigError in setup and litellm.AuthenticationError in setup and litellm.BudgetExceededError in setup assert not issubclass(litellm.Timeout, setup) and not issubclass(litellm.RateLimitError, setup) + + +def test_a_call_is_cut_off_by_a_cancel_or_a_timeout_even_one_a_retry_gave_up_on(): + timeout = litellm.Timeout("timed out", model="gpt-4o-mini", llm_provider="openai") + gave_up = RuntimeError("judge failed after 3 attempts") + gave_up.__cause__ = timeout + refused = litellm.RateLimitError("slow down", model="gpt-4o-mini", llm_provider="openai") + + assert all(model_call.cut_off(e) for e in (timeout, gave_up, asyncio.CancelledError())) + assert not any(model_call.cut_off(e) for e in (refused, ValueError("bad answer"))) diff --git a/tst/unit/task_step/usage_test.py b/tst/unit/task_step/usage_test.py index c454c7233..bd6203244 100644 --- a/tst/unit/task_step/usage_test.py +++ b/tst/unit/task_step/usage_test.py @@ -219,3 +219,17 @@ def test_an_endpoint_that_billed_only_some_calls_has_the_map_price_them_all(monk [entry] = context.metadata["step_usage"]["grade"] assert (entry["cost_status"], entry["cost_usd"]) == ("priced", pytest.approx(0.42)) + +def test_a_judges_call_cut_off_before_any_answered_starts_its_role_as_a_lower_bound(monkeypatch): + monkeypatch.setattr(usage_module, "litellm_prices", lambda: PRICES) + context = TaskStepContext() + usage = StepUsage(context, "grade") + usage.cut_off_call(ModelRole.JUDGE, model="gpt-4o-mini", endpoint_host="proxy:4000", reported_by=ReportedBy.PROVIDER) + [entry] = context.metadata["step_usage"]["grade"] + assert (entry["role"], entry["turns"], entry["input_tokens"], entry["cost_status"]) == ("judge", 1, None, "unpriced") + usage.call(ModelRole.JUDGE, Usage(input_tokens=1_000_000, output_tokens=100_000, input_includes_cache=True), + model="gpt-4o-mini", endpoint_host="proxy:4000") + [entry] = context.metadata["step_usage"]["grade"] + assert (entry["turns"], entry["partial"], entry["cost_status"]) == (2, True, "priced") + assert entry["cost_usd"] == pytest.approx(0.21) + diff --git a/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_usage.py b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_usage.py index 417a19c43..f58b1e1cf 100644 --- a/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_usage.py +++ b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_usage.py @@ -5,17 +5,22 @@ from __future__ import annotations +import asyncio import json from types import SimpleNamespace +import litellm import pytest from agent_env.a2a_agent import A2AAgent, protocol +from agent_env.config import model_call from agent_env.config.model import ModelRole +from agent_env.config.model_pricing import PriceTable, ReportedBy, price 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.rubrics_verifier import RubricsVerifierTaskStep from agent_env.task_step.usage import StepUsage +from tst.util.config import install_model_config CRITERIA = [{"id": f"c{i}", "title": f"Criterion {i}"} for i in range(1, 8)] @@ -171,3 +176,139 @@ def test_a_call_with_no_usage_is_a_turn_with_no_counts(): [entry] = context.metadata["step_usage"]["verify"] assert (entry["turns"], entry["input_tokens"], entry["partial"]) == (2, 10, True) assert entry["role"] == ModelRole.JUDGE.value + + +@pytest.mark.asyncio +async def test_an_agent_judge_turn_that_runs_out_of_time_is_a_call_of_unknown_usage(monkeypatch): + verifier = _agent_judge(monkeypatch, "completed", "", {}) + + async def times_out(url, task_id, **kwargs): + raise TimeoutError("the judge ran out of time") + + monkeypatch.setattr(protocol, "poll_a2a_task", times_out) + context = TaskStepContext() + + with pytest.raises(TimeoutError): + await _judge_once(verifier, context) + + [entry] = context.metadata["step_usage"]["verify"] + assert (entry["model"], entry["turns"], entry["input_tokens"], entry["partial"]) == ( + "claude-haiku-4-5", 1, None, True) + + +@pytest.mark.asyncio +async def test_a_cancelled_agent_judge_turn_is_a_call_of_unknown_usage(monkeypatch): + verifier = _agent_judge(monkeypatch, "completed", "", {}) + polling = asyncio.Event() + + async def waits(url, task_id, **kwargs): + polling.set() + await asyncio.sleep(3600) + + async def cancel(url, task_id): + return None + + monkeypatch.setattr(protocol, "poll_a2a_task", waits) + monkeypatch.setattr(protocol, "cancel_a2a_task", cancel) + context = TaskStepContext() + judging = asyncio.create_task(_judge_once(verifier, context)) + await polling.wait() + + judging.cancel() + with pytest.raises(asyncio.CancelledError): + await judging + + [entry] = context.metadata["step_usage"]["verify"] + assert (entry["turns"], entry["partial"]) == (1, True) + + +_ANSWER = json.dumps({"results": [{"id": "c1", "score": 1.0, "justification": "Checked record c1 with the sheet tool"}]}) + + +def _timeout() -> litellm.Timeout: + return litellm.Timeout("timed out", model="gpt-4o-mini", llm_provider="openai") + + +def _completes(monkeypatch, outcomes: list) -> None: + """The direct judge's model calls answered, one by one, by ``outcomes``: an exception raises, a string answers + with 100 prompt and 5 completion tokens.""" + install_model_config(monkeypatch, base_url="http://proxy.example:4000", api_key="configured-key") + + async def complete(route, messages, **kwargs): + outcome = outcomes.pop(0) + if isinstance(outcome, BaseException): + raise outcome + return model_call.ModelReply(outcome, "gpt-4o-mini", "proxy.example:4000", + {"prompt_tokens": 100, "completion_tokens": 5}, + price(None, None, model=None, prices=PriceTable(), reported_by=ReportedBy.PROVIDER)) + + monkeypatch.setattr(model_call, "complete", complete) + + +async def _direct_once(verifier: RubricsVerifierTaskStep, context: TaskStepContext) -> None: + await verifier._run_judge_with_output_retries( + eval_prompt="grade it", criteria=CRITERIA[:1], context=context, model="gpt-4o-mini", judge_a2a_url=None, + judge_agent_card={}, judge_agent=None, judge_effort=None, judge_max_thinking_tokens=None, + use_agent_judge=False, usage=StepUsage(context, "verify")) + + +@pytest.mark.asyncio +async def test_a_direct_judge_call_that_ran_out_of_time_before_one_answered_counts_as_unknown(monkeypatch): + _completes(monkeypatch, [_timeout(), _ANSWER]) + context = TaskStepContext() + + await _direct_once(_verifier(), context) + + [entry] = context.metadata["step_usage"]["verify"] + assert (entry["turns"], entry["input_tokens"], entry["partial"]) == (2, 100, True) + assert context.metadata["model_endpoints"]["judge"]["verify"]["endpoint_host"] == "proxy.example:4000" + + +@pytest.mark.asyncio +async def test_a_direct_judge_that_ran_out_of_time_on_every_attempt_leaves_a_call_of_unknown_usage(monkeypatch): + verifier = _verifier() + _completes(monkeypatch, [_timeout() for _ in range(verifier.DEFAULT_MAX_RETRIES)]) + context = TaskStepContext() + + with pytest.raises(RuntimeError, match="failed after"): + await _direct_once(verifier, context) + + [entry] = context.metadata["step_usage"]["verify"] + assert (entry["turns"], entry["input_tokens"], entry["partial"]) == (1, None, True) + + +@pytest.mark.asyncio +async def test_a_cancelled_direct_judge_call_is_a_call_of_unknown_usage(): + verifier = _verifier() + calling = asyncio.Event() + + async def waits(prompt, *, model, context): + calling.set() + await asyncio.sleep(3600) + + verifier._prompt_llm_judge = waits + context = TaskStepContext() + judging = asyncio.create_task(_direct_once(verifier, context)) + await calling.wait() + + judging.cancel() + with pytest.raises(asyncio.CancelledError): + await judging + + [entry] = context.metadata["step_usage"]["verify"] + assert (entry["turns"], entry["partial"], entry["cost_status"]) == (1, True, "unpriced") + + +@pytest.mark.asyncio +async def test_a_judge_refused_on_every_attempt_records_nothing(monkeypatch): + verifier = _verifier() + refused = [litellm.RateLimitError("slow down", model="gpt-4o-mini", llm_provider="openai") + for _ in range(verifier.DEFAULT_MAX_RETRIES)] + _completes(monkeypatch, refused) + context = TaskStepContext() + + with pytest.raises(RuntimeError, match="failed after"): + await _direct_once(verifier, context) + + assert "verify" not in context.metadata.get("step_usage", {}) + From 347063ade3b2b7beb8c753f73c13f38353783aa2 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Sun, 22 Nov 2026 21:40:03 -0800 Subject: [PATCH 2/4] docs(config): model_call.cut_off says a timeout LiteLLM's client retried on its own isn't seen Co-Authored-By: Claude Opus 5.5 --- src/agent_env/config/model_call.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/agent_env/config/model_call.py b/src/agent_env/config/model_call.py index 57bf94f91..2cc68a1f8 100644 --- a/src/agent_env/config/model_call.py +++ b/src/agent_env/config/model_call.py @@ -108,7 +108,8 @@ async def complete(route: ModelRoute, messages: list[dict], *, timeout: Optional def cut_off(exc: BaseException) -> bool: """Whether ``exc`` stopped a call that may have reached the model, so it may be billed with no answer: a cancel, or - LiteLLM's ``Timeout``, raised itself or as the cause of a failure after retries.""" + LiteLLM's ``Timeout``, raised itself or as the cause of a failure after retries. A timeout LiteLLM's client retried + on its own and then answered (the OpenAI SDK's ``max_retries``) never reaches the caller, so it isn't seen.""" import litellm return isinstance(exc, asyncio.CancelledError) or any( From 52e5ab66d3d6e36da698ab6a4a2a1f19d962b156 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Sun, 22 Nov 2026 22:07:39 -0800 Subject: [PATCH 3/4] fix(verifiers): an agent judge cut off while its message is sent counts as a call of unknown usage As send_and_wait's cut-off does for a prompt step: the judge may have taken the message before its task id came back. Co-Authored-By: Claude Opus 5.5 --- .../task_steps/verifiers/rubrics_verifier.py | 19 ++++++++++------ .../test_rubrics_verifier_judge_usage.py | 22 +++++++++++++++++++ 2 files changed, 34 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 aee2edd1d..056cbc1df 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 @@ -1491,14 +1491,19 @@ async def _invoke_judge_a2a( limit, a cancel, a judge that stopped answering) goes in as a call of unknown usage.""" from agent_env.a2a_agent import protocol - task_id, _ = await protocol.send_a2a_message( - judge_a2a_url, - parts=[{"kind": "text", "text": eval_prompt}], - message_id=uuid.uuid4().hex, - context_id=None, - timeout_seconds=self.judge_timeout_seconds, - ) host = getattr(judge_agent, "model_endpoint_host", None) + try: + task_id, _ = await protocol.send_a2a_message( + judge_a2a_url, + parts=[{"kind": "text", "text": eval_prompt}], + message_id=uuid.uuid4().hex, + context_id=None, + timeout_seconds=self.judge_timeout_seconds, + ) + 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) + raise try: result = await protocol.poll_a2a_task( judge_a2a_url, diff --git a/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_usage.py b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_usage.py index f58b1e1cf..efece60da 100644 --- a/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_usage.py +++ b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_usage.py @@ -222,6 +222,28 @@ async def cancel(url, task_id): assert (entry["turns"], entry["partial"]) == (1, True) +@pytest.mark.asyncio +async def test_an_agent_judge_cancelled_while_its_message_is_sent_is_a_call_of_unknown_usage(monkeypatch): + verifier = _agent_judge(monkeypatch, "completed", "", {}) + sending = asyncio.Event() + + async def waits(url, **kwargs): + sending.set() + await asyncio.sleep(3600) + + monkeypatch.setattr(protocol, "send_a2a_message", waits) + context = TaskStepContext() + judging = asyncio.create_task(_judge_once(verifier, context)) + await sending.wait() + + judging.cancel() + with pytest.raises(asyncio.CancelledError): + await judging + + [entry] = context.metadata["step_usage"]["verify"] + assert (entry["turns"], entry["partial"]) == (1, True) + + _ANSWER = json.dumps({"results": [{"id": "c1", "score": 1.0, "justification": "Checked record c1 with the sheet tool"}]}) From bd572889cd3e0fb963b17a0ce4772cff8f068710 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Sun, 22 Nov 2026 22:24:24 -0800 Subject: [PATCH 4/4] refactor(verifiers): drop the count of a direct judge's timed-out attempts before an answer It needed a new key out of _prompt_llm_judge for a case no live run reaches: all three of the client's own tries timing out, then the judge's next attempt answering. A cancel and a call whose every attempt timed out are still marked. Co-Authored-By: Claude Opus 5.5 --- .../task_steps/verifiers/rubrics_verifier.py | 13 +++---------- .../verifiers/test_rubrics_verifier_judge_usage.py | 12 ------------ 2 files changed, 3 insertions(+), 22 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 056cbc1df..79e9c919c 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 @@ -1372,7 +1372,7 @@ async def _prompt_llm_judge( ``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. ``cut_off_calls`` counts the attempts before the answer that ran out of time, when any did. + price map's figure. 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 @@ -1407,16 +1407,13 @@ async def _prompt_llm_judge( use_response_format = True last_exc: Exception | None = None - cut_off = 0 for attempt in range(1, self.DEFAULT_MAX_RETRIES + 1): try: reply = await model_call.complete(route, messages, timeout=self.judge_timeout_seconds, response_format=response_format if use_response_format else None) - return {"response": reply.content, "trajectory_object_url": None, **reply.fields(), - **({"cut_off_calls": cut_off} if cut_off else {})} + return {"response": reply.content, "trajectory_object_url": None, **reply.fields()} except Exception as exc: last_exc = exc - cut_off += model_call.cut_off(exc) if image_blocks and use_response_format and _looks_like_response_format_error(exc): logger.warning( f"Multimodal judge call with json_schema failed for verifier " @@ -1679,16 +1676,12 @@ 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; and each attempt before it that ran out of time, - as a call of unknown usage.""" + bill its cost when it sent one, with or without token counts.""" 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"]) usage.call(ModelRole.JUDGE, read, model=data.get("model") or model, endpoint_host=data.get("endpoint_host"), reported_by=ReportedBy.PROVIDER) - for _ in range(data.get("cut_off_calls", 0)): - usage.cut_off_call(ModelRole.JUDGE, model=data.get("model") or model, - endpoint_host=data.get("endpoint_host"), reported_by=ReportedBy.PROVIDER) async def _run_judge_with_output_retries( self, diff --git a/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_usage.py b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_usage.py index efece60da..f4301e119 100644 --- a/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_usage.py +++ b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_usage.py @@ -274,18 +274,6 @@ async def _direct_once(verifier: RubricsVerifierTaskStep, context: TaskStepConte use_agent_judge=False, usage=StepUsage(context, "verify")) -@pytest.mark.asyncio -async def test_a_direct_judge_call_that_ran_out_of_time_before_one_answered_counts_as_unknown(monkeypatch): - _completes(monkeypatch, [_timeout(), _ANSWER]) - context = TaskStepContext() - - await _direct_once(_verifier(), context) - - [entry] = context.metadata["step_usage"]["verify"] - assert (entry["turns"], entry["input_tokens"], entry["partial"]) == (2, 100, True) - assert context.metadata["model_endpoints"]["judge"]["verify"]["endpoint_host"] == "proxy.example:4000" - - @pytest.mark.asyncio async def test_a_direct_judge_that_ran_out_of_time_on_every_attempt_leaves_a_call_of_unknown_usage(monkeypatch): verifier = _verifier()