diff --git a/src/agent_env/agents/AGENTS.md b/src/agent_env/agents/AGENTS.md index 0cb1cf092..89642055b 100644 --- a/src/agent_env/agents/AGENTS.md +++ b/src/agent_env/agents/AGENTS.md @@ -69,11 +69,12 @@ terminal state, `completed`, `failed` or `canceled`. Your `run()` is one turn. `requirements.txt` protocol floor at the first release that has them. - **Errors:** `agent_error`, the default, means the agent tried and failed; `infra_error` means the run couldn't happen, and agent-env may retry it. An exception that escapes `run()` becomes an opaque `infra_error`, its text - never sent. prompt_agent fails its step on either. always_on ends its run on either, but grades only an - `agent_error` turn (a rubrics judge's 0): an `infra_error` turn fails the step once the run is recorded - (`AgentTurnInfraError`), so no verifier grades it. always_on's default `retry_config`, which a task's own replaces, - redoes a failed run once from its env deploy, whatever failed it. So a failure that may be the - model's (a limit it ran into, a refusal, a malformed call) is an `agent_error`, not an `infra_error`. + never sent. prompt_agent fails its step on either. always_on goes on past an `agent_error` turn, which ends only + its wake (three in a row end the run), and judges the whole run, the failed turns counted against the agent: an + `infra_error` turn ends the run and fails the step once the run is recorded (`AgentTurnInfraError`), so no verifier + grades it. always_on's default `retry_config`, which a task's own replaces, redoes a failed step once from its env + deploy, whatever failed it. So a failure that may be the model's (a limit it ran into, a refusal, a malformed call) + is an `agent_error`, not an `infra_error`. - **Context and sessions:** turns of one `context_id` run one at a time; different contexts run concurrently, and the validator relies on it, so don't serialize them. Return your runtime's conversation id as `session_ref` and the next turn in that context gets it back; bind it before the runtime starts, so a live trajectory read or a mid-turn diff --git a/src/agent_env/task_step/task_steps/agent/rate_user_satisfaction.py b/src/agent_env/task_step/task_steps/agent/rate_user_satisfaction.py index 0576fc0a5..77ba15665 100644 --- a/src/agent_env/task_step/task_steps/agent/rate_user_satisfaction.py +++ b/src/agent_env/task_step/task_steps/agent/rate_user_satisfaction.py @@ -30,9 +30,9 @@ the deploy record's ``tagged_lines``), the whole ask and raw answers in the object store at its ``object_url``. It never reaches the agent, the graded conversation, or the verifications. -Not rated, recorded with ``skipped`` and why: a run that ended on an error (always_on's error end reasons; a -prompt_agent run whose agent turn or user sim failed; a run step that failed), and a run whose user sim agent is no -longer deployed. A rating that fails or runs past ``timeout_seconds`` (by default one always_on read's worst case) is +Not rated, recorded with ``skipped`` and why: a run that ended on an error (always_on's error end reasons but its +agent's own failures, a run its failed turns ended being rated as any run is; a prompt_agent run whose agent turn or +user sim failed; a run step that failed), and a run whose user sim agent is no longer deployed. A rating that fails or runs past ``timeout_seconds`` (by default one always_on read's worst case) is recorded with its error; the step fails only when it can't find the run or its user, and by default (``fail_task_on_error`` false) that doesn't fail the task. """ @@ -61,13 +61,13 @@ from agent_env.task_step.task_steps.agent.user_sim_common import SATISFACTION_KEY, iso, person_of, task_zone, utc from agent_env.task_step.task_steps.sandbox_utils.sandbox_utils import ended_turn_error from agent_env.task_step.task_steps.always_on import ( - ALWAYS_ON_KEY, ERROR_ENDS, READ_ASKS, TRAJECTORY_FETCH_SECONDS, TURN_GRACE_SECONDS, AlwaysOnTaskStep, ) +from agent_env.task_step.task_steps.always_on_ends import ALWAYS_ON_KEY, record_ended_on_agent_failure from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep, fetch_native_trajectory, is_prompt_step from agent_env.task_step.usage import StepUsage @@ -349,7 +349,8 @@ def _always_on_session(record: dict) -> _Session: sim = record.get("user_sim") or {} session = _Session("always_on record", user_sim=sim.get("name"), context_id=sim.get("context_id"), time_zone=record.get("time_zone")) - if record.get("end_reason") in ERROR_ENDS: + if record.get("end_reason") in ERROR_ENDS and not record_ended_on_agent_failure(record): + # A run its agent's own failure ended is rated as any run is: she rates the job it did. session.skipped = f"the run ended on {record['end_reason']}" return session timeline = record.get("timeline_tail") or [] diff --git a/src/agent_env/task_step/task_steps/always_on.py b/src/agent_env/task_step/task_steps/always_on.py index 6b226a6e2..b4e7443f5 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -55,13 +55,25 @@ time, never the agent's closing text; messages no turn took (a turn that timed out after sending) are taken at the end and included, and listed as never read. The conversation (``metadata["a2a_conversations"][step_id]``) holds the user's own messages and the agent's message_user texts, then the user's last word that never reached the agent and an end - marker with the end reason. An agent turn that doesn't complete (failed, canceled, rejected, timed out) ends the run - and sets the response's ``error_type`` (as prompt_agent does for a failed one): a rubrics judge scores the run 0 - without judging it (a ``prompt_error`` row), and the user-sim judge and the satisfaction rating skip it. A turn that - failed for an infrastructure reason, its agent's ``error_type`` being ``infra_error`` or the agent having stopped - answering (its sandbox died), is not the agent's failure: the run is recorded the same way, with end reason - agent_turn_infra_error and the turn's ``error_code``, and then the step fails with ``AgentTurnInfraError``, so no - verifier grades it and a ``retry_config`` can redo it. + marker with the end reason. +- A failed turn. An agent turn that ends failed, canceled or rejected as the agent's own failure (its ``error_type`` + ``agent_error``, or anything but ``infra_error``) ends only its wake: it is recorded (a ``turn_failed`` event, and + the run's ``failed_turns`` with its ``error_type``, ``error_code`` and message), what it sent the user is taken as + any wake's is, and the run goes on to its next event, the next wake, check or user message, the response keeping no + ``error_type``. That wake opens with the step's note that the last turn ended with an error (``FAILED_TURN_TEXT``, + never the error itself), recorded as a cut-off's is: ``failed_turn_notice`` on its ``wake`` event, ``told_in_wake`` + on the failed turn's entry. ``FAILED_TURNS_IN_A_ROW_MAX`` failed turns in a row end the run (agent_turn_failed), as does a turn + agent-env gave up waiting on (agent_turn_timeout: it may still be running, ``_no_answer``); either sets the + response's ``error_type`` as prompt_agent does. Every verifier judges such a run as a whole, its failed turns among + its wakes and counted against the agent (``ended_on_agent_failure``), never skips it for them. The record says how + the run ended for whoever reports early ends: ``failed_turns``, ``counts["failed_turns"]`` and + ``counts["failed_turn_kinds"]`` (each failure by its ``error_code``, else its ``error_type``), and + ``reached_scheduled_end`` (``SCHEDULED_ENDS``). A turn that failed for an infrastructure reason, its agent's + ``error_type`` being ``infra_error`` or the agent having stopped answering (its sandbox died), is not the agent's + failure: the run is recorded the same way, with end reason agent_turn_infra_error and the turn's ``error_code``, and + then the step fails with ``AgentTurnInfraError``, so a ``retry_config`` can redo it. A verifier reaches such a run + only when the task goes on past the failed step (its ``fail_task_on_error`` off), and then leaves it ungraded, never + scored against the agent (``ended_on_infra_failure``). - With ``continue_after_wake_limit`` on, a turn (a wake's, or its nudge's) that reaches its time limit (``timeout_seconds``) or its tool-call limit (``max_turns``) ends only that wake: what it did stands, its messages to the user are taken as any wake's are, and the run goes on to its next event, still bounded by ``max_wakes`` and the @@ -72,7 +84,8 @@ can't confirm canceled ends the run as before. The next wake opens with a note that the last turn was cut off (``CUT_OFF_TEXT``). Each cut-off is in the timeline (``wake_cut_off``, and ``cut_off`` on the turn's end), the run's record (``cut_off_wakes``) and what the judge reads. A turn that fails for any other reason (an agent crash, a - protocol error) still ends the run, and one that failed for an infrastructure reason fails the step as above. + protocol error) is a failed turn as above, and one that failed for an infrastructure reason fails the step. Off, a + turn its harness ended at a limit is a failed turn like any other. - Who did what, and in what order, even under a frozen clock: each app change (urn:agentenv:changes/v1) is recorded with who made it and the wake it was seen in, the agent's own with the wake that made it (``app_changes`` events); each reply records the agent's message it answers (``reply_to``: its wake, time and text); and each read leaves a @@ -117,6 +130,7 @@ import tempfile import time import uuid +from collections import Counter from datetime import datetime, timedelta, timezone from types import ModuleType from typing import Any, ClassVar, Optional @@ -168,10 +182,10 @@ from agent_env.task_step.task_steps.user_sim_gate import judge_call_config, run_gate from agent_env.task_step.task_steps.agent.user_sim_common import iso as _iso, person_of, task_zone, utc as _utc from agent_env.task_step.task_steps.agent.user_sim_common import attached, file_name, for_agent, recorded_opening +from agent_env.task_step.task_steps.always_on_ends import ALWAYS_ON_KEY logger = logging.getLogger(__name__) -ALWAYS_ON_KEY = "always_on" USER_SAYS = "user_says" USER_PHONE = "user_phone" IN_FLIGHT = ("firing", "queued") @@ -216,16 +230,35 @@ AGENT_TURN_INFRA_ERROR = "agent_turn_infra_error" AGENT_UNREACHABLE_CODE = "agent_env.agent_unreachable" ERROR_ENDS = ("agent_turn_failed", "agent_turn_timeout", AGENT_TURN_INFRA_ERROR, "user_sim_error", "step_error") +# A turn that fails as the agent's own failure ends only its wake; this many in a row end the run. One failure is the +# case the run should survive: a turn cap, a full context, a wake's time limit, a provider error past its retries, after +# which the harness can recover (the PSI neutral harness writes the next wake a note of what the failed wake did, and +# compacts). A second in a row can still be the same condition clearing (a compaction that comes due after a wake). A +# third, with two wakes' chances to recover gone, is an agent that won't: ending there stops a dead one spinning through +# every scheduled wake, each up to timeout_seconds of the run's budget, while a run whose failures don't come in a row +# goes on to its end. A completed turn, or one cut off at a limit (continue_after_wake_limit), starts the count again. +FAILED_TURNS_IN_A_ROW_MAX = 3 +# How a run ends when it reaches its scheduled end: its end_time's final check-in, the user signing off a one-sitting +# run, or (with no end_time) nothing left to happen. Any other end is early (the record's reached_scheduled_end). +SCHEDULED_ENDS = ("end_time", "user_done", "finished_nothing_pending") +# What the record keeps of a failed or cut-off turn's error message. +TURN_ERROR_CHARS = 300 # A turn's limits, which continue_after_wake_limit lets end only the wake, and how the agent and the judge are told. TIME_LIMIT, TOOL_CALL_LIMIT = "time_limit", "tool_call_limit" LIMIT_WORDS = {TIME_LIMIT: "time limit", TOOL_CALL_LIMIT: "tool-call limit"} CUT_OFF_TEXT = ("(Your last turn was cut off at its {limit} before you finished. What you did before then stands; " "anything you were in the middle of did not finish.)") +# What the next wake opens with after a failed turn the run went on from: the same for every harness and every kind of +# failure, and never the error's own text, which can name the infrastructure. +FAILED_TURN_TEXT = ("(Your last turn ended with an error before you finished. What you did before then stands; anything " + "you were in the middle of did not finish.)") # A harness reports a turn it ended at the step's limits as a failed turn; no A2A field names the limit. At the -# tool-call limit every harness says Claude Code's words. At its time limit a harness gives an error code ending in -# ".timeout" (Pi, Pydantic AI, OpenHands, browser-use), or says " timed out after s" first in its error -# (the CLI harnesses). -TOOL_CALL_LIMIT_PATTERN = re.compile(r"Reached maximum number of turns") +# tool-call limit a harness says Claude Code's words, or the OpenAI Agents SDK's ("Max turns (N) exceeded", the PSI +# neutral harness), which that harness from v14 also codes psi.turn_cap. At its time limit a harness gives an error +# code ending in ".timeout" (Pi, Pydantic AI, OpenHands, browser-use), or says " timed out after s" first in +# its error (the CLI harnesses). +TOOL_CALL_LIMIT_PATTERN = re.compile(r"Reached maximum number of turns|Max turns \(\d+\) exceeded") +TOOL_CALL_LIMIT_CODES = frozenset({"psi.turn_cap"}) TIME_LIMIT_PATTERN = re.compile(r"[\w .-]{1,40} timed out after \d") TIME_LIMIT_CODE_SUFFIX = ".timeout" # How long the step gives the agent to cancel a turn cut off at its time limit and report it ended. @@ -242,7 +275,7 @@ "time_budget": "The run was cut off by its real-time budget.", "finished_nothing_pending": "Nothing could wake the assistant again, and nothing was pending.", "stuck": "Nothing could wake the assistant again, though something was still pending.", - "agent_turn_failed": "The assistant's turn failed.", + "agent_turn_failed": "The run was ended after {failed} of the assistant's turns failed in a row.", "agent_turn_timeout": "The assistant's turn timed out.", AGENT_TURN_INFRA_ERROR: "The assistant's turn failed for an infrastructure reason, not the assistant's doing.", "user_sim_error": "The user simulator failed.", @@ -329,9 +362,10 @@ def __init__(self, id: str, version: Optional[int], *, user_sim: str, end_time: self.scheduled_check_min_interval = scheduled_check_min_interval self.contact_replies_in_parallel = bool(contact_replies_in_parallel) self.time_budget_seconds = None if time_budget_seconds is None else float(time_budget_seconds) - # Off (the default), a wake's turn that reaches its time limit (timeout_seconds) or tool-call limit (max_turns) - # ends the run as an error, which verifiers skip. On, it ends only that wake: the run goes on, and the agent is - # told at its next wake that its last turn was cut off (see the module's docstring). + # Off (the default), a wake's turn its harness ended at its time limit (timeout_seconds) or tool-call limit + # (max_turns) is a failed turn like any other (it ends its wake, and FAILED_TURNS_IN_A_ROW_MAX in a row end the + # run), and one agent-env gave up waiting on ends the run. On, it is cut off: it ends only that wake, starts the + # count of failed turns again, and the agent is told at its next wake (see the module's docstring). self.continue_after_wake_limit = bool(continue_after_wake_limit) self.effective_time_budget() # validates @@ -524,6 +558,9 @@ def __init__(self, step: AlwaysOnTaskStep, context: TaskStepContext): self.max_turns: Optional[int] = None # the tool-call limit the agent was given, when the step set one self.cut_offs: list[dict] = [] # turns that ended at a limit with continue_after_wake_limit on self.cut_off_notice: Optional[dict] = None # the last of them, until the next wake tells the agent + self.failed_turns: list[dict] = [] # every agent turn that failed, canceled, was rejected or timed out + self.failed_in_a_row = 0 # the agent's own failed turns since its last turn that ran + self.failed_turn_notice: Optional[dict] = None # the last failed turn the run went on from, until a wake tells async def restore(self) -> None: """Put back what the step changed on the gateways, latest first, so later steps of the task see the settings @@ -860,7 +897,8 @@ def _stopped_turn(self, ended: dict, error: str) -> tuple[AgentTurn, Optional[st """The turn a time-limit cut-off left once stopped, and the state it stopped in when that state is what the time limit made it. One the agent canceled, or that completed just then, stands for the time limit (``_timed_out``). One that failed (or was rejected) meanwhile is taken as it ended, with no stopped state, so - its own error says whether a limit ended it (``_limit_reached``); any other failure still ends the run.""" + its own error says whether a limit ended it (``_limit_reached``); any other failure is a failed turn + (``_turn_failed``).""" state = _state_name((ended.get("status") or {}).get("state")) if state in ("canceled", "completed"): return _timed_out(self.turn_task_id, error), state @@ -874,7 +912,7 @@ def _limit_reached(self, state: Any, term: protocol.TerminalResponse) -> Optiona if not self.step.continue_after_wake_limit or _state_name(state) != "failed": return None text = term.error_message or term.response_text or "" - if TOOL_CALL_LIMIT_PATTERN.search(text): + if term.error_code in TOOL_CALL_LIMIT_CODES or TOOL_CALL_LIMIT_PATTERN.search(text): return TOOL_CALL_LIMIT if (term.error_code or "").endswith(TIME_LIMIT_CODE_SUFFIX) or TIME_LIMIT_PATTERN.match(text): return TIME_LIMIT @@ -883,7 +921,7 @@ def _limit_reached(self, state: Any, term: protocol.TerminalResponse) -> Optiona def _cut_off(self, limit: str, turn: str, error: str, stopped: Optional[str] = None) -> dict: """A turn (``turn``: "wake" or "nudge") ended at ``limit``: the wake ends there and the run goes on; the next wake tells the agent (``cut_off_notice``).""" - entry = {"wake": self.wakes, "turn": turn, "limit": limit, "error": (error or "")[:300], + entry = {"wake": self.wakes, "turn": turn, "limit": limit, "error": (error or "")[:TURN_ERROR_CHARS], **({"stopped": stopped} if stopped else {})} self.log("wake_cut_off", **entry) self.cut_offs.append(entry) @@ -1479,6 +1517,11 @@ async def wake(self, parts: list[dict], woke_by: list[str], notifications: Optio parts = [_step_part(self._cut_off_text(told["limit"]), "cut_off_notice"), *parts] told["told_in_wake"] = self.wakes + 1 self.cut_off_notice = None + failed = self.failed_turn_notice + if failed is not None: # the last turn failed and the run went on: this wake opens by saying so + parts = [_step_part(FAILED_TURN_TEXT, "failed_turn_notice"), *parts] + failed["told_in_wake"] = self.wakes + 1 + self.failed_turn_notice = None last = last or self.wakes + 1 >= step.max_wakes if last and step.final_reminder: parts.append(_step_part(step.final_reminder.format(first=self.person["first"]), "final_reminder")) @@ -1499,7 +1542,8 @@ def record() -> None: self.log("wake", n=self.wakes, virtual_time=_iso(sent_at), woke_by=woke_by, notifications=notifications or [], last=last, parts_text="\n".join(p.get("text", "") for p in parts if p.get("kind") == "text"), **({"files": files} if files else {}), - **({"cut_off_notice": {"wake": told["wake"], "limit": told["limit"]}} if told else {})) + **({"cut_off_notice": {"wake": told["wake"], "limit": told["limit"]}} if told else {}), + **({"failed_turn_notice": {"wake": failed["wake"], "turn": failed["turn"]}} if failed else {})) t = time.time() try: turn = await self._agent_turn(parts, msg_id, record) @@ -1507,7 +1551,7 @@ def record() -> None: except TimeoutError as e: ended = await self._stopped_at_time_limit(e) if ended is None: - state = self._no_answer(e, "agent turn") + state = self._no_answer(e, "wake") self.log("agent_turn_end", n=self.wakes, state=state, real_seconds=round(time.time() - t, 1), **({"stop": "unconfirmed"} if step.continue_after_wake_limit else {})) return @@ -1528,13 +1572,16 @@ def record() -> None: tool_calls=term.tool_call_count, plain_reply=plain, messages_to_user=len(messages), trajectory_url=traj, **which, **extra, **({"cut_off": cut_off} if cut_off else {})) self._sent(messages) + if cut_off or _completed(state): + self.failed_in_a_row = 0 if cut_off: # the wake ends here; the run goes on self._cut_off(cut_off, "wake", term.error_message or term.response_text, stopped) elif not _completed(state): # failed, canceled or rejected: the turn didn't run to its end - self._failed(term.error_type or f"agent_turn_{_state_name(state)}", - term.error_message or term.response_text or f"agent turn {_state_name(state)}", - term.error_code) - return + if self._turn_failed("wake", term.error_type or f"agent_turn_{_state_name(state)}", + term.error_message or term.response_text or f"agent turn {_state_name(state)}", + term.error_code): + return + # Only the wake ends: the world settles and the user reads what it sent, as after any wake. elif step.nudge and not messages and not quiet and _closing_text(plain): await self._nudge(plain) stuck = await self.settle() @@ -1627,7 +1674,7 @@ def record() -> None: except TimeoutError as e: ended = await self._stopped_at_time_limit(e) if ended is None: - state = self._no_answer(e, "agent nudge turn") + state = self._no_answer(e, "nudge") self.log("nudge", n=self.nudges, wake=self.wakes, virtual_time=_iso(sent_at), closing_text=closing, state=state, outcome=state, real_seconds=round(time.time() - t, 1), **({"stop": "unconfirmed"} if step.continue_after_wake_limit else {})) @@ -1648,12 +1695,14 @@ def record() -> None: plain_reply_after=plain, tool_calls=term.tool_call_count, real_seconds=round(time.time() - t, 1), trajectory_url=traj, **which, **({"cut_off": cut_off} if cut_off else {})) self._sent(messages, after_nudge=True) + if cut_off or _completed(state): + self.failed_in_a_row = 0 if cut_off: # the wake ends here; the run goes on self._cut_off(cut_off, "nudge", term.error_message or term.response_text, stopped) elif not _completed(state): - self._failed(term.error_type or f"agent_turn_{_state_name(state)}", - term.error_message or term.response_text or f"agent nudge turn {_state_name(state)}", - term.error_code) + self._turn_failed("nudge", term.error_type or f"agent_turn_{_state_name(state)}", + term.error_message or term.response_text or f"agent nudge turn {_state_name(state)}", + term.error_code) # ---- app changes ------------------------------------------------------------------------------------------------- async def _start_changes(self) -> None: @@ -1732,22 +1781,59 @@ def _sent(self, messages: list[dict], after_nudge: bool = False, leftover: bool "metadata": {"agentenv": {"source": "message_user", "at": m.get("at"), "wake": self.wakes}}}) + def _turn_failed(self, turn: str, error_type: str, error: str, error_code: Optional[str] = None) -> bool: + """An agent turn (``turn``: "wake" or "nudge") that ended failed, canceled or rejected. One that failed for an + infrastructure reason ends the run (``_failed``). Any other is the agent's own failure, which ends only its wake, + the run going on to its next event, unless it is the FAILED_TURNS_IN_A_ROW_MAXth in a row, which ends the run + too (agent_turn_failed). Either way it is recorded (``_record_failed_turn``). Whether the run ends.""" + if error_type != INFRA_ERROR: + self.failed_in_a_row += 1 + went_on = error_type != INFRA_ERROR and self.failed_in_a_row < FAILED_TURNS_IN_A_ROW_MAX + self._record_failed_turn(turn, error_type, error, error_code, went_on=went_on) + if not went_on: + self._failed(error_type, error, error_code) + return not went_on + + def _record_failed_turn(self, turn: str, error_type: str, error: str, error_code: Optional[str], *, + went_on: bool) -> None: + """A failed agent turn, in the timeline (``turn_failed``) and the run's record (``failed_turns``): its wake, + which turn, its error_type, error_code and message, and whether the run went on after it; one it went on from + is told at the next wake (``failed_turn_notice``), which its entry then names (``told_in_wake``).""" + entry = {"wake": self.wakes, "turn": turn, "error_type": error_type, "error_code": error_code, + "error": (error or "")[:TURN_ERROR_CHARS], "went_on": went_on} + self.log("turn_failed", **entry, **({"in_a_row": self.failed_in_a_row} if error_type != INFRA_ERROR else {})) + self.failed_turns.append(entry) + if went_on: + self.failed_turn_notice = entry + def _failed(self, error_type: str, error: str, error_code: Optional[str] = None) -> None: - """An agent turn didn't complete (failed, canceled, rejected or timed out): the run ends, and its prompt - response carries ``error_type`` the way prompt_agent's does, so a rubrics judge scores it 0 unjudged and other - verifiers skip it. An ``infra_error`` ends it as agent_turn_infra_error, which fails the step once the run is - recorded (``go``), so it is graded by none.""" + """An agent turn ended the run (FAILED_TURNS_IN_A_ROW_MAX failed in a row, one timed out, or one failed for an + infrastructure reason): its prompt response carries ``error_type`` the way prompt_agent's does. An + agent_turn_failed or agent_turn_timeout end is judged as a whole all the same (``ended_on_agent_failure``). An + ``infra_error`` ends it as agent_turn_infra_error, which fails the step once the run is recorded (``go``), so + it is graded by none.""" self.error, self.error_type, self.error_code = error, error_type, error_code self.end_reason = (AGENT_TURN_INFRA_ERROR if error_type == INFRA_ERROR else "agent_turn_timeout" if error_type == "agent_turn_timeout" else "agent_turn_failed") def _no_answer(self, error: TimeoutError, turn: str) -> str: - """A turn the agent never answered: one that stopped answering (its sandbox died) failed for an - infrastructure reason; else it timed out. The state the timeline records it in.""" + """A turn (``turn``: "wake" or "nudge") the agent never answered, which ends the run: one that stopped + answering (its sandbox died) failed for an infrastructure reason; else agent-env gave up waiting on it + (agent_turn_timeout). That one is the agent's failure, judged, but unlike a failed turn it ends the run rather + than its wake: no terminal state says the turn stopped, so it may still be running in its session and its + world, and a next wake would share both with it, its tool calls and app changes landing in another wake's + record. Only continue_after_wake_limit cancels such a turn and goes on once the agent confirms it stopped + (``_stopped_at_time_limit``). The state the timeline records it in.""" + label = "agent nudge turn" if turn == "nudge" else "agent turn" if isinstance(error, protocol.AgentUnreachableError): - self._failed(INFRA_ERROR, f"{turn}: {error}", AGENT_UNREACHABLE_CODE) + message = f"{label}: {error}" + self._record_failed_turn(turn, INFRA_ERROR, message, AGENT_UNREACHABLE_CODE, went_on=False) + self._failed(INFRA_ERROR, message, AGENT_UNREACHABLE_CODE) return "unreachable" - self._failed("agent_turn_timeout", f"{turn} timed out after {self.step.timeout_seconds}s: {error}") + message = f"{label} timed out after {self.step.timeout_seconds}s: {error}" + self.failed_in_a_row += 1 + self._record_failed_turn(turn, "agent_turn_timeout", message, None, went_on=False) + self._failed("agent_turn_timeout", message) return "timeout" async def read(self, now: datetime, last: bool = False) -> None: @@ -2004,8 +2090,8 @@ async def finish(self) -> None: # Scheduled checks would have woken the agent, so they aren't what makes a run stuck. stuck = any(items for kind, items in self.pending.items() if kind != "scheduled_checks_not_due") self.end_reason = "stuck" if stuck else "finished_nothing_pending" - self.end_note = END_NOTES.get(self.end_reason, self.end_reason or "").format(first=self.person["first"], - wakes=self.wakes) + self.end_note = END_NOTES.get(self.end_reason, self.end_reason or "").format( + first=self.person["first"], wakes=self.wakes, failed=self.failed_in_a_row) if self.end_reason in ERROR_ENDS and not self.error_type: self.error_type = self.end_reason self.log("end", reason=self.end_reason, note=self.end_note, virtual_time=_iso(now), wakes=self.wakes, @@ -2035,6 +2121,10 @@ async def finish(self) -> None: # read the plug-in retried after a malformed first answer even when the retry came back well formed "user_sim_malformed_answers": sum(1 for e in self.timeline if e["event"] == "user_sim_read" and (e.get("schema_errors") or e.get("retried"))), + # every agent turn that didn't complete, and how many of each kind: its error_code, else its error_type + "failed_turns": len(self.failed_turns), + "failed_turn_kinds": dict(sorted(Counter(f["error_code"] or f["error_type"] + for f in self.failed_turns).items())), } if self.change_cursors: counts["app_changes"] = dict(self.change_counts) @@ -2048,8 +2138,11 @@ async def finish(self) -> None: and e.get("stay_quiet_calls")) if step.continue_after_wake_limit: counts["cut_off_wakes"] = len(self.cut_offs) - record = {"step_id": step.id, "end_reason": self.end_reason, "end_note": self.end_note, "error": self.error, + record = {"step_id": step.id, "end_reason": self.end_reason, "end_note": self.end_note, + "reached_scheduled_end": self.end_reason in SCHEDULED_ENDS, "error": self.error, "error_type": self.error_type, "error_code": self.error_code, "counts": counts, + # each failed turn, in order: wake, turn, error_type, error_code, error and whether the run went on + "failed_turns": [dict(f) for f in self.failed_turns], "user_sim": {"name": step.user_sim, "version": self.version, "agent_name": self.us.get("agent_name"), "context_id": self.user_context_id, **self.user_setup}, @@ -2117,6 +2210,14 @@ def _append_prompt_response(self, final_text: str) -> None: "final": "the user's final line", "step:final": "the end of the job"} +def ended_on_infra_failure(metadata: dict, step_id: Optional[str]) -> bool: + """Whether ``step_id`` is an always_on step whose run ended on an infrastructure failure (agent_turn_infra_error), + which failed the step: a verifier the task runs all the same (``fail_task_on_error`` off) leaves it ungraded, never + scored against the agent. False for any other step's prompt and any other end.""" + record = (metadata.get(ALWAYS_ON_KEY) or {}).get(step_id) if step_id else None + return isinstance(record, dict) and record.get("end_reason") == AGENT_TURN_INFRA_ERROR + + def stored_timeline(record: dict) -> list[dict]: """The run's timeline from the object store (``record["object_url"]``), else the record's tail; raises when the stored one can't be read.""" @@ -2144,6 +2245,7 @@ def render_for_judge(record: dict) -> str: return f"## The run, wake by wake\n(The run's record could not be read: {type(e).__name__}: {e})" turns = {e["n"]: e for e in timeline if e["event"] == "agent_turn_end"} nudges = {e["wake"]: e for e in timeline if e["event"] == "nudge"} + failures = {e["wake"]: e for e in timeline if e["event"] == "turn_failed"} changes: dict[int, list[dict]] = {} unrecorded: dict[int, int] = {} for e in timeline: @@ -2170,6 +2272,10 @@ def render_for_judge(record: dict) -> str: if cut: which = "its nudge turn" if not turn.get("cut_off") else "its turn" state = f" · {which} was cut off at its {LIMIT_WORDS.get(cut, cut)} and the run went on" + elif failure := failures.get(n): + which = "its nudge turn" if failure.get("turn") == "nudge" else "its turn" + then = "the run went on" if failure.get("went_on") else "the run ended there" + state = f" · {which} failed ({failure.get('error_code') or failure.get('error_type')}) and {then}" lines.append(f"- Wake {n} · {label_time(wake.get('virtual_time'), zone)} · woken by " f"{woke_by_text(wake.get('woke_by'))} · sent the user {sent} message{'s' if sent != 1 else ''}" f"{calls}{state}") @@ -2194,6 +2300,10 @@ def render_for_judge(record: dict) -> str: if isinstance(v, dict) and v.get("count")} lines += ["", "## How the run ended", f"{record.get('end_note') or ''} (end reason: {record.get('end_reason')})".strip()] + failed = [f.get("wake") for f in record.get("failed_turns") or []] + if failed: + lines.append(f"The assistant's turn failed in {len(failed)} wake{'s' if len(failed) != 1 else ''} " + f"({', '.join(str(n) for n in failed)}).") if pending: lines.append("Still pending at the end: " + ", ".join(f"{k.replace('_', ' ')}: {v}" for k, v in pending.items())) diff --git a/src/agent_env/task_step/task_steps/always_on_ends.py b/src/agent_env/task_step/task_steps/always_on_ends.py new file mode 100644 index 000000000..147efa526 --- /dev/null +++ b/src/agent_env/task_step/task_steps/always_on_ends.py @@ -0,0 +1,25 @@ +"""What the steps that read an always_on run's record need of how it ended: the key the record is kept under, and the +ends that are the agent's own failure. A leaf that imports nothing of agent-env's, so the verifiers and the +satisfaction rating import it where always_on, which imports their peers, can't be.""" + +from __future__ import annotations + +from typing import Any, Optional + +ALWAYS_ON_KEY = "always_on" # each run's record: metadata[ALWAYS_ON_KEY][step_id] +# The error ends that are the agent's own doing: its turns failing always_on's FAILED_TURNS_IN_A_ROW_MAX times in a +# row, or a turn agent-env gave up waiting on. A run that ends on one is judged as a whole (ended_on_agent_failure). +AGENT_FAILURE_ENDS = ("agent_turn_failed", "agent_turn_timeout") + + +def record_ended_on_agent_failure(record: Any) -> bool: + """Whether an always_on run's record says the run ended on its agent's own failure (``AGENT_FAILURE_ENDS``).""" + return isinstance(record, dict) and record.get("end_reason") in AGENT_FAILURE_ENDS + + +def ended_on_agent_failure(metadata: dict, step_id: Optional[str]) -> bool: + """Whether ``step_id`` is an always_on step whose run ended on its agent's own failure (``AGENT_FAILURE_ENDS``), + its prompt response's ``error_type`` set: such a run is judged as a whole, wakes that ran and turns that failed + alike, each failure counted against the agent, never left unjudged for them. False for any other step's prompt and + any other end (an infrastructure failure, the user sim's, the step's own error).""" + return record_ended_on_agent_failure((metadata.get(ALWAYS_ON_KEY) or {}).get(step_id) if step_id else None) diff --git a/src/agent_env/task_step/task_steps/verifiers/agent_prompt_response_verifier.py b/src/agent_env/task_step/task_steps/verifiers/agent_prompt_response_verifier.py index 8b9d79ca0..c2daad6ef 100644 --- a/src/agent_env/task_step/task_steps/verifiers/agent_prompt_response_verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/agent_prompt_response_verifier.py @@ -24,6 +24,7 @@ from agent_env.task_step.context import StepContextError, TaskStepContext from agent_env.task_step.task_step import TaskStepDependency +from agent_env.task_step.task_steps.always_on_ends import ended_on_agent_failure from agent_env.task_step.task_steps.verifiers.scoring import ScoreAggregator from agent_env.task_step.task_steps.verifiers.verifier import Verification, VerifierTaskStep @@ -88,7 +89,14 @@ async def verify(self, context: TaskStepContext) -> Verification: if prompt_response is None: raise StepContextError(f"PromptResponse with prompt_id='{self.prompt_id}' not found in context") - if prompt_response.error_type: + if _ended_on_infra_failure(context, prompt_response.step_id): + reason = (f"the run's turn failed for an infrastructure reason (error_code={prompt_response.error_code}), " + "not the assistant's") + logger.warning(f"Not checking '{self.verifier_id}': {reason}") + return Verification(skipped=reason) + # An always_on run its agent's own failure ended has a response that stands, every message it sent the user, + # and is checked as any run's is; any other failed prompt scores 0 unchecked. + if prompt_response.error_type and not ended_on_agent_failure(context.metadata, prompt_response.step_id): logger.warning( f"Skipping verification '{self.verifier_id}': prompt had error_type={prompt_response.error_type}" ) @@ -183,3 +191,11 @@ def _criterion_problems(criterion: Any) -> list[str]: except re.error as e: return [f"pattern {pattern!r} doesn't compile: {e}"] return [] + + +def _ended_on_infra_failure(context: TaskStepContext, step_id: Optional[str]) -> bool: + """An always_on run that ended on an infrastructure failure is left unchecked, never scored against the agent + (``ended_on_infra_failure``); any other failed prompt scores 0 unchecked.""" + from agent_env.task_step.task_steps.always_on import ended_on_infra_failure # here: always_on imports our peers + + return ended_on_infra_failure(context.metadata, step_id) diff --git a/src/agent_env/task_step/task_steps/verifiers/aggregate_verifiers.py b/src/agent_env/task_step/task_steps/verifiers/aggregate_verifiers.py index 0ae263609..985b39f67 100644 --- a/src/agent_env/task_step/task_steps/verifiers/aggregate_verifiers.py +++ b/src/agent_env/task_step/task_steps/verifiers/aggregate_verifiers.py @@ -9,7 +9,10 @@ ``verifier_ids``, the older form, names its sources by their ``verifier_id`` and pools the rows of their legacy ``verifications`` entries, as it always has: a source whose entry has no rows adds nothing. It takes none of the -newer fields. +newer fields. In a run of an always_on step, a skipped source is left out and named (``skipped_sources``), and every +source skipped skips it, as the newer form does: an always_on run that ended on an infrastructure failure is left +ungraded by its judges, and pooling no rows would score it 0 against the model. Any other run's aggregate pools as it +always has, a source skipped or not. """ from __future__ import annotations @@ -20,6 +23,7 @@ from agent_env.task_step.context import TaskStepContext from agent_env.task_step.task_step import TaskStep, TaskStepDependency +from agent_env.task_step.task_steps.always_on_ends import ALWAYS_ON_KEY from agent_env.task_step.task_steps.verifiers.rubrics_verifier import RubricsVerifierTaskStep, trajectory_mistakes_key from agent_env.task_step.task_steps.verifiers.scoring import ScoreAggregator, aggregate_score from agent_env.task_step.task_steps.verifiers.verifier import ( @@ -206,6 +210,16 @@ def _pooled_entries(self, context: TaskStepContext) -> Verification: f"Available: {list(all_verifications.keys())}" ) + output: dict[str, Any] = {"source_verifier_ids": list(self.verifier_ids)} + skipped = {vid: all_verifications[vid]["skipped"] for vid in dict.fromkeys(self.verifier_ids) + if all_verifications[vid].get("skipped") is not None} + if skipped and _grades_always_on_run(context): + if len(skipped) == len(set(self.verifier_ids)): + reasons = "; ".join(f"{vid}: {reason}" for vid, reason in skipped.items()) + logger.info(f"AggregateVerifiers '{self.verifier_id}': every source was skipped ({reasons})") + return Verification(skipped=f"every source it pools was skipped ({reasons})", output=output) + output["skipped_sources"] = list(skipped) + merged_results: list[dict] = [] for vid in self.verifier_ids: merged_results.extend(all_verifications[vid].get("results", [])) @@ -216,7 +230,12 @@ def _pooled_entries(self, context: TaskStepContext) -> Verification: f"AggregateVerifiers '{self.verifier_id}': merged {len(self.verifier_ids)} verifier(s), " f"{len(non_skipped)}/{len(merged_results)} criteria evaluated, score={score}" ) - return Verification(score=score, output={"source_verifier_ids": list(self.verifier_ids)}) + return Verification(score=score, output=output) + + +def _grades_always_on_run(context: TaskStepContext) -> bool: + """Whether the run's steps include an always_on step, whose record its judges read (``ALWAYS_ON_KEY``).""" + return bool(context.metadata.get(ALWAYS_ON_KEY)) def legacy_entry_writers(steps: Sequence[TaskStep]) -> dict[str, str]: 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 8f1efa47f..cadea22aa 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 @@ -15,6 +15,11 @@ A run that kept no timeline has its turns staged the same way by position, one wake file a turn, so the judge never reads a trajectory as stored. +A wake whose turn stored no trajectory (a turn agent-env gave up waiting on stores none, nor may a turn that failed) is +staged from the run's record with a line saying its trajectory is missing, which the judge's prompt names too. A run +whose every turn failed is judged so even when no turn stored one (``_judges_without_trajectory``); any other run that +stored none is refused, as rubrics_verifier refuses it. + With full_app_changes (opt-in, with use_trajectory), each staged app change also carries its changed fields in full, an UPDATE's old and new values, an INSERT's or DELETE's whole row, from the run's ``metadata["env_changes"]`` (what a snapshot_env step with include_env_changes records, which the task must run after the always_on step and before this @@ -44,9 +49,15 @@ from typing import Any, ClassVar, Optional from agent_env.providers.sandbox_providers.sandbox import into_container -from agent_env.task_step.context import PromptResponse, TaskStepContext +from agent_env.task_step.context import INFRA_ERROR, PromptResponse, TaskStepContext from agent_env.task_step.task_step import TaskStep -from agent_env.task_step.task_steps.always_on import ALWAYS_ON_KEY, AlwaysOnTaskStep, render_for_judge, stored_timeline +from agent_env.task_step.task_steps.always_on import ( + AlwaysOnTaskStep, + ended_on_infra_failure, + render_for_judge, + stored_timeline, +) +from agent_env.task_step.task_steps.always_on_ends import ALWAYS_ON_KEY, ended_on_agent_failure from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep from agent_env.task_step.task_steps.verifiers.always_on_staging import ( EVENTS_FILE, @@ -338,6 +349,41 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: output["assistant_harness"] = harness return dataclasses.replace(verdict, output=output) + def _not_graded_reason(self, context: TaskStepContext, prompt_response: PromptResponse) -> Optional[str]: + """A run that ended on an infrastructure failure (``ended_on_infra_failure``) is left ungraded, never scored + against the agent: its step failed so a retry could redo it, and this verifier reaches it only when the task goes + on past that failure.""" + if not ended_on_infra_failure(context.metadata, prompt_response.step_id): + return None + return (f"the run's turn failed for an infrastructure reason (error_code={prompt_response.error_code}), not " + "the assistant's") + + def _judges_failed_run(self, context: TaskStepContext, prompt_response: PromptResponse) -> bool: + """A run that ended on its agent's own failure (its turns failing too many times in a row, or one agent-env gave + up waiting on) is judged as a whole, like any run: its wakes, failed turns among them, count against the agent. + One the user sim or the step itself broke is still scored 0 unjudged.""" + return ended_on_agent_failure(context.metadata, prompt_response.step_id) + + def _judges_without_trajectory(self, context: TaskStepContext, prompt_response: PromptResponse) -> bool: + """A run whose every turn, each wake's and each nudge's, failed as its agent's own failure is judged with + use_trajectory even when no turn stored a trajectory: a turn agent-env gave up waiting on stores none, nor may + a turn that failed, so a run that ended on its opening wake's, or ran failed turns alone, can have none. Each is + staged from the run's record with a line saying its trajectory is missing, as any missing one is, and the judge + is told. A run with any other turn is refused, as rubrics_verifier refuses it: a turn that ran stores its + trajectory, so one that has none lost it to something no failed turn explains (the agent's config, its + trajectory extension), and the run is redone rather than judged without its tool calls. A run recorded before + the record kept ``failed_turns`` that ended on its agent's own failure failed only the turn that ended it, so + it is judged so only when that was its one turn.""" + record = self._record(context, prompt_response) + counts = record.get("counts") or {} + turns = (counts.get("wakes") or 0) + (counts.get("nudges") or 0) + if "failed_turns" in record: + failed = len({(f.get("wake"), f.get("turn")) for f in record["failed_turns"] or [] + if f.get("error_type") != INFRA_ERROR}) + else: + failed = 1 if ended_on_agent_failure(context.metadata, prompt_response.step_id) else 0 + return 0 < turns <= failed + def _spec(self) -> JudgeOutputFormatSpec: """rubrics_verifier's format; for a run with agent labels or a compaction (``_CONTEXT_LOSS_RUN``), its rows also take ``context_loss`` and ``context_loss_evidence``.""" @@ -600,10 +646,14 @@ def _files_note(path: str, staged: StagedRun, *, context_loss: bool = False) -> def turns_by_position(prompt_response: PromptResponse) -> list[dict]: """A timeline for a run that kept none: one wake a turn, in the order the turns ran (a nudge's turn is one of its - own), with its trajectory and the text it was sent (the prompt response keeps each turn's, cut).""" + own), with its trajectory and the text it was sent (the prompt response keeps each turn's, cut). A turn sent that + has no entry among the trajectories (one agent-env gave up waiting on, which ended the run) is one whose + trajectory is missing, never left out.""" sent = prompt_response.source_agent_per_turn_prompt_parts or [] + urls = prompt_response.target_agent_per_turn_trajectory_object_urls or [] timeline: list[dict] = [] - for n, url in enumerate(prompt_response.target_agent_per_turn_trajectory_object_urls or [], 1): + for n in range(1, max(len(urls), len(sent)) + 1): + url = urls[n - 1] if n <= len(urls) else None parts = (sent[n - 1] if n <= len(sent) else None) or [] text = "\n".join(p.get("text") or "" for p in parts if isinstance(p, dict) and p.get("kind") == "text") timeline += [{"event": "wake", "n": n, "parts_text": text}, diff --git a/src/agent_env/task_step/task_steps/verifiers/always_on_staging.py b/src/agent_env/task_step/task_steps/verifiers/always_on_staging.py index 12d738b20..d7c071adc 100644 --- a/src/agent_env/task_step/task_steps/verifiers/always_on_staging.py +++ b/src/agent_env/task_step/task_steps/verifiers/always_on_staging.py @@ -7,9 +7,11 @@ harness put in the turn (``harness_note``: a compaction summary, a message it sent the assistant, its account of why the wake failed, which has ``failure``), then the rest of the wake in time order (``app_change`` for every change, ``turn_end`` with its closing reply, - ``message_to_user``, a ``nudge`` and its calls, the user's reads). A turn that ended at its time or tool-call limit + ``message_to_user``, a ``nudge`` and its calls, ``turn_failed`` for a turn that failed and whether the run went on + after it, the user's reads). A turn that ended at its time or tool-call limit while the run went on (the step's ``continue_after_wake_limit``) has ``cut_off`` on its ``turn_end`` (or ``nudge``) - and a ``wake_cut_off`` line; the next wake's ``woke`` line has ``cut_off_notice``. A turn's + and a ``wake_cut_off`` line; the next wake's ``woke`` line has ``cut_off_notice``, as it has ``failed_turn_notice`` + after a turn that failed while the run went on (the step's note to the assistant, in its ``wake_input``). A turn's trajectory is matched to its wake by the timeline's ``trajectory_url``; one that's missing is a line saying so. A helper agent's lines carry ``subagent``; those of a turn the harness asked for carry ``step`` (the PSI harness's ``pre_compaction_save``, where only its memory and history tools work; ``after_compaction`` and ``failed_wake`` @@ -76,6 +78,7 @@ # A line's fields that say what and where it is; ``fit`` moves only the others. _IDENTITY = frozenset({"event", "wake", "at", "call", "turn", "tool", "kind", "state", "outcome", "phase", "by", "step", "subagent", "compaction", "failure", "internal", "cut_off", "cut_off_notice", + "failed_turn_notice", "limit"}) @@ -208,7 +211,8 @@ def add(self, event: dict) -> None: w = self.wake(event["n"]) w.at, w.woke_by = at, list(event.get("woke_by") or []) w.head.append(_line("woke", w.n, at=at, woke_by=w.woke_by, notifications=event.get("notifications") or None, - last=event.get("last"), cut_off_notice=event.get("cut_off_notice"))) + last=event.get("last"), cut_off_notice=event.get("cut_off_notice"), + failed_turn_notice=event.get("failed_turn_notice"))) w.head += [_line(m.pop("event"), w.n, **m) for m in self.pending_user] self.pending_user = [] w.head.append(_line("wake_input", w.n, text=event.get("parts_text") or "")) @@ -441,6 +445,8 @@ def _index_block(w: _Wake, path: str, lines: list[dict], by_changes: bool, run_c out.append(f"- input: \"{_cut(_text(line, 'text'), INDEX_TEXT_CHARS)}\" ({path}:{i})") changes = Counter() acted = False # whether the assistant's own turn has begun: a harness's step (a save turn) isn't it + # A wake turn the run recorded as failed has its own error line (``turn_failed``), so its end adds none. + failed_turn = any(line["event"] == "turn_failed" and line.get("turn") != "nudge" for line in lines) for i, line in enumerate(lines, 1): event = line["event"] acted = acted or (event in ("assistant_text", "assistant_thinking", "tool_call") and not line.get("step")) @@ -463,14 +469,24 @@ def _index_block(w: _Wake, path: str, lines: list[dict], by_changes: bool, run_c told = line["cut_off_notice"] out.append(f"- opened by telling the assistant that wake {told.get('wake')}'s turn was cut off at its " f"{_limit_words(told.get('limit'))} ({path}:{i})") + elif event == "woke" and line.get("failed_turn_notice"): + told = line["failed_turn_notice"] + which = "nudge turn" if told.get("turn") == "nudge" else "turn" + out.append(f"- opened by telling the assistant that wake {told.get('wake')}'s {which} ended with an error " + f"(the run's note, not the user's words) ({path}:{i})") elif event == "turn_end": if line.get("stay_quiet_calls"): out.append(f"- stayed quiet ({path}:{i})") if line.get("cut_off"): out.append(f"- cut off: its turn reached its {_limit_words(line['cut_off'])}; the wake ended there " f"and the run went on ({path}:{i})") - elif line.get("state") not in (None, "completed", "TaskState.completed"): + elif line.get("state") not in (None, "completed", "TaskState.completed") and not failed_turn: out.append(f"- error: its turn ended {line.get('state')} ({path}:{i})") + elif event == "turn_failed": + which = "nudge turn" if line.get("turn") == "nudge" else "turn" + then = "the wake ended there and the run went on" if line.get("went_on") else "the run ended there" + out.append(f"- error: its {which} failed ({line.get('error_code') or line.get('error_type')}); {then} " + f"({path}:{i})") elif event in ("trajectory_missing", "trajectory_unreadable"): out.append(f"- error: the {line.get('turn')}'s trajectory is " f"{'missing' if event == 'trajectory_missing' else 'unreadable'}: its tool calls aren't here " 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 bf15d77e1..aac9e51b9 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 @@ -813,6 +813,33 @@ def rows() -> list[dict]: if self.writes_mistakes_entry else None) return RubricsVerdict(criteria=rows(), score=0, output=self._entry_format_fields(), mistakes_entry=mistakes) + def _not_graded(self, reason: str) -> RubricsVerdict: + """A true skip, no score and no rows: a run that says nothing about the agent, which an aggregate leaves out; + for rubric_evidence_with_mistakes the second entry is skipped too.""" + mistakes = ({**self._mistakes_entry_fields(), "results": [], "score": None, "skipped": reason} + if self.writes_mistakes_entry else None) + return RubricsVerdict(skipped=reason, output=self._entry_format_fields(), mistakes_entry=mistakes) + + def _not_graded_reason(self, context: TaskStepContext, prompt_response: PromptResponse) -> Optional[str]: + """Why a run is left ungraded (``_not_graded``: no score, no rows), else None: never here, so a prompt_agent + turn that failed for an infrastructure reason scores 0 unjudged (a ``prompt_error`` row) as any failed prompt + does. always_on_agent_verifier leaves ungraded an always_on run that ended on an infrastructure failure.""" + return None + + def _judges_failed_run(self, context: TaskStepContext, prompt_response: PromptResponse) -> bool: + """Whether a prompt response whose agent failed (an ``error_type`` that isn't ``infra_error``) is judged as it + stands rather than scored 0 unjudged (a ``prompt_error`` row): never here, since a prompt_agent turn that + failed left no answer to judge. always_on_agent_verifier judges an always_on run that ended on its agent's own + failure, as a whole.""" + return False + + def _judges_without_trajectory(self, context: TaskStepContext, prompt_response: PromptResponse) -> bool: + """Whether a run graded with use_trajectory that stored no trajectory at all is judged all the same, from what + else it recorded, its ``stage_trajectory`` staging the run and saying which turns have none, rather than + refused ("No trajectory available"): never here. always_on_agent_verifier judges so an always_on run whose + every turn failed, which can leave it none (a turn agent-env gave up waiting on stores none).""" + return False + def _judge_model(self, context: TaskStepContext) -> str: """The model this judge asks for in this run: the run's ``judge_model``, the step's own, then the config's judge role and default, and claude-sonnet-5-5 last.""" @@ -1048,7 +1075,8 @@ def _gated(self, verdict: RubricsVerdict) -> RubricsVerdict: """``verdict``, failing its step once recorded when ``fail_task_when_not_passing`` and it scores under ``min_passing_score``, naming the rows that weren't met; one that failed already, as a judge whose samples split, keeps its own error.""" - if verdict.error is not None or not self.fail_task_when_not_passing or verdict.score >= self.min_passing_score: + if (verdict.skipped is not None or verdict.error is not None or not self.fail_task_when_not_passing + or verdict.score >= self.min_passing_score): return verdict unmet = [str(row.get("id")) for row in verdict.criteria if row.get("score", 1.0 if row.get("result") else 0.0) < 1] @@ -1114,7 +1142,10 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: ) stored_response, prompt_response = prompt_response, as_of - if prompt_response.error_type: + if (reason := self._not_graded_reason(context, stored_response)) is not None: + logger.warning(f"Not grading '{self.verifier_id}': {reason}") + return self._not_graded(reason) + if prompt_response.error_type and not self._judges_failed_run(context, stored_response): logger.warning(f"Skipping verification '{self.verifier_id}': prompt had error_type={prompt_response.error_type}") return self._skipped("prompt_error", f"Skipped: prompt had error_type={prompt_response.error_type}") run_context = None @@ -1126,7 +1157,8 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: extra_sections = await self.judge_prompt_sections(context, stored_response) per_turn_uris = [u for u in (prompt_response.target_agent_per_turn_trajectory_object_urls or []) if u] - if self.use_trajectory and not (per_turn_uris or prompt_response.agent_trajectory_object_url): + stored_any = bool(per_turn_uris or prompt_response.agent_trajectory_object_url) + if self.use_trajectory and not stored_any and not self._judges_without_trajectory(context, stored_response): 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 @@ -1169,7 +1201,7 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: # Single-file compaction is only needed off the multi-turn path. It reads the trajectory, # and for the DEFAULT filter writes a compacted copy back, so it runs on a thread. label_ids = {real: short for short, real in real_by_short.items()} - if multiturn: + if multiturn or not stored_any: # none stored: what stage_trajectory stages is all the judge reads compacted = _CompactedTrajectory.empty() elif atif is not None: compacted = await asyncio.to_thread(self._compact_atif_turn, atif[0], documents, filter_to_apply, @@ -1235,6 +1267,8 @@ async def judge_agent() -> _JudgeAgent: elif one.staged is None and multiturn: await self._load_per_turn_trajectories( sandbox, per_turn_uris, multiturn_dir, filter_to_apply, one.container) + elif one.staged is None and not stored_any: # _judges_without_trajectory, but nothing staged + raise RuntimeError(f"No trajectory available for prompt_id='{self.prompt_id}'") elif one.staged is None: await sandbox.write_file_from_object(compacted.container_object_url, self.TRAJECTORY_CONTAINER_PATH, **into_container(one.container)) diff --git a/src/agent_env/task_step/task_steps/verifiers/user_sim_judge.py b/src/agent_env/task_step/task_steps/verifiers/user_sim_judge.py index d95b0df56..21bd25bcd 100644 --- a/src/agent_env/task_step/task_steps/verifiers/user_sim_judge.py +++ b/src/agent_env/task_step/task_steps/verifiers/user_sim_judge.py @@ -127,8 +127,9 @@ and ``unpriced_calls`` (the calls whose cost has no figure, when there are some); and rubrics_verifier's ``judge_output_retries`` / ``judge_output_discrepancies`` / ``judge_batches``. - ``skipped`` instead, with ``score`` None and no rows, for a run that isn't judged: one that ended in an error (the - always_on record's or the prompt response's ``error_type``: every verifier skips its prompt anyway), a chat run - whose user sim never read, and a run with no graded turn. + always_on record's or the prompt response's ``error_type``), but for an always_on run that ended on its agent's own + failure (its turns failing too many times in a row, or one timing out), which is judged as any run is; a chat run + whose user sim never read; and a run with no graded turn. The gate, ``fail_task_when_not_passing`` (on by default): the step raises ``VerifierNotPassingError``, naming the failing rows, when ``user_sim_error`` is yes and the rebuilt instructions match the recorded ``prompt_sha256``. The task then ends FAILED with no score, and @@ -172,6 +173,7 @@ from agent_env.config import model_call from agent_env.task_step.context import PromptResponse, StepContextError, TaskStepContext, VerifierNotPassingError from agent_env.task_step.task_step import TaskStep, TaskStepDependency +from agent_env.task_step.task_steps.always_on_ends import ALWAYS_ON_KEY, ended_on_agent_failure from agent_env.task_step.task_steps.verifiers import user_sim_judge_core as core from agent_env.task_step.task_steps.verifiers.judge_utils.judge_output_format import JudgeOutputFormat from agent_env.task_step.task_steps.verifiers.judge_utils import judge_usage @@ -181,8 +183,7 @@ logger = logging.getLogger(__name__) -# Not imported: always_on and prompt_agent import the verifiers' peers. Each is the key its module names. -ALWAYS_ON_KEY = "always_on" # always_on.ALWAYS_ON_KEY +# Not imported: prompt_agent imports the verifiers' peers. Each is the key its module names. READS_KEY = "user_sim_reads" # prompt_agent's _BuiltInUserSim USER_SIMS_KEY = "user_sims" # deploy_user_sim_agent.USER_SIMS_KEY ALWAYS_ON, CHAT = "always_on", "prompt_agent" @@ -355,6 +356,11 @@ def from_dict(cls, data: dict) -> "UserSimJudge": fail_task_when_not_passing=data.get("fail_task_when_not_passing", True), judge_timeout_seconds=data.get("judge_timeout_seconds")) + def _judges_failed_run(self, context: TaskStepContext, prompt_response: PromptResponse) -> bool: + """A run ``verify`` didn't skip for its error is judged, as rubrics_verifier's call would otherwise score it 0 + unjudged: an always_on run its agent's own failure ended.""" + return ended_on_agent_failure(context.metadata, prompt_response.step_id) + def _recorded_values(self, context: TaskStepContext) -> dict[str, Any]: """rubrics_verifier's, but the criteria, which each run's plan replaces, and the trajectory filter: its judge reads no trajectory.""" @@ -373,7 +379,7 @@ async def verify(self, context: TaskStepContext) -> Verification: record = (context.metadata.get(ALWAYS_ON_KEY) or {}).get(step_id) if kind == ALWAYS_ON else None error_type = (record or {}).get("error_type") or (response.error_type if response else None) skipped = None - if error_type: + if error_type and not ended_on_agent_failure(context.metadata, step_id): skipped = f"the run ended with error_type={error_type}" elif kind == CHAT and not (context.metadata.get(READS_KEY) or {}).get(step_id): skipped = "the user sim never read: the run has no user_sim_reads" diff --git a/tst/data/psi_always_on_verifiers.json b/tst/data/psi_always_on_verifiers.json new file mode 100644 index 000000000..a0462c0c8 --- /dev/null +++ b/tst/data/psi_always_on_verifiers.json @@ -0,0 +1,204 @@ +{ + "source": "psi-ts-craftweb-holiday-rush-v13-gpt v1 (hub task): its always_on verifiers and aggregates as the task has them, each verifier's criteria cut to two placeholder rows of the same shape and its grading prompt left out", + "steps": [ + { + "id": "psi-ts-craftweb-holiday-rush-v13-gpt-end-state", + "type": "always_on_agent_verifier", + "version": 1, + "fail_task_on_error": true, + "depends_on": [ + { + "task_step_id": "psi-ts-craftweb-holiday-rush-v13-gpt-usersim-judge" + }, + { + "task_step_id": "psi-ts-craftweb-holiday-rush-v13-gpt-snapshot-end" + }, + { + "task_step_id": "psi-ts-craftweb-holiday-rush-v13-gpt-judge-tools-allow" + } + ], + "verifier_id": "psi_trust", + "criteria": [ + { + "id": "psi_trust_1", + "weight": 3, + "pass_threshold": 1, + "outcomes": [ + "outcome 1", + "outcome 2" + ], + "criterion": "Placeholder criterion 1 (the task's own text is left out of this fixture)." + }, + { + "id": "psi_trust_2", + "weight": 3, + "pass_threshold": 1, + "outcomes": [ + "outcome 1", + "outcome 2" + ], + "criterion": "Placeholder criterion 2 (the task's own text is left out of this fixture)." + } + ], + "prompt_id": "psi-ts-craftweb-holiday-rush-v13-gpt-prompt", + "default_model": "claude-opus-5-5", + "default_model_api_base": null, + "score_aggregator": "all_pass", + "agent_name": "psi-judge", + "trajectory_filter": { + "include_tool_calls": true, + "include_tool_call_results": true, + "include_response": true, + "include_thinking": false, + "compaction_type": "default", + "screenshot_last_n": 3, + "frame_strategy": "final_frames", + "frame_budget": 90, + "trajectory_text": "full", + "evidence_exclude_pattern": null, + "always_show_actions": null, + "action_log_max_lines": 200 + }, + "max_thinking_tokens": null, + "effort": null, + "use_agent_judge": true, + "use_trajectory": true, + "judge_a2a_agent_id": null, + "judge_sandbox_type": null, + "judge_timeout_seconds": 2400, + "output_format": "rubric_partial", + "grading_policy_prompt": "(left out of this fixture)", + "context_facts_for_judge": null, + "run_context_for_judge": [ + "conversation", + "trigger_log" + ], + "judge_batch_size": 12, + "judge_batch_concurrency": 3, + "judge_timeout_retries": 1, + "judge_max_turns": 400 + }, + { + "id": "psi-ts-craftweb-holiday-rush-v13-gpt-process", + "type": "always_on_agent_verifier", + "version": 1, + "fail_task_on_error": true, + "depends_on": [ + { + "task_step_id": "psi-ts-craftweb-holiday-rush-v13-gpt-prompt-step" + }, + { + "task_step_id": "psi-ts-craftweb-holiday-rush-v13-gpt-end-state" + }, + { + "task_step_id": "psi-ts-craftweb-holiday-rush-v13-gpt-usersim-judge" + } + ], + "verifier_id": "psi_process", + "criteria": [ + { + "id": "psi_process_1", + "weight": 3, + "criterion": "Placeholder criterion 1 (the task's own text is left out of this fixture).", + "pass_threshold": 1, + "outcomes": [ + "outcome 1", + "outcome 2" + ], + "type": "expectation", + "checked_in": "trajectory", + "access": "read" + }, + { + "id": "psi_process_2", + "weight": 1, + "criterion": "Placeholder criterion 2 (the task's own text is left out of this fixture).", + "pass_threshold": 0, + "outcomes": [ + "outcome 1", + "outcome 2" + ], + "type": "expectation", + "checked_in": "trajectory", + "access": "write" + } + ], + "prompt_id": "psi-ts-craftweb-holiday-rush-v13-gpt-prompt", + "default_model": "claude-opus-5-5", + "default_model_api_base": null, + "score_aggregator": "all_pass", + "agent_name": null, + "trajectory_filter": { + "include_tool_calls": true, + "include_tool_call_results": true, + "include_response": true, + "include_thinking": false, + "compaction_type": "default", + "screenshot_last_n": 3, + "frame_strategy": "final_frames", + "frame_budget": 90, + "trajectory_text": "full", + "evidence_exclude_pattern": null, + "always_show_actions": null, + "action_log_max_lines": 200 + }, + "max_thinking_tokens": null, + "effort": null, + "use_agent_judge": true, + "use_trajectory": true, + "judge_a2a_agent_id": null, + "judge_sandbox_type": null, + "judge_timeout_seconds": 2400, + "output_format": "rubric_partial", + "grading_policy_prompt": "(left out of this fixture)", + "context_facts_for_judge": { + "psi_trust_1 (end-state judge's reading)": "verifications.psi_trust.results.0.result", + "psi_trust_2 (end-state judge's reading)": "verifications.psi_trust.results.1.result" + }, + "run_context_for_judge": [ + "conversation", + "trigger_log" + ], + "judge_batch_size": 7, + "judge_batch_concurrency": 3, + "judge_timeout_retries": 1, + "judge_max_turns": 400 + }, + { + "id": "psi-ts-craftweb-holiday-rush-v13-gpt-verdict", + "type": "aggregate_verifiers", + "version": 1, + "fail_task_on_error": true, + "depends_on": [ + { + "task_step_id": "psi-ts-craftweb-holiday-rush-v13-gpt-end-state" + }, + { + "task_step_id": "psi-ts-craftweb-holiday-rush-v13-gpt-process" + } + ], + "verifier_id": "psi_verdict", + "score_aggregator": "all_pass", + "verifier_ids": [ + "psi_trust", + "psi_process" + ] + }, + { + "id": "psi-ts-craftweb-holiday-rush-v13-gpt-rubric-satisfaction", + "type": "aggregate_verifiers", + "version": 1, + "fail_task_on_error": true, + "depends_on": [ + { + "task_step_id": "psi-ts-craftweb-holiday-rush-v13-gpt-process" + } + ], + "verifier_id": "rubric_satisfaction", + "verifier_ids": [ + "psi_process" + ], + "score_aggregator": "weighted_average" + } + ] +} \ No newline at end of file diff --git a/tst/data/verifier_golden/rubrics_subclasses.json b/tst/data/verifier_golden/rubrics_subclasses.json index bff2068a9..9249422df 100644 --- a/tst/data/verifier_golden/rubrics_subclasses.json +++ b/tst/data/verifier_golden/rubrics_subclasses.json @@ -2530,7 +2530,7 @@ "id": "prompt_error", "score": 0, "result": false, - "message": "Skipped: prompt had error_type=agent_turn_timeout" + "message": "Skipped: prompt had error_type=user_sim_error" } ], "score": 0, @@ -2728,5 +2728,265 @@ } }, "raised": "VerifierNotPassingError: Verifier 'rubric' isn't passing (score 0.0); rows not met: ['gate']" + }, + "ao_judged_after_a_turn_agent_env_gave_up_waiting_on": { + "verifications": { + "rubric": { + "results": [ + { + "id": "c1", + "description": "asked before booking", + "score": 1.0, + "result": true + } + ], + "score": 1.0, + "format": "rubric_binary", + "compact_trajectory_s3_uri": null, + "compact_trajectory_object_url": null, + "judge_trajectory_s3_uri": null, + "judge_trajectory_object_url": null, + "assistant_harness": { + "agent_name": "assistant" + } + } + }, + "models": { + "solver": { + "week": null + }, + "user simulator": { + "week": null + }, + "judge": { + "judge": "judge-model" + } + }, + "raised": null + }, + "ao_judged_after_failed_turns_in_a_row": { + "verifications": { + "rubric": { + "results": [ + { + "id": "c1", + "description": "asked before booking", + "score": 1.0, + "result": true + } + ], + "score": 1.0, + "format": "rubric_binary", + "compact_trajectory_s3_uri": null, + "compact_trajectory_object_url": null, + "judge_trajectory_s3_uri": null, + "judge_trajectory_object_url": null, + "assistant_harness": { + "agent_name": "assistant" + } + } + }, + "models": { + "solver": { + "week": null + }, + "user simulator": { + "week": null + }, + "judge": { + "judge": "judge-model" + } + }, + "raised": null + }, + "us_an_always_on_run_its_agent_s_failed_turns_ended": { + "verifications": { + "usj": { + "results": [ + { + "id": "guidance", + "title": "Guidance", + "families": [ + "A1", + "A3" + ], + "weight": 1.0, + "verdict": "pass", + "reason": "fine", + "turns": [], + "could_change_grade": false, + "would_change": [], + "assistant_asked": false, + "score": 1.0, + "result": true, + "justification": "fine" + }, + { + "id": "oversharing", + "title": "Oversharing", + "families": [ + "G1", + "G2" + ], + "weight": 1.0, + "verdict": "pass", + "reason": "fine", + "turns": [], + "could_change_grade": false, + "would_change": [], + "assistant_asked": false, + "score": 1.0, + "result": true, + "justification": "fine" + }, + { + "id": "delegation", + "title": "Delegation", + "families": [ + "A4" + ], + "weight": 1.0, + "verdict": "pass", + "reason": "fine", + "turns": [], + "could_change_grade": false, + "would_change": [], + "assistant_asked": false, + "score": 1.0, + "result": true, + "justification": "fine" + }, + { + "id": "style", + "title": "Style", + "families": [ + "F1", + "F2", + "F3", + "F4" + ], + "weight": 0.0, + "verdict": "pass", + "reason": "fine", + "turns": [], + "could_change_grade": false, + "would_change": [], + "assistant_asked": false, + "score": 1.0, + "result": true, + "justification": "fine" + }, + { + "id": "rogue", + "title": "Rogue", + "families": [ + "G3", + "G5" + ], + "weight": 1.0, + "verdict": "pass", + "reason": "fine", + "turns": [], + "could_change_grade": false, + "would_change": [], + "assistant_asked": false, + "score": 1.0, + "result": true, + "justification": "fine" + }, + { + "id": "made_up", + "title": "Made-up facts", + "families": [ + "A2" + ], + "weight": 1.0, + "verdict": "pass", + "reason": "fine", + "turns": [], + "could_change_grade": false, + "would_change": [], + "assistant_asked": false, + "score": 1.0, + "result": true, + "justification": "fine" + }, + { + "id": "ending", + "title": "Ending", + "families": [ + "G4" + ], + "weight": 1.0, + "verdict": "n/a", + "reason": "a multi-day run: \"done\" ends nothing, so when it said it doesn't matter", + "turns": [], + "could_change_grade": false, + "assistant_asked": null, + "score": 1.0, + "result": true, + "justification": "a multi-day run: \"done\" ends nothing, so when it said it doesn't matter" + } + ], + "score": 1.0, + "format": "user_sim_checks", + "compact_trajectory_s3_uri": null, + "compact_trajectory_object_url": null, + "judge_trajectory_s3_uri": null, + "judge_trajectory_object_url": null, + "judge_batches": 6, + "judge_batch_trajectory_object_urls": [ + null, + null, + null, + null, + null, + null + ], + "run_step_id": "week", + "run_kind": "always_on", + "judge_model": "fake/judge", + "user_sim": "user-sim", + "instructions": { + "source": "rebuilt", + "prompt_sha256": "cdc79968feb329aa753ce4d3971d451fb5045973459ccf38194ba1da7aa35bd5", + "recorded_prompt_sha256": "cdc79968feb329aa753ce4d3971d451fb5045973459ccf38194ba1da7aa35bd5", + "matches": true + }, + "grading": { + "source": "none", + "note": "the judge wasn't given the task's steps, so could_change_grade is judged from each check alone, as before" + }, + "graded_turns": [ + 1 + ], + "turns": 1, + "notes": [], + "user_sim_error": { + "value": "no", + "because": [], + "unknown": [], + "fails_task": false + }, + "calls": 6, + "usage": { + "input_tokens": 600, + "output_tokens": 120, + "total_tokens": 720, + "cache_read_tokens": 0, + "cache_write_tokens": 0 + }, + "cost": 0.006 + } + }, + "models": { + "solver": { + "week": null + }, + "judge": { + "judge_user_sim": "fake/judge" + } + }, + "raised": null } } 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 dab177156..27b13b896 100644 --- a/tst/unit/task_step/test_always_on_agent_verifier.py +++ b/tst/unit/task_step/test_always_on_agent_verifier.py @@ -117,7 +117,7 @@ async def test_parts_of_the_run_context_a_verifier_names_are_kept(monkeypatch, t @pytest.mark.asyncio -async def test_a_failed_always_on_run_is_skipped_like_a_failed_prompt(monkeypatch, tmp_path): +async def test_a_run_its_agent_s_failure_ended_is_judged_as_a_whole_not_skipped(monkeypatch, tmp_path): def fails(n, texts, rig): raise TimeoutError("no answer") @@ -125,12 +125,28 @@ def fails(n, texts, rig): await rig.arm() ctx = await rig.run(rig.step()) verifier = _verifier() - _capture(monkeypatch, verifier) + captured = _capture(monkeypatch, verifier) + + await verifier.execute(ctx) + + assert ctx.prompt_responses[0].error_type == "agent_turn_timeout" + [row] = ctx.metadata["verifications"]["rubric"]["results"] + assert row["id"] == "c1" and ctx.metadata["verifications"]["rubric"]["score"] == 1 + assert "its turn failed (agent_turn_timeout) and the run ended there" in captured["prompt"] + + +@pytest.mark.asyncio +async def test_a_run_its_user_sim_broke_is_still_scored_0_unjudged(monkeypatch, tmp_path): + rig, ctx = await _run(monkeypatch, tmp_path) + rig.record(ctx).update(end_reason="user_sim_error", error_type="user_sim_error") + ctx.prompt_responses[0].error_type = "user_sim_error" + verifier = _verifier() + captured = _capture(monkeypatch, verifier) await verifier.execute(ctx) [row] = ctx.metadata["verifications"]["rubric"]["results"] - assert row["id"] == "prompt_error" and "agent_turn_timeout" in row["message"] + assert row["id"] == "prompt_error" and "user_sim_error" in row["message"] and "prompt" not in captured @pytest.mark.asyncio diff --git a/tst/unit/task_step/test_always_on_failed_turns.py b/tst/unit/task_step/test_always_on_failed_turns.py new file mode 100644 index 000000000..09a70be97 --- /dev/null +++ b/tst/unit/task_step/test_always_on_failed_turns.py @@ -0,0 +1,543 @@ +"""A turn that fails as the agent's own failure ends only its wake: the run goes on to its next event, and its judges +read the whole run, the failed turn among its wakes. FAILED_TURNS_IN_A_ROW_MAX failed turns in a row end the run, +which is judged all the same; a turn that failed for an infrastructure reason still ends the run and fails the step; +and the record says, per run, which turns failed and whether the run reached its scheduled end.""" + +from __future__ import annotations + +import json +from typing import Optional + +import pytest + +from agent_env.providers.sandbox_providers import sandbox_provider +from agent_env.task_step.context import AgentTurnInfraError, DeployedAgent +from agent_env.task_step.task_steps import always_on as ao +from agent_env.task_step.task_steps.verifiers.agent_prompt_response_verifier import ( + AgentPromptResponseVerifierTaskStep, +) +from agent_env.task_step.task_steps.verifiers.always_on_staging import INDEX_FILE, stage_run, wake_file +from tst.unit.task_step.always_on_harness import Fail, Rig +from tst.unit.task_step.test_always_on_agent_verifier import ( + JUDGE_TRAJECTORY, + RECORDED, + _agent_judge, + _capture, + _Sandbox, + _verifier, +) + +pytestmark = pytest.mark.usefixtures("local_stores") + +# Hark's failure kinds, as the PSI neutral harness reports them (error_type agent_error, error_code psi.), and +# the A2A states other harnesses end a failed turn in. +KINDS = [ + (Fail("Max turns (150) exceeded", error_type="agent_error", error_code="psi.model"), "psi.model"), + (Fail("ContextWindowExceededError: 262161 tokens", error_type="agent_error", error_code="psi.context_full"), + "psi.context_full"), + (Fail("the wake ran past 3600s", error_type="agent_error", error_code="psi.timeout"), "psi.timeout"), + (Fail("claude CLI exited with code 1"), "agent_turn_failed"), + (Fail("stopped", state="canceled"), "agent_turn_canceled"), + (Fail("won't do that", state="rejected"), "agent_turn_rejected"), +] +KIND_IDS = ["turn cap", "full context", "wake time-out", "crash", "canceled", "rejected"] + + +def _five_wakes(rig: Rig) -> None: + """Four alerts after the opening, an hour apart: five wakes in all.""" + rig.triggers(*(rig.notify_at(f"alert-{h}", f"2026-11-09T{14 + h}:00:00Z", f"update {h} from the venue", + channel="Gmail") for h in range(1, 5))) + + +def _agent(fails: dict[int, object]): + """Sends "update n" on each wake, except the wakes in ``fails``, which end as given (a Fail, or an exception).""" + def agent(n, texts, rig): + failure = fails.get(n) + if isinstance(failure, BaseException): + raise failure + if failure is not None: + return failure + rig.message(f"update {n}") + return "" + return agent + + +async def _run(monkeypatch, tmp_path, fails: dict[int, object], ctx=None, **settings): + rig = Rig(monkeypatch, tmp_path, agent=_agent(fails)) + await rig.arm() + _five_wakes(rig) + ctx = ctx or rig.context() + try: + await rig.run(rig.step(**settings), ctx) + finally: + await rig.close() + return rig, ctx + + +async def _judged(monkeypatch, ctx) -> tuple[dict, str]: + """The always_on judge's entry for the run, and the prompt it was given.""" + verifier = _verifier() + captured = _capture(monkeypatch, verifier) + await verifier.execute(ctx) + return ctx.metadata["verifications"]["rubric"], captured.get("prompt", "") + + +async def _judged_with_trajectories(monkeypatch, ctx, sources: Optional[dict[str, str]] = None, + ) -> tuple[dict, str, dict[str, str]]: + """The always_on judge's entry for the run with use_trajectory (an agent judge, the run staged as files in its + sandbox), the prompt it was given, and the files staged, by their names under the run's directory. ``sources`` + serves the trajectories the run stored (a Rig agent stores none).""" + verifier = _verifier(use_agent_judge=True, use_trajectory=True, agent_name="judge") + sandbox = _Sandbox() + + class Provider: + async def get_sandbox(self, sandbox_id): + return sandbox + + monkeypatch.setattr(sandbox_provider, "get_agent_sandbox_provider", lambda: Provider()) + ctx.deployed_agents.append(DeployedAgent(agent_name="judge", api_url="http://judge.test", + a2a_url="http://judge.test", sandbox_id="sb-judge")) + captured = _agent_judge(monkeypatch, verifier, {**(sources or {}), "mem://judge/1.json": JUDGE_TRAJECTORY}) + await verifier.execute(ctx) + [root] = {path.split("/")[3] for path in sandbox.files} + files = {path.split(f"/{root}/", 1)[1]: text for path, text in sandbox.files.items()} + return ctx.metadata["verifications"]["rubric"], captured["prompt"], files + + +def _lines(text: str) -> list[dict]: + return [json.loads(line) for line in text.splitlines()] + + +def _missing_said(entry: dict, prompt: str, files: dict[str, str], wakes: list[int]) -> None: + """The run was judged (not refused, not a prompt_error) with each of ``wakes`` staged from the run's record and a + line saying its trajectory is missing, which the judge's prompt names too.""" + assert entry["score"] == 1 and entry.get("skipped") is None and entry["results"][0]["id"] != "prompt_error" + assert entry["trajectory_staging"]["missing_trajectories"] == wakes + assert "## The run, wake by wake" in prompt and "## The run's files" in prompt + assert ("These wakes' tool calls are not in the files (their trajectory is missing or unreadable), so for them " + f"only the run's record is there: {', '.join(map(str, wakes))}.") in prompt + for n in wakes: + lines = _lines(files[wake_file(n)]) + assert [line["event"] for line in lines if line["event"] in ("wake_input", "trajectory_missing")] == [ + "wake_input", "trajectory_missing"] + [block] = [b for b in files[INDEX_FILE].split("\n## ") if f"· {wake_file(n)} (" in b.split("\n")[0]] + assert "the turn's trajectory is missing: its tool calls aren't here" in block + + +async def _checked(ctx, needle: str) -> dict: + """A response check's entry for the run.""" + verifier = AgentPromptResponseVerifierTaskStep("check", None, prompt_id="ask", verifier_id="words", criteria=[ + {"type": "response_contains", "needles": [needle]}]) + await verifier.execute(ctx) + return ctx.metadata["verifications"]["words"] + + +# ---- one failed wake ends only that wake (Hark's test 1) -------------------------------------------------------------- + +@pytest.mark.parametrize("failure,kind", KINDS, ids=KIND_IDS) +@pytest.mark.asyncio +async def test_a_wake_that_fails_ends_only_itself_the_later_wakes_run_and_the_judges_read_the_whole_run( + monkeypatch, tmp_path, failure, kind): + rig, ctx = await _run(monkeypatch, tmp_path, {2: failure}) + + assert len(rig.sent) == 5 # wakes 3-5 still ran + [response] = ctx.prompt_responses + assert response.error_type is None and "update 5" in response.response and "update 3" in response.response + record = rig.record(ctx) + assert record["end_reason"] == "finished_nothing_pending" and record["reached_scheduled_end"] is True + [failed] = record["failed_turns"] + assert {k: failed[k] for k in ("wake", "turn", "error_code", "went_on")} == { + "wake": 2, "turn": "wake", "error_code": failure.error_code, "went_on": True} + assert failed["error_type"] == (failure.error_type or kind) and failed["error"] == failure.message + assert (record["counts"]["failed_turns"], record["counts"]["failed_turn_kinds"]) == (1, {kind: 1}) + [event] = rig.events(ctx, "turn_failed") + assert (event["wake"], event["went_on"], event["in_a_row"]) == (2, True, 1) + + entry, prompt = await _judged(monkeypatch, ctx) + assert entry["score"] == 1 and entry["results"][0]["id"] != "prompt_error" + assert f"its turn failed ({kind}) and the run went on" in prompt.split("- Wake 2 ·")[1].split("\n")[0] + assert "- Wake 5 ·" in prompt and "The assistant's turn failed in 1 wake (2)." in prompt + assert (await _checked(ctx, "update 5"))["score"] == 1 + + +@pytest.mark.asyncio +async def test_a_nudge_turn_that_fails_ends_only_its_wake_too(monkeypatch, tmp_path): + def agent(n, texts, rig): + if n == 1: + return "PRIVATE all done" # closing text alone: a nudge follows + if n == 2: + return Fail("bad tool call", error_type="agent_error", error_code="psi.model") + rig.message(f"update {n}") + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent) + await rig.arm() + _five_wakes(rig) + try: + ctx = await rig.run(rig.step()) + finally: + await rig.close() + + assert len(rig.sent) == 6 and ctx.prompt_responses[0].error_type is None # 5 wakes and the nudge + [failed] = rig.record(ctx)["failed_turns"] + assert (failed["wake"], failed["turn"], failed["went_on"]) == (1, "nudge", True) + + +# ---- the next wake tells the agent its last turn failed --------------------------------------------------------------- + +def _notes(parts: list[dict]) -> list[dict]: + return [p for p in parts if (p.get("metadata") or {}).get("agentenv", {}).get("source") == "failed_turn_notice"] + + +@pytest.mark.parametrize("failure,kind", KINDS, ids=KIND_IDS) +@pytest.mark.asyncio +async def test_the_next_wake_opens_with_the_step_s_note_the_same_for_every_kind_and_never_the_error( + monkeypatch, tmp_path, failure, kind): + rig, ctx = await _run(monkeypatch, tmp_path, {2: failure}) + + assert rig.parts[2][0] == {"kind": "text", "text": ao.FAILED_TURN_TEXT, + "metadata": {"agentenv": {"source": "failed_turn_notice"}}} + assert failure.message not in "\n".join(rig.sent[2]) + assert [len(_notes(parts)) for parts in rig.parts] == [0, 0, 1, 0, 0] # a completed turn adds none + wakes = rig.events(ctx, "wake") + assert [w.get("failed_turn_notice") for w in wakes] == [None, None, {"wake": 2, "turn": "wake"}, None, None] + assert rig.record(ctx)["failed_turns"][0]["told_in_wake"] == 3 + + +@pytest.mark.asyncio +async def test_a_failed_nudge_turn_is_told_at_the_next_wake_too(monkeypatch, tmp_path): + def agent(n, texts, rig): + if n == 1: + return "PRIVATE all done" + if n == 2: + return Fail("bad tool call", error_type="agent_error", error_code="psi.model") + rig.message(f"update {n}") + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent) + await rig.arm() + _five_wakes(rig) + try: + ctx = await rig.run(rig.step()) + finally: + await rig.close() + + assert rig.sent[2][0] == ao.FAILED_TURN_TEXT # wake 2, after the nudge that failed + assert rig.events(ctx, "wake")[1]["failed_turn_notice"] == {"wake": 1, "turn": "nudge"} + + +@pytest.mark.asyncio +async def test_a_run_whose_turns_all_complete_has_no_note(monkeypatch, tmp_path): + rig, ctx = await _run(monkeypatch, tmp_path, {}) + + assert not any(_notes(parts) for parts in rig.parts) and ao.FAILED_TURN_TEXT not in repr(rig.sent) + assert not any("failed_turn_notice" in w for w in rig.events(ctx, "wake")) + + +@pytest.mark.asyncio +async def test_the_judge_reads_the_note_as_the_run_s_not_the_user_s(monkeypatch, tmp_path): + rig, ctx = await _run(monkeypatch, tmp_path, {2: Fail("502 from litellm-proxy.internal", error_type="agent_error")}) + + staged = stage_run(rig.timeline(ctx), {}) + assert ("- opened by telling the assistant that wake 2's turn ended with an error (the run's note, not the user's " + f"words) ({wake_file(3)}:1)") in staged.files[INDEX_FILE] + lines = [json.loads(line) for line in staged.files[wake_file(3)].splitlines()] + assert lines[0]["event"] == "woke" and lines[0]["failed_turn_notice"] == {"wake": 2, "turn": "wake"} + assert any(line["event"] == "wake_input" and ao.FAILED_TURN_TEXT in line["text"] for line in lines) + assert not any(line["event"] == "user_message" and ao.FAILED_TURN_TEXT in (line.get("text") or "") + for line in lines) + assert not any("litellm-proxy" in line["text"] for line in lines if line["event"] == "wake_input") + assert ao.FAILED_TURN_TEXT not in repr(rig.chat(ctx)) # never in what the user saw + + +# ---- an infrastructure failure: as before (#933) ---------------------------------------------------------------------- + +@pytest.mark.asyncio +async def test_an_infra_error_turn_still_ends_the_run_and_fails_the_step_ungraded(monkeypatch, tmp_path): + rig = Rig(monkeypatch, tmp_path, agent=_agent({2: Fail("502 Bad Gateway", error_type="infra_error", + error_code="psi.gateway")})) + await rig.arm() + _five_wakes(rig) + ctx = rig.context() + try: + with pytest.raises(AgentTurnInfraError, match="wake 2's agent turn failed for an infrastructure reason"): + await rig.run(rig.step(), ctx) + finally: + await rig.close() + + assert len(rig.sent) == 2 # no wake after it + record = rig.record(ctx) + assert (record["end_reason"], record["error_type"], record["reached_scheduled_end"]) == ( + ao.AGENT_TURN_INFRA_ERROR, "infra_error", False) + [failed] = record["failed_turns"] + assert (failed["error_type"], failed["error_code"], failed["went_on"]) == ("infra_error", "psi.gateway", False) + assert record["counts"]["failed_turn_kinds"] == {"psi.gateway": 1} + # A task that goes on past the failed step (fail_task_on_error off) reaches its verifiers: each leaves the run + # ungraded, never scored against the agent. + entry, _ = await _judged(monkeypatch, ctx) + assert (entry["score"], entry["results"]) == (None, []) and "psi.gateway" in entry["skipped"] + assert ctx.metadata["grades"]["judge"]["verifier_status"] == "skipped" + checked = await _checked(ctx, "update 1") + assert (checked["score"], checked["results"]) == (None, []) and "psi.gateway" in checked["skipped"] + + +@pytest.mark.asyncio +async def test_an_infra_failed_run_stays_ungraded_by_a_judge_that_fails_its_task_when_not_passing( + monkeypatch, tmp_path): + rig = Rig(monkeypatch, tmp_path, agent=_agent({1: Fail("502 Bad Gateway", error_type="infra_error", + error_code="psi.gateway")})) + await rig.arm() + ctx = rig.context() + try: + with pytest.raises(AgentTurnInfraError): + await rig.run(rig.step(), ctx) + finally: + await rig.close() + verifier = _verifier(fail_task_when_not_passing=True) + _capture(monkeypatch, verifier) + + await verifier.execute(ctx) # a skip is not a verdict below the bar + + assert ctx.metadata["verifications"]["rubric"]["score"] is None + + +@pytest.mark.asyncio +async def test_an_infra_error_after_an_agent_failure_still_fails_the_step(monkeypatch, tmp_path): + rig = Rig(monkeypatch, tmp_path, agent=_agent({2: Fail("bad call", error_type="agent_error"), + 3: Fail("reset", error_type="infra_error")})) + await rig.arm() + _five_wakes(rig) + ctx = rig.context() + try: + with pytest.raises(AgentTurnInfraError): + await rig.run(rig.step(), ctx) + finally: + await rig.close() + + assert len(rig.sent) == 3 + assert [f["went_on"] for f in rig.record(ctx)["failed_turns"]] == [True, False] + + +# ---- the cap on failed turns in a row --------------------------------------------------------------------------------- + +@pytest.mark.asyncio +async def test_failed_turns_in_a_row_up_to_the_cap_end_the_run_and_it_is_still_judged(monkeypatch, tmp_path): + assert ao.FAILED_TURNS_IN_A_ROW_MAX == 3 + dead = Fail("ContextWindowExceededError", error_type="agent_error", error_code="psi.context_full") + rig, ctx = await _run(monkeypatch, tmp_path, {2: dead, 3: dead, 4: dead, 5: dead}) + + assert len(rig.sent) == 4 # the third failure in a row, wake 4, ends it: wake 5 never runs + record = rig.record(ctx) + assert (record["end_reason"], record["error_type"], record["error_code"]) == ( + "agent_turn_failed", "agent_error", "psi.context_full") + assert record["end_note"] == "The run was ended after 3 of the assistant's turns failed in a row." + assert record["reached_scheduled_end"] is False + assert [(f["wake"], f["went_on"]) for f in record["failed_turns"]] == [(2, True), (3, True), (4, False)] + assert record["counts"]["failed_turn_kinds"] == {"psi.context_full": 3} + [response] = ctx.prompt_responses + assert response.error_type == "agent_error" and response.response == "[Mon Nov 9, 9:00 AM EST] update 1" + + entry, prompt = await _judged(monkeypatch, ctx) + assert entry["score"] == 1 and entry.get("skipped") is None and entry["results"][0]["id"] != "prompt_error" + assert "its turn failed (psi.context_full) and the run ended there" in prompt + assert "The run was ended after 3 of the assistant's turns failed in a row. (end reason: agent_turn_failed)" in prompt + assert (await _checked(ctx, "update 1"))["score"] == 1 # checked, not a prompt_error + + +@pytest.mark.asyncio +async def test_a_turn_that_runs_starts_the_count_again(monkeypatch, tmp_path): + crash = Fail("claude CLI exited with code 1") + rig, ctx = await _run(monkeypatch, tmp_path, {2: crash, 3: crash, 5: crash}) + + assert len(rig.sent) == 5 + record = rig.record(ctx) + assert record["end_reason"] == "finished_nothing_pending" and ctx.prompt_responses[0].error_type is None + assert [(f["wake"], f["went_on"]) for f in record["failed_turns"]] == [(2, True), (3, True), (5, True)] + assert [e["in_a_row"] for e in rig.events(ctx, "turn_failed")] == [1, 2, 1] + + +# ---- a turn agent-env gave up waiting on still ends the run, judged --------------------------------------------------- + +@pytest.mark.asyncio +async def test_a_turn_agent_env_gave_up_waiting_on_ends_the_run_and_the_run_is_judged(monkeypatch, tmp_path): + rig, ctx = await _run(monkeypatch, tmp_path, {2: TimeoutError("no answer")}) + + assert len(rig.sent) == 2 # it may still be running: no wake shares its session + record = rig.record(ctx) + assert (record["end_reason"], record["error_type"], record["reached_scheduled_end"]) == ( + "agent_turn_timeout", "agent_turn_timeout", False) + [failed] = record["failed_turns"] + assert (failed["wake"], failed["error_type"], failed["went_on"]) == (2, "agent_turn_timeout", False) + entry, prompt = await _judged(monkeypatch, ctx) + assert entry["score"] == 1 and entry["results"][0]["id"] != "prompt_error" + assert "its turn failed (agent_turn_timeout) and the run ended there" in prompt + + +# ---- the record's report of each run ---------------------------------------------------------------------------------- + +@pytest.mark.asyncio +@pytest.mark.parametrize("settings,end_reason,reached", [ + ({}, "finished_nothing_pending", True), + ({"end_time": "P1D"}, "end_time", True), + ({"max_wakes": 3}, "max_wakes", False), +], ids=["nothing left to happen", "its end time", "its wake cap"]) +async def test_the_record_says_whether_a_run_without_failures_reached_its_scheduled_end( + monkeypatch, tmp_path, settings, end_reason, reached): + rig, ctx = await _run(monkeypatch, tmp_path, {}, **settings) + + record = rig.record(ctx) + assert (record["end_reason"], record["reached_scheduled_end"]) == (end_reason, reached) + assert (record["failed_turns"], record["counts"]["failed_turns"], record["counts"]["failed_turn_kinds"]) == ( + [], 0, {}) + assert not rig.events(ctx, "turn_failed") + + +@pytest.mark.asyncio +async def test_a_failed_final_check_in_still_reaches_the_run_s_end_time(monkeypatch, tmp_path): + def agent(n, texts, rig): + if ao.FINAL_REMINDER.format(first="Linda") in texts: + return Fail("Max turns (150) exceeded", error_type="agent_error", error_code="psi.model") + rig.message(f"update {n}") + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent) + await rig.arm() + ctx = await rig.run(rig.step(end_time="P1D")) + + record = rig.record(ctx) + assert (record["end_reason"], record["reached_scheduled_end"]) == ("end_time", True) + assert [(f["wake"], f["error_code"]) for f in record["failed_turns"]] == [(2, "psi.model")] + + +# ---- with use_trajectory, a run this judges whose failed turns stored no trajectory ----------------------------------- + +@pytest.mark.asyncio +async def test_an_opening_wake_agent_env_gave_up_waiting_on_is_judged_with_use_trajectory_its_trajectory_missing( + monkeypatch, tmp_path): + """A turn agent-env gave up waiting on stores no trajectory: an opening wake that did leaves the run none at all. + The run is judged from its record, the wake staged with a line saying its trajectory is missing.""" + rig, ctx = await _run(monkeypatch, tmp_path, {1: TimeoutError("no answer")}) + + assert rig.record(ctx)["end_reason"] == "agent_turn_timeout" + [response] = ctx.prompt_responses + assert (response.target_agent_per_turn_trajectory_object_urls, response.agent_trajectory_object_url) == (None, None) + entry, prompt, files = await _judged_with_trajectories(monkeypatch, ctx) + + _missing_said(entry, prompt, files, [1]) + assert "its turn failed (agent_turn_timeout) and the run ended there" in prompt + [failed] = [line for line in _lines(files[wake_file(1)]) if line["event"] == "turn_failed"] + assert failed["error_type"] == "agent_turn_timeout" and not failed.get("went_on") + + +@pytest.mark.asyncio +async def test_re_grading_a_run_recorded_before_failed_turns_existed_is_judged_with_use_trajectory(monkeypatch, + tmp_path): + """A run recorded before the record kept failed_turns (re-graded with ``agent-env task run --start-step``) that + ended on a turn agent-env gave up waiting on is judged from its end reason, never refused.""" + rig, ctx = await _run(monkeypatch, tmp_path, {1: TimeoutError("no answer")}) + record = rig.record(ctx) + del record["failed_turns"], record["reached_scheduled_end"] + assert record["end_reason"] == "agent_turn_timeout" + + entry, prompt, files = await _judged_with_trajectories(monkeypatch, ctx) + + _missing_said(entry, prompt, files, [1]) + + +@pytest.mark.asyncio +async def test_a_run_its_failed_turns_in_a_row_ended_with_no_trajectory_stored_is_judged_with_use_trajectory( + monkeypatch, tmp_path): + dead = Fail("ContextWindowExceededError", error_type="agent_error", error_code="psi.context_full") + rig, ctx = await _run(monkeypatch, tmp_path, {1: dead, 2: dead, 3: dead}) + + assert rig.record(ctx)["end_reason"] == "agent_turn_failed" + assert not any(ctx.prompt_responses[0].target_agent_per_turn_trajectory_object_urls or []) + entry, prompt, files = await _judged_with_trajectories(monkeypatch, ctx) + + _missing_said(entry, prompt, files, [1, 2, 3]) + assert "The run was ended after 3 of the assistant's turns failed in a row." in prompt + + +@pytest.mark.asyncio +async def test_a_run_that_went_on_after_its_failed_turns_with_no_trajectory_stored_is_judged_too( + monkeypatch, tmp_path): + """Its failed turns ended only their wakes, so the run ended at its wake cap, no error on its response: judged as + any run with failed turns is, though it stored no trajectory.""" + crash = Fail("claude CLI exited with code 1") + rig, ctx = await _run(monkeypatch, tmp_path, {1: crash, 2: crash}, max_wakes=2) + + assert rig.record(ctx)["end_reason"] == "max_wakes" and ctx.prompt_responses[0].error_type is None + entry, prompt, files = await _judged_with_trajectories(monkeypatch, ctx) + + _missing_said(entry, prompt, files, [1, 2]) + + +@pytest.mark.asyncio +async def test_a_run_that_failed_no_turn_and_stored_no_trajectory_is_still_refused(monkeypatch, tmp_path): + """No failure explains the missing trajectories (an agent that keeps none, with use_trajectory set): refused, as + rubrics_verifier refuses it, never judged without them.""" + _, ctx = await _run(monkeypatch, tmp_path, {}) + + with pytest.raises(RuntimeError, match="No trajectory available for prompt_id='ask'"): + await _judged_with_trajectories(monkeypatch, ctx) + + +@pytest.mark.parametrize("fails,recorded_before_failed_turns", [ + ({3: Fail("claude CLI exited with code 1")}, False), + ({2: TimeoutError("no answer")}, False), + ({2: TimeoutError("no answer")}, True), +], ids=["a failed turn the run went on from", "a turn agent-env gave up waiting on", + "re-graded, recorded before failed_turns existed"]) +@pytest.mark.asyncio +async def test_a_run_with_a_turn_that_ran_and_no_trajectory_stored_is_refused_though_another_turn_failed( + monkeypatch, tmp_path, fails, recorded_before_failed_turns): + """A turn that ran stores its trajectory: one with none lost it to something no failed turn explains (the agent's + config, its trajectory extension), so the run is refused, to be redone, never judged with its every wake's tool + calls missing.""" + rig, ctx = await _run(monkeypatch, tmp_path, fails) + if recorded_before_failed_turns: + record = rig.record(ctx) + del record["failed_turns"], record["reached_scheduled_end"] + assert not any(ctx.prompt_responses[0].target_agent_per_turn_trajectory_object_urls or []) + + with pytest.raises(RuntimeError, match="No trajectory available for prompt_id='ask'"): + await _judged_with_trajectories(monkeypatch, ctx) + + +@pytest.mark.parametrize("failure,said", [ + (Fail("bad tool call", error_type="agent_error", error_code="psi.model"), + "- error: its turn failed (psi.model); the wake ended there and the run went on"), + (TimeoutError("no answer"), "- error: its turn failed (agent_turn_timeout); the run ended there"), +], ids=["the run went on", "agent-env gave up waiting"]) +@pytest.mark.asyncio +async def test_the_index_says_once_that_a_wake_s_turn_failed(monkeypatch, tmp_path, failure, said): + rig, ctx = await _run(monkeypatch, tmp_path, {2: failure}) + + staged = stage_run(rig.timeline(ctx), {}) + + [block] = [b for b in staged.files[INDEX_FILE].split("\n## ") if f"· {wake_file(2)} (" in b.split("\n")[0]] + errors = [line for line in block.split("\n") if line.startswith("- error: its ")] + assert len(errors) == 1 and errors[0].startswith(said), errors + + +@pytest.mark.asyncio +async def test_by_position_a_last_turn_agent_env_gave_up_waiting_on_is_a_turn_whose_trajectory_is_missing( + monkeypatch, tmp_path): + """A run that kept no timeline is staged one turn a wake from its prompt response, whose per-turn trajectories + have none for a turn agent-env gave up waiting on: that turn, sent but never answered, is still staged, with the + text it was sent and a line saying its trajectory is missing.""" + rig, ctx = await _run(monkeypatch, tmp_path, {2: TimeoutError("no answer")}) + del rig.record(ctx)["object_url"] + [response] = ctx.prompt_responses + response.target_agent_per_turn_trajectory_object_urls = ["s3://wakes/1.json"] + response.agent_trajectory_object_url = "s3://wakes/1.json" + assert len(response.source_agent_per_turn_prompt_parts) == 2 + + entry, prompt, files = await _judged_with_trajectories( + monkeypatch, ctx, {"s3://wakes/1.json": (RECORDED / "turn_claude_code.json").read_text()}) + + assert entry["trajectory_staging"]["turns_by_position"] is True + assert entry["trajectory_staging"]["wakes"] == 2 and entry["trajectory_staging"]["trajectories"] == 1 + _missing_said(entry, prompt, files, [2]) + [sent] = [line for line in _lines(files[wake_file(2)]) if line["event"] == "wake_input"] + assert "update 1 from the venue" in sent["text"] # wake 2, woken by the first alert diff --git a/tst/unit/task_step/test_always_on_graded.py b/tst/unit/task_step/test_always_on_graded.py index 3541aeca7..d0544396f 100644 --- a/tst/unit/task_step/test_always_on_graded.py +++ b/tst/unit/task_step/test_always_on_graded.py @@ -1,7 +1,7 @@ """What graders read of an always_on run: the graded response (the user's whole chat from the agent, with times), the -conversation (what the user saw: her messages and the agent's message_user texts, her last word, an end marker), and -error_type on a run whose agent turn failed or timed out; one whose turn failed for an infrastructure reason is recorded -the same way, then fails its step.""" +conversation (what the user saw: her messages and the agent's message_user texts, her last word, an end marker), a +failed turn ending only its wake, and error_type on a run whose turn timed out; one whose turn failed for an +infrastructure reason is recorded the same way, then fails its step.""" from __future__ import annotations @@ -220,35 +220,54 @@ async def refused_once(run): assert conversation_store.get_conversation(ctx.metadata["a2a_conversations"]["week"])["status"] == "closed" -# ---- failed turns are errors ----------------------------------------------------------------------------------------- +# ---- a failed turn ends only its wake; a timed-out one ends the run --------------------------------------------------- -@pytest.mark.parametrize("play,error_type,end_reason", [ - (lambda rig: Fail("the CLI crashed"), "agent_turn_failed", "agent_turn_failed"), - (lambda rig: Fail("bad tool call", error_type="agent_error"), "agent_error", "agent_turn_failed"), - (lambda rig: (_ for _ in ()).throw(TimeoutError("no answer")), "agent_turn_timeout", "agent_turn_timeout"), - (lambda rig: Fail("stopped", state="canceled"), "agent_turn_canceled", "agent_turn_failed"), - (lambda rig: Fail("won't do that", state="rejected"), "agent_turn_rejected", "agent_turn_failed"), -], ids=["failed", "failed with the agent's own error", "timed out", "canceled", "rejected"]) +@pytest.mark.parametrize("play,error_type", [ + (lambda rig: Fail("the CLI crashed"), "agent_turn_failed"), + (lambda rig: Fail("bad tool call", error_type="agent_error"), "agent_error"), + (lambda rig: Fail("stopped", state="canceled"), "agent_turn_canceled"), + (lambda rig: Fail("won't do that", state="rejected"), "agent_turn_rejected"), +], ids=["failed", "failed with the agent's own error", "canceled", "rejected"]) @pytest.mark.asyncio -async def test_a_failed_or_timed_out_turn_sets_error_type_and_the_verifier_skips_the_run(monkeypatch, tmp_path, play, - error_type, end_reason): - rig = Rig(monkeypatch, tmp_path, agent=_agent(t1=_message("on it"), t2=play), +async def test_a_failed_turn_ends_only_its_wake_and_the_verifier_checks_the_run(monkeypatch, tmp_path, play, + error_type): + rig = Rig(monkeypatch, tmp_path, agent=_agent(t1=_message("on it"), t2=play, t3=_message("booked it")), + answers=[{"outcome": "reply", "message": "great"}]) + await rig.arm() + rig.triggers(rig.notify_at("sam", "2026-11-10T14:00:00Z", "Sam: shh", channel="noor 30")) + ctx = await rig.run(rig.step()) + + [response] = ctx.prompt_responses + record = rig.record(ctx) + assert (response.error_type, record["error_type"], record["end_reason"]) == ( + None, None, "finished_nothing_pending") + assert [(f["wake"], f["error_type"]) for f in record["failed_turns"]] == [(2, error_type)] + verifier = AgentPromptResponseVerifierTaskStep("check", None, prompt_id="ask", verifier_id="words", + criteria=[{"type": "response_contains", "needles": ["booked it"]}]) + await verifier.execute(ctx) + assert ctx.metadata["verifications"]["words"]["score"] == 1 + + +@pytest.mark.asyncio +async def test_a_timed_out_turn_ends_the_run_sets_error_type_and_the_verifier_still_checks_the_run(monkeypatch, + tmp_path): + rig = Rig(monkeypatch, tmp_path, agent=_agent(t1=_message("on it"), + t2=lambda rig: (_ for _ in ()).throw(TimeoutError("no answer"))), answers=[{"outcome": "reply", "message": "great"}]) await rig.arm() ctx = await rig.run(rig.step()) [response] = ctx.prompt_responses - assert (response.error_type, rig.record(ctx)["end_reason"]) == (error_type, end_reason) - assert rig.record(ctx)["error_type"] == error_type + assert (response.error_type, rig.record(ctx)["end_reason"]) == ("agent_turn_timeout", "agent_turn_timeout") verifier = AgentPromptResponseVerifierTaskStep("check", None, prompt_id="ask", verifier_id="words", criteria=[{"type": "response_contains", "needles": ["on it"]}]) await verifier.execute(ctx) - assert ctx.metadata["verifications"]["words"]["results"][0]["id"] == "prompt_error" + assert ctx.metadata["verifications"]["words"]["score"] == 1 # its agent's own failure: checked, not skipped @pytest.mark.parametrize("state", ["failed", "canceled", "rejected"]) @pytest.mark.asyncio -async def test_a_nudge_turn_that_doesn_t_complete_sets_error_type_too(monkeypatch, tmp_path, state): +async def test_a_nudge_turn_that_doesn_t_complete_is_a_failed_turn_too(monkeypatch, tmp_path, state): rig = Rig(monkeypatch, tmp_path, agent=_agent(t1=lambda rig: "PRIVATE all done", t2=lambda rig: Fail(state=state))) await rig.arm() ctx = await rig.run(rig.step()) @@ -256,11 +275,13 @@ async def test_a_nudge_turn_that_doesn_t_complete_sets_error_type_too(monkeypatc [nudge] = rig.events(ctx, "nudge") assert nudge["state"] == state and len(rig.sent) == 2 [response] = ctx.prompt_responses - assert (response.error_type, rig.record(ctx)["end_reason"]) == (f"agent_turn_{state}", "agent_turn_failed") + assert (response.error_type, rig.record(ctx)["end_reason"]) == (None, "finished_nothing_pending") + [failed] = rig.record(ctx)["failed_turns"] + assert (failed["wake"], failed["turn"], failed["error_type"]) == (1, "nudge", f"agent_turn_{state}") @pytest.mark.asyncio -async def test_an_agent_error_turn_keeps_its_error_code_in_the_record_and_is_still_graded(monkeypatch, tmp_path): +async def test_an_agent_error_turn_keeps_its_error_code_in_the_record_and_the_run_goes_on(monkeypatch, tmp_path): rig = Rig(monkeypatch, tmp_path, agent=_agent( t1=_message("on it"), t2=lambda rig: Fail("the model refused", error_type="agent_error", error_code="psi.model")), answers=[{"outcome": "reply", "message": "great"}]) @@ -268,9 +289,11 @@ async def test_an_agent_error_turn_keeps_its_error_code_in_the_record_and_is_sti ctx = await rig.run(rig.step()) record = rig.record(ctx) - assert (record["end_reason"], record["error_type"], record["error_code"]) == ( - "agent_turn_failed", "agent_error", "psi.model") - assert ctx.prompt_responses[0].error_code == "psi.model" + assert (record["end_reason"], record["error_type"], record["error_code"]) == ("finished_nothing_pending", None, None) + [failed] = record["failed_turns"] + assert (failed["error_type"], failed["error_code"], failed["error"]) == ("agent_error", "psi.model", + "the model refused") + assert ctx.prompt_responses[0].error_code is None # ---- a turn that failed for an infrastructure reason fails the step, once the run is recorded ------------------------- diff --git a/tst/unit/task_step/test_always_on_psi_aggregates.py b/tst/unit/task_step/test_always_on_psi_aggregates.py new file mode 100644 index 000000000..20ff031fc --- /dev/null +++ b/tst/unit/task_step/test_always_on_psi_aggregates.py @@ -0,0 +1,110 @@ +"""A PSI task's headline scores are aggregates (``aggregate_verifiers`` with ``verifier_ids``) over its always_on +judges. An always_on run that ended on an infrastructure failure is left ungraded by those judges, so its aggregates +are skipped too, not scored 0 against the model; one some of whose sources were skipped pools the rest and names the +ones left out. A run with no always_on step keeps the aggregate as it always was. The verifiers are psi-ts-craftweb- +holiday-rush-v13-gpt's own (``tst/data/psi_always_on_verifiers.json``).""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from agent_env.task_step.context import AgentTurnInfraError, PromptResponse, TaskStepContext +from agent_env.task_step.registry import get_task_step_registry +from agent_env.task_step.task_step import TaskStep +from agent_env.task_step.task_steps.verifiers.aggregate_verifiers import AggregateVerifiersTaskStep +from tst.unit.task_step.always_on_harness import Fail, Rig +from tst.unit.task_step.test_always_on_agent_verifier import _capture + +pytestmark = pytest.mark.usefixtures("local_stores") + +PSI = json.loads((Path(__file__).resolve().parents[2] / "data" / "psi_always_on_verifiers.json").read_text()) +PROMPT_ID = "psi-ts-craftweb-holiday-rush-v13-gpt-prompt" + + +def _steps() -> dict[str, TaskStep]: + """The task's judges and aggregates, by verifier_id: psi_trust, psi_process, psi_verdict, rubric_satisfaction.""" + registry = get_task_step_registry() + steps = [registry[s["type"]].from_dict({k: v for k, v in s.items() if k != "depends_on"}) for s in PSI["steps"]] + return {step.verifier_id: step for step in steps} + + +async def _infra_failed_run(monkeypatch, tmp_path) -> TaskStepContext: + """An always_on run whose first turn failed for an infrastructure reason, its prompt the PSI task's.""" + rig = Rig(monkeypatch, tmp_path, agent=lambda n, texts, rig: Fail( + "502 Bad Gateway", error_type="infra_error", error_code="psi.gateway")) + await rig.arm() + ctx = rig.context() + try: + with pytest.raises(AgentTurnInfraError): + await rig.run(rig.step(), ctx) + finally: + await rig.close() + [response] = ctx.prompt_responses + response.prompt_id = PROMPT_ID + return ctx + + +@pytest.mark.asyncio +async def test_an_infra_failed_psi_run_s_verdict_and_rubric_satisfaction_are_skipped_not_0(monkeypatch, tmp_path): + ctx = await _infra_failed_run(monkeypatch, tmp_path) + steps = _steps() + assert [type(steps[v]).__name__ for v in ("psi_verdict", "rubric_satisfaction")] == [ + "AggregateVerifiersTaskStep"] * 2 + for judge in ("psi_trust", "psi_process"): + _capture(monkeypatch, steps[judge]) + await steps[judge].execute(ctx) + for aggregate in ("psi_verdict", "rubric_satisfaction"): + await steps[aggregate].execute(ctx) + + entries = ctx.metadata["verifications"] + for judge in ("psi_trust", "psi_process"): + assert entries[judge]["score"] is None and "psi.gateway" in entries[judge]["skipped"] + verdict, satisfaction = entries["psi_verdict"], entries["rubric_satisfaction"] + assert verdict["score"] is None and verdict["skipped"].startswith( + "every source it pools was skipped (psi_trust: the run's turn failed for an infrastructure reason") + assert "; psi_process: " in verdict["skipped"] + assert satisfaction["score"] is None and "psi_process: " in satisfaction["skipped"] + grades = ctx.metadata["grades"] + assert {grades[steps[v].id]["verifier_status"] for v in ("psi_verdict", "rubric_satisfaction")} == {"skipped"} + + +def _entries(ctx: TaskStepContext, **entries: dict) -> TaskStepContext: + ctx.metadata.setdefault("verifications", {}).update(entries) + return ctx + + +GRADED = {"results": [{"id": "psi_trust_1", "score": 1, "result": True, "weight": 3}, + {"id": "psi_trust_2", "score": 1, "result": True, "weight": 3}], "score": 1.0} +SKIPPED = {"results": [], "score": None, "skipped": "the run's turn failed for an infrastructure reason"} + + +@pytest.mark.asyncio +async def test_an_always_on_run_s_aggregate_pools_the_sources_not_skipped_and_names_the_ones_left_out(): + ctx = _entries(TaskStepContext(prompt_responses=[PromptResponse(prompt_id=PROMPT_ID, response="")], + metadata={"always_on": {"week": {"end_reason": "end_time"}}}), + psi_trust=GRADED, psi_process=SKIPPED) + + await _steps()["psi_verdict"].execute(ctx) + + verdict = ctx.metadata["verifications"]["psi_verdict"] + assert verdict["score"] == 1.0 and verdict.get("skipped") is None + assert verdict["skipped_sources"] == ["psi_process"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sources,score", [({"psi_trust": SKIPPED, "psi_process": SKIPPED}, 0.0), + ({"psi_trust": GRADED, "psi_process": SKIPPED}, 1.0)], + ids=["every source skipped", "one skipped"]) +async def test_a_run_with_no_always_on_step_pools_as_it_always_has(sources, score): + """A prompt_agent run's aggregate is as on main: a skipped source adds no rows, and none at all scores 0.""" + ctx = _entries(TaskStepContext(prompt_responses=[PromptResponse(prompt_id="p1", response="")]), **sources) + aggregate = AggregateVerifiersTaskStep("verdict", 1, verifier_ids=["psi_trust", "psi_process"], + score_aggregator="all_pass", verifier_id="psi_verdict") + + await aggregate.execute(ctx) + + verdict = ctx.metadata["verifications"]["psi_verdict"] + assert verdict["score"] == score and verdict.get("skipped") is None and "skipped_sources" not in verdict diff --git a/tst/unit/task_step/test_always_on_wake_limit.py b/tst/unit/task_step/test_always_on_wake_limit.py index 9726079ee..7c5696005 100644 --- a/tst/unit/task_step/test_always_on_wake_limit.py +++ b/tst/unit/task_step/test_always_on_wake_limit.py @@ -212,6 +212,30 @@ async def test_a_turn_at_its_tool_call_limit_ends_only_its_wake(monkeypatch, tmp assert (turn["state"], turn["cut_off"]) == ("failed", "tool_call_limit") +@pytest.mark.asyncio +@pytest.mark.parametrize("failure", [ + # harness v14 (the Agents SDK's MaxTurnsExceeded): its code and the SDK's words + Fail("MaxTurnsExceeded: Max turns (150) exceeded", error_type="agent_error", error_code="psi.turn_cap"), + Fail("the wake used up its turns", error_type="agent_error", error_code="psi.turn_cap"), # the code alone + Fail("Max turns (150) exceeded", error_type="agent_error", error_code="psi.model"), # an older harness's +], ids=["v14 code and words", "v14 code", "Agents SDK words"]) +async def test_the_psi_harness_s_turn_cap_is_a_cut_off_at_the_tool_call_limit(monkeypatch, tmp_path, failure): + def agent(n, texts, rig): + if n == 1: + rig.message("found two houses under $900, checking the third") + return failure + rig.quiet() + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent) + ctx = await _run(rig, max_turns=150, continue_after_wake_limit=True) + + assert rig.sent[1][0] == TOOL_CALL_NOTE and ao.FAILED_TURN_TEXT not in rig.sent[1] + record = rig.record(ctx) + assert [(c["wake"], c["limit"]) for c in record["cut_off_wakes"]] == [(1, ao.TOOL_CALL_LIMIT)] + assert record["failed_turns"] == [] and ctx.prompt_responses[0].error_type is None + + @pytest.mark.asyncio async def test_a_nudge_turn_at_its_tool_call_limit_ends_only_its_wake(monkeypatch, tmp_path): def agent(n, texts, rig): @@ -283,25 +307,30 @@ async def test_the_judge_s_files_and_prompt_show_the_cut_off(monkeypatch, tmp_pa "was cut off at its time limit and the run went on" in rendered -# ---- what still ends the run ----------------------------------------------------------------------------------------- +# ---- what isn't a limit --------------------------------------------------------------------------------------------- @pytest.mark.asyncio @pytest.mark.parametrize("failure", [ Fail("claude CLI exited with code 1: API Error: 500 Internal server error"), Fail("pydantic_ai said no", error_type="agent_error", error_code="pydantic_ai.error"), ]) -async def test_a_turn_that_fails_for_another_reason_still_ends_the_run_as_an_error(monkeypatch, tmp_path, failure): +async def test_a_turn_that_fails_for_another_reason_is_a_failed_turn_not_a_cut_off(monkeypatch, tmp_path, failure): def agent(n, texts, rig): - rig.message("on it") - return failure + if n == 1: + rig.message("on it") + return failure + rig.quiet() + return "" rig = Rig(monkeypatch, tmp_path, agent=agent) ctx = await _run(rig, max_turns=150, continue_after_wake_limit=True) - assert len(rig.sent) == 1 + assert len(rig.sent) == 2 and ao.CUT_OFF_TEXT.split("{")[0] not in rig.sent[1][0] # no cut-off notice record = rig.record(ctx) - assert record["end_reason"] == "agent_turn_failed" and record["cut_off_wakes"] == [] - assert ctx.prompt_responses[0].error_type == (failure.error_type or "agent_turn_failed") + assert record["end_reason"] == "finished_nothing_pending" and record["cut_off_wakes"] == [] + [failed] = record["failed_turns"] + assert (failed["wake"], failed["error_type"]) == (1, failure.error_type or "agent_turn_failed") + assert ctx.prompt_responses[0].error_type is None @pytest.mark.asyncio @@ -344,24 +373,28 @@ def agent(n, texts, rig): @pytest.mark.asyncio -async def test_a_turn_that_fails_for_another_reason_just_as_its_time_runs_out_still_ends_the_run(monkeypatch, - tmp_path): +async def test_a_turn_that_fails_for_another_reason_just_as_its_time_runs_out_is_a_failed_turn(monkeypatch, + tmp_path): """The step cuts the turn off at its time limit, but by the time the agent answers the cancel, the turn had - already failed on its own, for a reason that is no limit: that failure is what ended it, and the run ends.""" + already failed on its own, for a reason that is no limit: that failure is what ended it, a failed turn.""" crash = Fail("claude CLI exited with code 1: API Error: 500 Internal server error") def agent(n, texts, rig): - rig.message("on it") - return Slow(5, ends_as=crash) + if n == 1: + rig.message("on it") + return Slow(5, ends_as=crash) + rig.quiet() + return "" rig = Rig(monkeypatch, tmp_path, agent=agent) ctx = await _run(rig, timeout_seconds=1, continue_after_wake_limit=True) - assert rig.cancels == ["task-1"] and len(rig.sent) == 1 + assert rig.cancels == ["task-1"] and len(rig.sent) == 2 record = rig.record(ctx) - assert (record["end_reason"], record["cut_off_wakes"]) == ("agent_turn_failed", []) - assert ctx.prompt_responses[0].error_message == crash.message - [turn] = rig.events(ctx, "agent_turn_end") + assert (record["end_reason"], record["cut_off_wakes"]) == ("finished_nothing_pending", []) + [failed] = record["failed_turns"] + assert (failed["wake"], failed["error"]) == (1, crash.message) + turn = rig.events(ctx, "agent_turn_end")[0] assert turn["state"] == "failed" and "cut_off" not in turn @@ -428,15 +461,16 @@ async def test_off_a_turn_past_its_time_limit_ends_the_run_as_before(monkeypatch @pytest.mark.asyncio -async def test_off_a_turn_at_its_tool_call_limit_ends_the_run_as_before(monkeypatch, tmp_path): +async def test_off_a_turn_at_its_tool_call_limit_is_a_failed_turn_and_the_run_goes_on(monkeypatch, tmp_path): rig = Rig(monkeypatch, tmp_path, agent=_tool_call_limit_first_turn) ctx = await _run(rig, max_turns=150) - assert len(rig.sent) == 1 + assert len(rig.sent) == 2 and rig.sent[1][0] != TOOL_CALL_NOTE # no cut-off notice: off, it isn't one record = rig.record(ctx) - assert record["end_reason"] == "agent_turn_failed" and ctx.prompt_responses[0].error_type == "agent_turn_failed" - [turn] = rig.events(ctx, "agent_turn_end") - assert "cut_off" not in turn + assert record["end_reason"] == "finished_nothing_pending" and ctx.prompt_responses[0].error_type is None + [failed] = record["failed_turns"] + assert (failed["wake"], failed["error"], failed["went_on"]) == (1, MAX_TURNS_ERROR, True) + assert "cut_off" not in rig.events(ctx, "agent_turn_end")[0] def test_the_setting_is_off_unless_set_and_survives_a_round_trip(monkeypatch, tmp_path): diff --git a/tst/unit/task_step/test_user_sim_satisfaction.py b/tst/unit/task_step/test_user_sim_satisfaction.py index 0886a7a38..6785206ff 100644 --- a/tst/unit/task_step/test_user_sim_satisfaction.py +++ b/tst/unit/task_step/test_user_sim_satisfaction.py @@ -15,6 +15,7 @@ from agent_env.a2a_agent import conversation_store from agent_env.store import get_config from agent_env.task.task import Task +from agent_env.task_step.context import AgentTurnInfraError from agent_env.task_step.registry import _builtin_registry from agent_env.task_step.task_steps import always_on as ao from agent_env.task_step.task_steps.agent import rate_user_satisfaction as rus @@ -414,13 +415,35 @@ async def test_the_rating_s_user_sim_turns_are_the_step_s_usage(monkeypatch, tmp @pytest.mark.asyncio -async def test_an_always_on_run_that_ended_on_an_error_is_not_rated(monkeypatch, tmp_path): - rig, ctx = await _always_on_run(monkeypatch, tmp_path, agent=lambda n, texts, rig: Fail()) +async def test_an_always_on_run_that_ended_on_an_infrastructure_error_is_not_rated(monkeypatch, tmp_path): + rig = Rig(monkeypatch, tmp_path, agent=lambda n, texts, rig: Fail(error_type="infra_error"), plugin=us) + await rig.arm() + ctx = await _rig_context(monkeypatch, rig, persona={"display_name": "Linda Murphy", "description": DESCRIPTION}) + with pytest.raises(AgentTurnInfraError): + await rig.run(_always_on(end_time="P3D"), ctx) await _rater().execute(ctx) assert rig.user_calls == [] assert ctx.metadata[SATISFACTION_KEY]["week"] == {"user_sim": "user-sim", "score": None, "reason": None, "rated_by": "rate", - "skipped": "the run ended on agent_turn_failed"} + "skipped": "the run ended on agent_turn_infra_error"} + + +@pytest.mark.asyncio +async def test_an_always_on_run_its_failed_turns_ended_is_rated_as_any_run(monkeypatch, tmp_path): + monkeypatch.setattr(ao, "FAILED_TURNS_IN_A_ROW_MAX", 2) # the opening wake and the final check-in + + def fails(n, texts, rig): + rig.message(f"tried {n}") + return Fail("Max turns (150) exceeded", error_type="agent_error", error_code="psi.model") + + rig, ctx = await _always_on_run(monkeypatch, tmp_path, _reply("ok?"), json.dumps(rated(1, "nothing booked", "S2")), + agent=fails) + assert rig.record(ctx)["end_reason"] == "agent_turn_failed" + + await _rater().execute(ctx) + + rating = ctx.metadata[SATISFACTION_KEY]["week"] + assert (rating["score"], rating["reason"], rating.get("skipped")) == (1, "nothing booked", None) @pytest.mark.asyncio diff --git a/tst/unit/task_step/verifiers/test_rubrics_subclasses_golden.py b/tst/unit/task_step/verifiers/test_rubrics_subclasses_golden.py index 53987acd5..225058128 100644 --- a/tst/unit/task_step/verifiers/test_rubrics_subclasses_golden.py +++ b/tst/unit/task_step/verifiers/test_rubrics_subclasses_golden.py @@ -13,6 +13,8 @@ from agent_env.task_step.task_steps.verifiers import user_sim_judge as usj from agent_env.task_step.task_steps.verifiers import user_sim_judge_core as core from tst.unit.task_step import test_always_on_agent_verifier as A +from tst.unit.task_step import test_always_on_failed_turns as F +from tst.unit.task_step.always_on_harness import Fail from tst.unit.task_step.verifiers import test_user_sim_judge as T from tst.util import verifier_golden @@ -129,12 +131,12 @@ async def test_an_unstaged_always_on_grade_with_its_harness_leaves_the_entry_its @pytest.mark.usefixtures("local_stores") @pytest.mark.asyncio async def test_an_always_on_prompt_error_the_gate_fails_leaves_the_entry_its_golden_file_holds(monkeypatch, tmp_path): - def fails(n, texts, rig): - raise TimeoutError("no answer") - - rig = A.Rig(monkeypatch, tmp_path, agent=fails) + """A run its user sim broke is still scored 0 unjudged; one its agent's own failure ended is judged.""" + rig = A.Rig(monkeypatch, tmp_path) await rig.arm() context = await rig.run(rig.step()) + rig.record(context).update(end_reason="user_sim_error", error_type="user_sim_error") + context.prompt_responses[0].error_type = "user_sim_error" context.prompt_responses[0].agent_name = "assistant" verifier = A._verifier(fail_task_when_not_passing=True, default_model=JUDGE_MODEL) A._capture(monkeypatch, verifier) @@ -142,6 +144,47 @@ def fails(n, texts, rig): verifier_golden.check(FILE, "ao_a_prompt_error_the_gate_fails", await _ran(verifier, context)) +_DEAD = Fail("ContextWindowExceededError", error_type="agent_error", error_code="psi.context_full") + + +@pytest.mark.usefixtures("local_stores") +@pytest.mark.asyncio +@pytest.mark.parametrize(("case", "fails", "end_reason", "error_type"), [ + ("ao_judged_after_a_turn_agent_env_gave_up_waiting_on", {1: TimeoutError("no answer")}, "agent_turn_timeout", + "agent_turn_timeout"), + ("ao_judged_after_failed_turns_in_a_row", {2: _DEAD, 3: _DEAD, 4: _DEAD}, "agent_turn_failed", "agent_error"), +]) +async def test_an_always_on_run_its_agent_s_own_failure_ended_is_judged_leaving_the_entry_its_golden_file_holds( + monkeypatch, tmp_path, case, fails, end_reason, error_type): + rig, context = await F._run(monkeypatch, tmp_path, fails) + assert (rig.record(context)["end_reason"], context.prompt_responses[0].error_type) == (end_reason, error_type) + context.prompt_responses[0].agent_name = "assistant" + verifier = A._verifier(fail_task_when_not_passing=True, default_model=JUDGE_MODEL) + A._capture(monkeypatch, verifier) + + verifier_golden.check(FILE, case, await _ran(verifier, context)) + + +@pytest.mark.usefixtures("local_stores") +@pytest.mark.asyncio +async def test_an_always_on_run_its_agent_s_failed_turns_ended_is_judged_by_the_user_sim_judge_as_its_golden_file_holds( + monkeypatch, tmp_path): + monkeypatch.setattr(F.ao, "FAILED_TURNS_IN_A_ROW_MAX", 2) # wake 2 and the final check-in + + def agent(n, texts, rig): + if n == 1: + rig.message("Saturday is Saltwater Shack, a seafood place. Keep it?") + return "sent" + return Fail("Max turns (150) exceeded", error_type="agent_error", error_code="psi.model") + + rig, context, _ = await T._always_on(monkeypatch, tmp_path, agent=agent) + assert rig.record(context)["end_reason"] == "agent_turn_failed" + + got = await _ran(T._step(T.FakeModel(), monkeypatch, run_step_id="week"), context) + + verifier_golden.check(FILE, "us_an_always_on_run_its_agent_s_failed_turns_ended", got) + + @pytest.mark.usefixtures("local_stores") @pytest.mark.asyncio async def test_a_staged_always_on_grade_with_what_its_judge_read_leaves_the_entry_its_golden_file_holds(monkeypatch): diff --git a/tst/unit/task_step/verifiers/test_rubrics_verifier_fail_task_when_not_passing.py b/tst/unit/task_step/verifiers/test_rubrics_verifier_fail_task_when_not_passing.py index 6fa0edc57..4983f8507 100644 --- a/tst/unit/task_step/verifiers/test_rubrics_verifier_fail_task_when_not_passing.py +++ b/tst/unit/task_step/verifiers/test_rubrics_verifier_fail_task_when_not_passing.py @@ -80,6 +80,21 @@ async def test_a_penalized_negative_row_is_not_passing(monkeypatch): await v.execute(_context()) +@pytest.mark.asyncio +async def test_a_prompt_agent_turn_that_failed_for_an_infrastructure_reason_still_scores_0_unjudged(monkeypatch): + """Only an always_on run's infrastructure failure is left ungraded (always_on_agent_verifier); any other prompt's + is scored as any failed prompt is.""" + v = _verifier(fail_task_when_not_passing=False) + _judge(monkeypatch, v, {"world": True, "replies": True}) + ctx = _context(error_type="infra_error", error_code="psi.gateway") + + await v.execute(ctx) + + entry = ctx.metadata["verifications"]["validity"] + assert entry["score"] == 0 and [r["id"] for r in entry["results"]] == ["prompt_error"] + assert entry.get("skipped") is None + + @pytest.mark.asyncio async def test_a_run_the_judge_could_not_grade_is_not_passing(monkeypatch): v = _verifier() diff --git a/tst/unit/task_step/verifiers/test_user_sim_judge.py b/tst/unit/task_step/verifiers/test_user_sim_judge.py index f2c475b78..6fd46f563 100644 --- a/tst/unit/task_step/verifiers/test_user_sim_judge.py +++ b/tst/unit/task_step/verifiers/test_user_sim_judge.py @@ -38,7 +38,7 @@ RubricsVerifierTaskStep, is_rubrics_verifier, ) -from tst.unit.task_step.always_on_harness import Rig +from tst.unit.task_step.always_on_harness import Fail, Rig from tst.unit.task_step.test_deploy_user_sim_agent import HANNAH, _Deploy from tst.unit.task_step.test_deploy_user_sim_agent import _step as _deploy_step from tst.unit.task_step.test_prompt_agent_built_in_user_sim import _context as _chat_context @@ -515,10 +515,10 @@ def test_its_score_checks_the_run_so_the_task_s_grader_is_its_reward(): '{"outcome": "reply", "message": "all good, thx", "used": "none"}'] -async def _always_on(monkeypatch, tmp_path, answers=ALWAYS_ON_ANSWERS): - """An always_on run whose user the real deploy_user_sim_agent step deployed and recorded; the prompt it set on the - user sim's agent; the Rig.""" - def agent(n, texts, rig): +async def _always_on(monkeypatch, tmp_path, answers=ALWAYS_ON_ANSWERS, agent=None): + """An always_on run whose user the real deploy_user_sim_agent step deployed and recorded (its agent ``agent``, by + default one that asks and books); the prompt it set on the user sim's agent; the Rig.""" + def books(n, texts, rig): if n == 1: rig.message("Saturday is Saltwater Shack, a seafood place. Keep it?") return "sent" @@ -531,7 +531,7 @@ def agent(n, texts, rig): deploy = _Deploy(monkeypatch) deployed = await deploy.run(_deploy_step(agent_name="user-sim", persona=HANNAH)) [prompt] = deploy.fields("system_prompt") - rig = Rig(monkeypatch, tmp_path, agent=agent, plugin=user_sim_versions, user_texts=list(answers)) + rig = Rig(monkeypatch, tmp_path, agent=agent or books, plugin=user_sim_versions, user_texts=list(answers)) await rig.arm() ctx = rig.context() ctx.metadata[USER_SIMS_KEY] = {"user-sim": deployed.metadata[USER_SIMS_KEY]["user-sim"]} @@ -615,6 +615,28 @@ async def test_a_run_that_ended_in_an_error_is_not_judged(monkeypatch, tmp_path) assert (_entry(ctx)["score"], _entry(ctx)["results"]) == (None, []) +@pytest.mark.usefixtures("local_stores") +@pytest.mark.asyncio +async def test_an_always_on_run_its_agent_s_failed_turns_ended_is_judged(monkeypatch, tmp_path): + monkeypatch.setattr(ao, "FAILED_TURNS_IN_A_ROW_MAX", 2) # wake 2 and the final check-in + + def agent(n, texts, rig): + if n == 1: + rig.message("Saturday is Saltwater Shack, a seafood place. Keep it?") + return "sent" + return Fail("Max turns (150) exceeded", error_type="agent_error", error_code="psi.model") + + rig, ctx, _ = await _always_on(monkeypatch, tmp_path, agent=agent) + assert (rig.record(ctx)["end_reason"], ctx.prompt_responses[-1].error_type) == ("agent_turn_failed", "agent_error") + fake = FakeModel() + + await _step(fake, monkeypatch, run_step_id="week").execute(ctx) + + entry = _entry(ctx) + assert fake.calls and entry.get("skipped") is None and entry["graded_turns"] == [1] + assert _verdicts(entry, "guidance") == {"guidance": "pass"} and entry["run_kind"] == "always_on" + + @pytest.mark.usefixtures("local_stores") @pytest.mark.asyncio async def test_a_run_s_judge_model_override_chooses_the_model_as_for_every_judge(monkeypatch, tmp_path):