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
15 changes: 10 additions & 5 deletions .github/workflows/harness.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
name: Harness contract

# TRL's harness rollouts on a bundle's own agents (agent_env.training.harness, tst/unit/training/harness_test.py)
# through OpenEnv's capture proxy, on the uv.lock pins and on the latest OpenEnv. The harness reads the proxy's internals
# (its session registry, export and training trace), which OpenEnv can change in any minor release. It runs on pull
# requests that touch the harness or its tier, weekly, and on demand; it isn't a required check.
# through OpenEnv's capture proxy, on the uv.lock pins and on the latest OpenEnv this project's pins allow. The harness
# reads the proxy's internals (its session registry, export and training trace), which OpenEnv can change in any minor
# release. It runs on pull requests that touch the harness or its tier, weekly, and on demand; it isn't a required check.

on:
pull_request:
Expand Down Expand Up @@ -42,11 +42,16 @@ jobs:
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
with:
python-version: "3.12"
- name: Install from uv.lock, with the latest OpenEnv for latest
- name: Install from uv.lock, with the latest OpenEnv this project's pins allow for latest
run: |
python -m pip install --quiet -r .github/ci-requirements.txt
uv sync --locked --extra dev --python "$(command -v python)"
if [ "${{ matrix.openenv }}" = latest ]; then uv pip install --python .venv/bin/python --upgrade openenv; fi
if [ "${{ matrix.openenv }}" = latest ]; then
# Resolved with the project's own pins (mcp<2, fastmcp<4), as an install of agent-env resolves it, not
# forced past them: OpenEnv 0.15 needs mcp 2, which agent-env can't import.
uv lock --upgrade-package openenv
uv sync --extra dev --python "$(command -v python)"
fi
.venv/bin/python -c "import importlib.metadata as m; print('openenv', m.version('openenv'))"
- name: Harness tier
run: .venv/bin/python -m pytest tst/unit/training/harness_test.py -rA --timeout=600 --junitxml=junit-harness.xml
Expand Down
9 changes: 9 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,15 @@ orchestrators call it the same way. What callers rely on:
under, in its own asyncio task, so the usage a prompt step records (`metadata["step_usage"]`,
`PromptResponse.usage`) says which attempt spent it. A runner that calls `step.execute()` itself, not
through `Task.run()`, sets it the same way, or its entries carry no attempt.
- When a call ends the run (its last step, a failure or a cancel; not a call `end_step` stops short), `Task.run()`
records the run's result on the instance (`task/result.py`): `result`, a top-level field outside the context, a
grade version per grading, each with its `result` and `cause` under `result_rules_version` (`RESULT_RULES`; v0 is
the bundle classifier, so `agent-env run`'s outcomes come from it), the scores it was decided on, each named grade
without its rows, output or judge calls, and when. A run that ends again replaces it, and an attempt a later one
replaced can't. The write runs on a thread, and a run cancelled during it is recorded `cancelled`, as its caller
takes it. A runner that calls `step.execute()` itself awaits `record_run_end` when its run ends, and calls
`record_cancelled_run` when it marks a run cancelled, so the run gets the same result. A submitter that fills an eval slot names it in `context.metadata["eval_slot"]`
(`{eval_instance_id, slot, attempt}`), which registering the run keeps as the instance's own fields.
- A runner records every run it accepts in the run index (`agent_env.runner.store`): `insert_run` at
submit, `set_running` when it starts, `mark_terminal` when it ends. The explorer lists, counts and
groups runs from that collection and never calls the runner to ask, so a run missing there is
Expand Down
23 changes: 13 additions & 10 deletions src/agent_env/bundle/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,12 @@
from agent_env.task_step.task_steps.verifiers.verifier import GRADES_KEY
from agent_env.store.base import NotFoundError
from agent_env.store.routing import namespace_routing, run_scope
from agent_env.task.store import find_task_instance, record_task_cancelled
from agent_env.task.store import find_task_instance
from agent_env.task.interrupts import Interrupts
from agent_env.task.lint import said
from agent_env.utils.progress import run_progress
from agent_env.task.task import Task, recorded_scores
from agent_env.task.result import RunResult, decide, record_cancelled_run, recorded_scores
from agent_env.task.task import Task
from agent_env.task.teardown import TeardownReport, attempt_epoch, record_teardown, teardown_run
from agent_env.task.usage.summary import UsageSummary, summarize
from agent_env.task_step.context import TaskStepContext, sandbox_overrides
Expand Down Expand Up @@ -66,6 +67,12 @@ class Outcome(Enum):
CANCELLED = "cancelled" # Ctrl-C or SIGTERM stopped it, or stopped it starting


# A run's result as the bundle summary names it.
_OUTCOMES = {RunResult.PASSED: Outcome.PASSED, RunResult.BELOW_THRESHOLD: Outcome.BELOW_ONE,
RunResult.GRADED: Outcome.UNSCORED, RunResult.UNGRADED: Outcome.FAILED,
RunResult.CANCELLED: Outcome.CANCELLED}


@dataclass(frozen=True)
class TaskRun:
"""One run of a bundle task, with the context it left, kept when it raised."""
Expand Down Expand Up @@ -116,13 +123,8 @@ def usage_summary(self) -> UsageSummary | None:

@property
def outcome(self) -> Outcome:
if self.cancelled:
return Outcome.CANCELLED
if self.error is not None or self.failed_steps:
return Outcome.FAILED
if not self.scores:
return Outcome.UNSCORED
return Outcome.PASSED if all(score >= 1 for score in self.scores.values()) else Outcome.BELOW_ONE
"""The run's result, decided as its instance's ``result`` is."""
return _OUTCOMES[decide(self.task.steps, self.context, self.error, self.cancelled).result]


@dataclass(frozen=True)
Expand Down Expand Up @@ -409,7 +411,8 @@ def _mark_cancelled(runs: tuple[TaskRun, ...], reason: str) -> None:
for run in runs:
if run.cancelled and run.instance_id:
with run_scope(run.task.id):
record_task_cancelled(run.instance_id, reason, Task._utc_now_str())
record_cancelled_run(run.instance_id, reason, Task._utc_now_str(), run.task.steps, run.context,
attempt_epoch=run.attempt_epoch)


def _with_usage(runs: tuple[TaskRun, ...]) -> tuple[TaskRun, ...]:
Expand Down
19 changes: 11 additions & 8 deletions src/agent_env/task/episode/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@
from agent_env.runner.runner import RunRecord, RunStatus, run_outcome
from agent_env.store.routing import namespace_routing, run_scope
from agent_env.task.episode.proxy import InProcessProxy, ProxyClient, ProxyRefused
from agent_env.task.store import record_task_cancelled
from agent_env.task.task import Task, recorded_scores, substitute_seed_in_steps
from agent_env.task.teardown import teardown_run
from agent_env.task.result import record_cancelled_run, recorded_scores
from agent_env.task.task import Task, substitute_seed_in_steps
from agent_env.task.teardown import attempt_epoch, teardown_run
from agent_env.task_step.context import DeployedAgent, TaskStepContext
from agent_env.task_step.task_steps.deploy_agent import _mcp_add_body

Expand Down Expand Up @@ -272,14 +272,16 @@ async def _drive(self, running: asyncio.Event) -> None:
raise
finally:
self._tearing_down = True
epoch = attempt_epoch(self.id) # the run's, before anything else could take the instance on
try:
await self._release_proxies()
report = await teardown_run(self._context)
if report.still_up:
logger.warning("episode %s: %s may still be up", self.id,
[s.sandbox_id for s in report.still_up])
if self._abandoned is not None:
await asyncio.to_thread(_record_cancelled, self._task.id, self.id, self._abandoned)
await asyncio.to_thread(_record_cancelled, self._task.id, self.id, self._abandoned,
self._seeded_steps(), self._context, epoch)
finally:
try:
await asyncio.to_thread(_record_ended, self._task.id, self.id, *self._outcome(failure))
Expand Down Expand Up @@ -419,8 +421,9 @@ def _run_id(instance_id: str) -> str:
return f"episode-{instance_id}"


def _record_cancelled(task_id: str, instance_id: str, reason: str) -> None:
"""Marked where the run recorded its instance, as ``Task.run`` scopes it: an ``@local`` task's in the local
stores."""
def _record_cancelled(task_id: str, instance_id: str, reason: str, steps: list, context: TaskStepContext,
epoch: int | None) -> None:
"""Marked, with its result, where the run recorded its instance, as ``Task.run`` scopes it: an ``@local`` task's in
the local stores. Both are the run's own, at ``epoch``: a later attempt's stand."""
with run_scope(task_id):
record_task_cancelled(instance_id, reason, Task._utc_now_str())
record_cancelled_run(instance_id, reason, Task._utc_now_str(), steps, context, attempt_epoch=epoch)
165 changes: 165 additions & 0 deletions src/agent_env/task/result.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
"""A finished run's result, decided in one place for every worker.

``grade_version`` decides it from the run's steps and context under a version of the result rules, and
``record_run_result`` keeps it on the task instance as ``result``, a top-level field outside the context, so it never
travels with the context between a worker's steps. ``Task.run`` records it when a call ends the run, through
``record_run_end``; a worker that runs the steps itself awaits ``record_run_end`` the same way when its run ends, so a
run gets the same result however it was launched, and ``record_cancelled_run`` when it marks a run cancelled.

Each version of the rules is a function in ``RESULT_RULES``. A stored result keeps the version it was decided under,
so a new version changes no stored result: a run's own grading uses ``RESULT_RULES_VERSION``.
"""

from __future__ import annotations

import asyncio
import contextlib
import logging
import threading
from dataclasses import dataclass
from datetime import datetime, timezone
from enum import StrEnum
from typing import Any, Callable, Optional, Sequence

from agent_env.runner.runner import RunStatus, run_outcome
from agent_env.task import store as _store
from agent_env.task_step.context import TaskStepContext
from agent_env.task_step.task_step import TaskStep
from agent_env.task_step.task_steps.verifiers.verifier import GRADES_KEY

logger = logging.getLogger(__name__)

# What a grade version keeps of each named grade; its rows, output and judge calls stay in the context's grades.
GRADE_FIELDS = ("score", "min_passing_score", "passed", "verifier_status", "verifier_type", "verifier_version",
"verifier_settings")
UNCLASSIFIED = "unclassified"


class RunResult(StrEnum):
PASSED = "passed"
BELOW_THRESHOLD = "below_threshold"
GRADED = "graded"
UNGRADED = "ungraded"
CANCELLED = "cancelled"


@dataclass(frozen=True)
class Decision:
result: RunResult
cause: Optional[str] = None


ResultRules = Callable[[Sequence[TaskStep], TaskStepContext, Optional[BaseException], bool], Decision]


def recorded_scores(steps: Sequence[TaskStep], context: TaskStepContext) -> dict[str, float]:
"""Every score a run of ``steps`` recorded, by the id of the step that recorded it, or by its verification's key
when that isn't a step's verifier id."""
step_ids = {step.verifier_id: step.id for step in steps if getattr(step, "verifier_id", None)}
scores = {}
for key, verification in (context.metadata.get("verifications") or {}).items():
score = verification.get("score")
if isinstance(score, (int, float)):
scores[step_ids.get(key, key)] = float(score)
return scores


def rules_v0(steps: Sequence[TaskStep], context: TaskStepContext, error: Optional[BaseException],
cancelled: bool) -> Decision:
"""The bundle classifier as it stood, under O1's names: ``cancelled``; ``ungraded`` with cause ``unclassified``
when the run raised or a step failed that no retry recovered (``run_outcome``); ``graded`` when it recorded no
score; ``passed`` when every score is at least 1; ``below_threshold`` otherwise."""
if cancelled:
return Decision(RunResult.CANCELLED)
if run_outcome(context, error)[0] is RunStatus.FAILED:
return Decision(RunResult.UNGRADED, UNCLASSIFIED)
scores = recorded_scores(steps, context)
if not scores:
return Decision(RunResult.GRADED)
return Decision(RunResult.PASSED if all(score >= 1 for score in scores.values()) else RunResult.BELOW_THRESHOLD)


RESULT_RULES: dict[int, ResultRules] = {0: rules_v0}
RESULT_RULES_VERSION = 0


def decide(steps: Sequence[TaskStep], context: TaskStepContext, error: Optional[BaseException] = None,
cancelled: bool = False) -> Decision:
"""The run's result and cause under ``RESULT_RULES_VERSION``."""
return RESULT_RULES[RESULT_RULES_VERSION](steps, context, error, cancelled)


def grade_version(steps: Sequence[TaskStep], context: TaskStepContext, *, error: Optional[BaseException] = None,
cancelled: bool = False, now: Optional[datetime] = None) -> dict[str, Any]:
"""The run's grading as one entry of ``result``: the result and its cause under ``RESULT_RULES_VERSION``, the
scores they were decided on, each named grade's ``GRADE_FIELDS``, and when."""
decision = decide(steps, context, error, cancelled)
grades = context.metadata.get(GRADES_KEY) or {}
return {
"result_rules_version": RESULT_RULES_VERSION,
"result": str(decision.result),
"cause": decision.cause,
"scores": recorded_scores(steps, context),
"grades": {name: {field: grade.get(field) for field in GRADE_FIELDS}
for name, grade in grades.items() if isinstance(grade, dict)},
"at": (now or datetime.now(timezone.utc)).isoformat(),
}


def record_run_result(instance_id: str, steps: Sequence[TaskStep], context: TaskStepContext, *,
error: Optional[BaseException] = None, cancelled: bool = False,
attempt_epoch: Optional[int] = None) -> Optional[dict[str, Any]]:
"""Decide how the run ended, ``error`` being what it raised, and keep that as its instance's ``result``, unless an
attempt later than ``attempt_epoch`` owns the instance. A run that ends again, as a resumed one does, replaces the
result it recorded before. Returns the entry it recorded, or None, logged, when it recorded none."""
entry = grade_version(steps, context, error=error, cancelled=cancelled)
if _store.record_result(instance_id, [entry], attempt_epoch):
return entry
logger.warning("The %s result of %s wasn't recorded: the instance wasn't found, or an attempt later than %s owns it",
entry["result"], instance_id, attempt_epoch)
return None


async def record_run_end(instance_id: str, steps: Sequence[TaskStep], context: TaskStepContext, attempt_epoch: int,
error: Optional[BaseException] = None) -> None:
"""Record how the run ended, on a thread, so a slow store holds up no other run. A cancel can't stop that write:
the run is then recorded cancelled after it, as every caller of a run that raises ``CancelledError`` takes it, and
the cancel is raised. Whichever side sees the other second records the cancel, whatever the first write was
answered, since a write answered as failed may have landed; a second cancel only cuts the wait short. With the store
reachable the result agrees with how the caller takes the run; with it down the result may be missing, or the run's
own if that write landed unanswered, both logged. A worker that awaits the result writes itself would reopen that
window, so it calls this."""
lock, seen = threading.Lock(), {"cancelled": False, "done": False}

def write() -> None:
record_run_result(instance_id, steps, context, error=error, attempt_epoch=attempt_epoch)
with lock:
seen["done"] = True
cancelled = seen["cancelled"]
if cancelled:
record_run_result(instance_id, steps, context, cancelled=True, attempt_epoch=attempt_epoch)

writing = asyncio.ensure_future(asyncio.to_thread(write))
try:
await asyncio.shield(writing)
except asyncio.CancelledError:
with lock:
seen["cancelled"] = True
follow = seen["done"]
if follow:
writing = asyncio.ensure_future(asyncio.to_thread(
record_run_result, instance_id, steps, context, cancelled=True, attempt_epoch=attempt_epoch))
with contextlib.suppress(asyncio.CancelledError):
await asyncio.shield(writing)
raise


def record_cancelled_run(instance_id: str, reason: str, completed_at_utc: str, steps: Sequence[TaskStep],
context: TaskStepContext, *, attempt_epoch: Optional[int] = None,
usage: Optional[list[dict]] = None) -> None:
"""Mark the run cancelled with ``reason``, its ``usage`` joining the ledger, and its ``cancelled`` result, in one
write, so the two never disagree and a store that is down costs one write's retries, unless an attempt later than
``attempt_epoch`` owns the instance. A completed run's status stays, its result is set: a run cancelled as it ended
is taken as cancelled. Synchronous: a bundle calls it once its event loop has closed."""
entry = grade_version(steps, context, cancelled=True)
_store.record_task_cancelled(instance_id, reason, completed_at_utc, attempt_epoch, usage, [entry])
Loading
Loading