diff --git a/src/agent_env/agents/AGENTS.md b/src/agent_env/agents/AGENTS.md index 2d90c16df..406063219 100644 --- a/src/agent_env/agents/AGENTS.md +++ b/src/agent_env/agents/AGENTS.md @@ -69,7 +69,11 @@ 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 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/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/task.py b/src/agent_env/task/task.py index 00b6f50c4..f0447e06e 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 @@ -383,6 +385,31 @@ 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``), 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) + 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/src/agent_env/task_step/context.py b/src/agent_env/task_step/context.py index a02304790..90d9c3c56 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_step.py b/src/agent_env/task_step/task_step.py index 07455a897..be3f32400 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.""" @@ -187,8 +197,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 73e6f18ee..56d162726 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,10 +143,17 @@ ) from agent_env.config.model import ModelRole, run_model 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 +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 @@ -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.", @@ -406,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.""" @@ -466,7 +489,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 +671,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 +1502,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 +1622,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 +1729,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 +2044,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..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 @@ -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,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 + 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"), - 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 @@ -384,6 +398,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 +481,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/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..dab177156 100644 --- a/tst/unit/task_step/test_always_on_agent_verifier.py +++ b/tst/unit/task_step/test_always_on_agent_verifier.py @@ -844,6 +844,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_default_retry.py b/tst/unit/task_step/test_always_on_default_retry.py new file mode 100644 index 000000000..9a892f5a0 --- /dev/null +++ b/tst/unit/task_step/test_always_on_default_retry.py @@ -0,0 +1,73 @@ +"""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.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 + + +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_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})) + + 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_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")] + + assert Task(id="t", version=None, steps=steps).steps[1].retry_config is None 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..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,6 +527,53 @@ 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, 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()) + 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": message, "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_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 + + 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."""