Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/agent_env/agents/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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
turn in that context gets it back; bind it before the runtime starts, so a live trajectory read or a mid-turn
Expand Down
3 changes: 2 additions & 1 deletion src/agent_env/task/episode/rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion src/agent_env/task/episode/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 4 additions & 3 deletions src/agent_env/task/outcome.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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]:
Expand Down
63 changes: 61 additions & 2 deletions src/agent_env/task/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ``<key>``
seed placeholders replaced in every string leaf, in one left-to-right pass
Expand Down Expand Up @@ -373,16 +379,62 @@ 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
self.headline_verifiers: list[str] | None = list(headline_verifiers) if headline_verifiers else None
self._validate_dag(self.steps)
self._validate_pairings(self.steps)
self._validate_headlines(self.headline_verifiers, 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``, else its type's default unless this task
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]:
"""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 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"):
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])
Comment thread
sarah-chitty-1 marked this conversation as resolved.
Resolved
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:
Expand Down Expand Up @@ -492,14 +544,20 @@ 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,
requires=data["requires"] if isinstance(data.get("requires"), list) else None,
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,
Expand Down Expand Up @@ -653,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)

Expand Down Expand Up @@ -788,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 = getattr(step_obj, "retry_config", None)
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))
Expand Down
9 changes: 9 additions & 0 deletions src/agent_env/task_step/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
14 changes: 12 additions & 2 deletions src/agent_env/task_step/task_step.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down Expand Up @@ -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."""
Expand All @@ -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()
Comment thread
sarah-chitty-1 marked this conversation as resolved.
Resolved
if self.step_role != type(self).step_role:
base["step_role"] = self.step_role.value
return base
Expand Down
Loading
Loading