diff --git a/src/agent_env/agents/AGENTS.md b/src/agent_env/agents/AGENTS.md index 406063219..0ab1f26df 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, and the run is redone once from its env deploy (always_on's - default `retry_config`, which a task's own replaces). 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, and the run is redone once from its env deploy (always_on's default `retry_config`, which a task's own + replaces). 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..c38346b18 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,6 +61,7 @@ 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 ( + AGENT_FAILURE_ENDS, ALWAYS_ON_KEY, ERROR_ENDS, READ_ASKS, @@ -349,7 +350,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 record["end_reason"] not in AGENT_FAILURE_ENDS: + # 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 56d162726..0deb0dff5 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,23 @@ 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 no verifier grades it and a ``retry_config`` can redo it. - 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 +82,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 +128,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 @@ -216,11 +228,31 @@ 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") +# The error ends that are the agent's own doing: its turns failing 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") +# 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 turn's error message. +FAILED_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 @@ -242,7 +274,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 +361,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 @@ -522,6 +555,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 @@ -1474,6 +1510,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")) @@ -1494,7 +1535,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) @@ -1502,7 +1544,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 @@ -1523,13 +1565,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() @@ -1622,7 +1667,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 {})) @@ -1643,12 +1688,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: @@ -1727,22 +1774,58 @@ 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 (``_failure``). 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._failure(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 _failure(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 "")[:FAILED_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._failure(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._failure(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: @@ -1999,8 +2082,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, @@ -2030,6 +2113,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) @@ -2043,8 +2130,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}, @@ -2112,6 +2202,15 @@ 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_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).""" + record = (metadata.get(ALWAYS_ON_KEY) or {}).get(step_id) if step_id else None + return isinstance(record, dict) and record.get("end_reason") in AGENT_FAILURE_ENDS + + 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.""" @@ -2139,6 +2238,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: @@ -2165,6 +2265,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}") @@ -2189,6 +2293,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/verifiers/agent_prompt_response_verifier.py b/src/agent_env/task_step/task_steps/verifiers/agent_prompt_response_verifier.py index 8b9d79ca0..cebd74291 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 @@ -88,7 +88,7 @@ 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 prompt_response.error_type and not _ended_on_agent_failure(context, prompt_response.step_id): logger.warning( f"Skipping verification '{self.verifier_id}': prompt had error_type={prompt_response.error_type}" ) @@ -183,3 +183,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_agent_failure(context: TaskStepContext, step_id: Optional[str]) -> bool: + """An always_on run that ended on its agent's own failure has a response that stands, every message it sent the + user, and is checked as any run's is (``ended_on_agent_failure``); any other failed prompt scores 0 unchecked.""" + from agent_env.task_step.task_steps.always_on import ended_on_agent_failure # here: always_on imports our peers + + return ended_on_agent_failure(context.metadata, step_id) 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..740d521d4 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 +with failed turns is judged so even when no turn stored one (``_judges_without_trajectory``); a run that failed no turn +and 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 ( + ALWAYS_ON_KEY, + AlwaysOnTaskStep, + ended_on_agent_failure, + render_for_judge, + stored_timeline, +) 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,21 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: output["assistant_harness"] = harness return dataclasses.replace(verdict, output=output) + 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 with a turn that 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 on failed turns alone, can have none. Each such turn 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 that + failed no turn and stored none is refused, as rubrics_verifier refuses it: nothing explains the gap.""" + record = (context.metadata.get(ALWAYS_ON_KEY) or {}).get(prompt_response.step_id) or {} + return any(f.get("error_type") != INFRA_ERROR for f in record.get("failed_turns") or []) + 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 +626,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..7dec7beff 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 "")) @@ -463,6 +467,11 @@ 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})") @@ -471,6 +480,11 @@ def _index_block(w: _Wake, path: str, lines: list[dict], by_changes: bool, run_c f"and the run went on ({path}:{i})") elif line.get("state") not in (None, "completed", "TaskState.completed"): 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 4d5ddc763..f4ca2e046 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 @@ -821,6 +821,20 @@ def _not_graded(self, reason: str) -> RubricsVerdict: if self.writes_mistakes_entry else None) return RubricsVerdict(skipped=reason, output=self._entry_format_fields(), mistakes_entry=mistakes) + 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 + turns 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.""" @@ -1128,7 +1142,7 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: f"{prompt_response.error_code}), not the assistant's") logger.warning(f"Not grading '{self.verifier_id}': {reason}") return self._not_graded(reason) - if prompt_response.error_type: + 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 @@ -1140,7 +1154,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 @@ -1183,7 +1198,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, @@ -1249,6 +1264,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..3696cf46e 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 @@ -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, 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, 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" @@ -679,6 +685,13 @@ def _grading_entry(grading: Optional[core.Grading]) -> dict: "end_state_steps": list(grading.end_state_steps)} +def _ended_on_agent_failure(context: TaskStepContext, step_id: str) -> bool: + """An always_on run that ended on its agent's own failure is judged as any run is (``ended_on_agent_failure``).""" + from agent_env.task_step.task_steps.always_on import ended_on_agent_failure # here: always_on imports our peers + + return ended_on_agent_failure(context.metadata, step_id) + + def _prompt_response(context: TaskStepContext, step_id: str) -> Optional[PromptResponse]: return next((p for p in reversed(context.prompt_responses) if p.step_id == step_id), None) diff --git a/tst/data/verifier_golden/rubrics_subclasses.json b/tst/data/verifier_golden/rubrics_subclasses.json index bff2068a9..d03e980be 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, 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 151084f98..6193f0df0 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..1ab6a1439 --- /dev/null +++ b/tst/unit/task_step/test_always_on_failed_turns.py @@ -0,0 +1,465 @@ +"""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} + entry, _ = await _judged(monkeypatch, ctx) + assert (entry["score"], entry["results"]) == (None, []) and "psi.gateway" in entry["skipped"] + + +@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_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.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_wake_limit.py b/tst/unit/task_step/test_always_on_wake_limit.py index 9726079ee..2753556f9 100644 --- a/tst/unit/task_step/test_always_on_wake_limit.py +++ b/tst/unit/task_step/test_always_on_wake_limit.py @@ -283,25 +283,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 +349,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 +437,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..9f766b233 100644 --- a/tst/unit/task_step/verifiers/test_rubrics_subclasses_golden.py +++ b/tst/unit/task_step/verifiers/test_rubrics_subclasses_golden.py @@ -129,12 +129,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) 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):