diff --git a/.github/workflows/harness.yml b/.github/workflows/harness.yml index b4bc1000a..b35fa2805 100644 --- a/.github/workflows/harness.yml +++ b/.github/workflows/harness.yml @@ -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: @@ -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 diff --git a/AGENTS.md b/AGENTS.md index 387f1ae3f..ecb3ff719 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 diff --git a/src/agent_env/bundle/run.py b/src/agent_env/bundle/run.py index 1f68b1102..6e8ca2b29 100644 --- a/src/agent_env/bundle/run.py +++ b/src/agent_env/bundle/run.py @@ -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 @@ -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.""" @@ -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) @@ -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, ...]: diff --git a/src/agent_env/task/episode/run.py b/src/agent_env/task/episode/run.py index 000b53b6d..a9af65c3d 100644 --- a/src/agent_env/task/episode/run.py +++ b/src/agent_env/task/episode/run.py @@ -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 @@ -272,6 +272,7 @@ 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) @@ -279,7 +280,8 @@ async def _drive(self, running: asyncio.Event) -> None: 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)) @@ -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) diff --git a/src/agent_env/task/result.py b/src/agent_env/task/result.py new file mode 100644 index 000000000..c94a1e971 --- /dev/null +++ b/src/agent_env/task/result.py @@ -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]) diff --git a/src/agent_env/task/store.py b/src/agent_env/task/store.py index 885428c91..0999bcb66 100644 --- a/src/agent_env/task/store.py +++ b/src/agent_env/task/store.py @@ -12,7 +12,7 @@ from dataclasses import dataclass, field from datetime import datetime, timezone from enum import StrEnum -from typing import TYPE_CHECKING, Callable, Optional, Self +from typing import TYPE_CHECKING, Callable, Optional, Self, TypeVar from agent_env.store.base import NotFoundError from agent_env.config import get_config @@ -47,6 +47,15 @@ _RERECORDED = "rerecorded_steps" # Which run the journal entries belong to; a re-register bumps it, retiring them without a delete. _GENERATION = "run_generation" +# The run's result, outside its context (``agent_env.task.result``): a grade version per grading, oldest first. +RESULT_KEY = "result" +# Where a submitter names the eval slot a run fills, in ``context.metadata``: ``{eval_instance_id, slot, attempt}``, +# which registering the run keeps as the instance's own fields. +EVAL_SLOT_KEY = "eval_slot" +_EVAL_SLOT_FIELDS = ("eval_instance_id", "slot", "attempt") +_T = TypeVar("_T") + + class TaskQuery(QueryBuilder["Task"]): def __init__(self, store: Optional["TaskStore"] = None) -> None: super().__init__() @@ -189,6 +198,12 @@ class TaskInstance: # The run's usage ledger (``usage.ledger``): every attempt's usage entries and their total, outside ``context``. usage: list[dict] = field(default_factory=list) usage_total: dict | None = None + # The eval slot this run fills, from ``EVAL_SLOT_KEY`` at register; None for a run no eval submitted. + eval_instance_id: str | None = None + slot: str | None = None + attempt: int | None = None + # A grade version per grading of the run, oldest first; empty until the run ends. + result: list[dict] = field(default_factory=list) @classmethod def from_dict(cls, data: dict) -> TaskInstance: @@ -209,6 +224,10 @@ def from_dict(cls, data: dict) -> TaskInstance: attempt_epoch=data.get("attempt_epoch", 0), usage=data.get(LEDGER_KEY) or [], usage_total=data.get(TOTAL_KEY), + eval_instance_id=data.get("eval_instance_id"), + slot=data.get("slot"), + attempt=data.get("attempt"), + result=data.get(RESULT_KEY) or [], ) @@ -254,21 +273,24 @@ def _fresh_run_state(start_step: int, completed_step_docs: list[dict]) -> dict: # mean "predates the journal", not "no re-records yet". _RERECORDED: [], "attempt_epoch": 0, + # A run running again has no result until it ends again. + RESULT_KEY: [], } def _new_instance_doc( instance_id: str, task_id: str, task_version: int, total_steps: int, - created_at_utc: str, run_state: dict, + created_at_utc: str, run_state: dict, eval_slot: dict, ) -> dict: - """A brand-new instance document: identity, the counters a re-register bumps, the usage ledger a re-register - keeps, run state.""" + """A brand-new instance document: identity, the eval slot it fills when an eval submitted it, the counters a + re-register bumps, the usage ledger a re-register keeps, run state.""" return { "instance_id": instance_id, "task_id": task_id, "task_version": task_version, "total_steps": total_steps, "created_at_utc": created_at_utc, + **eval_slot, "rev": 0, _GENERATION: 0, LEDGER_KEY: [], @@ -277,6 +299,20 @@ def _new_instance_doc( } +def eval_slot_fields(eval_slot: object) -> dict: + """The eval slot a submitter named, as the instance's fields: none for None, else exactly ``eval_instance_id`` and + ``slot`` as text and ``attempt`` counted from 1, refused otherwise before anything is written.""" + if eval_slot is None: + return {} + attempt = eval_slot.get("attempt") if isinstance(eval_slot, dict) else None + if not (isinstance(eval_slot, dict) and set(eval_slot) == set(_EVAL_SLOT_FIELDS) + and isinstance(eval_slot["eval_instance_id"], str) and isinstance(eval_slot["slot"], str) + and type(attempt) is int and attempt >= 1): + raise ValueError(f"{EVAL_SLOT_KEY} is {{eval_instance_id, slot, attempt}}, the attempt counted from 1, " + f"not {eval_slot!r}") + return {key: eval_slot[key] for key in _EVAL_SLOT_FIELDS} + + # A run records only the minute it started, so the instance id orders runs of one minute and pages never overlap. # Both keys descend so Mongo reads the sort from the (task_id, created_at_utc, instance_id) index scanned backward; # a mixed-direction sort matches no index and sorts every run's whole document in memory. @@ -290,7 +326,12 @@ def _task_filter(task_id: str, task_version: int | None) -> Filter: def _owns(doc: dict, attempt_epoch: int | None) -> bool: """Whether a terminal write may change ``doc``: the run hasn't completed, and no attempt later than ``attempt_epoch`` owns it.""" - return doc.get("status") != "completed" and (attempt_epoch is None or doc.get("attempt_epoch", 0) <= attempt_epoch) + return doc.get("status") != "completed" and _owns_attempt(doc, attempt_epoch) + + +def _owns_attempt(doc: dict, attempt_epoch: int | None) -> bool: + """Whether no attempt later than ``attempt_epoch`` owns ``doc``.""" + return attempt_epoch is None or doc.get("attempt_epoch", 0) <= attempt_epoch _STEP_USAGE_PATH = f"context.metadata.{STEP_USAGE_KEY}" @@ -342,7 +383,9 @@ def create_instance( total_steps: int, start_step: int = 0, completed_steps: list[TaskStepResult] | None = None, + slot_fields: dict | None = None, ) -> TaskInstance: + """A new instance under a fresh id; ``slot_fields`` are the eval slot's, as ``eval_slot_fields`` gives them.""" completed_step_docs = [ dataclasses.asdict(e) for e in completed_steps or [] ] @@ -350,7 +393,7 @@ def create_instance( created_at_utc = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC") doc = _new_instance_doc( instance_id, task_id, task_version, total_steps, created_at_utc, - _fresh_run_state(start_step, completed_step_docs), + _fresh_run_state(start_step, completed_step_docs), slot_fields or {}, ) store = self._doc_store store.insert(TASK_INSTANCES_COLLECTION, doc) @@ -365,8 +408,11 @@ def upsert_instance( total_steps: int, start_step: int = 0, completed_steps: list[TaskStepResult] | None = None, + slot_fields: dict | None = None, ) -> TaskInstance | None: - """Idempotent register on a caller-supplied ``instance_id``.""" + """Idempotent register on a caller-supplied ``instance_id``. A re-register sets the eval slot's fields when + given them (as ``eval_slot_fields`` gives them) and otherwise keeps the ones recorded, as a run continued + outside its eval still fills its slot.""" current_time_str = datetime.now(timezone.utc).strftime( "%Y-%m-%d %H:%M UTC" ) @@ -374,8 +420,9 @@ def upsert_instance( dataclasses.asdict(e) for e in completed_steps or [] ] run_state = _fresh_run_state(start_step, completed_step_docs) + slot_fields = slot_fields or {} fresh_doc = _new_instance_doc( - instance_id, task_id, task_version, total_steps, current_time_str, run_state, + instance_id, task_id, task_version, total_steps, current_time_str, run_state, slot_fields, ) store = self._doc_store try: @@ -391,7 +438,7 @@ def upsert_instance( updated = compare_and_swap( store, TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id), lambda doc: UpdateSpec( - set={**fresh, **ledger_fields(doc, entries_of(_get_path(doc, _STEP_USAGE_PATH)))}, + set={**fresh, **slot_fields, **ledger_fields(doc, entries_of(_get_path(doc, _STEP_USAGE_PATH)))}, inc={_GENERATION: 1, "attempt_epoch": 1}), counter_field=_REV, ) @@ -821,14 +868,26 @@ def fields(doc: dict) -> dict: def record_task_cancelled_sync( self, instance_id: str, reason: str, completed_at_utc: str, attempt_epoch: int | None = None, - usage: list[dict] | None = None, + usage: list[dict] | None = None, result: list[dict] | None = None, ) -> None: """Mark a run cancelled, over the ``failed`` its unwinding recorded, but never a completed one, nor one a later attempt than ``attempt_epoch`` owns. ``usage``, the entries of the steps that ran, joins the ledger - either way.""" + either way. ``result``, the run's cancelled result, is set in the same write unless a later attempt owns the + instance, a completed run's included, since a run cancelled as it ended is taken as cancelled.""" self._end_write(instance_id, usage or [], lambda doc: {"status": "cancelled", "error": reason, "completed_at_utc": completed_at_utc}, - owns=lambda doc: _owns(doc, attempt_epoch)) + owns=lambda doc: _owns(doc, attempt_epoch), + also=None if result is None else lambda doc: ( + {RESULT_KEY: result} if _owns_attempt(doc, attempt_epoch) else {})) + + def record_result_sync(self, instance_id: str, result: list[dict], attempt_epoch: int | None = None) -> bool: + """Set the run's ``result``, unless an attempt later than ``attempt_epoch`` owns the instance; whether it was set. + It replaces the result a run that ended before recorded, as a resumed run ends again.""" + def _mutate(doc: dict) -> UpdateSpec | None: + return UpdateSpec(set={RESULT_KEY: result}) if _owns_attempt(doc, attempt_epoch) else None + + return compare_and_swap(self._doc_store, TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id), + _mutate, counter_field=_REV) is not None def record_teardown_sync(self, instance_id: str, context: "TaskStepContext", attempt_epoch: int) -> None: """Keep the context a run's teardown ended with: what the run deployed, writes of a step a signal cut short @@ -854,14 +913,15 @@ def _mutate(doc: dict) -> UpdateSpec | None: counter_field=_REV) def _end_write(self, instance_id: str, usage: list[dict], fields: Callable[[dict], dict], *, - owns: Callable[[dict], bool]) -> None: - """A write that ends a run or an attempt, a CAS: ``fields`` of the document when ``owns`` it, and ``usage``, the - entries of the attempt the write ends, merged into the ledger either way, since they were spent.""" + owns: Callable[[dict], bool], also: Callable[[dict], dict] | None = None) -> None: + """A write that ends a run or an attempt, a CAS: ``fields`` of the document when ``owns`` it, ``also``'s whatever + ``owns`` says, and ``usage``, the entries of the attempt the write ends, merged into the ledger either way, since + they were spent.""" def _mutate(doc: dict) -> UpdateSpec | None: - spent = ledger_fields(doc, usage) + kept = {**(also(doc) if also else {}), **ledger_fields(doc, usage)} if not owns(doc): - return UpdateSpec(set=spent) if spent else None - return UpdateSpec(set={**fields(doc), **spent}) + return UpdateSpec(set=kept) if kept else None + return UpdateSpec(set={**fields(doc), **kept}) compare_and_swap(self._doc_store, TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id), _mutate, counter_field=_REV) @@ -929,6 +989,7 @@ def register_task_instance( start_step: int = 0, instance_id: str | None = None, completed_steps: list[TaskStepResult] | None = None, + eval_slot: dict | None = None, ) -> TaskInstance | None: """Register a task_instance row. @@ -937,12 +998,16 @@ def register_task_instance( Re-registering an existing instance advances its ``attempt_epoch``. A caller that dispatches the run's steps itself must record them under the returned instance's ``attempt_epoch``; an older one raises ``SupersededAttemptError``. + + ``eval_slot``, the ``EVAL_SLOT_KEY`` a submitter put in the run's metadata, becomes the instance's + ``eval_instance_id``, ``slot`` and ``attempt``; a malformed one raises ``ValueError`` either way. """ + slot_fields = eval_slot_fields(eval_slot) try: store = get_task_instance_store() if instance_id is None: return store.create_instance( - task_id, task_version, total_steps, start_step, completed_steps, + task_id, task_version, total_steps, start_step, completed_steps, slot_fields, ) return store.upsert_instance( instance_id, @@ -951,6 +1016,7 @@ def register_task_instance( total_steps, start_step, completed_steps, + slot_fields, ) except Exception: if instance_id is not None: @@ -1089,25 +1155,43 @@ async def record_task_failure( def record_task_cancelled( instance_id: str, reason: str, completed_at_utc: str, attempt_epoch: int | None = None, - usage: list[dict] | None = None, -) -> None: - """Write a cancelled run's terminal state, with ``usage`` for its ledger, retried like ``record_task_failure``. - It logs a write that keeps failing rather than raising. Synchronous: ``run_bundle`` calls it once its event loop - has closed.""" + usage: list[dict] | None = None, result: list[dict] | None = None, +) -> bool: + """Write a cancelled run's terminal state, with ``usage`` for its ledger and ``result`` in the same write, retried + like ``record_task_failure``; whether the store answered that it took the write, a guard refusing it included. It + logs a write that keeps failing rather than raising. Synchronous: ``run_bundle`` calls it once its event loop has + closed.""" store = get_task_instance_store() + + def mark() -> bool: + store.record_task_cancelled_sync(instance_id, reason, completed_at_utc, attempt_epoch, usage, result) + return True + + return _retried(mark, False, f"record the cancellation of instance_id={instance_id}") + + +def _retried(write: Callable[[], _T], failed: _T, what: str) -> _T: + """``write``, tried up to ``_FAILURE_WRITE_MAX_ATTEMPTS`` times with backoff; one that keeps failing is logged as + the attempt to ``what`` and returns ``failed``, never raising, as the end writes of a run do.""" last_exc: BaseException | None = None for attempt in range(_FAILURE_WRITE_MAX_ATTEMPTS): try: - store.record_task_cancelled_sync(instance_id, reason, completed_at_utc, attempt_epoch, usage) - return + return write() except Exception as exc: # noqa: BLE001 last_exc = exc if attempt + 1 < _FAILURE_WRITE_MAX_ATTEMPTS: time.sleep(_FAILURE_WRITE_BACKOFF_SECONDS * (2**attempt)) - logger.warning( - "Failed to record the cancellation of instance_id=%s after %d attempts", - instance_id, _FAILURE_WRITE_MAX_ATTEMPTS, exc_info=last_exc, - ) + logger.warning("Failed to %s after %d attempts", what, _FAILURE_WRITE_MAX_ATTEMPTS, exc_info=last_exc) + return failed + +def record_result(instance_id: str, result: list[dict], attempt_epoch: int | None = None) -> bool: + """``TaskInstanceStore.record_result_sync``, retried like ``record_task_failure``; whether it was set. A write that + keeps failing is logged rather than raised: the run's own state is recorded either way, and a result left + unrecorded reads as missing, never as another result.""" + store = get_task_instance_store() + return _retried(lambda: store.record_result_sync(instance_id, result, attempt_epoch), False, + f"record the result of instance_id={instance_id}") + # Best-effort, diagnostic-only wrapper around ``append_step_attempt_failure_sync``: retries a # transient write (like ``record_task_failure``), then logs and swallows — never raises. diff --git a/src/agent_env/task/task.py b/src/agent_env/task/task.py index 3f40431c4..542d08c93 100644 --- a/src/agent_env/task/task.py +++ b/src/agent_env/task/task.py @@ -25,6 +25,7 @@ from agent_env.store.routing import run_scope from agent_env.task_step.preflight import pinned from agent_env.task.outcome import FailedStep +from agent_env.task.result import record_cancelled_run, record_run_end from agent_env.task.teardown import env_record_ids from agent_env.task.usage.ledger import entries_of from agent_env.task.usage.running import running_usage @@ -152,18 +153,6 @@ def _sub(value): return out -def recorded_scores(steps: list["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 _dependency_ids(steps: list["TaskStep"]) -> dict[str, set[str]]: """Direct dependency ids per step; depends_on None = all prior (scheduler semantics).""" deps: dict[str, set[str]] = {} @@ -544,6 +533,7 @@ async def _run( instance_id: str | None, ) -> TaskStepContext: from .store import ( + EVAL_SLOT_KEY, TaskStepResult, TaskStepStatus, register_task_instance, @@ -609,6 +599,7 @@ async def _run( start_step, instance_id=instance_id, completed_steps=completed_steps, + eval_slot=context.metadata.get(EVAL_SLOT_KEY), ) instance_id = instance.instance_id if instance else None context.instance_id = instance_id @@ -624,7 +615,9 @@ async def _run( on_step_start, on_step_complete, log_prefix, ) if first_error is not None: - await self._handle_failure(first_error_step_id, first_error, context, instance_id, state.epoch) + await self._handle_failure(first_error_step_id, first_error, steps, context, instance_id, state.epoch) + elif instance_id and (end_step is None or end_step == total): + await record_run_end(instance_id, steps, context, state.epoch) return context async def _drive_dag( @@ -843,17 +836,18 @@ async def _drain_in_flight() -> set[str]: await _drain_in_flight() if instance_id and first_error is None and isinstance(exc, asyncio.CancelledError): await asyncio.to_thread( - _store.record_task_cancelled, instance_id, str(exc) or "cancelled", Task._utc_now_str(), state.epoch, - entries_of(context.metadata.get(STEP_USAGE_KEY)), + record_cancelled_run, instance_id, str(exc) or "cancelled", Task._utc_now_str(), steps, context, + attempt_epoch=state.epoch, usage=entries_of(context.metadata.get(STEP_USAGE_KEY)), ) elif instance_id: # Record with the fatal step's attribution: a cancellation landing # during the drain would otherwise overwrite the instance record # with the CancelledError and a null failing-step id. + error = first_error if first_error is not None else exc await _store.record_task_failure( - instance_id, first_error_step_id, context, - first_error if first_error is not None else exc, Task._utc_now_str(), state.epoch, + instance_id, first_error_step_id, context, error, Task._utc_now_str(), state.epoch, ) + await record_run_end(instance_id, steps, context, state.epoch, error=error) raise return first_error, first_error_step_id @@ -906,17 +900,19 @@ def _build_scheduler_state(self, steps: list, start_step: int, end_step: int | N async def _handle_failure( failing_step_id: str | None, error: BaseException, + steps: list[TaskStep], context: TaskStepContext, instance_id: str | None, attempt_epoch: int, ) -> None: - """Record the terminal failure on the instance and re-raise it.""" + """Record the terminal failure and the run's result on the instance, and re-raise it.""" from .store import record_task_failure if instance_id: await record_task_failure( instance_id, failing_step_id, context, error, Task._utc_now_str(), attempt_epoch, ) + await record_run_end(instance_id, steps, context, attempt_epoch, error=error) raise error @staticmethod diff --git a/src/agent_env/training/harness.py b/src/agent_env/training/harness.py index 89b927c69..cb7cded75 100644 --- a/src/agent_env/training/harness.py +++ b/src/agent_env/training/harness.py @@ -33,7 +33,8 @@ from agent_env.store.routing import namespace_routing from agent_env.openenv.reward import reward_of from agent_env.task.lint import judges_in_solver -from agent_env.task.task import Task, recorded_scores +from agent_env.task.result import recorded_scores +from agent_env.task.task import Task from agent_env.task.teardown import teardown_run from agent_env.task_step.context import TaskStepContext, sandbox_overrides from agent_env.task_step.task_steps.agent.user_sim_common import opening_parts, opening_text diff --git a/tst/integration/cli/run_bundle_test.py b/tst/integration/cli/run_bundle_test.py index 2163aae05..8d8f44665 100644 --- a/tst/integration/cli/run_bundle_test.py +++ b/tst/integration/cli/run_bundle_test.py @@ -104,6 +104,11 @@ def test_the_shipped_hello_runs_by_name_and_a_rerun_reuses_every_write(bundle, q instance = Task.get_instance(instance_id) assert instance.status == "completed" assert instance.context["metadata"]["verifications"]["hello"]["score"] == 1.0 + (result,) = instance.result + assert (result["result_rules_version"], result["result"], result["cause"]) == (0, "passed", None) + assert result["scores"] == {"hello": 1.0} + assert (result["grades"]["hello"]["score"], result["grades"]["hello"]["passed"]) == (1.0, True) + assert "verifier_criteria" not in result["grades"]["hello"] and "result" not in instance.context["metadata"] def test_the_shipped_hello_stays_local_when_config_defaults_to_another_provider(bundle, monkeypatch, tmp_path, @@ -311,7 +316,9 @@ def test_a_signal_mid_run_marks_the_run_cancelled_tears_it_down_and_stops_its_co assert output.endswith("\nTore down 1 sandbox.\n") (instance_id,) = re.findall(r"instance (\S+)", output) with namespace_routing(): - assert Task.get_instance(instance_id).status == "cancelled" + instance = Task.get_instance(instance_id) + assert instance.status == "cancelled" + assert [entry["result"] for entry in instance.result] == ["cancelled"] assert not _alive(int(nap.read_text())) diff --git a/tst/unit/task/result_test.py b/tst/unit/task/result_test.py new file mode 100644 index 000000000..d270c5413 --- /dev/null +++ b/tst/unit/task/result_test.py @@ -0,0 +1,468 @@ +"""A run's result: decided once, under a versioned set of rules, and kept on its task instance outside the context, the +same however the run was launched.""" + +import asyncio +import itertools +import threading +from datetime import datetime, timezone +from typing import ClassVar + +import pytest + +from agent_env.bundle.run import Outcome, TaskRun, _mark_cancelled +from agent_env.config.runtime import Config +from agent_env.runner.local_runner import LocalRunner +from agent_env.runner.runner import RunStatus +from agent_env.task import Task +from agent_env.task import store as task_store +from agent_env.task import result as result_module +from agent_env.task.result import ( + GRADE_FIELDS, + RESULT_RULES, + RESULT_RULES_VERSION, + UNCLASSIFIED, + RunResult, + decide, + grade_version, + record_cancelled_run, + record_run_end, + record_run_result, +) +from agent_env.task.store import ( + EVAL_SLOT_KEY, + RESULT_KEY, + TaskStepStatus, + find_task_instance, + get_task_instance_store, + record_step_complete, + register_task_instance, +) +from agent_env.task_step.context import TaskStepContext +from agent_env.task_step.context_ops import build_context_update_ops +from agent_env.task_step.task_step import RetryConfig, TaskStep +from agent_env.task_step.task_steps.verifiers.verifier import Grade, Verification, VerifierTaskStep + + +class _Score(VerifierTaskStep): + """A verifier whose score is given.""" + + type: ClassVar[str] = "result_test_score" + entity_refs = () + + def __init__(self, id, score=1.0, **kwargs): + super().__init__(id, None, verifier_id=f"{id}-vid", **kwargs) + self.fixed = score + + async def verify(self, context): + return Verification(score=self.fixed) + + +class _Step(TaskStep): + """Does nothing, fails when ``fails``, fails once when ``flaky``, or waits until cancelled when ``hangs``.""" + + type: ClassVar[str] = "result_test_step" + entity_refs = () + tried: ClassVar[set] = set() + + def __init__(self, id, *, fails=False, flaky=False, hangs=False, **kwargs): + super().__init__(id, None, **kwargs) + self.fails, self.flaky, self.hangs = fails, flaky, hangs + + async def execute(self, context): + if self.hangs: + await asyncio.Event().wait() + if self.fails or (self.flaky and self.id not in _Step.tried): + _Step.tried.add(self.id) + raise RuntimeError(f"step {self.id} failed") + return context + + +@pytest.fixture(autouse=True) +def registries(monkeypatch): + steps = {**Config().task_step_registry(), _Score.type: _Score, _Step.type: _Step} + monkeypatch.setattr(Config, "task_step_registry", lambda self: steps) + monkeypatch.setattr(_Step, "tried", set()) + + +def _stored(instance_id: str) -> dict: + return get_task_instance_store()._doc_store.find_one( + task_store.TASK_INSTANCES_COLLECTION, task_store.Filter.of(instance_id=instance_id)) + + +def _without_time(entries: list[dict]) -> list[dict]: + return [{k: v for k, v in entry.items() if k != "at"} for entry in entries] + + +def _bundle_outcome_before(cancelled, error, failed_steps, scores) -> Outcome: + """bundle/run.py's ``TaskRun.outcome`` as it stood before the result rules, which v0 ports.""" + if cancelled: + return Outcome.CANCELLED + if error is not None or [f for f in failed_steps if not f.get("retried")]: + return Outcome.FAILED + if not scores: + return Outcome.UNSCORED + return Outcome.PASSED if all(score >= 1 for score in scores.values()) else Outcome.BELOW_ONE + + +_FAILED_STEPS = ([], [{"step_id": "a", "retried": True}], [{"step_id": "a"}], + [{"step_id": "a", "retried": True}, {"step_id": "b"}]) +_VERIFICATIONS = ({}, {"v-vid": {"score": 1.0}}, {"v-vid": {"score": 1}}, {"v-vid": {"score": 0.99}}, + {"v-vid": {"score": 1.0}, "w-vid": {"score": 0.0}}, {"v-vid": {"score": 2.5}}, + {"v-vid": {"score": None}}, {"v-vid": {"score": "1"}}, {"other": {"score": 1.0}}, + {"v-vid": {"results": []}}) + + +@pytest.mark.parametrize(("cancelled", "error", "failed_steps", "verifications"), list(itertools.product( + (False, True), (None, RuntimeError("boom")), _FAILED_STEPS, _VERIFICATIONS))) +def test_rules_v0_give_every_finished_bundle_run_the_outcome_the_bundle_gave_it(cancelled, error, failed_steps, + verifications): + steps = [_Score("v"), _Score("w")] + context = TaskStepContext() + context.metadata.update(failed_steps=failed_steps, verifications=verifications) + scores = {key: float(v["score"]) for key, v in verifications.items() if isinstance(v.get("score"), (int, float))} + scores = {{"v-vid": "v", "w-vid": "w"}.get(key, key): score for key, score in scores.items()} + + run = TaskRun(entry=None, task=Task(id="t", version=1, steps=steps), context=context, error=error, duration=0.0, + cancelled=cancelled) + + assert run.outcome is _bundle_outcome_before(cancelled, error, failed_steps, scores) + assert grade_version(steps, context, error=error, cancelled=cancelled)["scores"] == scores + + +def test_v0_names_each_outcome_by_its_result_and_says_why_a_run_is_ungraded(): + context = TaskStepContext() + assert decide([], context).result is RunResult.GRADED + assert decide([], context, RuntimeError("boom")) == decide([], context, RuntimeError("other")) + assert decide([], context, RuntimeError("boom")).result is RunResult.UNGRADED + assert decide([], context, RuntimeError("boom")).cause == UNCLASSIFIED + assert decide([], context, cancelled=True).result is RunResult.CANCELLED + assert decide([], context, cancelled=True).cause is None + assert RESULT_RULES_VERSION == 0 and set(RESULT_RULES) == {0} + + +def test_a_grade_version_copies_fields_a_named_grade_has(): + assert set(GRADE_FIELDS) <= Grade.__required_keys__ | Grade.__optional_keys__ + + +@pytest.mark.asyncio +async def test_a_run_records_one_grade_version_on_its_instance_and_none_in_its_context(local_stores): + task = Task(id="t", version=1, steps=[_Step("a"), _Score("good", 1.0), _Score("low", 0.5, min_passing_score=0.4)]) + + context = await task.run(context=TaskStepContext()) + + stored = find_task_instance(context.instance_id) + [entry] = stored.result + assert {k: v for k, v in entry.items() if k not in ("at", "grades")} == { + "result_rules_version": 0, "result": "below_threshold", "cause": None, "scores": {"good": 1.0, "low": 0.5}} + assert set(entry["grades"]) == {"good", "low"} + assert entry["grades"]["low"] == { + **{field: context.metadata["grades"]["low"][field] for field in GRADE_FIELDS}, "passed": True} + assert set(entry["grades"]["low"]) == set(GRADE_FIELDS) + assert RESULT_KEY not in context.metadata and RESULT_KEY not in context.to_safe_dict()["metadata"] + assert RESULT_KEY not in _stored(context.instance_id)["context"]["metadata"] + + +@pytest.mark.asyncio +async def test_a_failed_step_makes_the_run_ungraded_and_a_retried_one_doesnt(local_stores): + failing = Task(id="t", version=1, steps=[_Step("a", fails=True), _Score("v")]) + with pytest.raises(RuntimeError): + await failing.run(context=(failed := TaskStepContext())) + [entry] = find_task_instance(failed.instance_id).result + assert (entry["result"], entry["cause"]) == ("ungraded", UNCLASSIFIED) + + tolerated = Task(id="t", version=1, steps=[_Step("a", fails=True, fail_task_on_error=False), _Score("v")]) + context = await tolerated.run(context=TaskStepContext()) + assert find_task_instance(context.instance_id).result[0]["result"] == "ungraded" + + retried = Task(id="t", version=1, steps=[ + _Step("b", flaky=True, retry_config=RetryConfig(retry_from_step_id="b", max_retries=1)), _Score("v")]) + context = await retried.run(context=TaskStepContext()) + assert [f.get("retried") for f in context.metadata["failed_steps"]] == [True] + assert find_task_instance(context.instance_id).result[0]["result"] == "passed" + + +@pytest.mark.asyncio +async def test_a_cancelled_run_is_recorded_cancelled(local_stores): + task = Task(id="t", version=1, steps=[_Score("v"), _Step("wait", hangs=True)]) + context = TaskStepContext() + run = asyncio.ensure_future(task.run(context=context)) + while not (context.instance_id and find_task_instance(context.instance_id).completed_steps): + await asyncio.sleep(0.01) + run.cancel() + with pytest.raises(asyncio.CancelledError): + await run + + stored = find_task_instance(context.instance_id) + assert stored.status == "cancelled" + [entry] = stored.result + assert (entry["result"], entry["scores"]) == ("cancelled", {"v": 1.0}) + + +@pytest.mark.asyncio +async def test_only_the_call_that_ends_the_run_records_its_result_and_a_resumed_run_replaces_it(local_stores): + task = Task(id="t", version=1, steps=[_Step("a"), _Score("v"), _Step("c")]) + + context = await task.run(context=TaskStepContext(), end_step=2) + assert find_task_instance(context.instance_id).result == [] + await task.run(context=context, start_step=2, instance_id=context.instance_id) + first = find_task_instance(context.instance_id).result + assert [entry["result"] for entry in first] == ["passed"] + + await task.run(context=context, start_step=1, instance_id=context.instance_id) + again = find_task_instance(context.instance_id).result + assert len(again) == 1 and again[0]["at"] >= first[0]["at"] + + +def test_a_result_from_an_attempt_a_later_one_replaced_is_refused(local_stores): + instance = register_task_instance("t", 1, 1) + register_task_instance("t", 1, 1, instance_id=instance.instance_id) # a retry: attempt epoch 1 + + assert record_run_result(instance.instance_id, [], TaskStepContext(), attempt_epoch=0) is None + assert find_task_instance(instance.instance_id).result == [] + assert record_run_result(instance.instance_id, [], TaskStepContext(), attempt_epoch=1)["result"] == "graded" + assert record_run_result(instance.instance_id, [], TaskStepContext())["result"] == "graded" + + +def test_a_rerun_clears_the_result_until_it_ends_again(local_stores): + instance = register_task_instance("t", 1, 1) + record_run_result(instance.instance_id, [], TaskStepContext()) + + register_task_instance("t", 1, 1, instance_id=instance.instance_id) + + assert find_task_instance(instance.instance_id).result == [] + + +@pytest.mark.asyncio +async def test_a_run_an_eval_submitted_names_its_slot_and_attempt_on_its_instance(local_stores): + slot = {"eval_instance_id": "evals/e-k3m8q1zt", "slot": "t@1#2", "attempt": 3} + task = Task(id="t", version=1, steps=[_Score("v")]) + + context = TaskStepContext() + context.metadata[EVAL_SLOT_KEY] = dict(slot) + await task.run(context=context) + + stored = find_task_instance(context.instance_id) + assert (stored.eval_instance_id, stored.slot, stored.attempt) == ("evals/e-k3m8q1zt", "t@1#2", 3) + register_task_instance("t", 1, 1, instance_id=context.instance_id) # continued outside its eval + assert find_task_instance(context.instance_id).slot == "t@1#2" + plain = await task.run(context=TaskStepContext()) + assert find_task_instance(plain.instance_id).eval_instance_id is None + + +@pytest.mark.parametrize("eval_slot", [ + {"eval_instance_id": "e", "slot": "t@1#1"}, + {"eval_instance_id": "e", "slot": "t@1#1", "attempt": 0}, + {"eval_instance_id": "e", "slot": "t@1#1", "attempt": True}, + {"eval_instance_id": "e", "slot": "t@1#1", "attempt": "1"}, + {"eval_instance_id": "e", "slot": 2, "attempt": 1}, + {"eval_instance_id": "e", "slot": "t@1#1", "attempt": 1, "extra": 1}, + "e:t@1#1:1", +]) +def test_a_malformed_eval_slot_is_refused_before_anything_is_written(local_stores, eval_slot): + with pytest.raises(ValueError, match=EVAL_SLOT_KEY): + register_task_instance("t", 1, 1, eval_slot=eval_slot) + assert task_store.task_instances("t") == [] + + +@pytest.mark.asyncio +async def test_every_worker_records_the_same_result_for_the_same_run(local_stores, monkeypatch): + """Task.run (task run, run BUNDLE), LocalRunner (eval run and task run through the configured runner) and a worker + that dispatches the steps itself, as AgentEnvHub's does, then records the result through the shared function.""" + def build(): + return Task(id="t", version=1, steps=[ + _Step("a"), _Step("b", fails=True, fail_task_on_error=False), _Score("good", 1.0), _Score("low", 0.25)]) + + direct = await build().run(context=TaskStepContext()) + + monkeypatch.setattr(Task, "get", classmethod(lambda cls, task_id, version=None: build())) + runner = LocalRunner(workers=1) + await runner.start() + try: + handle = await runner.submit("t", 1) + while not (record := await runner.status(handle.run_id)) or not record.status.is_terminal: + await asyncio.sleep(0.02) + finally: + await runner.stop() + assert record.status is RunStatus.FAILED + + task = build() + instance = register_task_instance(task.id, task.version, len(task.steps)) + context = TaskStepContext() + context.instance_id = instance.instance_id + for step in task.steps: + before = TaskStepContext.from_dict(context.to_dict()) + try: + context = await step.execute(context) or context + except RuntimeError as exc: + context.metadata.setdefault("failed_steps", []).append({"step_id": step.id, "error": str(exc)}) + await record_step_complete(instance.instance_id, step.id, build_context_update_ops(before, context), + len(task.steps), datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"), + TaskStepStatus.SUCCESS) + await record_run_end(instance.instance_id, task.steps, context, instance.attempt_epoch) + + results = [_without_time(find_task_instance(i).result) + for i in (direct.instance_id, handle.instance_id, instance.instance_id)] + assert results[0] == results[1] == results[2] + assert results[0][0]["result"] == "ungraded" + + +def _blocking_first_write(monkeypatch): + """The first result write waits until released; every call is kept.""" + release, calls = threading.Event(), [] + + def write(instance_id, steps, context, **kwargs): + calls.append(kwargs) + if len(calls) == 1: + release.wait(10) + return record_run_result(instance_id, steps, context, **kwargs) + + monkeypatch.setattr(result_module, "record_run_result", write) + return release, calls + + +async def _until(done, what: str, seconds: float = 10.0): + deadline = asyncio.get_running_loop().time() + seconds + while not done(): + assert asyncio.get_running_loop().time() < deadline, f"no {what} within {seconds} s" + await asyncio.sleep(0.01) + + +@pytest.mark.asyncio +async def test_a_cancel_while_the_result_is_written_lets_it_land_then_records_the_run_cancelled(local_stores, + monkeypatch): + """A caller takes a Task.run that raises CancelledError as cancelled, so its result says so too.""" + release, calls = _blocking_first_write(monkeypatch) + context = TaskStepContext() + run = asyncio.ensure_future(Task(id="t", version=1, steps=[_Score("v")]).run(context=context)) + await _until(lambda: calls, "result write") + run.cancel() + await asyncio.sleep(0.05) + release.set() + with pytest.raises(asyncio.CancelledError): + await run + + assert [kwargs.get("cancelled", False) for kwargs in calls] == [False, True] + [entry] = find_task_instance(context.instance_id).result + assert (entry["result"], entry["scores"]) == ("cancelled", {"v": 1.0}) + + +@pytest.mark.asyncio +async def test_a_cancel_racing_the_end_of_the_result_write_still_records_the_run_cancelled(local_stores, monkeypatch): + """The cancel lands as the write returns, so either side may see the other first; one of them records it.""" + loop = asyncio.get_running_loop() + for _ in range(20): + runs = [] + + def write(instance_id, steps, context, **kwargs): + entry = record_run_result(instance_id, steps, context, **kwargs) + if not kwargs.get("cancelled"): + loop.call_soon_threadsafe(runs[0].cancel) + return entry + + monkeypatch.setattr(result_module, "record_run_result", write) + context = TaskStepContext() + runs.append(asyncio.ensure_future(Task(id="t", version=1, steps=[_Score("v")]).run(context=context))) + with pytest.raises(asyncio.CancelledError): + await runs[0] + assert [e["result"] for e in find_task_instance(context.instance_id).result] == ["cancelled"] + + +@pytest.mark.asyncio +async def test_localrunners_cancel_during_the_result_write_ends_canceled_and_recorded_cancelled(local_stores, + monkeypatch): + """LocalRunner cancels a run (twice, coalesced): the run waits for its write, then is recorded cancelled.""" + release, calls = _blocking_first_write(monkeypatch) + monkeypatch.setattr(Task, "get", classmethod(lambda cls, task_id, version=None: Task( + id="t", version=1, steps=[_Score("v")]))) + runner = LocalRunner(workers=1) + await runner.start() + try: + handle = await runner.submit("t", 1) + await _until(lambda: calls, "result write") + assert await runner.cancel(handle.run_id) + await asyncio.sleep(0.05) + release.set() + while not (record := await runner.status(handle.run_id)) or not record.status.is_terminal: + await asyncio.sleep(0.02) + await _until(lambda: [e["result"] for e in find_task_instance(handle.instance_id).result] == ["cancelled"], + "cancelled result") + finally: + release.set() + await runner.stop() + assert record.status is RunStatus.CANCELED + + +@pytest.mark.asyncio +async def test_a_result_write_that_hangs_holds_up_no_other_run(local_stores, monkeypatch): + release, calls = _blocking_first_write(monkeypatch) + stuck = asyncio.ensure_future(Task(id="t", version=1, steps=[_Score("v")]).run(context=TaskStepContext())) + await _until(lambda: calls, "result write") + + other = await asyncio.wait_for(Task(id="t", version=1, steps=[_Score("v", 0.5)]).run(context=TaskStepContext()), 5) + + assert [e["result"] for e in find_task_instance(other.instance_id).result] == ["below_threshold"] + release.set() + await stuck + + +def test_a_bundle_runs_late_cancel_mark_leaves_a_newer_attempts_status_and_result(local_stores): + instance = register_task_instance("t", 1, 1) + context = TaskStepContext() + context.instance_id = instance.instance_id + run = TaskRun(entry=None, task=Task(id="t", version=1, steps=[_Score("v")]), context=context, error=None, + duration=0.0, cancelled=True, attempt_epoch=0) + retry = register_task_instance("t", 1, 1, instance_id=instance.instance_id) + record_run_result(instance.instance_id, [], TaskStepContext(), attempt_epoch=retry.attempt_epoch) + + _mark_cancelled((run,), "Ctrl-C") + + stored = find_task_instance(instance.instance_id) + assert (stored.status, [entry["result"] for entry in stored.result]) == ("running", ["graded"]) + + +def test_a_cancelled_run_is_marked_with_its_result_in_one_write(local_stores, monkeypatch): + """Status and result never disagree, and a running run, a completed one and a later attempt's each take what they + should: cancelled and cancelled, completed and cancelled, and nothing.""" + writes = [] + real = task_store.TaskInstanceStore.record_task_cancelled_sync + monkeypatch.setattr(task_store.TaskInstanceStore, "record_task_cancelled_sync", + lambda self, *args, **kwargs: writes.append(args) or real(self, *args, **kwargs)) + running, completed, newer = (register_task_instance("t", 1, 1) for _ in range(3)) + get_task_instance_store()._doc_store.update(task_store.TASK_INSTANCES_COLLECTION, + task_store.Filter.of(instance_id=completed.instance_id), + task_store.UpdateSpec(set={"status": "completed"})) + register_task_instance("t", 1, 1, instance_id=newer.instance_id) # attempt 1 owns it now + + for instance in (running, completed, newer): + record_cancelled_run(instance.instance_id, "Ctrl-C", "2026-11-29 12:00 UTC", [], TaskStepContext(), + attempt_epoch=0) + + stored = [find_task_instance(i.instance_id) for i in (running, completed, newer)] + assert [(i.status, _results_of(i)) for i in stored] == [ + ("cancelled", ["cancelled"]), ("completed", ["cancelled"]), ("running", [])] + assert len(writes) == 3 + + +def _results_of(instance): + return [entry["result"] for entry in instance.result] + + +@pytest.mark.asyncio +async def test_the_cancel_follows_a_result_write_answered_as_failed(monkeypatch): + """A write answered as failed may have landed, so the cancel is recorded after it whatever its answer.""" + release, calls = threading.Event(), [] + + def answered_failed(*args, **kwargs): + calls.append(kwargs) + if len(calls) == 1: + release.wait(10) + + monkeypatch.setattr(result_module, "record_run_result", answered_failed) + end = asyncio.ensure_future(record_run_end("i", [], TaskStepContext(), 0)) + await _until(lambda: calls, "result write") + end.cancel() + await asyncio.sleep(0.05) + release.set() + with pytest.raises(asyncio.CancelledError): + await end + assert [kwargs.get("cancelled", False) for kwargs in calls] == [False, True] diff --git a/tst/unit/task/task_failure_write_retry_test.py b/tst/unit/task/task_failure_write_retry_test.py index 266e5663d..6c95c9219 100644 --- a/tst/unit/task/task_failure_write_retry_test.py +++ b/tst/unit/task/task_failure_write_retry_test.py @@ -210,10 +210,21 @@ def test_record_task_cancelled_retries_until_write_succeeds(monkeypatch): flaky = _FlakyDocStore(fail_times=2) set_task_instance_store(_store_with(flaky)) try: - record_task_cancelled("inst-1", "cancelled by SIGTERM", "2026-09-29 18:00 UTC") + taken = record_task_cancelled("inst-1", "cancelled by SIGTERM", "2026-09-29 18:00 UTC") finally: set_task_instance_store(None) - assert flaky.calls == 3 + assert (flaky.calls, taken) == (3, True) + + +def test_record_task_cancelled_says_when_the_store_never_took_it(monkeypatch): + monkeypatch.setattr(store_mod, "_FAILURE_WRITE_BACKOFF_SECONDS", 0) + down = _FlakyDocStore(fail_times=100) + set_task_instance_store(_store_with(down)) + try: + taken = record_task_cancelled("inst-1", "cancelled by SIGTERM", "2026-09-29 18:00 UTC") + finally: + set_task_instance_store(None) + assert (down.calls, taken) == (store_mod._FAILURE_WRITE_MAX_ATTEMPTS, False) def test_registering_a_given_instance_id_raises_when_the_store_fails(monkeypatch): diff --git a/tst/unit/task_step/verifiers/test_agent_prompt_response_verifier.py b/tst/unit/task_step/verifiers/test_agent_prompt_response_verifier.py index 22914b37f..434f89fc3 100644 --- a/tst/unit/task_step/verifiers/test_agent_prompt_response_verifier.py +++ b/tst/unit/task_step/verifiers/test_agent_prompt_response_verifier.py @@ -6,7 +6,7 @@ import pytest from agent_env.plugins import _requirements -from agent_env.task.task import recorded_scores +from agent_env.task.result import recorded_scores from agent_env.task_step.context import PromptResponse, StepContextError, TaskStepContext from agent_env.task_step.task_steps.verifiers import AgentPromptResponseVerifierTaskStep