From f052eba88669e4fa565119af55c1a6d0e494979a Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 25 Nov 2026 16:09:19 -0800 Subject: [PATCH 01/19] fix(always_on): an infra-failed turn fails the step instead of scoring 0; judges read the harness's failure A PSI always_on run whose wake failed for an infrastructure reason (a gateway 5xx, throttling, a dead sandbox) was recorded as a normal end and then scored 0 by the rubrics judges, so it counted as the model's failure (BELOW_ONE). The A2A protocol already says which failures are the agent's (error_type agent_error) and which aren't (infra_error, "agent-env may retry it"); nothing acted on it. - always_on: a turn whose error_type is infra_error, or whose agent stopped answering (AgentUnreachableError, error_code agent_env.agent_unreachable), ends the run as agent_turn_infra_error (in ERROR_ENDS and END_NOTES). The timeline, record, conversation and prompt response are written as before, and the record now keeps error_code. Then the step raises AgentTurnInfraError, so no verifier grades it and a retry_config can redo it. agent_error turns are graded as before. Docstrings now say what a failed turn gets (a rubrics 0, not a skip). - task/outcome.py: AgentTurnInfraError classifies as TRANSIENT (key budget/auth text still wins). - rubrics_verifier: an infra_error prompt response is a true skip (no score, no rows; the mistakes entry skipped too), so an aggregate leaves it out and a run with every source skipped is UNSCORED. _gated no longer compares a skipped verdict's missing score. - turn_events (native OpenInference): a harness.error span is a failure note (kind, message, HTTP status, retries) instead of being dropped as the harness's own span; a failed_wake message names the kind. gateway, throttled, timeout_call and harness kinds are said to be no doing of the assistant's. - staging: harness_note lines carry failure, the index gets an error line for it, the record lists harness_failures, and the judge's files note explains failure lines only when there is one. - agents/AGENTS.md: what always_on does with each error_type. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/agents/AGENTS.md | 5 +- src/agent_env/task/outcome.py | 7 +- src/agent_env/task_step/context.py | 9 ++ .../task_step/task_steps/always_on.py | 61 ++++++++--- .../verifiers/always_on_agent_verifier.py | 10 +- .../task_steps/verifiers/always_on_staging.py | 26 ++++- .../verifiers/judge_utils/turn_events.py | 54 ++++++++-- .../task_steps/verifiers/rubrics_verifier.py | 16 ++- tst/unit/task/outcome_test.py | 9 +- .../test_always_on_agent_verifier.py | 41 ++++++- tst/unit/task_step/test_always_on_graded.py | 73 ++++++++++++- .../task_step/test_always_on_wake_limit.py | 64 ++++++++++- .../verifiers/judge_utils/test_turn_events.py | 50 +++++++++ .../verifiers/test_always_on_staging.py | 36 +++++++ .../test_rubrics_verifier_infra_error.py | 102 ++++++++++++++++++ 15 files changed, 521 insertions(+), 42 deletions(-) create mode 100644 tst/unit/task_step/verifiers/test_rubrics_verifier_infra_error.py diff --git a/src/agent_env/agents/AGENTS.md b/src/agent_env/agents/AGENTS.md index 89db3aa41..f9358522e 100644 --- a/src/agent_env/agents/AGENTS.md +++ b/src/agent_env/agents/AGENTS.md @@ -69,7 +69,10 @@ 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. + 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 its `retry_config` can redo 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/outcome.py b/src/agent_env/task/outcome.py index 1b75ffc2c..ab898acaa 100644 --- a/src/agent_env/task/outcome.py +++ b/src/agent_env/task/outcome.py @@ -14,7 +14,7 @@ import httpx -from agent_env.task_step.context import VerifierNotPassingError +from agent_env.task_step.context import AgentTurnInfraError, VerifierNotPassingError from agent_env.task_step.task_step import StepRole if TYPE_CHECKING: @@ -54,8 +54,9 @@ class FailureCause(StrEnum): )), ) -# A failure of one of these types is one the A2A client or the model SDK retries, whatever its message says. -_TRANSIENT_TYPES = (TimeoutError, ConnectionError, httpx.TransportError) +# A failure of one of these types is one the A2A client or the model SDK retries, whatever its message says; or, for +# an agent turn that failed for an infrastructure reason, one its agent says agent-env may retry. +_TRANSIENT_TYPES = (TimeoutError, ConnectionError, httpx.TransportError, AgentTurnInfraError) def _chain(exc: BaseException) -> Iterator[BaseException]: diff --git a/src/agent_env/task_step/context.py b/src/agent_env/task_step/context.py index dbf22a199..1bf29ec42 100644 --- a/src/agent_env/task_step/context.py +++ b/src/agent_env/task_step/context.py @@ -65,6 +65,15 @@ class VerifierNotPassingError(RuntimeError): """A verifier set to fail its task when its verdict isn't passing recorded one that isn't. Grading the same run again could pass it, so a runner should not retry it.""" + +# The A2A error_type of a turn that couldn't happen for a reason that isn't the agent's, which agent-env may retry. +INFRA_ERROR = "infra_error" + + +class AgentTurnInfraError(RuntimeError): + """An agent turn failed for an infrastructure reason (its agent said ``infra_error``, or stopped answering), so the + run says nothing about the agent: its step fails once the run is recorded, and a ``retry_config`` can redo it.""" + _REDACTED_KEYS = { "litellm_api_key", "judge_litellm_api_key", "usersim_api_key", "remote_tokens", "cf_access_client_secret", HEARTBEAT_KEY, 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 b5718e92c..e85bf77dc 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -48,7 +48,7 @@ closing wake, with the step's wrap-up line and the last-turn notice, and the run ends with end reason time_budget. - End reasons: end_time, user_done (one sitting), max_wakes, time_budget, finished_nothing_pending or stuck (nothing can wake the agent, with nothing pending or with something still pending), agent_turn_failed, agent_turn_timeout, - user_sim_error, user_sim_invalid, step_error. With no end_time, a world that only repeats ends the run too (``IDLE_JUMPS_MAX``, in the + agent_turn_infra_error, user_sim_error, user_sim_invalid, step_error. With no end_time, a world that only repeats ends the run too (``IDLE_JUMPS_MAX``, in the loop's docstring), so a recurring trigger that never wakes the agent can't move the clock forever. What was still pending is recorded (``pending_at_end``): replies held, messages the user never read, user lines and alerts never delivered, the agent's checks not yet due, contact replies in progress. - Graders read what the user saw. The prompt response is every message_user text in order, each with its pretend @@ -56,7 +56,12 @@ 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), so verifiers skip 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. - 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 @@ -67,7 +72,7 @@ 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. + protocol error) still ends the run, and one that failed for an infrastructure reason fails the step as above. - 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 @@ -138,7 +143,14 @@ ) from agent_env.config.model import ModelRole from agent_env.store import DuplicateKeyError, get_config -from agent_env.task_step.context import PromptResponse, StepContextError, TaskStepContext, TurnTrajectory +from agent_env.task_step.context import ( + INFRA_ERROR, + AgentTurnInfraError, + PromptResponse, + StepContextError, + TaskStepContext, + TurnTrajectory, +) from agent_env.task_step.snapshot_utils.atif_copies import AtifCopies from agent_env.task_step.usage import StepUsage from agent_env.task_step.task_step import TaskStep @@ -199,7 +211,11 @@ # The final check-in's line when the task sets no `final`: the step's, not the user's. FINAL_DEFAULT_TEXT = "Time's up on this job. Send {first} a short wrap-up: what's done, and anything still open." NOTHING_CAN_WAKE = "nothing_can_wake_the_agent" # until finish() tells finished_nothing_pending from stuck -ERROR_ENDS = ("agent_turn_failed", "agent_turn_timeout", "user_sim_error", "step_error") +# An agent turn that failed for an infrastructure reason: recorded as any failed turn, then the step fails +# (AgentTurnInfraError). An agent that stopped answering is one, with this error_code. +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'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"} @@ -228,6 +244,7 @@ "stuck": "Nothing could wake the assistant again, though something was still pending.", "agent_turn_failed": "The assistant's turn failed.", "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.", "user_sim_invalid": "The user simulator's answer still read as the assistant's after its rewrites.", "step_error": "The run stopped on an error.", @@ -466,7 +483,7 @@ def __init__(self, step: AlwaysOnTaskStep, context: TaskStepContext): self.all_messages: list[dict] = [] self.final_task_id = "" self.error: Optional[str] = None - self.error_type: Optional[str] = None # set as prompt_agent sets it, so verifiers skip a run that broke + self.error_type: Optional[str] = None # set as prompt_agent sets it, so verifiers know the run broke self.error_code: Optional[str] = None self.chat_pending: list[dict] = [] # the agent's message_user texts not yet in the graded conversation self.reaction: Optional[dict] = None # her last read's answer when she said nothing @@ -648,6 +665,11 @@ async def go(self) -> None: raise finally: await self.finish() + if self.end_reason == AGENT_TURN_INFRA_ERROR: + raise AgentTurnInfraError( + f"always_on: wake {self.wakes}'s agent turn failed for an infrastructure reason " + f"(error_type={self.error_type}, error_code={self.error_code}); the run is recorded but not graded: " + f"{self.error}") async def _load_plugin(self, spec: Optional[dict]) -> ModuleType: if not spec: @@ -1474,8 +1496,8 @@ def record() -> None: except TimeoutError as e: ended = await self._stopped_at_time_limit(e) if ended is None: - self._failed("agent_turn_timeout", f"agent turn timed out after {step.timeout_seconds}s: {e}") - self.log("agent_turn_end", n=self.wakes, state="timeout", real_seconds=round(time.time() - t, 1), + state = self._no_answer(e, "agent turn") + 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 turn, stopped = self._stopped_turn(ended, f"agent turn timed out after {step.timeout_seconds}s: {e}") @@ -1594,9 +1616,9 @@ def record() -> None: except TimeoutError as e: ended = await self._stopped_at_time_limit(e) if ended is None: - self._failed("agent_turn_timeout", f"agent nudge turn timed out after {step.timeout_seconds}s: {e}") + state = self._no_answer(e, "agent nudge turn") self.log("nudge", n=self.nudges, wake=self.wakes, virtual_time=_iso(sent_at), closing_text=closing, - state="timeout", outcome="timeout", real_seconds=round(time.time() - t, 1), + state=state, outcome=state, real_seconds=round(time.time() - t, 1), **({"stop": "unconfirmed"} if step.continue_after_wake_limit else {})) return turn, stopped = self._stopped_turn(ended, f"agent nudge turn timed out after {step.timeout_seconds}s: {e}") @@ -1701,10 +1723,21 @@ def _sent(self, messages: list[dict], after_nudge: bool = False, leftover: bool 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 verifiers skip it instead of grading it as a - normal run.""" + 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.""" self.error, self.error_type, self.error_code = error, error_type, error_code - self.end_reason = "agent_turn_timeout" if error_type == "agent_turn_timeout" else "agent_turn_failed" + 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.""" + if isinstance(error, protocol.AgentUnreachableError): + self._failed(INFRA_ERROR, f"{turn}: {error}", AGENT_UNREACHABLE_CODE) + return "unreachable" + self._failed("agent_turn_timeout", f"{turn} timed out after {self.step.timeout_seconds}s: {error}") + return "timeout" async def read(self, now: datetime, last: bool = False) -> None: """The user sim reads what the agent sent since her last read, at ``now``; ``last`` marks the read after the @@ -2005,7 +2038,7 @@ async def finish(self) -> None: 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, - "error_type": self.error_type, "counts": counts, + "error_type": self.error_type, "error_code": self.error_code, "counts": counts, "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}, 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 bdc1db2be..8f1efa47f 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 @@ -66,6 +66,7 @@ from agent_env.task_step.task_steps.verifiers.judge_utils.atif_turns import AtifDocuments, TurnSource from agent_env.task_step.task_steps.verifiers.judge_utils.atif_turns import turns as turn_sources from agent_env.task_step.task_steps.verifiers.judge_utils.turn_events import ( + INFRA_FAILURE_KINDS, TrajectoryFormatError, TurnEvents, atif_turn_events, @@ -154,6 +155,12 @@ the assistant saw this wake, such as a contact's reply); a "turn" or "nudge" change after that turn's tool calls (the \ assistant's own were made by its calls of the tool "actors" names; another's came at some point during that turn); \ an "after_turn" change after the turn ended (contacts and triggers answering it).{missing}""" +# Added after _HARNESS_NOTE for a run in which the harness says a wake failed (its record's "harness_failures"). +_INFRA_KINDS = sorted(INFRA_FAILURE_KINDS) +_FAILURE_NOTE = f""" +- A "harness_note" line with "failure" is the harness saying why that wake failed ("kind"). A failure of kind \ +{", ".join(_INFRA_KINDS[:-1])} or {_INFRA_KINDS[-1]} is the infrastructure's (the model endpoint, or the harness \ +itself), not the assistant's doing.""" # Added after _HARNESS_NOTE for a run with a compaction, by who wrote its summary (its note's "written_by", in # "compaction"): whose a loss the summary caused is. _COMPACTION_NOTES = { @@ -577,7 +584,8 @@ def _files_note(path: str, staged: StagedRun, *, context_loss: bool = False) -> "for them only the run's record is there: " + ", ".join(str(n) for n in gaps) + ".") if gaps else "" writers = r.get("compaction_summaries_written_by") or {} lines = _HARNESS_NOTE if r.get("agent_labeled_trajectories") else _HARNESS_LINES + _NOTES_ORDER - harness = (lines + "".join(note for writer, note in _COMPACTION_NOTES.items() if writer in writers) + harness = (lines + (_FAILURE_NOTE if r.get("harness_failures") else "") + + "".join(note for writer, note in _COMPACTION_NOTES.items() if writer in writers) + (_CONTEXT_LOSS_NOTE if context_loss else "")) if _harness_read(r) else "" values = r.get("app_change_values") missing = (f"\n- {values['missing']} app changes have no \"changed_fields\": the run's record of its apps' changes " 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 2a2bfbcf2..dbd8b1b67 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 @@ -4,7 +4,8 @@ - ``wakes/wake_NNN.jsonl``: what woke the assistant (``woke``, the user's messages in full ``user_message``, the full text it was sent ``wake_input``), then its turn's tool calls with their inputs and results (``tool_call``), its own text (``assistant_text``) and its thinking when the trajectory recorded it (``assistant_thinking``), what the - harness put in the turn (``harness_note``: a compaction summary, a message it sent the assistant), then the rest + 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 while the run went on (the step's ``continue_after_wake_limit``) has ``cut_off`` on its ``turn_end`` (or ``nudge``) @@ -18,7 +19,8 @@ - ``events.jsonl``: every line of every wake, and the run's start and end. ``triggers.jsonl``: every trigger firing. - ``index.md``: a block per wake with its time, what woke it, the user's message, its write actions (tool and key arguments) and messages with the ``file:line`` they're at, a - compaction the harness ran before its turn, and its errors. + compaction the harness ran before its turn, and its errors, a failure the harness reports among them, said to be no + doing of the assistant's when it is the infrastructure's. A run that kept no timeline is staged from one made of its turns by position (``by_position``): each wake file is one turn, in the order the turns ran, with the text it was sent and its own events. @@ -39,7 +41,12 @@ from agent_env.task_step.task_steps.always_on import BULKY_EVENT_FIELDS, LIMIT_WORDS, woke_by_text from agent_env.task_step.task_steps.notification_delivery import label_time -from agent_env.task_step.task_steps.verifiers.judge_utils.turn_events import UNKNOWN, TurnEvents, compaction_words +from agent_env.task_step.task_steps.verifiers.judge_utils.turn_events import ( + UNKNOWN, + TurnEvents, + compaction_words, + is_infra_failure, +) from agent_env.task_step.task_steps.verifiers.run_context import Firing WAKES_DIR = "wakes" @@ -68,7 +75,8 @@ _BEFORE_WAKE_STEPS = frozenset({_SAVE_STEP, "after_compaction", "failed_wake"}) # 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", "internal", "cut_off", "cut_off_notice", "limit"}) + "step", "subagent", "compaction", "failure", "internal", "cut_off", "cut_off_notice", + "limit"}) @dataclass(frozen=True) @@ -186,6 +194,7 @@ def __init__(self, turns: Mapping[str, Optional[TurnEvents]], last_wake: int): self.change_values_found = self.change_values_missing = 0 self.labelled = 0 # trajectories whose spans say which agent made each (``TurnEvents.agent_labels``) self.summary_writers: Counter = Counter() # compactions by who wrote their summary (``written_by``) + self.harness_failures: list[dict] = [] # each wake the harness says failed: {wake, kind} def wake(self, n: Optional[int]) -> _Wake: n = n or self.current @@ -298,8 +307,10 @@ def turn(self, w: _Wake, url: Optional[str], which: str) -> list[dict]: elif kind == "note": if e.get("compaction"): self.summary_writers[e["compaction"]["written_by"]] += 1 + if e.get("failure"): + self.harness_failures.append({"wake": w.n, "kind": e["failure"].get("kind")}) lines.append(_line("harness_note", w.n, turn=which, step=e.get("step"), compaction=e.get("compaction"), - text=e["text"])) + failure=e.get("failure"), text=e["text"])) elif kind == "raw": lines.append(_line("trajectory_item", w.n, turn=which, item=e["event"])) staged = sum(len(_dumps(line).encode()) for line in lines) + side @@ -384,6 +395,7 @@ def finish(self, firings: Sequence[Firing], unavailable: Mapping[str, str]) -> S ("app_changes_not_recorded", self.unrecorded_changes), ("agent_labeled_trajectories", self.labelled), ("compaction_summaries_written_by", dict(sorted(self.summary_writers.items()))), + ("harness_failures", self.harness_failures), ("turns_by_position", self.by_position)): if value: record[key] = value @@ -466,6 +478,10 @@ def _index_block(w: _Wake, path: str, lines: list[dict], by_changes: bool, run_c out.append(f"- nudged after closing text; then {line.get('outcome')}{cut} ({path}:{i})") elif event == "harness_note" and line.get("compaction") is not None: out.append(f"- {_compaction_line(line['compaction'], during=acted)} ({path}:{i})") + elif event == "harness_note" and line.get("failure"): + failure = line["failure"] + whose = "; an infrastructure failure isn't the assistant's doing" if is_infra_failure(failure) else "" + out.append(f"- error: the harness says the wake failed ({failure.get('kind')}){whose} ({path}:{i})") elif event == "app_change": changes["by the assistant" if line.get("by") == "agent" else "by others" if line.get("by") else "with no known actor"] += 1 diff --git a/src/agent_env/task_step/task_steps/verifiers/judge_utils/turn_events.py b/src/agent_env/task_step/task_steps/verifiers/judge_utils/turn_events.py index 6bd7a5119..7561c9328 100644 --- a/src/agent_env/task_step/task_steps/verifiers/judge_utils/turn_events.py +++ b/src/agent_env/task_step/task_steps/verifiers/judge_utils/turn_events.py @@ -55,7 +55,8 @@ class TurnEvents: "result", "error"}`` (``result`` absent when none came back; ``internal`` for a tool the harness provides itself), ``{"type": "prompt", "text"}`` (the turn's input, when the format records it), ``{"type": "note", "text"}`` (a message the harness put in the turn; a compaction's also has ``compaction``, what its span recorded: ``written_by``, ``wakes_summarized``, ``wakes_kept``, - ``first_kept_wake``, ``waited_s``) or ``{"type": "final", "text", "error"}``; for an unknown format, + ``first_kept_wake``, ``waited_s``; the harness's account of a failed wake has ``failure``: its ``kind`` and what + else its span recorded) or ``{"type": "final", "text", "error"}``; for an unknown format, ``{"type": "raw", "event"}`` per stored item. ``agent_labels``: its spans say which agent made each, or hold the harness's own compaction or messages (``has_agent_labels``).""" @@ -169,17 +170,24 @@ def _settle(call: dict, result: Any, error: bool) -> None: # assistant). A model span's ``gen_ai.output.messages`` lists its parts in order: reasoning, text, tool calls (the # summary call's text is a ``compaction`` part). The harness's own records are ``harness.*`` spans: the compaction # (``harness.compaction``, from the start of the save turn to the end of the summary, its ``written_by`` saying who -# wrote the summary) and each message it put before the assistant (``harness.message``, with its ``purpose``). +# wrote the summary), each message it put before the assistant (``harness.message``, with its ``purpose``), and why a +# wake failed (``harness.error``, its ``kind`` also on that wake's ``failed_wake`` message). _AGENT = "gen_ai.agent.name" _MAIN_AGENT = "gen_ai.main_agent.name" _OUTPUT_MESSAGES = "gen_ai.output.messages" _COMPACTION = "harness.compaction" _MESSAGE = "harness.message" +_ERROR = "harness.error" _SAVE = "pre_compaction_save" _AFTER = "after_compaction" _FAILED_WAKE = "failed_wake" # The step a harness message's purpose stands for, as staging and the judge name it. _STEP_OF_PURPOSE = {"save_request": _SAVE, "after_summary": _AFTER, "failed_wake": _FAILED_WAKE} +# The kinds of wake failure a harness reports (``harness.error.kind``) that are its infrastructure's, not the +# assistant's: the model endpoint failing, throttling past its retries, a model call timing out, the harness's own bug. +# Its other kinds (the model's own doing, a full context, the wake's time limit, a cost cap, unknown) say nothing either +# way. +INFRA_FAILURE_KINDS = frozenset({"gateway", "throttled", "timeout_call", "harness"}) def _span_id(span: dict) -> Optional[str]: @@ -239,6 +247,10 @@ def _otel_events(spans: list[dict]) -> list[dict]: if span.get("name") == _MESSAGE: timed.append((start, i, {"type": "note", "text": _harness_message_note(attrs), **tag})) continue + if span.get("name") == _ERROR: # the harness's own span, which _is_harness_own would leave out + failure = _span_failure(attrs) + timed.append((start, i, {"type": "note", "text": _failure_note(failure), "failure": failure})) + continue if harness and _is_harness_own(span, attrs, by_id): continue thinking = _span_thinking(attrs) @@ -405,15 +417,45 @@ def compaction_note(facts: dict, summary: str) -> str: def _harness_message_note(attrs: dict) -> str: - """A ``harness.message`` span as a note: the text the harness put before the model, labelled by its purpose. The - message after a compaction repeats the user's first request word for word: it is the harness's, not a new one from - the user.""" + """A ``harness.message`` span as a note: the text the harness put before the model, labelled by its purpose, and + for the message after a failed wake, the kind of failure the harness says it was. The message after a compaction + repeats the user's first request word for word: it is the harness's, not a new one from the user.""" step = _STEP_OF_PURPOSE.get(str(attrs.get("harness.message.purpose") or "")) who = "re-sent by the harness, it repeats the user's earlier words" if step == _AFTER else "not from the user" - return (f"Message the harness sent the assistant ({f'step {step}; ' if step else ''}{who}):\n" + kind = attrs.get(f"{_ERROR}.kind") if step == _FAILED_WAKE else None + failed = f"the wake failed: {_kind_words(kind)}; " if kind else "" + return (f"Message the harness sent the assistant ({f'step {step}; ' if step else ''}{failed}{who}):\n" + str(attrs.get("harness.message.text") or "")) +def _span_failure(attrs: dict) -> dict: + """What a ``harness.error`` span recorded, by its attributes' names after ``harness.error.``: ``kind``, ``class``, + ``message``, and when they apply ``http_status``, ``retries``, ``timeout_s``, ``during`` and the gateway's ids.""" + prefix = f"{_ERROR}." + return {key[len(prefix):]: value for key, value in attrs.items() if key.startswith(prefix) and value is not None} + + +def is_infra_failure(failure: Mapping) -> bool: + """Whether a failure note's ``failure`` is the infrastructure's (``INFRA_FAILURE_KINDS``), not the assistant's.""" + return failure.get("kind") in INFRA_FAILURE_KINDS + + +def _kind_words(kind: Any) -> str: + return f"{kind}, an infrastructure failure, not the assistant's doing" if kind in INFRA_FAILURE_KINDS else str(kind) + + +def _failure_note(failure: Mapping) -> str: + """A failed wake as the harness tells it: the kind of failure (said to be no doing of the assistant's when it is + the infrastructure's), its message (for the wake's time limit, what was running), the HTTP status and retries.""" + details = [str(failure["message"])] if failure.get("message") else [] + if failure.get("http_status") is not None: + details.append(f"HTTP {failure['http_status']}") + if failure.get("retries") is not None: + details.append(f"after {failure['retries']} retries") + return (f"The harness says this wake failed: {_kind_words(failure.get('kind') or 'unknown')}" + + (f" ({'; '.join(details)})" if details else "")) + + def _span_text(attrs: dict) -> str: """A model span's own output text: OpenInference's ``llm.output_messages.N.message.content``, a GenAI ``chat`` span's text blocks, or the text parts of its ``gen_ai.output.messages``.""" 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 2159664d7..3bcd37257 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 @@ -29,6 +29,7 @@ from agent_env.providers.sandbox_providers.local_docker.provider import remove_local_work_dir from agent_env.providers.sandbox_providers.sandbox import into_container from agent_env.task_step.context import ( + INFRA_ERROR, PromptResponse, StepContextError, TaskStepContext, @@ -813,6 +814,13 @@ 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 _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.""" @@ -1047,7 +1055,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] @@ -1117,6 +1126,11 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: ) stored_response, prompt_response = prompt_response, as_of + if prompt_response.error_type == INFRA_ERROR: + reason = (f"the run's turn failed for an infrastructure reason (error_code=" + 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: 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}") diff --git a/tst/unit/task/outcome_test.py b/tst/unit/task/outcome_test.py index 367d44850..a22353a33 100644 --- a/tst/unit/task/outcome_test.py +++ b/tst/unit/task/outcome_test.py @@ -12,7 +12,7 @@ from agent_env.task.outcome import FailureCause, StepRole, classify_failure from agent_env.task.store import TASK_INSTANCES_COLLECTION, TaskInstanceStore, set_task_instance_store from agent_env.task.task import Task -from agent_env.task_step.context import TaskStepContext, VerifierNotPassingError +from agent_env.task_step.context import AgentTurnInfraError, TaskStepContext, VerifierNotPassingError from agent_env.task_step.registry import get_task_step_registry from agent_env.task_step.task_steps.collect_artifacts import CollectArtifactsTaskStep from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep @@ -78,6 +78,13 @@ def _chained(outer: BaseException, inner: BaseException, *, explicit: bool = Tru (RuntimeError("codex CLI stalled (attempt 1: unexpected status 408 Request Timeout: request body arrived too slowly)"), FailureCause.TRANSIENT), (VerifierNotPassingError("verifier 'grade' scored 0.5: rows not met: done"), FailureCause.VERDICT), + # An agent turn that its agent says failed for an infrastructure reason is one agent-env may retry; a key out of + # budget in its message still wins, since a retry fails the same way. + (AgentTurnInfraError("always_on: wake 3's agent turn failed for an infrastructure reason (error_type=infra_error, " + "error_code=psi.harness): TypeError: 'NoneType' object is not iterable"), + FailureCause.TRANSIENT), + (AgentTurnInfraError(f"always_on: wake 3's agent turn failed for an infrastructure reason: {BUDGET_400}"), + FailureCause.KEY_BUDGET), # Text from an env, a tool, a script or a model mentions codes and words the proxy also uses; none of it is ours. (RuntimeError("tool get_account returned HTTP 401 Unauthorized from env MCP server"), FailureCause.UNKNOWN), (RuntimeError("run_code 'reload': exited 1: urllib.error.HTTPError: HTTP Error 401: Unauthorized"), 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 66d98ca81..151084f98 100644 --- a/tst/unit/task_step/test_always_on_agent_verifier.py +++ b/tst/unit/task_step/test_always_on_agent_verifier.py @@ -18,7 +18,7 @@ from agent_env.config import get_config from agent_env.providers.sandbox_providers import sandbox_provider from agent_env.task.task import Task -from agent_env.task_step.context import DeployedAgent, PromptResponse, TaskStepContext +from agent_env.task_step.context import AgentTurnInfraError, DeployedAgent, PromptResponse, TaskStepContext from agent_env.task_step.task_steps import always_on as ao from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep from agent_env.task_step.task_steps.verifiers import is_rubrics_verifier @@ -27,7 +27,7 @@ UngradableRunError, ) from agent_env.task_step.task_steps.verifiers.rubrics_verifier import RUN_CONTEXT_PARTS, RubricsVerifierTaskStep -from tst.unit.task_step.always_on_harness import Rig +from tst.unit.task_step.always_on_harness import Fail, Rig from tst.util import atif_runs from tst.util.config import install_model_config @@ -133,6 +133,27 @@ def fails(n, texts, rig): assert row["id"] == "prompt_error" and "agent_turn_timeout" in row["message"] +@pytest.mark.asyncio +async def test_a_tolerated_run_whose_turn_failed_for_an_infrastructure_reason_is_skipped_not_scored(monkeypatch, + tmp_path): + def fails(n, texts, rig): + return Fail("APIStatusError: 502 Bad Gateway", error_type="infra_error", error_code="psi.gateway") + + rig = Rig(monkeypatch, tmp_path, agent=fails) + await rig.arm() + ctx = rig.context() + with pytest.raises(AgentTurnInfraError): + await rig.run(rig.step(), ctx) + verifier = _verifier() + _capture(monkeypatch, verifier) + + await verifier.execute(ctx) + + entry = ctx.metadata["verifications"]["rubric"] + assert (entry["results"], entry["score"]) == ([], None) and "psi.gateway" in entry["skipped"] + assert ctx.metadata["grades"]["judge"]["verifier_status"] == "skipped" + + @pytest.mark.asyncio async def test_a_run_s_grade_up_to_turn_is_refused(monkeypatch, tmp_path): rig, ctx = await _run(monkeypatch, tmp_path) @@ -844,6 +865,22 @@ async def test_a_compaction_that_doesn_t_say_who_wrote_its_summary_leaves_the_ru assert "rubric" not in (ctx.metadata.get("verifications") or {}) +def test_the_files_note_says_how_to_read_a_failure_only_for_a_run_whose_harness_reports_one(): + from agent_env.task_step.task_steps.verifiers.always_on_agent_verifier import _files_note + from agent_env.task_step.task_steps.verifiers.always_on_staging import StagedRun + + files = {"index.md": "", "wakes/wake_001.jsonl": ""} + rule = ('A "harness_note" line with "failure" is the harness saying why that wake failed ("kind"). A failure of kind ' + "gateway, harness, throttled or timeout_call is the infrastructure's (the model endpoint, or the harness " + "itself), not the assistant's doing.") + + failed = _files_note("/s", StagedRun(files, {"agent_labeled_trajectories": 1, + "harness_failures": [{"wake": 1, "kind": "gateway"}]})) + + assert rule in failed + assert rule not in _files_note("/s", StagedRun(files, {"agent_labeled_trajectories": 1})) + + def test_the_files_note_says_whose_a_summary_s_losses_are_by_who_wrote_it(): from agent_env.task_step.task_steps.verifiers.always_on_agent_verifier import _files_note from agent_env.task_step.task_steps.verifiers.always_on_staging import StagedRun diff --git a/tst/unit/task_step/test_always_on_graded.py b/tst/unit/task_step/test_always_on_graded.py index 9e9d3ad6a..3541aeca7 100644 --- a/tst/unit/task_step/test_always_on_graded.py +++ b/tst/unit/task_step/test_always_on_graded.py @@ -1,12 +1,14 @@ """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, so verifiers skip it.""" +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.""" from __future__ import annotations import pytest from agent_env.a2a_agent import conversation_store +from agent_env.task_step.context import AgentTurnInfraError 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, @@ -222,11 +224,11 @@ async def refused_once(run): @pytest.mark.parametrize("play,error_type,end_reason", [ (lambda rig: Fail("the CLI crashed"), "agent_turn_failed", "agent_turn_failed"), - (lambda rig: Fail("sandbox gone", error_type="infra_error"), "infra_error", "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 error type", "timed out", "canceled", "rejected"]) +], ids=["failed", "failed with the agent's own error", "timed out", "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): @@ -255,3 +257,68 @@ async def test_a_nudge_turn_that_doesn_t_complete_sets_error_type_too(monkeypatc 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") + + +@pytest.mark.asyncio +async def test_an_agent_error_turn_keeps_its_error_code_in_the_record_and_is_still_graded(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"}]) + await rig.arm() + 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" + + +# ---- a turn that failed for an infrastructure reason fails the step, once the run is recorded ------------------------- + +def _gateway_502(rig): + rig.message("checking flights now") + return Fail("APIStatusError: 502 Bad Gateway", error_type="infra_error", error_code="psi.gateway") + + +@pytest.mark.asyncio +async def test_an_infra_error_turn_is_recorded_as_any_failed_turn_and_then_fails_the_step(monkeypatch, tmp_path): + rig = Rig(monkeypatch, tmp_path, agent=_agent(t1=_message("on it"), t2=_gateway_502), + answers=[{"outcome": "reply", "message": "great"}]) + await rig.arm() + ctx = rig.context() + with pytest.raises(AgentTurnInfraError, match=r"wake 2's agent turn failed for an infrastructure reason " + r"\(error_type=infra_error, error_code=psi.gateway\)"): + await rig.run(rig.step(), ctx) + + record = rig.record(ctx) + assert (record["end_reason"], record["error_type"], record["error_code"]) == ( + ao.AGENT_TURN_INFRA_ERROR, "infra_error", "psi.gateway") + assert record["error"] == "APIStatusError: 502 Bad Gateway" and record["object_url"] + [response] = ctx.prompt_responses + assert (response.error_type, response.error_code, response.error_message) == ( + "infra_error", "psi.gateway", "APIStatusError: 502 Bad Gateway") + assert response.response == ("[Mon Nov 9, 9:00 AM EST] on it\n\n" + "[Mon Nov 9, 9:00 AM EST] checking flights now") + assert len(response.target_agent_per_turn_trajectory_object_urls) == 2 + [end] = rig.events(ctx, "end") + assert end["reason"] == ao.AGENT_TURN_INFRA_ERROR + assert rig.events(ctx, "agent_turn_end")[-1]["state"] == "failed" + assert rig.chat(ctx)[-1]["parts"][-1]["metadata"]["agentenv"]["end_reason"] == ao.AGENT_TURN_INFRA_ERROR + assert conversation_store.get_conversation(ctx.metadata["a2a_conversations"]["week"])["status"] == "closed" + + +@pytest.mark.asyncio +async def test_a_nudge_turn_that_fails_for_an_infrastructure_reason_fails_the_step_too(monkeypatch, tmp_path): + rig = Rig(monkeypatch, tmp_path, agent=_agent( + t1=lambda rig: "PRIVATE all done", + t2=lambda rig: Fail("connection reset", error_type="infra_error", error_code="psi.gateway"))) + await rig.arm() + ctx = rig.context() + with pytest.raises(AgentTurnInfraError): + await rig.run(rig.step(), ctx) + + [nudge] = rig.events(ctx, "nudge") + assert nudge["state"] == "failed" + record = rig.record(ctx) + assert (record["end_reason"], record["error_code"]) == (ao.AGENT_TURN_INFRA_ERROR, "psi.gateway") + assert ctx.prompt_responses[0].error_type == "infra_error" 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 df1f9b31c..9726079ee 100644 --- a/tst/unit/task_step/test_always_on_wake_limit.py +++ b/tst/unit/task_step/test_always_on_wake_limit.py @@ -1,6 +1,7 @@ """A wake whose turn reaches its time or tool-call limit, with continue_after_wake_limit on: only that wake ends, its work stands, the agent is told at its next wake, the run goes on, and the record and the judge's files say so. Off, -and for any other failure, the run ends as an error, as it always has.""" +and for any other failure, the run ends as an error, as it always has; one that failed for an infrastructure reason +also fails its step.""" from __future__ import annotations @@ -9,6 +10,7 @@ import pytest from agent_env.a2a_agent.protocol import AgentUnreachableError +from agent_env.task_step.context import AgentTurnInfraError from agent_env.task_step.task_steps import always_on as ao 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, Slow @@ -286,7 +288,7 @@ async def test_the_judge_s_files_and_prompt_show_the_cut_off(monkeypatch, tmp_pa @pytest.mark.asyncio @pytest.mark.parametrize("failure", [ Fail("claude CLI exited with code 1: API Error: 500 Internal server error"), - Fail("A2A protocol error: invalid task state", error_type="infra_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): def agent(n, texts, rig): @@ -302,6 +304,45 @@ def agent(n, texts, rig): assert ctx.prompt_responses[0].error_type == (failure.error_type or "agent_turn_failed") +@pytest.mark.asyncio +async def test_an_infra_error_turn_is_no_limit_so_it_ends_the_run_and_fails_the_step(monkeypatch, tmp_path): + def agent(n, texts, rig): + rig.message("on it") + return Fail("A2A protocol error: invalid task state", error_type="infra_error", error_code="framework.x") + + rig = Rig(monkeypatch, tmp_path, agent=agent) + ctx = rig.context() + await rig.arm() + _alert_later(rig) + try: + with pytest.raises(AgentTurnInfraError): + await rig.run(rig.step(max_turns=150, continue_after_wake_limit=True), ctx) + finally: + await rig.close() + + assert len(rig.sent) == 1 + record = rig.record(ctx) + assert (record["end_reason"], record["cut_off_wakes"]) == (ao.AGENT_TURN_INFRA_ERROR, []) + assert (ctx.prompt_responses[0].error_type, ctx.prompt_responses[0].error_code) == ("infra_error", "framework.x") + + +@pytest.mark.asyncio +async def test_a_harness_timeout_code_with_the_setting_on_cuts_the_wake_off_with_no_message_to_match(monkeypatch, + tmp_path): + def agent(n, texts, rig): + if n == 1: + rig.message("on it") + return Fail("the run stopped", error_code="psi.timeout") + rig.quiet() + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent) + ctx = await _run(rig, continue_after_wake_limit=True) + + [cut] = rig.record(ctx)["cut_off_wakes"] + assert cut["limit"] == "time_limit" and rig.record(ctx)["end_reason"] == "finished_nothing_pending" + + @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): @@ -343,15 +384,28 @@ def agent(n, texts, rig): @pytest.mark.asyncio -async def test_an_agent_that_stops_answering_still_ends_the_run(monkeypatch, tmp_path): +@pytest.mark.parametrize("continue_after_wake_limit", [True, False], ids=["on", "off"]) +async def test_an_agent_that_stops_answering_ends_the_run_and_fails_the_step_as_infra(monkeypatch, tmp_path, + continue_after_wake_limit): def agent(n, texts, rig): raise AgentUnreachableError("The agent on sandbox sb stopped answering") rig = Rig(monkeypatch, tmp_path, agent=agent) - ctx = await _run(rig, continue_after_wake_limit=True) + ctx = rig.context() + await rig.arm() + try: + with pytest.raises(AgentTurnInfraError, match="error_code=agent_env.agent_unreachable"): + await rig.run(rig.step(continue_after_wake_limit=continue_after_wake_limit), ctx) + finally: + await rig.close() assert rig.cancels == [] and len(rig.sent) == 1 - assert rig.record(ctx)["end_reason"] == "agent_turn_timeout" + record = rig.record(ctx) + assert (record["end_reason"], record["error_type"], record["error_code"]) == ( + ao.AGENT_TURN_INFRA_ERROR, "infra_error", ao.AGENT_UNREACHABLE_CODE) + assert "stopped answering" in record["error"] + [turn] = rig.events(ctx, "agent_turn_end") + assert turn["state"] == "unreachable" # ---- off: as before -------------------------------------------------------------------------------------------------- diff --git a/tst/unit/task_step/verifiers/judge_utils/test_turn_events.py b/tst/unit/task_step/verifiers/judge_utils/test_turn_events.py index 36b764179..262a7db33 100644 --- a/tst/unit/task_step/verifiers/judge_utils/test_turn_events.py +++ b/tst/unit/task_step/verifiers/judge_utils/test_turn_events.py @@ -328,6 +328,56 @@ def test_a_failed_wake_s_message_is_a_note_in_its_step(): "[Harness: your last wake ended with an error before it finished (TimeoutError).]")} +def _error_span(kind: str, **attrs) -> dict: + """A failed wake's harness.error span, as the PSI harness writes it: the harness's own, status ERROR.""" + return {"name": "harness.error", "start_time": "9", "end_time": "9", "parent_id": None, + "status": {"status_code": "ERROR", "description": attrs.get("harness.error.message", "")}, + "attributes": {"gen_ai.agent.name": "harness", "gen_ai.main_agent.name": "Orchestrator", + "harness.error.kind": kind, "harness.error.class": "APIStatusError", **attrs}} + + +def test_a_harness_error_span_is_a_failure_note_with_its_kind_after_the_wake_s_own_events(): + spans = _v7("claude") + turn_start = next(s["start_time"] for s in spans if s["name"] == "mcp_tools") + spans = [s for s in spans if s["start_time"] >= turn_start] + error = _error_span("gateway", **{"harness.error.message": "APIStatusError: Error code: 502 - Bad Gateway", + "harness.error.http_status": 502, "harness.error.retries": 2, + "harness.error.router_request_id": "req-1"}) + error["start_time"] = error["end_time"] = max(str(s.get("end_time") or s["start_time"]) for s in spans) + spans.append(error) + + events = turn_events(json.dumps(spans)).events + + assert events[-1] == {"type": "note", "text": ( + "The harness says this wake failed: gateway, an infrastructure failure, not the assistant's doing " + "(APIStatusError: Error code: 502 - Bad Gateway; HTTP 502; after 2 retries)"), "failure": { + "kind": "gateway", "class": "APIStatusError", "message": "APIStatusError: Error code: 502 - Bad Gateway", + "http_status": 502, "retries": 2, "router_request_id": "req-1"}} + assert [e["type"] for e in events[:-1]] == ["thinking", "text", "tool_call", "thinking", "text"] + + +@pytest.mark.parametrize("kind", ["model", "timeout_wake", "context_full", "cost_cap", "unknown"]) +def test_a_failure_the_harness_doesn_t_put_on_the_infrastructure_is_named_without_saying_whose_it_is(kind): + [note] = turn_events(json.dumps([_error_span(kind, **{"harness.error.message": "it stopped"})])).events + + assert note["text"] == f"The harness says this wake failed: {kind} (it stopped)" + assert note["failure"]["kind"] == kind + + +def test_a_failed_wake_s_message_names_the_kind_of_failure_the_harness_says_it_was(): + span = {"name": "harness.message", "start_time": "1", "attributes": { + "gen_ai.agent.name": "harness", "gen_ai.main_agent.name": "Orchestrator", + "harness.message.purpose": "failed_wake", "harness.error.kind": "throttled", + "harness.message.text": "[Harness: your last wake ended with an error before it finished (RateLimitError).]"}} + + [note] = turn_events(json.dumps([span])).events + + assert note["text"] == ( + "Message the harness sent the assistant (step failed_wake; the wake failed: throttled, an infrastructure " + "failure, not the assistant's doing; not from the user):\n" + "[Harness: your last wake ended with an error before it finished (RateLimitError).]") + + def test_a_harness_wake_with_no_compaction_messages_or_helpers_gets_no_notes_or_marks(): # A wake with no compaction before it: the recorded wake's own turn and its usage record. spans = _v7("claude") diff --git a/tst/unit/task_step/verifiers/test_always_on_staging.py b/tst/unit/task_step/verifiers/test_always_on_staging.py index f769b7154..d5f54d4ad 100644 --- a/tst/unit/task_step/verifiers/test_always_on_staging.py +++ b/tst/unit/task_step/verifiers/test_always_on_staging.py @@ -527,6 +527,42 @@ def test_the_index_has_a_line_for_a_compaction_naming_its_wakes_and_pointing_at_ "written_by": "assistant", "wakes_summarized": 3, "wakes_kept": 2, "first_kept_wake": 4} +def _failed_v7_run(run, kind: str): + """The v7 run with wake 4's trace ending in the harness's account of why the wake failed (a harness.error span).""" + timeline, turns = _v7_run(run) + spans = json.loads((RECORDED / "turn_otel_v7_compaction_gpt.json").read_text()) + at = max(str(s.get("end_time") or s["start_time"]) for s in spans) + spans.append({"name": "harness.error", "start_time": at, "end_time": at, "parent_id": None, + "status": {"status_code": "ERROR"}, + "attributes": {"gen_ai.agent.name": "harness", "gen_ai.main_agent.name": "Orchestrator", + "harness.error.kind": kind, "harness.error.class": "APIStatusError", + "harness.error.message": "APIStatusError: Error code: 502", "harness.error.http_status": 502}}) + turns[_url(timeline, 4)] = turn_events(json.dumps(spans)) + return timeline, turns + + +@pytest.mark.parametrize("kind,whose", [ + ("gateway", "; an infrastructure failure isn't the assistant's doing"), + ("model", ""), +]) +def test_a_wake_the_harness_says_failed_has_a_note_with_its_failure_and_an_index_error_line(run, kind, whose): + staged = stage_run(*_failed_v7_run(run, kind)) + + wake4 = _lines(staged.files, "wakes/wake_004.jsonl") + [i] = [i for i, line in enumerate(wake4, 1) if line.get("failure")] + note = wake4[i - 1] + assert note["event"] == "harness_note" and note["failure"]["kind"] == kind + assert note["failure"]["http_status"] == 502 and note["text"].startswith("The harness says this wake failed: ") + assert not [line for line in wake4[i:] if line["event"] in ("tool_call", "assistant_text", "assistant_thinking")] + block = staged.files[INDEX_FILE][staged.files[INDEX_FILE].index("## Wake 4 "):] + assert f"- error: the harness says the wake failed ({kind}){whose} (wakes/wake_004.jsonl:{i})" in block + assert staged.record["harness_failures"] == [{"wake": 4, "kind": kind}] + + +def test_a_run_whose_harness_reports_no_failure_records_none(run): + assert "harness_failures" not in stage_run(*_v7_run(run)).record + + def test_the_index_says_a_compaction_came_partway_through_the_turn_when_the_assistant_had_acted(run): """Claude Code compacts inside a turn, once the history fills; a harness's save turn before its compaction isn't the assistant's own turn, so the v7 wake's stays before it.""" diff --git a/tst/unit/task_step/verifiers/test_rubrics_verifier_infra_error.py b/tst/unit/task_step/verifiers/test_rubrics_verifier_infra_error.py new file mode 100644 index 000000000..860dbf499 --- /dev/null +++ b/tst/unit/task_step/verifiers/test_rubrics_verifier_infra_error.py @@ -0,0 +1,102 @@ +"""A run whose agent turn failed for an infrastructure reason (``error_type`` infra_error) says nothing about the agent: +a rubrics verifier skips it, unscored, where any other failed turn is scored 0 unjudged, and an aggregate of such +sources is skipped too, so the run is unscored rather than scored below 1.""" +from __future__ import annotations + +import pytest + +from agent_env.bundle.run import Outcome, TaskRun +from agent_env.task import Task +from agent_env.task.task import recorded_scores +from agent_env.task_step.context import PromptResponse, TaskStepContext +from agent_env.task_step.task_steps.verifiers.aggregate_verifiers import AggregateVerifiersTaskStep +from agent_env.task_step.task_steps.verifiers.judge_utils.trajectory_filter import ( + CompactionType, + FrameStrategy, + TrajectoryFilter, +) +from agent_env.task_step.task_steps.verifiers.rubrics_verifier import RubricsVerifierTaskStep, trajectory_mistakes_key +from agent_env.task_step.task_steps.verifiers.verifier import GRADES_KEY, VerifierStatus + +CRITERIA = [{"id": "done", "description": "it is done"}] +REASON = "the run's turn failed for an infrastructure reason (error_code=psi.gateway), not the assistant's" + + +def _verifier(monkeypatch, step_id: str, **kw) -> RubricsVerifierTaskStep: + step = RubricsVerifierTaskStep(**{ + "id": step_id, "version": 1, "criteria": CRITERIA, "prompt_id": "p1", "use_agent_judge": False, + "use_trajectory": True, "verifier_id": step_id, **kw}) + + async def judge(**kwargs): + raise AssertionError("a run that failed for an infrastructure reason is never judged") + + monkeypatch.setattr(step, "_read_trajectory_text", lambda uri: "EVENTS") + monkeypatch.setattr(step, "_run_judge_with_output_retries", judge) + return step + + +def _context(error_type: str = "infra_error") -> TaskStepContext: + return TaskStepContext(prompt_responses=[PromptResponse( + prompt_id="p1", response="[Mon] on it", prompt_text="plan the trip", agent_trajectory_object_url="s3://t/1.json", + error_type=error_type, error_code="psi.gateway", error_message="APIStatusError: 502 Bad Gateway")]) + + +@pytest.mark.asyncio +async def test_an_infra_error_run_is_skipped_unscored_not_scored_0(monkeypatch): + ctx = _context() + + await _verifier(monkeypatch, "psi-trust").execute(ctx) + + grade = ctx.metadata[GRADES_KEY]["psi-trust"] + assert (grade["verifier_status"], grade["score"]) == (VerifierStatus.SKIPPED, None) + entry = ctx.metadata["verifications"]["psi-trust"] + assert (entry["results"], entry["score"], entry["skipped"]) == ([], None, REASON) + + +@pytest.mark.asyncio +async def test_an_agent_error_run_is_still_scored_0_unjudged(monkeypatch): + ctx = _context(error_type="agent_error") + + await _verifier(monkeypatch, "psi-trust").execute(ctx) + + [row] = ctx.metadata["verifications"]["psi-trust"]["results"] + assert (row["id"], ctx.metadata["verifications"]["psi-trust"]["score"]) == ("prompt_error", 0) + assert ctx.metadata[GRADES_KEY]["psi-trust"]["verifier_status"] == VerifierStatus.GRADED + + +@pytest.mark.asyncio +async def test_a_skip_does_not_fail_a_verifier_that_fails_its_task_when_not_passing(monkeypatch): + ctx = _context() + + await _verifier(monkeypatch, "psi-trust", fail_task_when_not_passing=True).execute(ctx) + + assert ctx.metadata[GRADES_KEY]["psi-trust"]["verifier_status"] == VerifierStatus.SKIPPED + + +@pytest.mark.asyncio +async def test_the_trajectory_mistakes_entry_is_skipped_too(monkeypatch): + ctx = _context() + + frames = TrajectoryFilter(compaction_type=CompactionType.SCREENSHOT, frame_strategy=FrameStrategy.PER_CRITERION) + await _verifier(monkeypatch, "psi-process", output_format="rubric_evidence_with_mistakes", + trajectory_filter=frames).execute(ctx) + + mistakes = ctx.metadata["verifications"][trajectory_mistakes_key("psi-process")] + assert (mistakes["results"], mistakes["score"], mistakes["skipped"]) == ([], None, REASON) + + +@pytest.mark.asyncio +async def test_a_verdict_over_sources_all_skipped_is_skipped_and_the_run_unscored(monkeypatch, local_stores): + trust, process = _verifier(monkeypatch, "psi-trust"), _verifier(monkeypatch, "psi-process") + verdict = AggregateVerifiersTaskStep(id="psi-verdict", version=None, sources=["psi-trust", "psi-process"], + score_aggregator="all_pass", depends_on=["psi-trust", "psi-process"]) + task = Task(id="t", version=None, steps=[trust, process, verdict]) + ctx = _context() + + await task.run(context=ctx) + + grade = ctx.metadata[GRADES_KEY]["psi-verdict"] + assert (grade["verifier_status"], grade["verifier_skip_reasoning"]) == (VerifierStatus.SKIPPED, + "every source it weighs was skipped") + assert recorded_scores(task.steps, ctx) == {} + assert TaskRun(None, task, ctx, None, 0.0).outcome is Outcome.UNSCORED From 6edb1980bcbc37d8e4b9af762233d32478c6d680 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Tue, 1 Dec 2026 10:27:52 -0800 Subject: [PATCH 02/19] fix(verifiers): an all-skipped verifier_ids aggregate is skipped; a failure's message stays out of its staged line Co-Authored-By: Claude Opus 5.5 --- .../verifiers/aggregate_verifiers.py | 9 +++-- .../task_steps/verifiers/always_on_staging.py | 9 +++-- .../verifiers/test_always_on_staging.py | 15 +++++++-- .../test_rubrics_verifier_infra_error.py | 33 +++++++++++++++++++ 4 files changed, 58 insertions(+), 8 deletions(-) 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..7661fe0c0 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 @@ -8,8 +8,8 @@ skipped source is left out, and every source skipped, or a gate skipped, skips it. ``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. +``verifications`` entries, as it always has: a source whose entry has no rows adds nothing, and every source's entry +skipped skips it. It takes none of the newer fields. """ from __future__ import annotations @@ -206,6 +206,9 @@ def _pooled_entries(self, context: TaskStepContext) -> Verification: f"Available: {list(all_verifications.keys())}" ) + output = {"source_verifier_ids": list(self.verifier_ids)} + if self.verifier_ids and all(all_verifications[vid].get("skipped") is not None for vid in self.verifier_ids): + return Verification(skipped="every source it weighs was skipped", output=output) merged_results: list[dict] = [] for vid in self.verifier_ids: merged_results.extend(all_verifications[vid].get("results", [])) @@ -216,7 +219,7 @@ 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 legacy_entry_writers(steps: Sequence[TaskStep]) -> dict[str, str]: 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 dbd8b1b67..12d738b20 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 @@ -307,10 +307,13 @@ def turn(self, w: _Wake, url: Optional[str], which: str) -> list[dict]: elif kind == "note": if e.get("compaction"): self.summary_writers[e["compaction"]["written_by"]] += 1 - if e.get("failure"): - self.harness_failures.append({"wake": w.n, "kind": e["failure"].get("kind")}) + failure = e.get("failure") + if failure: + self.harness_failures.append({"wake": w.n, "kind": failure.get("kind")}) + # Its message is in the note's text, which moves to a file when long; ``failure`` stays inline. + failure = {k: v for k, v in failure.items() if k != "message"} lines.append(_line("harness_note", w.n, turn=which, step=e.get("step"), compaction=e.get("compaction"), - failure=e.get("failure"), text=e["text"])) + failure=failure, text=e["text"])) elif kind == "raw": lines.append(_line("trajectory_item", w.n, turn=which, item=e["event"])) staged = sum(len(_dumps(line).encode()) for line in lines) + side diff --git a/tst/unit/task_step/verifiers/test_always_on_staging.py b/tst/unit/task_step/verifiers/test_always_on_staging.py index d5f54d4ad..a7acbaf96 100644 --- a/tst/unit/task_step/verifiers/test_always_on_staging.py +++ b/tst/unit/task_step/verifiers/test_always_on_staging.py @@ -527,7 +527,7 @@ def test_the_index_has_a_line_for_a_compaction_naming_its_wakes_and_pointing_at_ "written_by": "assistant", "wakes_summarized": 3, "wakes_kept": 2, "first_kept_wake": 4} -def _failed_v7_run(run, kind: str): +def _failed_v7_run(run, kind: str, message: str = "APIStatusError: Error code: 502"): """The v7 run with wake 4's trace ending in the harness's account of why the wake failed (a harness.error span).""" timeline, turns = _v7_run(run) spans = json.loads((RECORDED / "turn_otel_v7_compaction_gpt.json").read_text()) @@ -536,7 +536,7 @@ def _failed_v7_run(run, kind: str): "status": {"status_code": "ERROR"}, "attributes": {"gen_ai.agent.name": "harness", "gen_ai.main_agent.name": "Orchestrator", "harness.error.kind": kind, "harness.error.class": "APIStatusError", - "harness.error.message": "APIStatusError: Error code: 502", "harness.error.http_status": 502}}) + "harness.error.message": message, "harness.error.http_status": 502}}) turns[_url(timeline, 4)] = turn_events(json.dumps(spans)) return timeline, turns @@ -559,6 +559,17 @@ def test_a_wake_the_harness_says_failed_has_a_note_with_its_failure_and_an_index assert staged.record["harness_failures"] == [{"wake": 4, "kind": kind}] +def test_a_long_failure_message_moves_aside_with_the_note_and_its_line_fits(run): + body = "upstream said: " + "x" * (3 * LINE_CHARS) + staged = stage_run(*_failed_v7_run(run, "gateway", message=body)) + + wake4 = staged.files["wakes/wake_004.jsonl"] + [note] = [line for line in _lines(staged.files, "wakes/wake_004.jsonl") if line.get("failure")] + assert "message" not in note["failure"] and note["failure"]["kind"] == "gateway" + assert all(len(line) <= LINE_CHARS for line in wake4.splitlines()) + assert any(body in text.replace("\n", "") for path, text in staged.files.items() if path != "wakes/wake_004.jsonl") + + def test_a_run_whose_harness_reports_no_failure_records_none(run): assert "harness_failures" not in stage_run(*_v7_run(run)).record diff --git a/tst/unit/task_step/verifiers/test_rubrics_verifier_infra_error.py b/tst/unit/task_step/verifiers/test_rubrics_verifier_infra_error.py index 860dbf499..63a1be013 100644 --- a/tst/unit/task_step/verifiers/test_rubrics_verifier_infra_error.py +++ b/tst/unit/task_step/verifiers/test_rubrics_verifier_infra_error.py @@ -100,3 +100,36 @@ async def test_a_verdict_over_sources_all_skipped_is_skipped_and_the_run_unscore "every source it weighs was skipped") assert recorded_scores(task.steps, ctx) == {} assert TaskRun(None, task, ctx, None, 0.0).outcome is Outcome.UNSCORED + + +@pytest.mark.asyncio +async def test_a_verdict_over_verifier_ids_all_skipped_is_skipped_too(monkeypatch, local_stores): + trust, process = _verifier(monkeypatch, "psi-trust"), _verifier(monkeypatch, "psi-process") + verdict = AggregateVerifiersTaskStep(id="psi-verdict", version=None, verifier_ids=["psi-trust", "psi-process"], + score_aggregator="all_pass", depends_on=["psi-trust", "psi-process"]) + task = Task(id="t", version=None, steps=[trust, process, verdict]) + ctx = _context() + + await task.run(context=ctx) + + grade = ctx.metadata[GRADES_KEY]["psi-verdict"] + assert (grade["verifier_status"], grade["verifier_skip_reasoning"]) == (VerifierStatus.SKIPPED, + "every source it weighs was skipped") + assert recorded_scores(task.steps, ctx) == {} + assert TaskRun(None, task, ctx, None, 0.0).outcome is Outcome.UNSCORED + + +@pytest.mark.asyncio +async def test_a_verdict_over_verifier_ids_pools_the_sources_not_skipped(monkeypatch, local_stores): + trust = _verifier(monkeypatch, "psi-trust") + verdict = AggregateVerifiersTaskStep(id="psi-verdict", version=None, verifier_ids=["psi-trust", "psi-line"], + score_aggregator="all_pass", depends_on=["psi-trust"]) + task = Task(id="t", version=None, steps=[trust, verdict]) + ctx = _context() + ctx.metadata["verifications"] = {"psi-line": {"results": [{"id": "said_done", "score": 1.0, "result": True}], + "score": 1.0}} + + await task.run(context=ctx) + + grade = ctx.metadata[GRADES_KEY]["psi-verdict"] + assert (grade["verifier_status"], grade["score"]) == (VerifierStatus.GRADED, 1.0) From 6ea9f0f63264dd1131fbaab191b5ef07bacd6732 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Tue, 1 Dec 2026 10:51:39 -0800 Subject: [PATCH 03/19] feat(always_on): an always_on step with no retry_config is redone once from its env deploy The step type's own default (TaskStep.default_retry_config), applied when a Task is built and never written into the stored task. A task's own retry_config replaces it. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/agents/AGENTS.md | 3 +- src/agent_env/task/task.py | 13 +++++ src/agent_env/task_step/task_step.py | 14 +++++- .../task_step/task_steps/always_on.py | 8 +++- .../task_step/test_always_on_default_retry.py | 48 +++++++++++++++++++ 5 files changed, 82 insertions(+), 4 deletions(-) create mode 100644 tst/unit/task_step/test_always_on_default_retry.py diff --git a/src/agent_env/agents/AGENTS.md b/src/agent_env/agents/AGENTS.md index f9358522e..3acd49ef4 100644 --- a/src/agent_env/agents/AGENTS.md +++ b/src/agent_env/agents/AGENTS.md @@ -71,7 +71,8 @@ terminal state, `completed`, `failed` or `canceled`. Your `run()` is one turn. 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 its `retry_config` can redo it. So a failure that may be the + (`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 diff --git a/src/agent_env/task/task.py b/src/agent_env/task/task.py index 3f40431c4..42fcf3607 100644 --- a/src/agent_env/task/task.py +++ b/src/agent_env/task/task.py @@ -392,6 +392,19 @@ def __init__( self._validate_dag(self.steps) self._validate_pairings(self.steps) self._validate_headlines(self.headline_verifiers, self.steps) + self._imply_retries(self.steps) + + @staticmethod + def _imply_retries(steps: list[TaskStep]) -> None: + """Give each step the task left without a ``retry_config`` the one its type implies + (``TaskStep.default_retry_config``). A step built without TaskStep, as some tests build one, has none.""" + deps: dict[str, set[str]] | None = None + for step in steps: + if getattr(step, "retry_config", None) is not None or not hasattr(step, "default_retry_config"): + continue + deps = deps if deps is not None else _dependency_ids(steps) + ancestors = _ancestor_ids(step.id, deps) + step.retry_config = step.default_retry_config([s for s in steps if s.id in ancestors]) @staticmethod def _validate_headlines(headlines: list[str] | None, steps: list[TaskStep]) -> None: diff --git a/src/agent_env/task_step/task_step.py b/src/agent_env/task_step/task_step.py index 141b77221..6fd70cee6 100644 --- a/src/agent_env/task_step/task_step.py +++ b/src/agent_env/task_step/task_step.py @@ -77,6 +77,11 @@ class RetryConfig: retry_from_step_id: str max_retries: int = 1 + # A step type's own default (``TaskStep.default_retry_config``), never written into the stored task. + implied: bool = dataclasses.field(default=False, compare=False) + + def to_dict(self) -> dict[str, Any]: + return {"retry_from_step_id": self.retry_from_step_id, "max_retries": self.max_retries} @classmethod def from_dict(cls, data: dict[str, Any]) -> "RetryConfig": @@ -163,6 +168,11 @@ def config_warnings(self) -> list[str]: fine. Task lint reports them as warnings, as it reports ``config_problems`` as errors.""" return [] + def default_retry_config(self, ancestors: list["TaskStep"]) -> Optional["RetryConfig"]: + """The retry a step of this type takes when its task gives it none (``ancestors``: the steps it depends on, + directly or not, in task order); None for no retry. A task's own ``retry_config`` always wins.""" + return None + def task_problems(self, steps: list["TaskStep"]) -> list[str]: """Problems this step has with the task's other steps (``steps``: all of them, this one included, in order), found without reading a store; empty when fine. A task with any is refused when it loads.""" @@ -180,8 +190,8 @@ def to_dict(self) -> dict[str, Any]: base: dict[str, Any] = {"id": self.id, "type": self.type, "version": self.version, "fail_task_on_error": self.fail_task_on_error} if self.depends_on is not None: base["depends_on"] = [dataclasses.asdict(d) for d in self.depends_on] - if self.retry_config is not None: - base["retry_config"] = dataclasses.asdict(self.retry_config) + if self.retry_config is not None and not self.retry_config.implied: + base["retry_config"] = self.retry_config.to_dict() if self.step_role != type(self).step_role: base["step_role"] = self.step_role.value return base 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 e85bf77dc..c6a6f0bb4 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -153,7 +153,7 @@ ) from agent_env.task_step.snapshot_utils.atif_copies import AtifCopies from agent_env.task_step.usage import StepUsage -from agent_env.task_step.task_step import TaskStep +from agent_env.task_step.task_step import RetryConfig, TaskStep from agent_env.task_step.task_steps.agent import user_sim_versions from agent_env.task_step.task_steps.agent.deploy_user_sim_agent import USER_SIMS_KEY, recorded_instructions, user_sim_model from agent_env.task_step.task_steps.notification_delivery import delivered_parts, label_time, take_due @@ -423,6 +423,12 @@ def from_dict(cls, data: dict) -> AlwaysOnTaskStep: fields["user_sim_gate"] = data["user_sim_gate"] return cls(**cls._base_from_dict(data), retry_config=data.get("retry_config"), **fields, **own) + def default_retry_config(self, ancestors: list[TaskStep]) -> Optional[RetryConfig]: + """A turn that failed for an infrastructure reason (``AgentTurnInfraError``), or an attempt a dead worker lost, + is redone once on a fresh world, from the first env deploy before this step; never in the world it changed.""" + deploy = next((s for s in ancestors if s.type == "deploy_env"), None) + return RetryConfig(deploy.id, max_retries=1, implied=True) if deploy is not None else None + def task_problems(self, steps: list[TaskStep]) -> list[str]: """Its prompt is graded by always_on_agent_verifier: a plain rubrics_verifier, which would grade it from every wake's trajectory, is refused.""" diff --git a/tst/unit/task_step/test_always_on_default_retry.py b/tst/unit/task_step/test_always_on_default_retry.py new file mode 100644 index 000000000..c8d8b3907 --- /dev/null +++ b/tst/unit/task_step/test_always_on_default_retry.py @@ -0,0 +1,48 @@ +"""An always_on step the task gives no ``retry_config`` is redone once from the first env deploy before it, so a turn +that failed for an infrastructure reason, or an attempt a dead worker lost, runs again on a fresh world. The default is +the step type's, never written into the stored task; a task's own ``retry_config`` wins.""" +from __future__ import annotations + +from agent_env.task import Task +from agent_env.task_step.task_step import RetryConfig +from agent_env.task_step.task_steps import always_on as ao +from agent_env.task_step.task_steps.deploy_env import DeployEnvTaskStep + + +def _steps(**settings): + return [DeployEnvTaskStep(id="env", version=None, env_id="mail"), + ao.AlwaysOnTaskStep("week", None, user_sim="linda", prompt_id="ask", agent_name="solver", **settings)] + + +def test_an_always_on_step_without_one_is_redone_once_from_the_env_deploy(): + task = Task(id="t", version=None, steps=_steps()) + + assert task.steps[1].retry_config == RetryConfig("env", max_retries=1) + assert task.steps[1].retry_config.implied + + +def test_the_default_is_not_written_into_the_stored_task_and_comes_back_on_load(): + stored = Task(id="t", version=None, steps=_steps()).to_dict() + + assert "retry_config" not in stored["steps"][1] + assert Task.from_dict(stored).steps[1].retry_config == RetryConfig("env", max_retries=1) + + +def test_a_tasks_own_retry_config_wins_and_is_stored(): + task = Task(id="t", version=None, steps=_steps(retry_config={"retry_from_step_id": "week", "max_retries": 0})) + + assert task.steps[1].retry_config == RetryConfig("week", max_retries=0) + assert task.to_dict()["steps"][1]["retry_config"] == {"retry_from_step_id": "week", "max_retries": 0} + + +def test_an_always_on_step_with_no_env_deploy_before_it_takes_none(): + task = Task(id="t", version=None, steps=_steps()[1:]) + + assert task.steps[0].retry_config is None + + +def test_the_deploy_must_be_an_ancestor_not_just_an_earlier_step(): + steps = [DeployEnvTaskStep(id="env", version=None, env_id="mail"), + ao.AlwaysOnTaskStep("week", None, depends_on=[], user_sim="linda", prompt_id="ask", agent_name="solver")] + + assert Task(id="t", version=None, steps=steps).steps[1].retry_config is None From 34e8b0b9110f93573ded1dcf12437b1d13bbf331 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Tue, 1 Dec 2026 10:55:28 -0800 Subject: [PATCH 04/19] test: import recorded_scores from task.result after main moved it Co-Authored-By: Claude Opus 5.5 --- .../task_step/verifiers/test_rubrics_verifier_infra_error.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tst/unit/task_step/verifiers/test_rubrics_verifier_infra_error.py b/tst/unit/task_step/verifiers/test_rubrics_verifier_infra_error.py index 63a1be013..619f36287 100644 --- a/tst/unit/task_step/verifiers/test_rubrics_verifier_infra_error.py +++ b/tst/unit/task_step/verifiers/test_rubrics_verifier_infra_error.py @@ -7,7 +7,7 @@ from agent_env.bundle.run import Outcome, TaskRun from agent_env.task import Task -from agent_env.task.task import recorded_scores +from agent_env.task.result import recorded_scores from agent_env.task_step.context import PromptResponse, TaskStepContext from agent_env.task_step.task_steps.verifiers.aggregate_verifiers import AggregateVerifiersTaskStep from agent_env.task_step.task_steps.verifiers.judge_utils.trajectory_filter import ( From 91a2a169b343cab96e013412d5ccfbafd7a239fc Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Tue, 1 Dec 2026 12:02:08 -0800 Subject: [PATCH 05/19] fix(always_on): keep the default retry in seeded runs; leave rubrics_verifier and aggregate_verifiers as on main The infra-error skip in rubrics_verifier and the all-skipped verifier_ids aggregate changed other tasks' scores, and no always_on run reaches them: the step fails first and its default retry redoes the run. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task/task.py | 2 + .../verifiers/aggregate_verifiers.py | 9 +- .../task_steps/verifiers/rubrics_verifier.py | 16 +-- .../test_always_on_agent_verifier.py | 25 +--- .../task_step/test_always_on_default_retry.py | 7 + .../test_rubrics_verifier_infra_error.py | 135 ------------------ 6 files changed, 15 insertions(+), 179 deletions(-) delete mode 100644 tst/unit/task_step/verifiers/test_rubrics_verifier_infra_error.py diff --git a/src/agent_env/task/task.py b/src/agent_env/task/task.py index 55c31196c..74baefb3b 100644 --- a/src/agent_env/task/task.py +++ b/src/agent_env/task/task.py @@ -151,6 +151,8 @@ def _sub(value): seeded = attach_base_fields(type(step).from_dict(data), data) if (keep := getattr(seeded, "seeded_from", None)) is not None: # a step that keeps something as written keep(step) + if seeded.retry_config is None and (implied := getattr(step, "retry_config", None)) is not None: + seeded.retry_config = implied # its type's default, which to_dict leaves out out.append(seeded) return out 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 7661fe0c0..0ae263609 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 @@ -8,8 +8,8 @@ skipped source is left out, and every source skipped, or a gate skipped, skips it. ``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, and every source's entry -skipped skips it. It takes none of the newer fields. +``verifications`` entries, as it always has: a source whose entry has no rows adds nothing. It takes none of the +newer fields. """ from __future__ import annotations @@ -206,9 +206,6 @@ def _pooled_entries(self, context: TaskStepContext) -> Verification: f"Available: {list(all_verifications.keys())}" ) - output = {"source_verifier_ids": list(self.verifier_ids)} - if self.verifier_ids and all(all_verifications[vid].get("skipped") is not None for vid in self.verifier_ids): - return Verification(skipped="every source it weighs was skipped", output=output) merged_results: list[dict] = [] for vid in self.verifier_ids: merged_results.extend(all_verifications[vid].get("results", [])) @@ -219,7 +216,7 @@ 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=output) + return Verification(score=score, output={"source_verifier_ids": list(self.verifier_ids)}) def legacy_entry_writers(steps: Sequence[TaskStep]) -> dict[str, str]: 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..bf15d77e1 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 @@ -29,7 +29,6 @@ from agent_env.providers.sandbox_providers.local_docker.provider import remove_local_work_dir from agent_env.providers.sandbox_providers.sandbox import into_container from agent_env.task_step.context import ( - INFRA_ERROR, PromptResponse, StepContextError, TaskStepContext, @@ -814,13 +813,6 @@ 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 _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.""" @@ -1056,8 +1048,7 @@ 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.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): + if 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] @@ -1123,11 +1114,6 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: ) stored_response, prompt_response = prompt_response, as_of - if prompt_response.error_type == INFRA_ERROR: - reason = (f"the run's turn failed for an infrastructure reason (error_code=" - 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: 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}") 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..dab177156 100644 --- a/tst/unit/task_step/test_always_on_agent_verifier.py +++ b/tst/unit/task_step/test_always_on_agent_verifier.py @@ -18,7 +18,7 @@ from agent_env.config import get_config from agent_env.providers.sandbox_providers import sandbox_provider from agent_env.task.task import Task -from agent_env.task_step.context import AgentTurnInfraError, DeployedAgent, PromptResponse, TaskStepContext +from agent_env.task_step.context import DeployedAgent, PromptResponse, TaskStepContext from agent_env.task_step.task_steps import always_on as ao from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep from agent_env.task_step.task_steps.verifiers import is_rubrics_verifier @@ -27,7 +27,7 @@ UngradableRunError, ) from agent_env.task_step.task_steps.verifiers.rubrics_verifier import RUN_CONTEXT_PARTS, RubricsVerifierTaskStep -from tst.unit.task_step.always_on_harness import Fail, Rig +from tst.unit.task_step.always_on_harness import Rig from tst.util import atif_runs from tst.util.config import install_model_config @@ -133,27 +133,6 @@ def fails(n, texts, rig): assert row["id"] == "prompt_error" and "agent_turn_timeout" in row["message"] -@pytest.mark.asyncio -async def test_a_tolerated_run_whose_turn_failed_for_an_infrastructure_reason_is_skipped_not_scored(monkeypatch, - tmp_path): - def fails(n, texts, rig): - return Fail("APIStatusError: 502 Bad Gateway", error_type="infra_error", error_code="psi.gateway") - - rig = Rig(monkeypatch, tmp_path, agent=fails) - await rig.arm() - ctx = rig.context() - with pytest.raises(AgentTurnInfraError): - await rig.run(rig.step(), ctx) - verifier = _verifier() - _capture(monkeypatch, verifier) - - await verifier.execute(ctx) - - entry = ctx.metadata["verifications"]["rubric"] - assert (entry["results"], entry["score"]) == ([], None) and "psi.gateway" in entry["skipped"] - assert ctx.metadata["grades"]["judge"]["verifier_status"] == "skipped" - - @pytest.mark.asyncio async def test_a_run_s_grade_up_to_turn_is_refused(monkeypatch, tmp_path): rig, ctx = await _run(monkeypatch, tmp_path) diff --git a/tst/unit/task_step/test_always_on_default_retry.py b/tst/unit/task_step/test_always_on_default_retry.py index c8d8b3907..95013c823 100644 --- a/tst/unit/task_step/test_always_on_default_retry.py +++ b/tst/unit/task_step/test_always_on_default_retry.py @@ -4,6 +4,7 @@ from __future__ import annotations from agent_env.task import Task +from agent_env.task.task import substitute_seed_in_steps from agent_env.task_step.task_step import RetryConfig from agent_env.task_step.task_steps import always_on as ao from agent_env.task_step.task_steps.deploy_env import DeployEnvTaskStep @@ -28,6 +29,12 @@ def test_the_default_is_not_written_into_the_stored_task_and_comes_back_on_load( assert Task.from_dict(stored).steps[1].retry_config == RetryConfig("env", max_retries=1) +def test_a_seeded_run_keeps_the_default(): + [_, seeded] = substitute_seed_in_steps(Task(id="t", version=None, steps=_steps()).steps, {"name": "Linda"}) + + assert seeded.retry_config == RetryConfig("env", max_retries=1) and seeded.retry_config.implied + + def test_a_tasks_own_retry_config_wins_and_is_stored(): task = Task(id="t", version=None, steps=_steps(retry_config={"retry_from_step_id": "week", "max_retries": 0})) diff --git a/tst/unit/task_step/verifiers/test_rubrics_verifier_infra_error.py b/tst/unit/task_step/verifiers/test_rubrics_verifier_infra_error.py deleted file mode 100644 index 619f36287..000000000 --- a/tst/unit/task_step/verifiers/test_rubrics_verifier_infra_error.py +++ /dev/null @@ -1,135 +0,0 @@ -"""A run whose agent turn failed for an infrastructure reason (``error_type`` infra_error) says nothing about the agent: -a rubrics verifier skips it, unscored, where any other failed turn is scored 0 unjudged, and an aggregate of such -sources is skipped too, so the run is unscored rather than scored below 1.""" -from __future__ import annotations - -import pytest - -from agent_env.bundle.run import Outcome, TaskRun -from agent_env.task import Task -from agent_env.task.result import recorded_scores -from agent_env.task_step.context import PromptResponse, TaskStepContext -from agent_env.task_step.task_steps.verifiers.aggregate_verifiers import AggregateVerifiersTaskStep -from agent_env.task_step.task_steps.verifiers.judge_utils.trajectory_filter import ( - CompactionType, - FrameStrategy, - TrajectoryFilter, -) -from agent_env.task_step.task_steps.verifiers.rubrics_verifier import RubricsVerifierTaskStep, trajectory_mistakes_key -from agent_env.task_step.task_steps.verifiers.verifier import GRADES_KEY, VerifierStatus - -CRITERIA = [{"id": "done", "description": "it is done"}] -REASON = "the run's turn failed for an infrastructure reason (error_code=psi.gateway), not the assistant's" - - -def _verifier(monkeypatch, step_id: str, **kw) -> RubricsVerifierTaskStep: - step = RubricsVerifierTaskStep(**{ - "id": step_id, "version": 1, "criteria": CRITERIA, "prompt_id": "p1", "use_agent_judge": False, - "use_trajectory": True, "verifier_id": step_id, **kw}) - - async def judge(**kwargs): - raise AssertionError("a run that failed for an infrastructure reason is never judged") - - monkeypatch.setattr(step, "_read_trajectory_text", lambda uri: "EVENTS") - monkeypatch.setattr(step, "_run_judge_with_output_retries", judge) - return step - - -def _context(error_type: str = "infra_error") -> TaskStepContext: - return TaskStepContext(prompt_responses=[PromptResponse( - prompt_id="p1", response="[Mon] on it", prompt_text="plan the trip", agent_trajectory_object_url="s3://t/1.json", - error_type=error_type, error_code="psi.gateway", error_message="APIStatusError: 502 Bad Gateway")]) - - -@pytest.mark.asyncio -async def test_an_infra_error_run_is_skipped_unscored_not_scored_0(monkeypatch): - ctx = _context() - - await _verifier(monkeypatch, "psi-trust").execute(ctx) - - grade = ctx.metadata[GRADES_KEY]["psi-trust"] - assert (grade["verifier_status"], grade["score"]) == (VerifierStatus.SKIPPED, None) - entry = ctx.metadata["verifications"]["psi-trust"] - assert (entry["results"], entry["score"], entry["skipped"]) == ([], None, REASON) - - -@pytest.mark.asyncio -async def test_an_agent_error_run_is_still_scored_0_unjudged(monkeypatch): - ctx = _context(error_type="agent_error") - - await _verifier(monkeypatch, "psi-trust").execute(ctx) - - [row] = ctx.metadata["verifications"]["psi-trust"]["results"] - assert (row["id"], ctx.metadata["verifications"]["psi-trust"]["score"]) == ("prompt_error", 0) - assert ctx.metadata[GRADES_KEY]["psi-trust"]["verifier_status"] == VerifierStatus.GRADED - - -@pytest.mark.asyncio -async def test_a_skip_does_not_fail_a_verifier_that_fails_its_task_when_not_passing(monkeypatch): - ctx = _context() - - await _verifier(monkeypatch, "psi-trust", fail_task_when_not_passing=True).execute(ctx) - - assert ctx.metadata[GRADES_KEY]["psi-trust"]["verifier_status"] == VerifierStatus.SKIPPED - - -@pytest.mark.asyncio -async def test_the_trajectory_mistakes_entry_is_skipped_too(monkeypatch): - ctx = _context() - - frames = TrajectoryFilter(compaction_type=CompactionType.SCREENSHOT, frame_strategy=FrameStrategy.PER_CRITERION) - await _verifier(monkeypatch, "psi-process", output_format="rubric_evidence_with_mistakes", - trajectory_filter=frames).execute(ctx) - - mistakes = ctx.metadata["verifications"][trajectory_mistakes_key("psi-process")] - assert (mistakes["results"], mistakes["score"], mistakes["skipped"]) == ([], None, REASON) - - -@pytest.mark.asyncio -async def test_a_verdict_over_sources_all_skipped_is_skipped_and_the_run_unscored(monkeypatch, local_stores): - trust, process = _verifier(monkeypatch, "psi-trust"), _verifier(monkeypatch, "psi-process") - verdict = AggregateVerifiersTaskStep(id="psi-verdict", version=None, sources=["psi-trust", "psi-process"], - score_aggregator="all_pass", depends_on=["psi-trust", "psi-process"]) - task = Task(id="t", version=None, steps=[trust, process, verdict]) - ctx = _context() - - await task.run(context=ctx) - - grade = ctx.metadata[GRADES_KEY]["psi-verdict"] - assert (grade["verifier_status"], grade["verifier_skip_reasoning"]) == (VerifierStatus.SKIPPED, - "every source it weighs was skipped") - assert recorded_scores(task.steps, ctx) == {} - assert TaskRun(None, task, ctx, None, 0.0).outcome is Outcome.UNSCORED - - -@pytest.mark.asyncio -async def test_a_verdict_over_verifier_ids_all_skipped_is_skipped_too(monkeypatch, local_stores): - trust, process = _verifier(monkeypatch, "psi-trust"), _verifier(monkeypatch, "psi-process") - verdict = AggregateVerifiersTaskStep(id="psi-verdict", version=None, verifier_ids=["psi-trust", "psi-process"], - score_aggregator="all_pass", depends_on=["psi-trust", "psi-process"]) - task = Task(id="t", version=None, steps=[trust, process, verdict]) - ctx = _context() - - await task.run(context=ctx) - - grade = ctx.metadata[GRADES_KEY]["psi-verdict"] - assert (grade["verifier_status"], grade["verifier_skip_reasoning"]) == (VerifierStatus.SKIPPED, - "every source it weighs was skipped") - assert recorded_scores(task.steps, ctx) == {} - assert TaskRun(None, task, ctx, None, 0.0).outcome is Outcome.UNSCORED - - -@pytest.mark.asyncio -async def test_a_verdict_over_verifier_ids_pools_the_sources_not_skipped(monkeypatch, local_stores): - trust = _verifier(monkeypatch, "psi-trust") - verdict = AggregateVerifiersTaskStep(id="psi-verdict", version=None, verifier_ids=["psi-trust", "psi-line"], - score_aggregator="all_pass", depends_on=["psi-trust"]) - task = Task(id="t", version=None, steps=[trust, verdict]) - ctx = _context() - ctx.metadata["verifications"] = {"psi-line": {"results": [{"id": "said_done", "score": 1.0, "result": True}], - "score": 1.0}} - - await task.run(context=ctx) - - grade = ctx.metadata[GRADES_KEY]["psi-verdict"] - assert (grade["verifier_status"], grade["score"]) == (VerifierStatus.GRADED, 1.0) From 85c551091cb538cb58deaa64b97126d4fae5d293 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Tue, 1 Dec 2026 12:18:11 -0800 Subject: [PATCH 06/19] feat(always_on): a failed wake ends only that wake, and the whole run is judged A turn that fails as the agent's own failure (error_type agent_error, or anything but infra_error) no longer ends the multi-day run. It is recorded (a turn_failed timeline event, and the record'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 wake, check or user message, the prompt response keeping no error_type. - Infra failures keep #933's behaviour: the run ends as agent_turn_infra_error and the step fails with AgentTurnInfraError. - FAILED_TURNS_IN_A_ROW_MAX (3) failed turns in a row end the run as agent_turn_failed, so a dead agent can't spin through every scheduled wake. A completed or cut-off turn starts the count again. - A turn agent-env gave up waiting on (agent_turn_timeout) still ends the run: no terminal state says it stopped, so a next wake would share its session and world with it. - A run that ended on its agent's own failure (AGENT_FAILURE_ENDS) is judged as a whole, not skipped: always_on_agent_verifier (via a rubrics_verifier hook), user_sim_judge, agent_prompt_response_verifier and rate_user_satisfaction. env_outcome never skipped. A run the user sim or the step broke is still scored 0 unjudged. - The record reports early ends per run: failed_turns, counts.failed_turns, counts.failed_turn_kinds (by error_code, else error_type) and reached_scheduled_end. The judge's wake-by-wake text and the staged index say which turn failed and whether the run went on. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/agents/AGENTS.md | 11 +- .../agent/rate_user_satisfaction.py | 10 +- .../task_step/task_steps/always_on.py | 156 ++++++++--- .../agent_prompt_response_verifier.py | 10 +- .../verifiers/always_on_agent_verifier.py | 14 +- .../task_steps/verifiers/always_on_staging.py | 8 +- .../task_steps/verifiers/rubrics_verifier.py | 9 +- .../task_steps/verifiers/user_sim_judge.py | 19 +- .../verifier_golden/rubrics_subclasses.json | 2 +- .../test_always_on_agent_verifier.py | 22 +- .../task_step/test_always_on_failed_turns.py | 263 ++++++++++++++++++ tst/unit/task_step/test_always_on_graded.py | 69 +++-- .../task_step/test_always_on_wake_limit.py | 52 ++-- .../task_step/test_user_sim_satisfaction.py | 29 +- .../test_rubrics_subclasses_golden.py | 8 +- .../verifiers/test_user_sim_judge.py | 34 ++- 16 files changed, 607 insertions(+), 109 deletions(-) create mode 100644 tst/unit/task_step/test_always_on_failed_turns.py 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..9b95a4470 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,21 @@ 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``. ``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 +80,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 +126,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,6 +226,22 @@ 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"} @@ -242,7 +268,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 +355,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 +549,8 @@ 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 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 @@ -1502,7 +1531,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 +1552,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 +1654,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 +1675,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 +1761,55 @@ 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.""" + 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) + 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 +2066,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 +2097,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 +2114,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 +2186,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 +2222,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 +2249,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 +2277,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..c8b8ca23c 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 @@ -46,7 +46,13 @@ from agent_env.providers.sandbox_providers.sandbox import into_container from agent_env.task_step.context import 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 +344,12 @@ 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 _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``.""" 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..658fcd979 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,7 +7,8 @@ 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 trajectory is matched to its wake by the timeline's ``trajectory_url``; one that's missing is a line saying so. A @@ -471,6 +472,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..1e01609b1 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,13 @@ 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 _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 +1135,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 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..942d12bb6 --- /dev/null +++ b/tst/unit/task_step/test_always_on_failed_turns.py @@ -0,0 +1,263 @@ +"""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 pytest + +from agent_env.task_step.context import AgentTurnInfraError +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 tst.unit.task_step.always_on_harness import Fail, Rig +from tst.unit.task_step.test_always_on_agent_verifier import _capture, _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 _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) + + +# ---- 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")] 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): From 5c7cf964d22bc49ea34a8a0ec953915db713a66c Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Tue, 1 Dec 2026 13:36:09 -0800 Subject: [PATCH 07/19] feat(always_on): the next wake tells the agent its last turn ended with an error After a failed turn the run went on from, the next wake opens with the step's own note (FAILED_TURN_TEXT), as it does after a cut-off (CUT_OFF_TEXT). It is the same for every harness and failure kind and never carries the error's text, which can name the infrastructure. It is recorded as the cut-off note is: failed_turn_notice on the wake event and the staged "woke" line, told_in_wake on the failed turn's entry, and the judge's index says it is the run's note, not the user's words. Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/always_on.py | 22 +++++- .../task_steps/verifiers/always_on_staging.py | 12 +++- .../task_step/test_always_on_failed_turns.py | 70 +++++++++++++++++++ 3 files changed, 99 insertions(+), 5 deletions(-) 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 9b95a4470..0deb0dff5 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -60,7 +60,9 @@ ``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``. ``FAILED_TURNS_IN_A_ROW_MAX`` failed turns in a row end the run (agent_turn_failed), as does a turn + ``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 @@ -247,6 +249,10 @@ 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 @@ -551,6 +557,7 @@ def __init__(self, step: AlwaysOnTaskStep, context: TaskStepContext): 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 @@ -1503,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")) @@ -1523,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) @@ -1776,11 +1789,14 @@ def _turn_failed(self, turn: str, error_type: str, error: str, error_code: Optio 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.""" + 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 ended the run (FAILED_TURNS_IN_A_ROW_MAX failed in a row, one timed out, or one failed for an 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 658fcd979..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 @@ -10,7 +10,8 @@ ``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`` @@ -77,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"}) @@ -209,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 "")) @@ -464,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})") diff --git a/tst/unit/task_step/test_always_on_failed_turns.py b/tst/unit/task_step/test_always_on_failed_turns.py index 942d12bb6..ed35049ca 100644 --- a/tst/unit/task_step/test_always_on_failed_turns.py +++ b/tst/unit/task_step/test_always_on_failed_turns.py @@ -5,6 +5,8 @@ from __future__ import annotations +import json + import pytest from agent_env.task_step.context import AgentTurnInfraError @@ -12,6 +14,7 @@ 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 _capture, _verifier @@ -129,6 +132,73 @@ def agent(n, texts, rig): 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 From bf8e40c60006fc2b40cb987af078c93db48cdf27 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Tue, 1 Dec 2026 14:49:07 -0800 Subject: [PATCH 08/19] fix(always_on): imply the default retry only when its rollback redoes every step the always_on step depends on Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task/task.py | 16 ++++++++++++++-- .../task_step/test_always_on_default_retry.py | 18 ++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/agent_env/task/task.py b/src/agent_env/task/task.py index 74baefb3b..f0447e06e 100644 --- a/src/agent_env/task/task.py +++ b/src/agent_env/task/task.py @@ -390,14 +390,26 @@ def __init__( @staticmethod def _imply_retries(steps: list[TaskStep]) -> None: """Give each step the task left without a ``retry_config`` the one its type implies - (``TaskStep.default_retry_config``). A step built without TaskStep, as some tests build one, has none.""" + (``TaskStep.default_retry_config``), when its rollback covers everything the step depends on: each of the step's + ancestors comes before the step it resumes from or after it, none beside it, which a rollback would leave as the + failed attempt left it. A step built without TaskStep, as some tests build one, has none.""" deps: dict[str, set[str]] | None = None for step in steps: if getattr(step, "retry_config", None) is not None or not hasattr(step, "default_retry_config"): continue deps = deps if deps is not None else _dependency_ids(steps) ancestors = _ancestor_ids(step.id, deps) - step.retry_config = step.default_retry_config([s for s in steps if s.id in ancestors]) + implied = step.default_retry_config([s for s in steps if s.id in ancestors]) + if implied is None: + continue + start = implied.retry_from_step_id + before = _ancestor_ids(start, deps) + beside = [a for a in ancestors - before - {start} if start not in _ancestor_ids(a, deps)] + if beside: + logger.info("%s: no default retry from %s, which doesn't redo %s; give it a retry_config", + step.id, start, ", ".join(sorted(beside))) + continue + step.retry_config = implied @staticmethod def _validate_headlines(headlines: list[str] | None, steps: list[TaskStep]) -> None: diff --git a/tst/unit/task_step/test_always_on_default_retry.py b/tst/unit/task_step/test_always_on_default_retry.py index 95013c823..9a892f5a0 100644 --- a/tst/unit/task_step/test_always_on_default_retry.py +++ b/tst/unit/task_step/test_always_on_default_retry.py @@ -48,6 +48,24 @@ def test_an_always_on_step_with_no_env_deploy_before_it_takes_none(): assert task.steps[0].retry_config is None +def test_no_default_when_a_step_it_depends_on_runs_beside_the_deploy_a_rollback_would_not_redo(): + steps = [DeployEnvTaskStep(id="env", version=None, env_id="mail", depends_on=[]), + DeployEnvTaskStep(id="env-b", version=None, env_id="shop", depends_on=[]), + ao.AlwaysOnTaskStep("week", None, depends_on=["env", "env-b"], user_sim="linda", prompt_id="ask", + agent_name="solver")] + + assert Task(id="t", version=None, steps=steps).steps[2].retry_config is None + + +def test_the_default_holds_when_every_step_it_depends_on_comes_after_the_deploy(): + steps = [DeployEnvTaskStep(id="env", version=None, env_id="mail", depends_on=[]), + DeployEnvTaskStep(id="env-b", version=None, env_id="shop", depends_on=["env"]), + ao.AlwaysOnTaskStep("week", None, depends_on=["env", "env-b"], user_sim="linda", prompt_id="ask", + agent_name="solver")] + + assert Task(id="t", version=None, steps=steps).steps[2].retry_config == RetryConfig("env", max_retries=1) + + def test_the_deploy_must_be_an_ancestor_not_just_an_earlier_step(): steps = [DeployEnvTaskStep(id="env", version=None, env_id="mail"), ao.AlwaysOnTaskStep("week", None, depends_on=[], user_sim="linda", prompt_id="ask", agent_name="solver")] From 1334eac5ac432dece7b202d84bde925e78b050b7 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Tue, 1 Dec 2026 14:56:33 -0800 Subject: [PATCH 09/19] fix(always_on): a judged run whose failed turns stored no trajectory reaches staging, never "No trajectory available" A turn agent-env gave up waiting on returns before its trajectory is read, so a run whose opening wake timed out stored none; with use_trajectory, rubrics_verifier then raised "No trajectory available" (and _compact_trajectory would again) instead of judging the run #981 now judges. The same held for a run its failed turns in a row ended, and for one that went on after failed turns (ended at its wake cap, no error on its response), whenever none stored one. rubrics_verifier gets a hook, _judges_without_trajectory (never in the base): when it says so, a run with no trajectory skips the guard and the single-file compaction and goes to stage_trajectory, refused still if nothing was staged. always_on_agent_verifier says so for a run with any failed turn of its agent's own; each such wake is staged from the run's record with a trajectory_missing line and named in the judge's prompt. A run that failed no turn and stored none is still refused. Staged by position (no timeline kept), the turn agent-env gave up waiting on, sent but with no per-turn trajectory entry, is now staged as a turn whose trajectory is missing instead of left out. Co-Authored-By: Claude Opus 5.5 --- .../verifiers/always_on_agent_verifier.py | 24 +++- .../task_steps/verifiers/rubrics_verifier.py | 14 +- .../task_step/test_always_on_failed_turns.py | 136 +++++++++++++++++- 3 files changed, 167 insertions(+), 7 deletions(-) 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 c8b8ca23c..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,7 +49,7 @@ 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, @@ -350,6 +355,15 @@ def _judges_failed_run(self, context: TaskStepContext, prompt_response: PromptRe 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``.""" @@ -612,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/rubrics_verifier.py b/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py index 1e01609b1..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 @@ -828,6 +828,13 @@ def _judges_failed_run(self, context: TaskStepContext, prompt_response: PromptRe 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.""" @@ -1147,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 @@ -1190,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, @@ -1256,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/tst/unit/task_step/test_always_on_failed_turns.py b/tst/unit/task_step/test_always_on_failed_turns.py index ed35049ca..1ab6a1439 100644 --- a/tst/unit/task_step/test_always_on_failed_turns.py +++ b/tst/unit/task_step/test_always_on_failed_turns.py @@ -6,17 +6,26 @@ from __future__ import annotations import json +from typing import Optional import pytest -from agent_env.task_step.context import AgentTurnInfraError +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 _capture, _verifier +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") @@ -73,6 +82,48 @@ async def _judged(monkeypatch, ctx) -> tuple[dict, str]: 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=[ @@ -331,3 +382,84 @@ def agent(n, texts, rig): 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 From fe36f38d5940f3738851db2c4ee93cd3bedb6471 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 10:48:41 -0800 Subject: [PATCH 10/19] fix(always_on): the default retry redoes only an infra-failed run The scheduler retried any failure a retry_config covered, so always_on's implied retry also redeployed and reran a run that failed on a config error or a broken user sim, which fails the same way again. RetryConfig.retry_on names the failures a retry redoes (raised as or from one of its types); always_on's default sets it to AgentTurnInfraError. A task's own retry_config, with no retry_on, still redoes any failure. Tests run the implied retry through the scheduler: an infra failure redeploys and reruns once, a second fails the task, and any other failure fails it without redeploying. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task/task.py | 2 +- src/agent_env/task_step/task_step.py | 14 ++++ .../task_step/task_steps/always_on.py | 7 +- .../task_step/test_always_on_default_retry.py | 82 +++++++++++++++++++ 4 files changed, 102 insertions(+), 3 deletions(-) diff --git a/src/agent_env/task/task.py b/src/agent_env/task/task.py index f0447e06e..5fece60a9 100644 --- a/src/agent_env/task/task.py +++ b/src/agent_env/task/task.py @@ -817,7 +817,7 @@ async def _drain_in_flight() -> set[str]: continue retry_cfg = getattr(step_obj, "retry_config", None) if (retry_cfg is not None and retry_counts.get(step_id, 0) < retry_cfg.max_retries - and not isinstance(exc, VerifierNotPassingError)): + and not isinstance(exc, VerifierNotPassingError) and retry_cfg.redoes(exc)): retryable.append((step_obj, retry_cfg, exc)) continue if not getattr(step_obj, "fail_task_on_error", True): diff --git a/src/agent_env/task_step/task_step.py b/src/agent_env/task_step/task_step.py index be3f32400..d2773e861 100644 --- a/src/agent_env/task_step/task_step.py +++ b/src/agent_env/task_step/task_step.py @@ -79,6 +79,20 @@ class RetryConfig: max_retries: int = 1 # A step type's own default (``TaskStep.default_retry_config``), never written into the stored task. implied: bool = dataclasses.field(default=False, compare=False) + # The failures it redoes, each raised as or from one of these types; None, a task's own, redoes any. A default + # names the failures it was made for, so one that would happen again isn't paid for twice. + retry_on: tuple[type[BaseException], ...] | None = dataclasses.field(default=None, compare=False) + + def redoes(self, exc: BaseException) -> bool: + """Whether a step that failed with ``exc`` is retried: any failure, or one ``retry_on`` names.""" + if self.retry_on is None: + return True + cause: BaseException | None = exc + while cause is not None: + if isinstance(cause, self.retry_on): + return True + cause = cause.__cause__ + return False def to_dict(self) -> dict[str, Any]: return {"retry_from_step_id": self.retry_from_step_id, "max_retries": self.max_retries} 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..ad00e3be8 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -425,9 +425,12 @@ def from_dict(cls, data: dict) -> AlwaysOnTaskStep: def default_retry_config(self, ancestors: list[TaskStep]) -> Optional[RetryConfig]: """A turn that failed for an infrastructure reason (``AgentTurnInfraError``), or an attempt a dead worker lost, - is redone once on a fresh world, from the first env deploy before this step; never in the world it changed.""" + is redone once on a fresh world, from the first env deploy before this step; never in the world it changed. Any + other failure, as a config error or a broken user sim, would fail again, so it isn't redone.""" deploy = next((s for s in ancestors if s.type == "deploy_env"), None) - return RetryConfig(deploy.id, max_retries=1, implied=True) if deploy is not None else None + if deploy is None: + return None + return RetryConfig(deploy.id, max_retries=1, implied=True, retry_on=(AgentTurnInfraError,)) def task_problems(self, steps: list[TaskStep]) -> list[str]: """Its prompt is graded by always_on_agent_verifier: a plain rubrics_verifier, which would grade it from every diff --git a/tst/unit/task_step/test_always_on_default_retry.py b/tst/unit/task_step/test_always_on_default_retry.py index 9a892f5a0..e956b5992 100644 --- a/tst/unit/task_step/test_always_on_default_retry.py +++ b/tst/unit/task_step/test_always_on_default_retry.py @@ -3,11 +3,16 @@ the step type's, never written into the stored task; a task's own ``retry_config`` wins.""" from __future__ import annotations +import pytest + from agent_env.task import Task +from agent_env.task.store import set_task_instance_store from agent_env.task.task import substitute_seed_in_steps +from agent_env.task_step.context import AgentTurnInfraError, TaskStepContext from agent_env.task_step.task_step import RetryConfig from agent_env.task_step.task_steps import always_on as ao from agent_env.task_step.task_steps.deploy_env import DeployEnvTaskStep +from tst.unit.task_step.retry_test import _FakeDeployEnv, _FlakyPrompt, _sqlite_store def _steps(**settings): @@ -71,3 +76,80 @@ def test_the_deploy_must_be_an_ancestor_not_just_an_earlier_step(): ao.AlwaysOnTaskStep("week", None, depends_on=[], user_sim="linda", prompt_id="ask", agent_name="solver")] assert Task(id="t", version=None, steps=steps).steps[1].retry_config is None + + +def test_the_default_redoes_only_an_infra_failure_however_it_was_raised(): + implied = Task(id="t", version=None, steps=_steps()).steps[1].retry_config + + def raised_from(cause: BaseException) -> RuntimeError: + try: + raise RuntimeError("step failed") from cause + except RuntimeError as exc: + return exc + + assert implied.redoes(AgentTurnInfraError("gateway 502")) + assert implied.redoes(raised_from(AgentTurnInfraError("gateway 502"))) + assert not implied.redoes(RuntimeError("user sim plugin: TypeError")) + assert not implied.redoes(ValueError("always_on: no opening_prompt")) + assert RetryConfig("week").redoes(ValueError("a task's own retry redoes any failure")) + + +class _AlwaysOnLike(_FlakyPrompt): + """A step that takes always_on's default retry and fails its first attempts with ``error``.""" + + type = ao.AlwaysOnTaskStep.type + default_retry_config = ao.AlwaysOnTaskStep.default_retry_config + + def __init__(self, id: str, error: BaseException, fail_times: int = 1): + super().__init__(id, fail_times=fail_times) + self._error = error + + async def execute(self, context: TaskStepContext) -> TaskStepContext: + try: + return await super().execute(context) + except RuntimeError: + raise self._error from None + + +@pytest.fixture +def store(tmp_path): + set_task_instance_store(store := _sqlite_store(tmp_path)) + try: + yield store + finally: + set_task_instance_store(None) + + +@pytest.mark.asyncio +async def test_an_infra_failed_run_is_redone_once_from_the_env_deploy(store): + deploy, week = _FakeDeployEnv("env"), _AlwaysOnLike("week", AgentTurnInfraError("gateway 502")) + + result = await Task(id="t", version=1, steps=[deploy, week]).run(context=TaskStepContext()) + + assert deploy.deploy_calls == ["env", "env"] + assert week.attempts == 2 + assert [p.response for p in result.prompt_responses] == ["attempt-2"] + + +@pytest.mark.asyncio +async def test_a_second_infra_failure_fails_the_task(store): + deploy, week = _FakeDeployEnv("env"), _AlwaysOnLike("week", AgentTurnInfraError("gateway 502"), fail_times=2) + + with pytest.raises(AgentTurnInfraError): + await Task(id="t", version=1, steps=[deploy, week]).run(context=(ctx := TaskStepContext())) + + assert deploy.deploy_calls == ["env", "env"] + assert week.attempts == 2 + assert store.get(ctx.instance_id).status == "failed" + + +@pytest.mark.asyncio +async def test_a_failure_that_isnt_infra_fails_the_task_without_redeploying(store): + deploy, week = _FakeDeployEnv("env"), _AlwaysOnLike("week", TypeError("user sim plugin broke")) + + with pytest.raises(TypeError): + await Task(id="t", version=1, steps=[deploy, week]).run(context=(ctx := TaskStepContext())) + + assert deploy.deploy_calls == ["env"] + assert week.attempts == 1 + assert store.get(ctx.instance_id).status == "failed" From 1f220a670ee22bfe9d6a9eeb4a7e3f83a4b79b1f Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 11:05:08 -0800 Subject: [PATCH 11/19] revert: the default retry redoes only an infra-failed run Reverts fe36f38d. The hub's run-task workflow decides its own rollbacks and doesn't read RetryConfig.retry_on, so the filter held only in Task.run and local runs and the hub would redo different failures. Until the hub honours it too, always_on's default retry redoes a failed run on both the same way. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task/task.py | 2 +- src/agent_env/task_step/task_step.py | 14 ---- .../task_step/task_steps/always_on.py | 7 +- .../task_step/test_always_on_default_retry.py | 82 ------------------- 4 files changed, 3 insertions(+), 102 deletions(-) diff --git a/src/agent_env/task/task.py b/src/agent_env/task/task.py index 5fece60a9..f0447e06e 100644 --- a/src/agent_env/task/task.py +++ b/src/agent_env/task/task.py @@ -817,7 +817,7 @@ async def _drain_in_flight() -> set[str]: continue retry_cfg = getattr(step_obj, "retry_config", None) if (retry_cfg is not None and retry_counts.get(step_id, 0) < retry_cfg.max_retries - and not isinstance(exc, VerifierNotPassingError) and retry_cfg.redoes(exc)): + and not isinstance(exc, VerifierNotPassingError)): retryable.append((step_obj, retry_cfg, exc)) continue if not getattr(step_obj, "fail_task_on_error", True): diff --git a/src/agent_env/task_step/task_step.py b/src/agent_env/task_step/task_step.py index d2773e861..be3f32400 100644 --- a/src/agent_env/task_step/task_step.py +++ b/src/agent_env/task_step/task_step.py @@ -79,20 +79,6 @@ class RetryConfig: max_retries: int = 1 # A step type's own default (``TaskStep.default_retry_config``), never written into the stored task. implied: bool = dataclasses.field(default=False, compare=False) - # The failures it redoes, each raised as or from one of these types; None, a task's own, redoes any. A default - # names the failures it was made for, so one that would happen again isn't paid for twice. - retry_on: tuple[type[BaseException], ...] | None = dataclasses.field(default=None, compare=False) - - def redoes(self, exc: BaseException) -> bool: - """Whether a step that failed with ``exc`` is retried: any failure, or one ``retry_on`` names.""" - if self.retry_on is None: - return True - cause: BaseException | None = exc - while cause is not None: - if isinstance(cause, self.retry_on): - return True - cause = cause.__cause__ - return False def to_dict(self) -> dict[str, Any]: return {"retry_from_step_id": self.retry_from_step_id, "max_retries": self.max_retries} 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 ad00e3be8..56d162726 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -425,12 +425,9 @@ def from_dict(cls, data: dict) -> AlwaysOnTaskStep: def default_retry_config(self, ancestors: list[TaskStep]) -> Optional[RetryConfig]: """A turn that failed for an infrastructure reason (``AgentTurnInfraError``), or an attempt a dead worker lost, - is redone once on a fresh world, from the first env deploy before this step; never in the world it changed. Any - other failure, as a config error or a broken user sim, would fail again, so it isn't redone.""" + is redone once on a fresh world, from the first env deploy before this step; never in the world it changed.""" deploy = next((s for s in ancestors if s.type == "deploy_env"), None) - if deploy is None: - return None - return RetryConfig(deploy.id, max_retries=1, implied=True, retry_on=(AgentTurnInfraError,)) + return RetryConfig(deploy.id, max_retries=1, implied=True) if deploy is not None else None def task_problems(self, steps: list[TaskStep]) -> list[str]: """Its prompt is graded by always_on_agent_verifier: a plain rubrics_verifier, which would grade it from every diff --git a/tst/unit/task_step/test_always_on_default_retry.py b/tst/unit/task_step/test_always_on_default_retry.py index e956b5992..9a892f5a0 100644 --- a/tst/unit/task_step/test_always_on_default_retry.py +++ b/tst/unit/task_step/test_always_on_default_retry.py @@ -3,16 +3,11 @@ the step type's, never written into the stored task; a task's own ``retry_config`` wins.""" from __future__ import annotations -import pytest - from agent_env.task import Task -from agent_env.task.store import set_task_instance_store from agent_env.task.task import substitute_seed_in_steps -from agent_env.task_step.context import AgentTurnInfraError, TaskStepContext from agent_env.task_step.task_step import RetryConfig from agent_env.task_step.task_steps import always_on as ao from agent_env.task_step.task_steps.deploy_env import DeployEnvTaskStep -from tst.unit.task_step.retry_test import _FakeDeployEnv, _FlakyPrompt, _sqlite_store def _steps(**settings): @@ -76,80 +71,3 @@ def test_the_deploy_must_be_an_ancestor_not_just_an_earlier_step(): ao.AlwaysOnTaskStep("week", None, depends_on=[], user_sim="linda", prompt_id="ask", agent_name="solver")] assert Task(id="t", version=None, steps=steps).steps[1].retry_config is None - - -def test_the_default_redoes_only_an_infra_failure_however_it_was_raised(): - implied = Task(id="t", version=None, steps=_steps()).steps[1].retry_config - - def raised_from(cause: BaseException) -> RuntimeError: - try: - raise RuntimeError("step failed") from cause - except RuntimeError as exc: - return exc - - assert implied.redoes(AgentTurnInfraError("gateway 502")) - assert implied.redoes(raised_from(AgentTurnInfraError("gateway 502"))) - assert not implied.redoes(RuntimeError("user sim plugin: TypeError")) - assert not implied.redoes(ValueError("always_on: no opening_prompt")) - assert RetryConfig("week").redoes(ValueError("a task's own retry redoes any failure")) - - -class _AlwaysOnLike(_FlakyPrompt): - """A step that takes always_on's default retry and fails its first attempts with ``error``.""" - - type = ao.AlwaysOnTaskStep.type - default_retry_config = ao.AlwaysOnTaskStep.default_retry_config - - def __init__(self, id: str, error: BaseException, fail_times: int = 1): - super().__init__(id, fail_times=fail_times) - self._error = error - - async def execute(self, context: TaskStepContext) -> TaskStepContext: - try: - return await super().execute(context) - except RuntimeError: - raise self._error from None - - -@pytest.fixture -def store(tmp_path): - set_task_instance_store(store := _sqlite_store(tmp_path)) - try: - yield store - finally: - set_task_instance_store(None) - - -@pytest.mark.asyncio -async def test_an_infra_failed_run_is_redone_once_from_the_env_deploy(store): - deploy, week = _FakeDeployEnv("env"), _AlwaysOnLike("week", AgentTurnInfraError("gateway 502")) - - result = await Task(id="t", version=1, steps=[deploy, week]).run(context=TaskStepContext()) - - assert deploy.deploy_calls == ["env", "env"] - assert week.attempts == 2 - assert [p.response for p in result.prompt_responses] == ["attempt-2"] - - -@pytest.mark.asyncio -async def test_a_second_infra_failure_fails_the_task(store): - deploy, week = _FakeDeployEnv("env"), _AlwaysOnLike("week", AgentTurnInfraError("gateway 502"), fail_times=2) - - with pytest.raises(AgentTurnInfraError): - await Task(id="t", version=1, steps=[deploy, week]).run(context=(ctx := TaskStepContext())) - - assert deploy.deploy_calls == ["env", "env"] - assert week.attempts == 2 - assert store.get(ctx.instance_id).status == "failed" - - -@pytest.mark.asyncio -async def test_a_failure_that_isnt_infra_fails_the_task_without_redeploying(store): - deploy, week = _FakeDeployEnv("env"), _AlwaysOnLike("week", TypeError("user sim plugin broke")) - - with pytest.raises(TypeError): - await Task(id="t", version=1, steps=[deploy, week]).run(context=(ctx := TaskStepContext())) - - assert deploy.deploy_calls == ["env"] - assert week.attempts == 1 - assert store.get(ctx.instance_id).status == "failed" From b833d418be2d511ce030d08d463d2a274a7c12e2 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 11:31:16 -0800 Subject: [PATCH 12/19] fix(always_on): a verifier leaves an infra-failed always_on run ungraded, never scores it 0 With #933's head, an always_on run that ended on an infrastructure failure and reached its verifiers (the task's fail_task_on_error off) was scored 0 with a prompt_error row, against the model. The always_on judge and the response check now skip it (ended_on_infra_failure, read from the run's record). A prompt_agent turn's infra_error still scores 0 unjudged, as on main, so no other task's score moves. rubrics_verifier's gate lets a skip through when fail_task_when_not_passing is on. Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/always_on.py | 12 ++++++++- .../agent_prompt_response_verifier.py | 13 ++++++++++ .../verifiers/always_on_agent_verifier.py | 10 ++++++++ .../task_steps/verifiers/rubrics_verifier.py | 19 +++++++++++++- .../task_step/test_always_on_failed_turns.py | 25 +++++++++++++++++++ ...ics_verifier_fail_task_when_not_passing.py | 15 +++++++++++ 6 files changed, 92 insertions(+), 2 deletions(-) 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 0deb0dff5..a641991f5 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -71,7 +71,9 @@ ``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. + 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 @@ -2211,6 +2213,14 @@ def ended_on_agent_failure(metadata: dict, step_id: Optional[str]) -> bool: return isinstance(record, dict) and record.get("end_reason") in AGENT_FAILURE_ENDS +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.""" 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 cebd74291..fa53aa9b2 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,6 +88,11 @@ 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 _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) 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}" @@ -191,3 +196,11 @@ def _ended_on_agent_failure(context: TaskStepContext, step_id: Optional[str]) -> 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 _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, as above.""" + 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/always_on_agent_verifier.py b/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py index 740d521d4..0329b031e 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 @@ -55,6 +55,7 @@ ALWAYS_ON_KEY, AlwaysOnTaskStep, ended_on_agent_failure, + ended_on_infra_failure, render_for_judge, stored_timeline, ) @@ -349,6 +350,15 @@ 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. 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 59f524d4c..979cdebc7 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,19 @@ 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 @@ -1062,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] @@ -1128,6 +1142,9 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: ) stored_response, prompt_response = prompt_response, as_of + 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}") diff --git a/tst/unit/task_step/test_always_on_failed_turns.py b/tst/unit/task_step/test_always_on_failed_turns.py index 1ab6a1439..baa358de2 100644 --- a/tst/unit/task_step/test_always_on_failed_turns.py +++ b/tst/unit/task_step/test_always_on_failed_turns.py @@ -272,8 +272,33 @@ async def test_an_infra_error_turn_still_ends_the_run_and_fails_the_step_ungrade [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 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() From 38c43db4d5873bf763176c0a036d2a83b2462ba6 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 11:32:07 -0800 Subject: [PATCH 13/19] fix(always_on): harness v14's turn cap is a cut-off at the tool-call limit With continue_after_wake_limit on, _limit_reached knew only Claude Code's words for the tool-call limit, so the PSI neutral harness's turn cap (v14: error_code psi.turn_cap, the Agents SDK's "Max turns (N) exceeded") was a failed turn, counted towards FAILED_TURNS_IN_A_ROW_MAX and told with FAILED_TURN_TEXT. Either the code or the words now cut the wake off at the tool-call limit. Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/always_on.py | 12 ++++++---- .../task_step/test_always_on_wake_limit.py | 24 +++++++++++++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) 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 a641991f5..31bcd5dad 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -256,10 +256,12 @@ 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. @@ -907,7 +909,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 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 2753556f9..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): From 2e09297633988e886d7a3d406c7bcd28f2ad3c2a Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 11:32:29 -0800 Subject: [PATCH 14/19] fix(always_on_agent_verifier): re-grading a run recorded before failed_turns existed doesn't raise A run recorded before #981 has no failed_turns, so _judges_without_trajectory found none and a use_trajectory judge raised "No trajectory available" for a run that ended on a turn agent-env gave up waiting on, where it used to write a prompt_error row. A run whose end is one of AGENT_FAILURE_ENDS failed a turn whatever its record lists, so it is judged. Co-Authored-By: Claude Opus 5.5 --- .../verifiers/always_on_agent_verifier.py | 6 +++++- tst/unit/task_step/test_always_on_failed_turns.py | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) 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 0329b031e..c0b76342c 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 @@ -370,7 +370,11 @@ def _judges_without_trajectory(self, context: TaskStepContext, prompt_response: 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.""" + failed no turn and stored none is refused, as rubrics_verifier refuses it: nothing explains the gap. A run that + ended on its agent's own failure failed a turn whatever its record lists, so one recorded before the record + kept ``failed_turns`` is judged too when re-graded.""" + if ended_on_agent_failure(context.metadata, prompt_response.step_id): + return True 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 []) diff --git a/tst/unit/task_step/test_always_on_failed_turns.py b/tst/unit/task_step/test_always_on_failed_turns.py index baa358de2..ce3a36ddf 100644 --- a/tst/unit/task_step/test_always_on_failed_turns.py +++ b/tst/unit/task_step/test_always_on_failed_turns.py @@ -429,6 +429,21 @@ async def test_an_opening_wake_agent_env_gave_up_waiting_on_is_judged_with_use_t 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): From 6c7cb2b129ea5b3e867159613cd90e9d4c920d86 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 11:52:18 -0800 Subject: [PATCH 15/19] fix(aggregate_verifiers): an always_on run's aggregate of skipped judges is skipped, not 0 An infra-failed always_on run is left ungraded by its judges, but a verifier_ids aggregate over them pooled no rows and scored 0, so PSI's psi_verdict and rubric_satisfaction still counted the failure against the model. In a run of an always_on step, an aggregate whose every source was skipped is skipped too, naming each source and its reason; one with some skipped pools the rest and lists the others in skipped_sources. A run with no always_on step (prompt_agent) pools as on main. Tests use the PSI task's own verifiers and aggregates (tst/data/psi_always_on_verifiers.json, its criteria cut to placeholder rows). Co-Authored-By: Claude Opus 5.5 --- .../verifiers/aggregate_verifiers.py | 24 ++- tst/data/psi_always_on_verifiers.json | 204 ++++++++++++++++++ .../test_always_on_psi_aggregates.py | 110 ++++++++++ 3 files changed, 336 insertions(+), 2 deletions(-) create mode 100644 tst/data/psi_always_on_verifiers.json create mode 100644 tst/unit/task_step/test_always_on_psi_aggregates.py 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..776506252 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 @@ -206,6 +209,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 +229,14 @@ 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``).""" + from agent_env.task_step.task_steps.always_on import ALWAYS_ON_KEY # here: always_on imports the verifiers + + return bool(context.metadata.get(ALWAYS_ON_KEY)) def legacy_entry_writers(steps: Sequence[TaskStep]) -> dict[str, str]: 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/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 From e1747cd56cb118b4646eb7019a45b25b2406a4d0 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 14:02:42 -0800 Subject: [PATCH 16/19] fix(always_on): judge a run with no trajectories only when every turn failed; one place for how a run ended Review findings on #981: - always_on_agent_verifier._judges_without_trajectory let a run that stored no trajectory at all be judged whenever any turn failed, or whenever the run ended on its agent's own failure. A run with turns that ran and lost their trajectories to a config or extension problem, plus one failed wake, was judged with every wake's tool calls missing instead of refused and redone. It is now judged so only when every turn, each wake's and each nudge's, is a recorded failed turn. A record from before failed_turns existed counts its ending turn as its one failed turn. - ALWAYS_ON_KEY, AGENT_FAILURE_ENDS and ended_on_agent_failure move to a leaf module, always_on_ends, which the verifiers, aggregate_verifiers and rate_user_satisfaction import at module level. This replaces the lazy-import wrappers in agent_prompt_response_verifier and user_sim_judge, user_sim_judge's copy of the key, aggregate_verifiers' lazy import and rate_user_satisfaction's inline check. - The staged index gave a failed wake turn two error lines (turn_end's "its turn ended failed" and turn_failed's). A wake with a turn_failed line now gets only that one. A run without one (by position, or recorded before turn_failed existed) keeps turn_end's. - _stopped_turn's docstring no longer says any other failure ends the run. - _cut_off uses the same error-message cap as a failed turn (TURN_ERROR_CHARS, was FAILED_TURN_ERROR_CHARS), not a literal 300. - _failure is renamed _record_failed_turn. - Golden cases: the always_on judge on runs that ended on agent_turn_timeout and agent_turn_failed, and user_sim_judge on one that ended on agent_turn_failed. Co-Authored-By: Claude Opus 5.5 --- .../agent/rate_user_satisfaction.py | 5 +- .../task_step/task_steps/always_on.py | 36 +-- .../task_step/task_steps/always_on_ends.py | 25 ++ .../agent_prompt_response_verifier.py | 15 +- .../verifiers/aggregate_verifiers.py | 3 +- .../verifiers/always_on_agent_verifier.py | 36 ++- .../task_steps/verifiers/always_on_staging.py | 4 +- .../task_steps/verifiers/rubrics_verifier.py | 2 +- .../task_steps/verifiers/user_sim_judge.py | 15 +- .../verifier_golden/rubrics_subclasses.json | 260 ++++++++++++++++++ .../task_step/test_always_on_failed_turns.py | 38 +++ .../test_rubrics_subclasses_golden.py | 43 +++ 12 files changed, 416 insertions(+), 66 deletions(-) create mode 100644 src/agent_env/task_step/task_steps/always_on_ends.py 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 c38346b18..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 @@ -61,14 +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 ( - AGENT_FAILURE_ENDS, - 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 @@ -350,7 +349,7 @@ 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 and record["end_reason"] not in AGENT_FAILURE_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 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 31bcd5dad..c6b919f34 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -182,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") @@ -230,9 +230,6 @@ 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 @@ -244,8 +241,8 @@ # 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 +# 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"} @@ -895,7 +892,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 @@ -918,7 +916,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) @@ -1782,21 +1780,22 @@ def _turn_failed(self, turn: str, error_type: str, error: str, error_code: Optio """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.""" + 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._failure(turn, error_type, error, error_code, went_on=went_on) + 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 _failure(self, turn: str, error_type: str, error: str, error_code: Optional[str], *, went_on: bool) -> None: + 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 "")[:FAILED_TURN_ERROR_CHARS], "went_on": went_on} + "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: @@ -1823,12 +1822,12 @@ def _no_answer(self, error: TimeoutError, turn: str) -> str: label = "agent nudge turn" if turn == "nudge" else "agent turn" if isinstance(error, protocol.AgentUnreachableError): message = f"{label}: {error}" - self._failure(turn, INFRA_ERROR, message, AGENT_UNREACHABLE_CODE, went_on=False) + self._record_failed_turn(turn, INFRA_ERROR, message, AGENT_UNREACHABLE_CODE, went_on=False) self._failed(INFRA_ERROR, message, AGENT_UNREACHABLE_CODE) return "unreachable" 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._record_failed_turn(turn, "agent_turn_timeout", message, None, went_on=False) self._failed("agent_turn_timeout", message) return "timeout" @@ -2206,15 +2205,6 @@ 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 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 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 fa53aa9b2..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 @@ -93,7 +94,9 @@ async def verify(self, context: TaskStepContext) -> Verification: "not the assistant's") logger.warning(f"Not checking '{self.verifier_id}': {reason}") return Verification(skipped=reason) - if prompt_response.error_type and not _ended_on_agent_failure(context, prompt_response.step_id): + # 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}" ) @@ -190,17 +193,9 @@ def _criterion_problems(criterion: Any) -> list[str]: 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) - - 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, as above.""" + (``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 776506252..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 @@ -23,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 ( @@ -234,8 +235,6 @@ def _pooled_entries(self, context: TaskStepContext) -> Verification: 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``).""" - from agent_env.task_step.task_steps.always_on import ALWAYS_ON_KEY # here: always_on imports the verifiers - return bool(context.metadata.get(ALWAYS_ON_KEY)) 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 c0b76342c..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 @@ -17,8 +17,8 @@ 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. +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 @@ -52,13 +52,12 @@ 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, - ended_on_agent_failure, 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, @@ -366,17 +365,24 @@ def _judges_failed_run(self, context: TaskStepContext, prompt_response: PromptRe 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. A run that - ended on its agent's own failure failed a turn whatever its record lists, so one recorded before the record - kept ``failed_turns`` is judged too when re-graded.""" - if ended_on_agent_failure(context.metadata, prompt_response.step_id): - return True - 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 []) + """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 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 7dec7beff..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 @@ -445,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")) @@ -478,7 +480,7 @@ def _index_block(w: _Wake, path: str, lines: list[dict], by_changes: bool, run_c 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" 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 979cdebc7..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 @@ -837,7 +837,7 @@ def _judges_without_trajectory(self, context: TaskStepContext, prompt_response: """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).""" + 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: 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 3696cf46e..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 @@ -173,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 @@ -182,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" @@ -359,7 +359,7 @@ def from_dict(cls, data: dict) -> "UserSimJudge": 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) + 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 @@ -379,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 and not _ended_on_agent_failure(context, step_id): + 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" @@ -685,13 +685,6 @@ 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 d03e980be..9249422df 100644 --- a/tst/data/verifier_golden/rubrics_subclasses.json +++ b/tst/data/verifier_golden/rubrics_subclasses.json @@ -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_failed_turns.py b/tst/unit/task_step/test_always_on_failed_turns.py index ce3a36ddf..09a70be97 100644 --- a/tst/unit/task_step/test_always_on_failed_turns.py +++ b/tst/unit/task_step/test_always_on_failed_turns.py @@ -482,6 +482,44 @@ async def test_a_run_that_failed_no_turn_and_stored_no_trajectory_is_still_refus 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): 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 9f766b233..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 @@ -142,6 +144,47 @@ async def test_an_always_on_prompt_error_the_gate_fails_leaves_the_entry_its_gol 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): From 91ae270e393f31c73480dbc34998ee2b54df6e23 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 14:33:44 -0800 Subject: [PATCH 17/19] fix(always_on): episodes take no default retry; a task works out its own default; test the retry end to end - Task(implied_retries=False) and Task.retry_config_of: an episode's copy runs no step type's default retry, so episode/rules no longer refuses an always_on task for a retry_config its author never wrote. A retry the author wrote is still refused. The default stays on the step, where the hub worker reads it. - _imply_retries works a default out again for each task built from the same step objects, instead of keeping the one an earlier task's graph gave. - Scheduler tests: a failed run is redeployed and run again once, whatever failed it; a second failure fails the task; a task that takes no default fails without redeploying. - Docs say a failed run is redone once, whatever failed it. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/agents/AGENTS.md | 4 +- src/agent_env/task/episode/rules.py | 3 +- src/agent_env/task/episode/spec.py | 3 +- src/agent_env/task/task.py | 42 ++++++--- .../task_step/task_steps/always_on.py | 5 +- tst/unit/task/episode/spec_test.py | 27 ++++++ .../task_step/test_always_on_default_retry.py | 92 ++++++++++++++++++- 7 files changed, 153 insertions(+), 23 deletions(-) diff --git a/src/agent_env/agents/AGENTS.md b/src/agent_env/agents/AGENTS.md index 406063219..0cb1cf092 100644 --- a/src/agent_env/agents/AGENTS.md +++ b/src/agent_env/agents/AGENTS.md @@ -71,8 +71,8 @@ terminal state, `completed`, `failed` or `canceled`. Your `run()` is one turn. 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 + (`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`. - **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 diff --git a/src/agent_env/task/episode/rules.py b/src/agent_env/task/episode/rules.py index d13328f9d..369db27b5 100644 --- a/src/agent_env/task/episode/rules.py +++ b/src/agent_env/task/episode/rules.py @@ -42,7 +42,8 @@ def problems(steps: list[TaskStep], outside: list[str]) -> list[str]: step.id: step.prompt_id for step in steps if step.type == "prompt_agent" and step.agent_name in outside }) for step in steps: - why = ["retry_config can replay an outside turn"] if step.retry_config is not None else [] + retry = step.retry_config + why = ["retry_config can replay an outside turn"] if retry is not None and not retry.implied else [] if check := CHECKS.get(step.type): why += check(step, scope) found.extend(f"step {step.id!r}: {reason}" for reason in why) diff --git a/src/agent_env/task/episode/spec.py b/src/agent_env/task/episode/spec.py index fefa9269e..070925d7c 100644 --- a/src/agent_env/task/episode/spec.py +++ b/src/agent_env/task/episode/spec.py @@ -38,7 +38,8 @@ def from_task( raise EpisodeError(f"task {task.id!r} can't run as an episode: " + "; ".join(found)) sandboxed = {name: works_in_sandbox(seeded, name) for name in outside} steps = [_in_episode(step, as_run, sandboxed, turn_timeout) for step, as_run in zip(task.steps, seeded)] - copy = Task(id=task.id, version=task.version, steps=steps, headline_verifiers=task.headline_verifiers) + copy = Task(id=task.id, version=task.version, steps=steps, headline_verifiers=task.headline_verifiers, + implied_retries=False) return cls(copy=copy, trainer_agents=tuple(outside), seed=seed) @property diff --git a/src/agent_env/task/task.py b/src/agent_env/task/task.py index f0447e06e..a1ed4c844 100644 --- a/src/agent_env/task/task.py +++ b/src/agent_env/task/task.py @@ -375,9 +375,14 @@ def __init__( requires: Sequence[str] | None = None, entity_ids: Mapping[str, str] | None = None, headline_verifiers: Sequence[str] | None = None, + *, + implied_retries: bool = True, ): self.id = id self.version = version + # False for a run that takes no step type's default retry (``retry_config_of``), as an episode's copy, whose + # steps a rollback could replay an outside player's turn in. + self.implied_retries = implied_retries self.steps: list[TaskStep] = steps or [] self.requires: list[str] | None = list(requires) if requires is not None else None self.entity_ids: dict[str, str] | None = dict(entity_ids) if entity_ids else None @@ -385,30 +390,39 @@ def __init__( self._validate_dag(self.steps) self._validate_pairings(self.steps) self._validate_headlines(self.headline_verifiers, self.steps) - self._imply_retries(self.steps) + if implied_retries: + self._imply_retries(self.steps) + + def retry_config_of(self, step: TaskStep) -> Optional[RetryConfig]: + """The retry this task runs ``step`` with: its own ``retry_config``, or its type's default unless this task + takes none (``implied_retries``).""" + retry_config = getattr(step, "retry_config", None) + if retry_config is not None and retry_config.implied and not self.implied_retries: + return None + return retry_config @staticmethod def _imply_retries(steps: list[TaskStep]) -> None: """Give each step the task left without a ``retry_config`` the one its type implies (``TaskStep.default_retry_config``), when its rollback covers everything the step depends on: each of the step's ancestors comes before the step it resumes from or after it, none beside it, which a rollback would leave as the - failed attempt left it. A step built without TaskStep, as some tests build one, has none.""" - deps: dict[str, set[str]] | None = None + failed attempt left it. A default an earlier task put on the same step object is worked out again for this + task's steps. A step built without TaskStep, as some tests build one, has none.""" + deps: dict[str, set[str]] | None = None # built only for a task with such a step: it costs a pass per step for step in steps: - if getattr(step, "retry_config", None) is not None or not hasattr(step, "default_retry_config"): + current = getattr(step, "retry_config", None) + if (current is not None and not current.implied) or not hasattr(step, "default_retry_config"): continue deps = deps if deps is not None else _dependency_ids(steps) ancestors = _ancestor_ids(step.id, deps) implied = step.default_retry_config([s for s in steps if s.id in ancestors]) - if implied is None: - continue - start = implied.retry_from_step_id - before = _ancestor_ids(start, deps) - beside = [a for a in ancestors - before - {start} if start not in _ancestor_ids(a, deps)] - if beside: - logger.info("%s: no default retry from %s, which doesn't redo %s; give it a retry_config", - step.id, start, ", ".join(sorted(beside))) - continue + if implied is not None: + start = implied.retry_from_step_id + before = _ancestor_ids(start, deps) + if beside := [a for a in ancestors - before - {start} if start not in _ancestor_ids(a, deps)]: + logger.info("%s: no default retry from %s, which doesn't redo %s; give it a retry_config", + step.id, start, ", ".join(sorted(beside))) + implied = None step.retry_config = implied @staticmethod @@ -815,7 +829,7 @@ async def _drain_in_flight() -> set[str]: if first_error is None: first_error, first_error_step_id = exc, step_id continue - retry_cfg = getattr(step_obj, "retry_config", None) + retry_cfg = self.retry_config_of(step_obj) if (retry_cfg is not None and retry_counts.get(step_id, 0) < retry_cfg.max_retries and not isinstance(exc, VerifierNotPassingError)): retryable.append((step_obj, retry_cfg, exc)) 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..a00aa4001 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -424,8 +424,9 @@ def from_dict(cls, data: dict) -> AlwaysOnTaskStep: return cls(**cls._base_from_dict(data), retry_config=data.get("retry_config"), **fields, **own) def default_retry_config(self, ancestors: list[TaskStep]) -> Optional[RetryConfig]: - """A turn that failed for an infrastructure reason (``AgentTurnInfraError``), or an attempt a dead worker lost, - is redone once on a fresh world, from the first env deploy before this step; never in the world it changed.""" + """A failed run is redone once on a fresh world, from the first env deploy before this step, never in the world + it changed: a turn that failed for an infrastructure reason (``AgentTurnInfraError``), an attempt a dead worker + lost, and any other failure but a verifier's, as a config error, which fails again and then fails the task.""" deploy = next((s for s in ancestors if s.type == "deploy_env"), None) return RetryConfig(deploy.id, max_retries=1, implied=True) if deploy is not None else None diff --git a/tst/unit/task/episode/spec_test.py b/tst/unit/task/episode/spec_test.py index c7c590562..5468194c5 100644 --- a/tst/unit/task/episode/spec_test.py +++ b/tst/unit/task/episode/spec_test.py @@ -10,6 +10,7 @@ from agent_env.task_step.registry import _builtin_registry from agent_env.task_step.task_steps.deploy_agent import DeployAgentTaskStep from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep +from agent_env.task_step.task_step import RetryConfig ENV = {"id": "env", "type": "deploy_env", "env_id": "portsim"} LOAD = {"id": "load", "type": "load_artifact", "env_id": "portsim", "artifact_id": "week-"} @@ -337,3 +338,29 @@ class _Unregistered(PromptAgentTaskStep): assert [type(step) for step in seeded] == [type(step) for step in steps] assert (seeded[2].role, seeded[3].prompt, seeded[-1].prompt) == ( "planner@Valencia", "Plan week 3.", "Berth at Valencia.") + + +def _always_on_beside_the_played_agent(): + """The task, with an always_on step that wakes bob, deployed in the task, beside the agent played from outside.""" + from agent_env.task_step.task_steps.always_on import AlwaysOnTaskStep + + loop = AlwaysOnTaskStep("loop", None, user_sim="linda", prompt_id="loop", agent_name="bob") + return Task(id="dock", version=4, steps=[*_portsim(BOB).steps, loop]) + + +def test_an_always_on_step_woken_on_an_agent_of_the_task_runs_without_the_retry_it_was_never_given(): + task = _always_on_beside_the_played_agent() + loop = task.steps[-1] + assert loop.retry_config is not None and loop.retry_config.implied + + spec = EpisodeSpec.from_task(task, trainer_agents=["default-agent"]) + + assert spec._copy.retry_config_of(spec._copy.steps[-1]) is None + assert task.retry_config_of(loop) == loop.retry_config + + +def test_a_retry_the_author_gave_an_always_on_step_is_still_refused(): + task = _always_on_beside_the_played_agent() + task.steps[-1].retry_config = RetryConfig("env") + + assert "step 'loop': retry_config can replay an outside turn" in _refusal(task, ["default-agent"]) diff --git a/tst/unit/task_step/test_always_on_default_retry.py b/tst/unit/task_step/test_always_on_default_retry.py index 9a892f5a0..23dd7f2c4 100644 --- a/tst/unit/task_step/test_always_on_default_retry.py +++ b/tst/unit/task_step/test_always_on_default_retry.py @@ -1,13 +1,18 @@ -"""An always_on step the task gives no ``retry_config`` is redone once from the first env deploy before it, so a turn -that failed for an infrastructure reason, or an attempt a dead worker lost, runs again on a fresh world. The default is -the step type's, never written into the stored task; a task's own ``retry_config`` wins.""" +"""An always_on step the task gives no ``retry_config`` is redone once from the first env deploy before it, so a failed +run, a turn that failed for an infrastructure reason or an attempt a dead worker lost, runs again on a fresh world. The +default is the step type's, never written into the stored task; a task's own ``retry_config`` wins.""" from __future__ import annotations +import pytest + from agent_env.task import Task +from agent_env.task.store import set_task_instance_store from agent_env.task.task import substitute_seed_in_steps +from agent_env.task_step.context import AgentTurnInfraError, TaskStepContext from agent_env.task_step.task_step import RetryConfig from agent_env.task_step.task_steps import always_on as ao from agent_env.task_step.task_steps.deploy_env import DeployEnvTaskStep +from tst.unit.task_step.retry_test import _FakeDeployEnv, _FlakyPrompt, _sqlite_store def _steps(**settings): @@ -66,8 +71,89 @@ def test_the_default_holds_when_every_step_it_depends_on_comes_after_the_deploy( assert Task(id="t", version=None, steps=steps).steps[2].retry_config == RetryConfig("env", max_retries=1) +def test_a_task_built_again_from_the_same_steps_reads_its_own_graph_not_the_last_tasks(): + env, week = DeployEnvTaskStep(id="env", version=None, env_id="mail"), _steps()[1] + Task(id="t", version=None, steps=[env, week]) + beside = DeployEnvTaskStep(id="env-b", version=None, env_id="shop", depends_on=[]) + + assert Task(id="t2", version=None, steps=[env, beside, week]).retry_config_of(week) is None + + def test_the_deploy_must_be_an_ancestor_not_just_an_earlier_step(): steps = [DeployEnvTaskStep(id="env", version=None, env_id="mail"), ao.AlwaysOnTaskStep("week", None, depends_on=[], user_sim="linda", prompt_id="ask", agent_name="solver")] assert Task(id="t", version=None, steps=steps).steps[1].retry_config is None + + +class _AlwaysOnLike(_FlakyPrompt): + """A step that takes always_on's default retry and fails its first attempts with ``error``.""" + + type = ao.AlwaysOnTaskStep.type + default_retry_config = ao.AlwaysOnTaskStep.default_retry_config + + def __init__(self, id: str, error: BaseException, fail_times: int = 1): + super().__init__(id, fail_times=fail_times) + self._error = error + + async def execute(self, context: TaskStepContext) -> TaskStepContext: + try: + return await super().execute(context) + except RuntimeError: + raise self._error from None + + +@pytest.fixture +def store(tmp_path): + set_task_instance_store(store := _sqlite_store(tmp_path)) + try: + yield store + finally: + set_task_instance_store(None) + + +@pytest.mark.asyncio +async def test_an_infra_failed_run_is_redeployed_and_run_again_once(store): + deploy, week = _FakeDeployEnv("env"), _AlwaysOnLike("week", AgentTurnInfraError("gateway 502")) + + result = await Task(id="t", version=1, steps=[deploy, week]).run(context=TaskStepContext()) + + assert deploy.deploy_calls == ["env", "env"] + assert week.attempts == 2 + assert [p.response for p in result.prompt_responses] == ["attempt-2"] + + +@pytest.mark.asyncio +async def test_a_second_failure_fails_the_task(store): + deploy, week = _FakeDeployEnv("env"), _AlwaysOnLike("week", AgentTurnInfraError("gateway 502"), fail_times=2) + + with pytest.raises(AgentTurnInfraError): + await Task(id="t", version=1, steps=[deploy, week]).run(context=(ctx := TaskStepContext())) + + assert deploy.deploy_calls == ["env", "env"] + assert week.attempts == 2 + assert store.get(ctx.instance_id).status == "failed" + + +@pytest.mark.asyncio +async def test_a_failure_that_isnt_infra_is_redone_once_too(store): + deploy, week = _FakeDeployEnv("env"), _AlwaysOnLike("week", TypeError("user sim plugin broke"), fail_times=2) + + with pytest.raises(TypeError): + await Task(id="t", version=1, steps=[deploy, week]).run(context=(ctx := TaskStepContext())) + + assert deploy.deploy_calls == ["env", "env"] + assert week.attempts == 2 + assert store.get(ctx.instance_id).status == "failed" + + +@pytest.mark.asyncio +async def test_a_task_that_takes_no_default_retry_fails_without_redeploying(store): + deploy, week = _FakeDeployEnv("env"), _AlwaysOnLike("week", AgentTurnInfraError("gateway 502")) + Task(id="t", version=1, steps=[deploy, week]) + + with pytest.raises(AgentTurnInfraError): + await Task(id="t", version=1, steps=[deploy, week], implied_retries=False).run(context=TaskStepContext()) + + assert deploy.deploy_calls == ["env"] + assert week.attempts == 1 From 7098a184ca32387794d8286003c15d939bb02fbb Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 14:55:41 -0800 Subject: [PATCH 18/19] fix(always_on): each task keeps its own default retries and changes no step it was given Building a second Task from the same step objects rewrote their default retry, so the first task's retry_config_of read the second's policy. A Task now keeps each step's type default in its own dict, read by retry_config_of; it never writes it onto the steps it is given. Task.from_dict, whose steps are its own, also puts the default on them, for a runner that reads a step's retry_config (a hub worker reads them off Task.get). The seed pass no longer copies it over. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task/task.py | 48 +++++++++++-------- tst/unit/task/episode/spec_test.py | 13 ++++- .../task_step/test_always_on_default_retry.py | 27 +++++++---- 3 files changed, 57 insertions(+), 31 deletions(-) diff --git a/src/agent_env/task/task.py b/src/agent_env/task/task.py index a1ed4c844..69d16af35 100644 --- a/src/agent_env/task/task.py +++ b/src/agent_env/task/task.py @@ -151,8 +151,6 @@ def _sub(value): seeded = attach_base_fields(type(step).from_dict(data), data) if (keep := getattr(seeded, "seeded_from", None)) is not None: # a step that keeps something as written keep(step) - if seeded.retry_config is None and (implied := getattr(step, "retry_config", None)) is not None: - seeded.retry_config = implied # its type's default, which to_dict leaves out out.append(seeded) return out @@ -390,25 +388,25 @@ def __init__( self._validate_dag(self.steps) self._validate_pairings(self.steps) self._validate_headlines(self.headline_verifiers, self.steps) - if implied_retries: - self._imply_retries(self.steps) + # Each step's type default, by step id: this task's own, so steps it shares with another task are never changed. + self._implied: dict[str, RetryConfig] = self._implied_retry_configs(self.steps) if implied_retries else {} def retry_config_of(self, step: TaskStep) -> Optional[RetryConfig]: - """The retry this task runs ``step`` with: its own ``retry_config``, or its type's default unless this task + """The retry this task runs ``step`` with: its own ``retry_config``, else its type's default unless this task takes none (``implied_retries``).""" retry_config = getattr(step, "retry_config", None) - if retry_config is not None and retry_config.implied and not self.implied_retries: - return None - return retry_config + if retry_config is not None and not retry_config.implied: + return retry_config + return self._implied.get(step.id) @staticmethod - def _imply_retries(steps: list[TaskStep]) -> None: - """Give each step the task left without a ``retry_config`` the one its type implies + def _implied_retry_configs(steps: list[TaskStep]) -> dict[str, RetryConfig]: + """For each step the task left without a ``retry_config``, the one its type implies (``TaskStep.default_retry_config``), when its rollback covers everything the step depends on: each of the step's ancestors comes before the step it resumes from or after it, none beside it, which a rollback would leave as the - failed attempt left it. A default an earlier task put on the same step object is worked out again for this - task's steps. A step built without TaskStep, as some tests build one, has none.""" + failed attempt left it. A step built without TaskStep, as some tests build one, has none.""" deps: dict[str, set[str]] | None = None # built only for a task with such a step: it costs a pass per step + implied_by_id: dict[str, RetryConfig] = {} for step in steps: current = getattr(step, "retry_config", None) if (current is not None and not current.implied) or not hasattr(step, "default_retry_config"): @@ -416,14 +414,16 @@ def _imply_retries(steps: list[TaskStep]) -> None: deps = deps if deps is not None else _dependency_ids(steps) ancestors = _ancestor_ids(step.id, deps) implied = step.default_retry_config([s for s in steps if s.id in ancestors]) - if implied is not None: - start = implied.retry_from_step_id - before = _ancestor_ids(start, deps) - if beside := [a for a in ancestors - before - {start} if start not in _ancestor_ids(a, deps)]: - logger.info("%s: no default retry from %s, which doesn't redo %s; give it a retry_config", - step.id, start, ", ".join(sorted(beside))) - implied = None - step.retry_config = implied + if implied is None: + continue + start = implied.retry_from_step_id + before = _ancestor_ids(start, deps) + if beside := [a for a in ancestors - before - {start} if start not in _ancestor_ids(a, deps)]: + logger.info("%s: no default retry from %s, which doesn't redo %s; give it a retry_config", + step.id, start, ", ".join(sorted(beside))) + continue + implied_by_id[step.id] = implied + return implied_by_id @staticmethod def _validate_headlines(headlines: list[str] | None, steps: list[TaskStep]) -> None: @@ -533,7 +533,7 @@ def from_dict(cls, data: dict) -> "Task": from agent_env.task_step.task_step import attach_base_fields steps.append(attach_base_fields(step_cls.from_dict(step_dict), step_dict)) - return cls( + task = cls( id=data["id"], version=data.get("version"), steps=steps, @@ -541,6 +541,12 @@ def from_dict(cls, data: dict) -> "Task": entity_ids=data["entity_ids"] if isinstance(data.get("entity_ids"), dict) else None, headline_verifiers=data["headline_verifiers"] if isinstance(data.get("headline_verifiers"), list) else None, ) + # These steps are this task's alone, so each carries its default too, for a runner that reads a step's + # retry_config rather than asking the task (a hub worker reads them off Task.get). + for step in steps: + if step.retry_config is None and (implied := task._implied.get(step.id)) is not None: + step.retry_config = implied + return task async def run( self, diff --git a/tst/unit/task/episode/spec_test.py b/tst/unit/task/episode/spec_test.py index 5468194c5..e93b92d52 100644 --- a/tst/unit/task/episode/spec_test.py +++ b/tst/unit/task/episode/spec_test.py @@ -351,12 +351,21 @@ def _always_on_beside_the_played_agent(): def test_an_always_on_step_woken_on_an_agent_of_the_task_runs_without_the_retry_it_was_never_given(): task = _always_on_beside_the_played_agent() loop = task.steps[-1] - assert loop.retry_config is not None and loop.retry_config.implied + assert task.retry_config_of(loop) is not None + + spec = EpisodeSpec.from_task(task, trainer_agents=["default-agent"]) + + assert spec._copy.retry_config_of(spec._copy.steps[-1]) is None + assert task.retry_config_of(loop) is not None + + +def test_an_always_on_task_loaded_from_its_stored_form_runs_as_an_episode_too(): + task = Task.from_dict(_always_on_beside_the_played_agent().to_dict()) + assert task.steps[-1].retry_config is not None and task.steps[-1].retry_config.implied spec = EpisodeSpec.from_task(task, trainer_agents=["default-agent"]) assert spec._copy.retry_config_of(spec._copy.steps[-1]) is None - assert task.retry_config_of(loop) == loop.retry_config def test_a_retry_the_author_gave_an_always_on_step_is_still_refused(): diff --git a/tst/unit/task_step/test_always_on_default_retry.py b/tst/unit/task_step/test_always_on_default_retry.py index 23dd7f2c4..426f437d9 100644 --- a/tst/unit/task_step/test_always_on_default_retry.py +++ b/tst/unit/task_step/test_always_on_default_retry.py @@ -23,8 +23,9 @@ def _steps(**settings): def test_an_always_on_step_without_one_is_redone_once_from_the_env_deploy(): task = Task(id="t", version=None, steps=_steps()) - assert task.steps[1].retry_config == RetryConfig("env", max_retries=1) - assert task.steps[1].retry_config.implied + assert task.retry_config_of(task.steps[1]) == RetryConfig("env", max_retries=1) + assert task.retry_config_of(task.steps[1]).implied + assert task.steps[1].retry_config is None def test_the_default_is_not_written_into_the_stored_task_and_comes_back_on_load(): @@ -35,9 +36,10 @@ def test_the_default_is_not_written_into_the_stored_task_and_comes_back_on_load( def test_a_seeded_run_keeps_the_default(): - [_, seeded] = substitute_seed_in_steps(Task(id="t", version=None, steps=_steps()).steps, {"name": "Linda"}) + task = Task(id="t", version=None, steps=_steps()) + [_, seeded] = substitute_seed_in_steps(task.steps, {"name": "Linda"}) - assert seeded.retry_config == RetryConfig("env", max_retries=1) and seeded.retry_config.implied + assert task.retry_config_of(seeded) == RetryConfig("env", max_retries=1) def test_a_tasks_own_retry_config_wins_and_is_stored(): @@ -50,7 +52,7 @@ def test_a_tasks_own_retry_config_wins_and_is_stored(): def test_an_always_on_step_with_no_env_deploy_before_it_takes_none(): task = Task(id="t", version=None, steps=_steps()[1:]) - assert task.steps[0].retry_config is None + assert task.retry_config_of(task.steps[0]) is None def test_no_default_when_a_step_it_depends_on_runs_beside_the_deploy_a_rollback_would_not_redo(): @@ -59,7 +61,7 @@ def test_no_default_when_a_step_it_depends_on_runs_beside_the_deploy_a_rollback_ ao.AlwaysOnTaskStep("week", None, depends_on=["env", "env-b"], user_sim="linda", prompt_id="ask", agent_name="solver")] - assert Task(id="t", version=None, steps=steps).steps[2].retry_config is None + assert (task := Task(id="t", version=None, steps=steps)).retry_config_of(task.steps[2]) is None def test_the_default_holds_when_every_step_it_depends_on_comes_after_the_deploy(): @@ -68,7 +70,7 @@ def test_the_default_holds_when_every_step_it_depends_on_comes_after_the_deploy( ao.AlwaysOnTaskStep("week", None, depends_on=["env", "env-b"], user_sim="linda", prompt_id="ask", agent_name="solver")] - assert Task(id="t", version=None, steps=steps).steps[2].retry_config == RetryConfig("env", max_retries=1) + assert (task := Task(id="t", version=None, steps=steps)).retry_config_of(task.steps[2]) == RetryConfig("env") def test_a_task_built_again_from_the_same_steps_reads_its_own_graph_not_the_last_tasks(): @@ -79,11 +81,20 @@ def test_a_task_built_again_from_the_same_steps_reads_its_own_graph_not_the_last assert Task(id="t2", version=None, steps=[env, beside, week]).retry_config_of(week) is None +def test_a_task_built_from_the_same_steps_leaves_the_first_tasks_default_alone(): + env, week = DeployEnvTaskStep(id="env", version=None, env_id="mail"), _steps()[1] + first = Task(id="t", version=None, steps=[env, week]) + Task(id="t2", version=None, steps=[env, DeployEnvTaskStep(id="env-b", version=None, env_id="shop", depends_on=[]), + week]) + + assert first.retry_config_of(week) == RetryConfig("env", max_retries=1) + + def test_the_deploy_must_be_an_ancestor_not_just_an_earlier_step(): steps = [DeployEnvTaskStep(id="env", version=None, env_id="mail"), ao.AlwaysOnTaskStep("week", None, depends_on=[], user_sim="linda", prompt_id="ask", agent_name="solver")] - assert Task(id="t", version=None, steps=steps).steps[1].retry_config is None + assert (task := Task(id="t", version=None, steps=steps)).retry_config_of(task.steps[1]) is None class _AlwaysOnLike(_FlakyPrompt): From 26ae0f9267080006c1910239e79787d502b61490 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 15:05:07 -0800 Subject: [PATCH 19/19] fix(always_on): a seeded run works its default retries out from its seeded steps A seed can fill placeholders in step ids, so the task's defaults, keyed by its unseeded ids, missed the seeded steps, and their resume points named unseeded ids too. The scheduler now asks the run: the task's own defaults, or, for a seeded run, those its seeded steps imply, kept per run. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task/task.py | 24 ++++++++++++++----- .../task_step/test_always_on_default_retry.py | 18 ++++++++++++++ 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/src/agent_env/task/task.py b/src/agent_env/task/task.py index 69d16af35..51cc84ee5 100644 --- a/src/agent_env/task/task.py +++ b/src/agent_env/task/task.py @@ -124,6 +124,12 @@ def _overlapping_survivors( ) +def _own_retry(step: "TaskStep") -> Optional[RetryConfig]: + """The ``retry_config`` a task gave ``step``, not a type default a task put on it.""" + retry_config = getattr(step, "retry_config", None) + return retry_config if retry_config is not None and not retry_config.implied else None + + def substitute_seed_in_steps(steps: list["TaskStep"], seed: dict) -> list["TaskStep"]: """Round-trip each step through its own to_dict/from_dict with ```` seed placeholders replaced in every string leaf, in one left-to-right pass @@ -393,11 +399,16 @@ def __init__( def retry_config_of(self, step: TaskStep) -> Optional[RetryConfig]: """The retry this task runs ``step`` with: its own ``retry_config``, else its type's default unless this task - takes none (``implied_retries``).""" - retry_config = getattr(step, "retry_config", None) - if retry_config is not None and not retry_config.implied: - return retry_config - return self._implied.get(step.id) + takes none (``implied_retries``). A seeded run works its defaults out from its seeded steps.""" + return _own_retry(step) or self._implied.get(step.id) + + def _run_implied_retries(self, steps: list[TaskStep]) -> dict[str, RetryConfig]: + """The defaults a run of ``steps`` takes: this task's own, or, for a run whose seed rebuilt its steps (ids and + resume points with their placeholders filled in), those the seeded steps imply. Kept per run, never on the task, + so concurrent runs with different seeds don't share them.""" + if steps is self.steps or not self.implied_retries: + return self._implied + return self._implied_retry_configs(steps) @staticmethod def _implied_retry_configs(steps: list[TaskStep]) -> dict[str, RetryConfig]: @@ -700,6 +711,7 @@ async def _drive_dag( """ from agent_env.task import store as _store + implied = self._run_implied_retries(steps) index_of = {s.id: i for i, s in enumerate(steps)} active_ids = set(state.step_by_id) @@ -835,7 +847,7 @@ async def _drain_in_flight() -> set[str]: if first_error is None: first_error, first_error_step_id = exc, step_id continue - retry_cfg = self.retry_config_of(step_obj) + retry_cfg = _own_retry(step_obj) or implied.get(step_obj.id) if (retry_cfg is not None and retry_counts.get(step_id, 0) < retry_cfg.max_retries and not isinstance(exc, VerifierNotPassingError)): retryable.append((step_obj, retry_cfg, exc)) diff --git a/tst/unit/task_step/test_always_on_default_retry.py b/tst/unit/task_step/test_always_on_default_retry.py index 426f437d9..0c3863c91 100644 --- a/tst/unit/task_step/test_always_on_default_retry.py +++ b/tst/unit/task_step/test_always_on_default_retry.py @@ -42,6 +42,24 @@ def test_a_seeded_run_keeps_the_default(): assert task.retry_config_of(seeded) == RetryConfig("env", max_retries=1) +def test_a_seeded_run_works_its_defaults_out_from_its_seeded_steps(): + task = Task(id="t", version=None, steps=[DeployEnvTaskStep(id="env-", version=None, env_id="mail"), + ao.AlwaysOnTaskStep("week-", None, user_sim="linda", prompt_id="ask", + agent_name="solver")]) + seeded = substitute_seed_in_steps(task.steps, {"week": "3"}) + + assert task._run_implied_retries(seeded) == {"week-3": RetryConfig("env-3", max_retries=1)} + assert task._run_implied_retries(task.steps) == {"week-": RetryConfig("env-", max_retries=1)} + + +def test_a_seeded_run_of_a_task_that_takes_no_default_takes_none(): + steps = [DeployEnvTaskStep(id="env-", version=None, env_id="mail"), + ao.AlwaysOnTaskStep("week-", None, user_sim="linda", prompt_id="ask", agent_name="solver")] + task = Task(id="t", version=None, steps=steps, implied_retries=False) + + assert task._run_implied_retries(substitute_seed_in_steps(task.steps, {"week": "3"})) == {} + + def test_a_tasks_own_retry_config_wins_and_is_stored(): task = Task(id="t", version=None, steps=_steps(retry_config={"retry_from_step_id": "week", "max_retries": 0}))