From 3e66c9d767321c8794fb6816c2f561105a80169f Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 30 Nov 2026 15:45:22 -0800 Subject: [PATCH 01/10] feat(task): compare two attempts' run records by the lock table, and `agent-env task diff` `task/drift.py` classes every difference between two attempts' records by the lock table's rows: hard when they ran different things (task, entity versions and image identity, role models, overrides, result rules and verifier settings, the last two also offering a regrade), soft for code meant to change under a run (core and plugin packages, Python, verifier packages, a role's endpoint host, where its sandboxes ran), never for how a version was asked for or how the config was found. Every record field is in a row or named as not compared, which a test holds. An image's identity, not its artifact's version, says whether it changed, so an image put again from an unchanged context is the same image. `agent-env task diff A [B]` lists the differences of two attempts, an instance's latest or INSTANCE@EPOCH, or of one instance's first and latest, and exits 0 when they ran the same thing, 1 on hard drift and 2 when they can't be compared; `--json` prints the comparison. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 7 +- src/agent_env/cli/task/__init__.py | 2 + src/agent_env/cli/task/diff.py | 100 ++++++++++ src/agent_env/task/drift.py | 288 +++++++++++++++++++++++++++++ tst/unit/cli/task_diff_test.py | 141 ++++++++++++++ tst/unit/task/drift_test.py | 241 ++++++++++++++++++++++++ 6 files changed, 778 insertions(+), 1 deletion(-) create mode 100644 src/agent_env/cli/task/diff.py create mode 100644 src/agent_env/task/drift.py create mode 100644 tst/unit/cli/task_diff_test.py create mode 100644 tst/unit/task/drift_test.py diff --git a/AGENTS.md b/AGENTS.md index 181ad45b9..131b079dc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -500,7 +500,12 @@ orchestrators call it the same way. What callers rely on: writes don't check, nor these theirs (on DynamoDB, which conditions a write on the whole item, one still retries the other); the store keeps the finished record whichever lands last, and a resume adds its own. An instance leaves out, with a warning, a record this version can't read. A worker that runs a task's steps itself enters `run_recorded` - around them, once per attempt in the process that runs them all, as it sets `run_pins`. + around them, once per attempt in the process that runs them all, as it sets `run_pins`. `task/drift.py` classes every + difference between two attempts' records by the lock table (`compare`, its rows `ROWS`, every record field in one or + in `NOT_COMPARED`): `hard` when they ran different things, `regrade` too for the result rules or a verifier's + settings, `soft` for code meant to change under a run, as an upgraded package, and `never`, as how a version was asked + for; an image's identity, not its artifact's version, says whether it changed. `agent-env task diff` lists the + differences, exiting 1 on hard drift. - A runner that must hear from a long step puts a zero-argument callable at `context.metadata[HEARTBEAT_KEY]` (`task_step/context.py`); a step that blocks for long calls `context.heartbeat()`, a no-op without one. The key is in `_REDACTED_KEYS`, so it is never persisted. diff --git a/src/agent_env/cli/task/__init__.py b/src/agent_env/cli/task/__init__.py index e99bd7b44..b7f21948f 100644 --- a/src/agent_env/cli/task/__init__.py +++ b/src/agent_env/cli/task/__init__.py @@ -1,6 +1,7 @@ import click from .create import create +from .diff import diff from .get import get from .get_instance import get_instance from .lint import lint @@ -16,6 +17,7 @@ def task(): task.add_command(create) +task.add_command(diff) task.add_command(get) task.add_command(get_instance) task.add_command(lint) diff --git a/src/agent_env/cli/task/diff.py b/src/agent_env/cli/task/diff.py new file mode 100644 index 000000000..b0ad2a5be --- /dev/null +++ b/src/agent_env/cli/task/diff.py @@ -0,0 +1,100 @@ +"""Compare what two attempts of a task ran, by the lock table.""" + +import json +from typing import Any, NoReturn, Optional + +import click + +from agent_env.task.drift import Comparison, Difference, Drift, Records, compare +from agent_env.task.store import find_task_instance + +# A value longer than this is cut in the listing; --json prints it whole. +SHOWN_CHARS = 100 +NOT_COMPARABLE = 2 + + +@click.command("diff") +@click.argument("first") +@click.argument("second", required=False) +@click.option("--json", "as_json", is_flag=True, help="Print the comparison as JSON.") +def diff(first: str, second: Optional[str], as_json: bool): + """List every difference between what two attempts of a task ran, as their run records keep it, each hard, soft + or never drift by the lock table. FIRST and SECOND each name a task instance, for its latest attempt, or one of + its attempts as INSTANCE@EPOCH. With FIRST alone, its first attempt is compared with its latest, as a run with its + resume. Exits 0 when the two ran the same thing, 1 when they didn't (hard drift), 2 when they can't be compared.""" + if second is None: + a, b = _first_and_latest(first) + else: + a, b = _records(first), _records(second) + comparison = compare(a, b) + if as_json: + click.echo(json.dumps(comparison.to_dict(), indent=2, default=str)) + else: + _echo(comparison) + if not comparison.like_for_like: + raise SystemExit(1) + + +def _records(spec: str) -> Records: + instance_id, epoch = _parse(spec) + instance = find_task_instance(instance_id) + if instance is None: + _fail(f"no task instance {instance_id!r}") + try: + return Records.of(instance, epoch) + except LookupError as e: + _fail(str(e)) + + +def _first_and_latest(spec: str) -> tuple[Records, Records]: + instance_id, epoch = _parse(spec) + if epoch is not None: + _fail(f"{spec}: name a second attempt to compare attempt {epoch} with") + instance = find_task_instance(instance_id) + if instance is None: + _fail(f"no task instance {instance_id!r}") + epochs = Records.epochs(instance) + if len(epochs) < 2: + _fail(f"instance {instance_id} has records of {len(epochs)} attempt{'s' * (len(epochs) != 1)}; name a second " + "instance to compare it with") + return Records.of(instance, epochs[0]), Records.of(instance, epochs[-1]) + + +def _parse(spec: str) -> tuple[str, Optional[int]]: + """``INSTANCE@EPOCH`` as the instance and the epoch, else the instance alone: an id may start with ``@``, as a + local one does, so only a last ``@`` followed by digits names an attempt.""" + head, at, tail = spec.rpartition("@") + return (head, int(tail)) if at and head and tail.isdigit() else (spec, None) + + +def _fail(message: str) -> NoReturn: + click.echo(f"Error: {message}", err=True) + raise SystemExit(NOT_COMPARABLE) + + +def _echo(comparison: Comparison) -> None: + a, b = comparison.a, comparison.b + click.echo(f"attempt {a.attempt_epoch} of {a.instance_id} -> attempt {b.attempt_epoch} of {b.instance_id}") + for difference in comparison.differences: + click.echo(f" {difference.drift:<5} {_line(difference)}") + for note in comparison.not_compared: + click.echo(f" not compared: {note}") + counts = ", ".join(f"{len(comparison.of(drift))} {drift}" for drift in Drift) + verdict = ("the same thing ran" if comparison.like_for_like else "they didn't run the same thing") + click.echo(f"{counts}: {verdict}" if comparison.differences else "no differences: the same thing ran") + if comparison.regrade: + click.echo("Their grades are under different result rules or verifier settings: regrade one under the other's " + "before comparing their scores.") + + +def _line(difference: Difference) -> str: + where = " ".join([difference.row, *difference.key]) if difference.key else difference.row + regrade = " (regrade)" if difference.regrade else "" + return f"{where}: {_shown(difference.old)} -> {_shown(difference.new)}{regrade}" + + +def _shown(value: Any) -> str: + if value is None: + return "-" + text = value if isinstance(value, str) else json.dumps(value, default=str, sort_keys=True) + return text if len(text) <= SHOWN_CHARS else text[:SHOWN_CHARS - 1] + "…" diff --git a/src/agent_env/task/drift.py b/src/agent_env/task/drift.py new file mode 100644 index 000000000..203cbe830 --- /dev/null +++ b/src/agent_env/task/drift.py @@ -0,0 +1,288 @@ +"""Which differences between two attempts' run records (``agent_env.task.run_records``) matter, by the lock table: a row +per thing a run records, each with its class (``Drift``). ``hard``: the two ran different things, so a resume or a rerun +across them isn't like for like; a change of the result rules or of a verifier's settings is also ``regrade``, as their +grades can't be compared until one is regraded under the other's rules. ``soft``: the code that ran differed in a way +meant to change under a run, as an upgraded package, which only warns. ``never``: recorded, and never drift, as how a +version was asked for. Every field of the records is in a row or in ``NOT_COMPARED``. + +An image's identity, not its artifact's version, says whether it changed: an image read at another version with the same +identity is the same image, so its version's change is ``never``. A row that reports a thing added or removed, a +verifier, a role or a plugin, is the only one that does; the rows of that thing's other fields compare it only where +both attempts have it. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import StrEnum +from typing import Any, Callable, Iterable, Mapping, Optional + +from agent_env.task.run_records import ReadRecord, RunLock, RunRuntime +from agent_env.task.store import TaskInstance + +Key = tuple[str, ...] + +# Overrides of where a run's sandboxes run, not of what runs in them, which the image identities record. +_PLACEMENT_OVERRIDES = frozenset({"agent_sandbox", "env_sandbox"}) +# The override that holds each step's own, by step id (``TaskStep.step_param_overrides``). +_STEP_PARAMS = "step_params" + + +class Drift(StrEnum): + HARD = "hard" + SOFT = "soft" + NEVER = "never" + + +@dataclass(frozen=True) +class Records: + """One attempt's records: the runtime and the lock it keeps on its instance, by its ``attempt_epoch``.""" + + instance_id: str + runtime: RunRuntime + lock: RunLock + + @property + def attempt_epoch(self) -> int: + return self.lock.attempt_epoch + + @staticmethod + def epochs(instance: TaskInstance) -> list[int]: + """The attempts of ``instance`` that recorded both a runtime and a lock, oldest first.""" + return sorted({r.attempt_epoch for r in instance.runtimes} & {lock.attempt_epoch for lock in instance.run_locks}) + + @classmethod + def of(cls, instance: TaskInstance, attempt_epoch: Optional[int] = None) -> Records: + """The records of ``instance``'s attempt that started under ``attempt_epoch``, its latest by default.""" + epochs = cls.epochs(instance) + if not epochs: + raise LookupError(f"instance {instance.instance_id} has no run records") + epoch = epochs[-1] if attempt_epoch is None else attempt_epoch + if epoch not in epochs: + raise LookupError(f"instance {instance.instance_id} has no records of attempt {epoch}; it has {epochs}") + runtime = next(r for r in instance.runtimes if r.attempt_epoch == epoch) + lock = next(lock for lock in instance.run_locks if lock.attempt_epoch == epoch) + return cls(instance.instance_id, runtime, lock) + + def to_dict(self) -> dict: + return {"instance_id": self.instance_id, "attempt_epoch": self.attempt_epoch, "stage": str(self.lock.stage)} + + +@dataclass(frozen=True) +class Difference: + """One difference between two attempts' records: the lock-table ``row`` it's in, the ``key`` within the row that + differs (empty for a row of one value), the first attempt's value and the second's, None where one has none, its + class, and ``regrade`` for a hard difference in the result rules or a verifier's settings.""" + + row: str + key: Key + old: Any + new: Any + drift: Drift + regrade: bool = False + + def to_dict(self) -> dict: + return {"row": self.row, "key": list(self.key), "old": self.old, "new": self.new, "drift": str(self.drift), + "regrade": self.regrade} + + +@dataclass(frozen=True) +class Comparison: + """Every difference between attempts ``a`` and ``b``, in lock-table order, and what couldn't be compared, as what + an attempt that didn't finish read.""" + + a: Records + b: Records + differences: list[Difference] + not_compared: list[str] + + def of(self, drift: Drift) -> list[Difference]: + return [d for d in self.differences if d.drift is drift] + + @property + def like_for_like(self) -> bool: + """Whether the two ran the same thing: no hard difference.""" + return not self.of(Drift.HARD) + + @property + def regrade(self) -> bool: + """Whether their grades are under different rules, which a regrade would put on one.""" + return any(d.regrade for d in self.differences) + + def to_dict(self) -> dict: + return {"a": self.a.to_dict(), "b": self.b.to_dict(), "like_for_like": self.like_for_like, + "regrade": self.regrade, "differences": [d.to_dict() for d in self.differences], + "not_compared": list(self.not_compared)} + + +@dataclass(frozen=True) +class _Row: + """A lock-table row: the record ``fields`` it covers, as ``Class.field``; its class; its values in an attempt's + records by key, None when the attempt didn't record them; and, for a row whose class or reach depends on the key, + ``classify`` and ``compared``.""" + + name: str + fields: tuple[str, ...] + drift: Drift + values: Callable[[Records], Optional[Mapping[Key, Any]]] + regrade: bool = False + classify: Optional[Callable[[Key, Records, Records], Drift]] = None + compared: Optional[Callable[[Key, Records, Records], bool]] = None + + +def compare(a: Records, b: Records) -> Comparison: + """Every difference between the records of attempts ``a`` and ``b``, each classed by its lock-table row.""" + differences: list[Difference] = [] + unread = [records for records in (a, b) if records.lock.reads is None] + for row in ROWS: + old, new = row.values(a), row.values(b) + if old is None or new is None: + continue + for key in sorted(old.keys() | new.keys()): + if row.compared is not None and not row.compared(key, a, b): + continue + before, after = old.get(key), new.get(key) + if before == after: + continue + drift = row.classify(key, a, b) if row.classify is not None else row.drift + differences.append(Difference(row.name, key, before, after, drift, row.regrade and drift is Drift.HARD)) + not_compared = [f"what each read: attempt {r.attempt_epoch} of {r.instance_id} didn't finish, so its reads aren't " + "recorded" for r in unread] + return Comparison(a, b, differences, not_compared) + + +def _one(value: Any) -> dict[Key, Any]: + return {(): value} + + +def _by_entity(records: Records, field_name: str, *, known: bool = False) -> Optional[dict[Key, Any]]: + """Each entity the attempt read, by kind and id, with the value of ``field_name``, or the values, in order, across + the versions of it it read, those that are None left out when ``known``; None when its reads aren't recorded.""" + reads: Optional[Iterable[ReadRecord]] = records.lock.reads + if reads is None: + return None + found: dict[Key, set] = {} + for read in reads: + value = getattr(read, field_name) + if known and value is None: + continue + found.setdefault((read.kind, read.id), set()).add(value) + return {key: values.pop() if len(values) == 1 else tuple(sorted(values, key=lambda v: (v is None, v))) + for key, values in found.items()} + + +def _version_drift(key: Key, a: Records, b: Records) -> Drift: + identities = [(_by_entity(records, "image_identity", known=True) or {}).get(key) for records in (a, b)] + return Drift.NEVER if identities[0] and identities[0] == identities[1] else Drift.HARD + + +def _overrides(records: Records) -> dict[Key, Any]: + """The run's overrides by name, a step's ``step_params`` by the step's id.""" + values: dict[Key, Any] = {} + for name, value in records.lock.intent.overrides.items(): + if name == _STEP_PARAMS and isinstance(value, Mapping): + values.update({(name, str(step)): params for step, params in value.items()}) + else: + values[(name,)] = value + return values + + +def _override_drift(key: Key, a: Records, b: Records) -> Drift: + return Drift.SOFT if key[0] in _PLACEMENT_OVERRIDES else Drift.HARD + + +def _in_both(of: Callable[[Records], Mapping[str, Any]]) -> Callable[[Key, Records, Records], bool]: + """Compare a key only where both attempts have the thing its first part names.""" + return lambda key, a, b: key[0] in of(a) and key[0] in of(b) + + +def _verifiers(records: Records) -> Mapping[str, Any]: + return records.lock.verifiers + + +def _graded(records: Records) -> Mapping[str, Any]: + return {step: v for step, v in records.lock.verifiers.items() if v.graded_settings is not None} + + +def _roles(records: Records) -> Mapping[str, Any]: + return records.lock.intent.roles + + +def _plugins(records: Records) -> Mapping[str, Any]: + return records.runtime.plugins + + +def _settings(records: Records) -> dict[Key, Any]: + return {(step, name): value for step, verifier in records.lock.verifiers.items() + for name, value in verifier.settings.items()} + + +def _set_while_grading(records: Records) -> dict[Key, Any]: + """Each verifier's settings its grading set or changed, as a judge's model it resolves as it calls: those its + grade records otherwise than it started with, which the starting settings' row already compares.""" + return {(step, name): value for step, verifier in records.lock.verifiers.items() + for name, value in (verifier.graded_settings or {}).items() + if name not in verifier.settings or verifier.settings[name] != value} + + +ROWS: tuple[_Row, ...] = ( + _Row("task id", ("RunIntent.task_id",), Drift.HARD, lambda r: _one(r.lock.intent.task_id)), + _Row("task version", ("RunIntent.task_version",), Drift.HARD, lambda r: _one(r.lock.intent.task_version)), + _Row("task content", ("RunIntent.content_hash",), Drift.HARD, lambda r: _one(r.lock.intent.content_hash)), + _Row("steps as run", ("RunIntent.steps_hash",), Drift.HARD, lambda r: _one(r.lock.intent.steps_hash)), + _Row("entity version", ("ReadRecord.kind", "ReadRecord.id", "ReadRecord.version"), Drift.HARD, + lambda r: _by_entity(r, "version"), classify=_version_drift), + _Row("entity type", ("ReadRecord.type",), Drift.HARD, lambda r: _by_entity(r, "type")), + _Row("image identity", ("ReadRecord.image_identity",), Drift.HARD, + lambda r: _by_entity(r, "image_identity", known=True)), + _Row("read at its latest", ("ReadRecord.latest",), Drift.NEVER, lambda r: _by_entity(r, "latest")), + _Row("read through an alias", ("ReadRecord.alias",), Drift.NEVER, lambda r: _by_entity(r, "alias")), + _Row("role model", ("RoleModel.model",), Drift.HARD, + lambda r: {(name,): role.model for name, role in r.lock.intent.roles.items()}), + _Row("role endpoint host", ("RoleModel.endpoint_host",), Drift.SOFT, + lambda r: {(name,): role.endpoint_host for name, role in r.lock.intent.roles.items()}, + compared=_in_both(_roles)), + _Row("role model's source", ("RoleModel.source",), Drift.NEVER, + lambda r: {(name,): role.source for name, role in r.lock.intent.roles.items()}, compared=_in_both(_roles)), + _Row("override", ("RunIntent.overrides",), Drift.HARD, _overrides, classify=_override_drift), + _Row("result rules", ("RunIntent.result_rules_version",), Drift.HARD, + lambda r: _one(r.lock.intent.result_rules_version), regrade=True), + _Row("verifier", ("VerifierRecord.type",), Drift.HARD, + lambda r: {(step,): v.type for step, v in r.lock.verifiers.items()}), + _Row("verifier settings", ("VerifierRecord.settings",), Drift.HARD, _settings, regrade=True, + compared=_in_both(_verifiers)), + _Row("verifier settings set while grading", ("VerifierRecord.graded_settings",), Drift.HARD, _set_while_grading, + regrade=True, compared=_in_both(_graded)), + _Row("verifier package", ("VerifierRecord.distribution",), Drift.SOFT, + lambda r: {(step,): v.distribution for step, v in r.lock.verifiers.items()}, compared=_in_both(_verifiers)), + _Row("verifier package version", ("VerifierRecord.version",), Drift.SOFT, + lambda r: {(step,): v.version for step, v in r.lock.verifiers.items()}, compared=_in_both(_verifiers)), + _Row("core package", ("RunRuntime.packages",), Drift.SOFT, + lambda r: {(name,): version for name, version in r.runtime.packages.items()}), + _Row("python", ("RunRuntime.python",), Drift.SOFT, lambda r: _one(r.runtime.python)), + _Row("plugin", ("InstalledPlugin.version",), Drift.SOFT, + lambda r: {(name,): plugin.version for name, plugin in r.runtime.plugins.items()}), + _Row("plugin install", ("InstalledPlugin.origin",), Drift.SOFT, + lambda r: {(name,): plugin.origin for name, plugin in r.runtime.plugins.items()}, + compared=_in_both(_plugins)), + _Row("type's package", ("RunRuntime.types",), Drift.SOFT, + lambda r: {(group, name): found for group, types in r.runtime.types.items() for name, found in types.items()}), + _Row("config found by", ("RunRuntime.config_selected_by",), Drift.NEVER, + lambda r: _one(r.runtime.config_selected_by)), +) + +# The record fields no row compares, and why. +NOT_COMPARED: Mapping[str, str] = { + "RunRuntime.attempt_epoch": "it names the attempt", + "RunLock.attempt_epoch": "it names the attempt", + "RunRuntime.stage": "whether the attempt finished says what was recorded, not what ran", + "RunLock.stage": "whether the attempt finished says what was recorded, not what ran", + "RunRuntime.record_version": "the shape the record was written in", + "RunLock.record_version": "the shape the record was written in", + "RunIntent.pins": "the versions the run was told to read, which its reads show", + "RunRuntime.plugins": "compared by each plugin's fields", + "RunLock.intent": "compared by its fields", + "RunIntent.roles": "compared by each role's fields", + "RunLock.verifiers": "compared by each verifier's fields", + "RunLock.reads": "compared by each read's fields", +} diff --git a/tst/unit/cli/task_diff_test.py b/tst/unit/cli/task_diff_test.py new file mode 100644 index 000000000..2ca026269 --- /dev/null +++ b/tst/unit/cli/task_diff_test.py @@ -0,0 +1,141 @@ +"""``agent-env task diff`` lists what two attempts' run records differ in, exits by whether they ran the same thing, and +names what it can't compare.""" + +import asyncio +import json + +import pytest +from click.testing import CliRunner + +from agent_env.cli.task.diff import _parse, diff +from agent_env.eval.lock import RoleModel +from agent_env.task import Task +from agent_env.task.record_writer import flush_run_records +from agent_env.task.run_records import RunIntent, RunLock, RunRuntime, Stage, VerifierRecord +from agent_env.task.store import get_task_instance_store +from agent_env.task_step.context import TaskStepContext +from agent_env.task_step.task_steps.verifiers.verifier import Verification, VerifierTaskStep + + +class _Score(VerifierTaskStep): + type = "task_diff_test_score" + entity_refs = () + + def __init__(self, *, threshold=0.5, **kwargs): + super().__init__(**kwargs) + self.threshold = threshold + + def to_dict(self): + return {**super().to_dict(), "threshold": self.threshold} + + @classmethod + def from_dict(cls, data): + return cls(**cls._base_from_dict(data), threshold=data.get("threshold", 0.5)) + + def verifier_settings(self, context): + return {**super().verifier_settings(context), **self.step_param_overrides(context)} + + async def verify(self, context): + return Verification(score=1.0) + + +@pytest.fixture(autouse=True) +def stores(local_stores): + yield + + +def _instance(*attempts) -> str: + """An instance whose attempts recorded the judge model and the threshold of each of ``attempts``.""" + store = get_task_instance_store() + instance_id = store.create_instance("t", 1, 1).instance_id + for epoch, (judge, threshold) in enumerate(attempts): + intent = RunIntent(task_id="t", task_version=1, content_hash="sha256:c", steps_hash="sha256:s", + roles={"judge": RoleModel(judge, "run", "models.example")}, result_rules_version=1) + verifiers = {"score": VerifierRecord("grade", "agentenv-framework", "1.0", {"threshold": threshold})} + store.record_run_records_sync( + instance_id, RunRuntime(epoch, {"agentenv-framework": "1.0"}, "3.12.4", stage=Stage.FINISHED), + RunLock(epoch, intent, verifiers, reads=[], stage=Stage.FINISHED)) + return instance_id + + +def _diff(*args): + return CliRunner().invoke(diff, list(args)) + + +def test_two_attempts_that_ran_the_same_thing_exit_0(): + result = _diff(_instance(("j", 0.5)), _instance(("j", 0.5))) + assert result.exit_code == 0 and "no differences: the same thing ran" in result.output + + +def test_a_hard_difference_exits_1_and_a_verifier_settings_one_offers_a_regrade(): + result = _diff(_instance(("j", 0.5)), _instance(("k", 0.9))) + + assert result.exit_code == 1 + assert "hard role model judge: j -> k" in result.output + assert "hard verifier settings score threshold: 0.5 -> 0.9 (regrade)" in result.output + assert "2 hard, 0 soft, 0 never: they didn't run the same thing" in result.output + assert "regrade one under the other's" in result.output + + +def test_one_instance_alone_compares_its_first_attempt_with_its_latest(): + instance_id = _instance(("j", 0.5), ("j", 0.5), ("k", 0.5)) + + result = _diff(instance_id) + + assert result.exit_code == 1 and f"attempt 0 of {instance_id} -> attempt 2 of {instance_id}" in result.output + + +def test_an_attempt_is_named_after_its_instance_and_an_at_sign(): + instance_id = _instance(("j", 0.5), ("k", 0.5)) + + assert _diff(f"{instance_id}@0", f"{instance_id}@0").exit_code == 0 + assert _diff(f"{instance_id}@0", f"{instance_id}@1").exit_code == 1 + assert _parse("@local/~/triage/runs-7f3a@2") == ("@local/~/triage/runs-7f3a", 2) + assert _parse("@local/~/triage/runs-7f3a") == ("@local/~/triage/runs-7f3a", None) + + +def test_the_comparison_as_json(): + result = _diff(_instance(("j", 0.5)), _instance(("k", 0.5)), "--json") + + printed = json.loads(result.output) + assert (result.exit_code, printed["like_for_like"], printed["regrade"]) == (1, False, False) + assert printed["differences"] == [{"row": "role model", "key": ["judge"], "old": "j", "new": "k", "drift": "hard", + "regrade": False}] + + +@pytest.mark.parametrize("args, message", [ + (["nowhere"], "no task instance 'nowhere'"), + (["ONE"], "has records of 1 attempt; name a second instance"), + (["ONE@3", "ONE"], "has no records of attempt 3"), + (["ONE@0"], "name a second attempt to compare attempt 0 with"), +]) +def test_what_cant_be_compared_exits_2_and_says_why(args, message): + instance_id = _instance(("j", 0.5)) + + result = _diff(*[arg.replace("ONE", instance_id) for arg in args]) + + assert result.exit_code == 2 and message in result.output + + +def test_two_runs_of_a_task_with_different_step_params_and_a_resume_of_one(monkeypatch): + """Records a real run wrote, through Task.run: a run with another verifier threshold differs in its override and + its verifier's settings; a resume that reruns only the verifier ran the same thing as its first attempt.""" + task = Task(id="t", version=1, steps=[_Score(id="score", version=None, verifier_id="score")]) + + def run(**kwargs): + context = TaskStepContext(metadata={"user_overrides": kwargs.pop("overrides", {})}) + asyncio.run(task.run(context=context, **kwargs)) + assert flush_run_records(10) + return context.instance_id + + first = run() + other = run(overrides={"step_params": {"score": {"threshold": 0.9}}}) + run(instance_id=first, start_step=0) + + differs = _diff(first, other) + resumed = _diff(first) + + assert differs.exit_code == 1, differs.output + assert "hard override step_params score:" in differs.output + assert "verifier settings score threshold: 0.5 -> 0.9 (regrade)" in differs.output + assert resumed.exit_code == 0 and f"attempt 0 of {first} -> attempt 1 of {first}" in resumed.output diff --git a/tst/unit/task/drift_test.py b/tst/unit/task/drift_test.py new file mode 100644 index 000000000..a81741686 --- /dev/null +++ b/tst/unit/task/drift_test.py @@ -0,0 +1,241 @@ +"""Two attempts' run records compare by the lock table: each row's change is one difference of its class, every record +field is in a row or named as not compared, and an image's identity, not its artifact's version, says whether it +changed.""" + +import copy +import dataclasses +from dataclasses import dataclass, replace +from typing import Callable + +import pytest + +from agent_env.eval.lock import RoleModel +from agent_env.task.drift import NOT_COMPARED, ROWS, Drift, Records, compare +from agent_env.task.run_records import ( + InstalledPlugin, + ReadRecord, + RunIntent, + RunLock, + RunRuntime, + Stage, + VerifierRecord, +) +from agent_env.task.store import TaskInstance + +RECORD_CLASSES = (RunRuntime, InstalledPlugin, RunLock, RunIntent, RoleModel, VerifierRecord, ReadRecord) +HARD, SOFT, NEVER = Drift.HARD, Drift.SOFT, Drift.NEVER + + +def _records(instance_id="first", epoch=0) -> Records: + """An attempt whose every field is set, the base each case changes one thing of.""" + runtime = RunRuntime(attempt_epoch=epoch, packages={"agentenv-framework": "1.0", "agentenv-framework-protocol": "1.0"}, + python="3.12.4", plugins={"acme-steps": InstalledPlugin("1.2.0", "index")}, + config_selected_by="discovered", types={"task_steps": {"grade": "acme-steps"}}, + stage=Stage.FINISHED) + intent = RunIntent(task_id="t", task_version=1, content_hash="sha256:c", steps_hash="sha256:s", + pins={"env": {"office": 1}}, + roles={"solver": RoleModel("m", "run", "models.example"), + "judge": RoleModel("j", "config_role", "models.example")}, + overrides={"judge_model": "j", "agent_sandbox": "local", + "step_params": {"score": {"threshold": 0.5}}}, + result_rules_version=1) + verifiers = {"score": VerifierRecord("grade", "acme-steps", "1.2.0", {"threshold": 0.5}, + {"threshold": 0.5, "model": "j"})} + reads = [ReadRecord("env", "office", 1, "multi", latest=True), + ReadRecord("artifact", "office-image", 3, "docker_image", image_identity="source:sha256:x"), + ReadRecord("agent", "solver", 2, "a2a_agent", latest=True), + ReadRecord("artifact", "solver-image", 1, "docker_image", image_identity="registry:sha256:h1")] + return Records(instance_id, runtime, RunLock(epoch, intent, verifiers, reads, stage=Stage.FINISHED)) + + +def _changed(change: Callable[[Records], None]) -> Records: + records = copy.deepcopy(_records("second")) + change(records) + return records + + +def _read(records: Records, entity_id: str, **fields) -> None: + records.lock.reads[:] = [replace(r, **fields) if r.id == entity_id else r for r in records.lock.reads] + + +def _threshold(records: Records, value: float) -> None: + """A starting setting changed as a run changes it: its grade records it too, which is still one difference.""" + verifier = records.lock.verifiers["score"] + verifier.settings["threshold"] = verifier.graded_settings["threshold"] = value + + +@dataclass(frozen=True) +class Case: + row: str + change: Callable[[Records], None] + key: tuple + drift: Drift + regrade: bool = False + + +def _set(path: str, value): + """A change that sets the attribute at the dotted ``path`` of the records, through any mapping on the way.""" + *parents, name = path.split(".") + + def change(records): + target = records + for part in parents: + target = target[part] if isinstance(target, dict) else getattr(target, part) + if isinstance(target, dict): + target[name] = value + else: + setattr(target, name, value) + return change + + +CASES = ( + Case("task id", _set("lock.intent.task_id", "u"), (), HARD), + Case("task version", _set("lock.intent.task_version", 2), (), HARD), + Case("task content", _set("lock.intent.content_hash", "sha256:d"), (), HARD), + Case("steps as run", _set("lock.intent.steps_hash", "sha256:t"), (), HARD), + Case("entity version", lambda r: _read(r, "office", version=2), ("env", "office"), HARD), + Case("entity type", lambda r: _read(r, "office", type="mcp_server"), ("env", "office"), HARD), + Case("image identity", lambda r: _read(r, "solver-image", image_identity="registry:sha256:h2"), + ("artifact", "solver-image"), HARD), + Case("read at its latest", lambda r: _read(r, "office", latest=False), ("env", "office"), NEVER), + Case("read through an alias", lambda r: _read(r, "solver", alias=True), ("agent", "solver"), NEVER), + Case("role model", lambda r: r.lock.intent.roles.update(judge=RoleModel("k", "config_role", "models.example")), + ("judge",), HARD), + Case("role endpoint host", + lambda r: r.lock.intent.roles.update(judge=RoleModel("j", "config_role", "other.example")), ("judge",), SOFT), + Case("role model's source", lambda r: r.lock.intent.roles.update(judge=RoleModel("j", "run", "models.example")), + ("judge",), NEVER), + Case("override", _set("lock.intent.overrides.judge_model", "k"), ("judge_model",), HARD), + Case("result rules", _set("lock.intent.result_rules_version", 2), (), HARD, regrade=True), + Case("verifier", lambda r: r.lock.verifiers.update(score=replace(r.lock.verifiers["score"], type="rubric")), + ("score",), HARD), + Case("verifier settings", lambda r: _threshold(r, 0.9), ("score", "threshold"), HARD, regrade=True), + Case("verifier settings set while grading", + lambda r: r.lock.verifiers["score"].graded_settings.update(model="k"), ("score", "model"), HARD, regrade=True), + Case("verifier package", lambda r: r.lock.verifiers.update(score=replace(r.lock.verifiers["score"], + distribution="acme-grades")), + ("score",), SOFT), + Case("verifier package version", + lambda r: r.lock.verifiers.update(score=replace(r.lock.verifiers["score"], version="1.3.0")), ("score",), SOFT), + Case("core package", _set("runtime.packages.agentenv-framework", "1.1"), ("agentenv-framework",), SOFT), + Case("python", _set("runtime.python", "3.13.1"), (), SOFT), + Case("plugin", lambda r: r.runtime.plugins.update({"acme-steps": InstalledPlugin("1.3.0", "index")}), + ("acme-steps",), SOFT), + Case("plugin install", lambda r: r.runtime.plugins.update({"acme-steps": InstalledPlugin("1.2.0", "editable")}), + ("acme-steps",), SOFT), + Case("type's package", lambda r: r.runtime.types["task_steps"].update(grade="acme-grades"), + ("task_steps", "grade"), SOFT), + Case("config found by", _set("runtime.config_selected_by", "environment"), (), NEVER), +) + + +def test_every_row_has_a_case_and_every_record_field_a_row_or_a_reason(): + assert {case.row for case in CASES} == {row.name for row in ROWS} + fields = {f"{cls.__name__}.{f.name}" for cls in RECORD_CLASSES for f in dataclasses.fields(cls)} + in_rows = [name for row in ROWS for name in row.fields] + assert len(in_rows) == len(set(in_rows)) and not set(in_rows) & set(NOT_COMPARED) + assert set(in_rows) | set(NOT_COMPARED) == fields + + +@pytest.mark.parametrize("case", CASES, ids=[case.row for case in CASES]) +def test_a_change_in_one_row_is_one_difference_of_its_class(case): + comparison = compare(_records(), _changed(case.change)) + + [difference] = comparison.differences + assert (difference.row, difference.key, difference.drift, difference.regrade) == ( + case.row, case.key, case.drift, case.regrade) + assert comparison.like_for_like is (case.drift is not HARD) and comparison.regrade is case.regrade + + +def test_identical_attempts_have_no_differences(): + comparison = compare(_records(), _records("second", epoch=1)) + assert (comparison.differences, comparison.not_compared, comparison.like_for_like) == ([], [], True) + + +def test_an_image_put_again_from_an_unchanged_context_is_the_same_image(): + """Rebuilding an unchanged build context makes a new version of its artifact with the same identity.""" + comparison = compare(_records(), _changed(lambda r: _read(r, "office-image", version=4))) + + [difference] = comparison.differences + assert (difference.row, difference.drift, difference.old, difference.new) == ("entity version", NEVER, 3, 4) + assert comparison.like_for_like + + +def test_an_image_at_another_version_with_another_identity_is_hard_drift_in_both_rows(): + comparison = compare(_records(), _changed( + lambda r: _read(r, "office-image", version=4, image_identity="source:sha256:y"))) + + assert [(d.row, d.drift) for d in comparison.differences] == [("entity version", HARD), ("image identity", HARD)] + + +def test_an_entity_read_at_two_versions_lists_both_in_order(): + def change(records): + records.lock.reads.append(ReadRecord("agent", "solver", 10, "a2a_agent")) + + differences = compare(_records(), _changed(change)).differences + assert [(d.row, d.old, d.new) for d in differences] == [("entity version", 2, (2, 10)), + ("read at its latest", True, (False, True))] + + +def test_where_a_run_ran_is_soft_and_each_steps_params_are_their_own_override(): + def change(records): + records.lock.intent.overrides.update(agent_sandbox="modal", step_params={"score": {"threshold": 0.9}}) + + comparison = compare(_records(), _changed(change)) + + assert [(d.key, d.drift) for d in comparison.differences] == [(("agent_sandbox",), SOFT), + (("step_params", "score"), HARD)] + + +def test_a_verifier_added_is_one_difference_however_many_fields_it_has(): + def change(records): + records.lock.verifiers["late"] = VerifierRecord("grade", "acme-steps", "1.2.0", {"threshold": 0.7}, None) + + [difference] = compare(_records(), _changed(change)).differences + assert (difference.row, difference.key, difference.old, difference.new) == ("verifier", ("late",), None, "grade") + + +def test_a_verifier_one_attempt_didnt_grade_is_compared_by_its_starting_settings_alone(): + """A resume that doesn't rerun a verifier records no graded settings for it, which isn't a difference.""" + def change(records): + records.lock.verifiers["score"] = replace(records.lock.verifiers["score"], graded_settings=None) + + assert compare(_records(), _changed(change)).differences == [] + + +def test_an_attempt_that_didnt_finish_is_compared_without_its_reads(): + def change(records): + records.lock.reads = None + records.lock.stage = Stage.STARTED + + comparison = compare(_records(), _changed(change)) + + assert comparison.differences == [] + assert comparison.not_compared == ["what each read: attempt 0 of second didn't finish, so its reads aren't " + "recorded"] + + +@pytest.mark.parametrize("gap, change, row", [ + ("an unpinned harness version: the agent's image rebuilt with another one", + lambda r: _read(r, "solver-image", image_identity="registry:sha256:h2"), "image identity"), + ("an unpinned effort: one run pins it", + lambda r: r.lock.intent.overrides.update(agent_effort="high"), "override"), + ("an unrecorded macOS build: the computer's image differs", + lambda r: r.lock.reads.append(ReadRecord("artifact", "macos-15", 1, "computer", image_identity="registry:sha256:m")), + "entity version"), +], ids=["harness version", "effort", "macos build"]) +def test_the_run_manifest_gaps_each_show_up_as_a_hard_difference(gap, change, row): + comparison = compare(_records(), _changed(change)) + assert row in {d.row for d in comparison.differences} and not comparison.like_for_like, gap + + +def test_an_instances_records_by_attempt_and_its_latest_by_default(): + first, later = _records(epoch=0), _records(epoch=2) + instance = TaskInstance(instance_id="i", task_id="t", task_version=1, status="completed", current_step=1, + total_steps=1, runtimes=[first.runtime, later.runtime], + run_locks=[first.lock, later.lock, replace(first.lock, attempt_epoch=5)]) + + assert Records.epochs(instance) == [0, 2] + assert Records.of(instance).attempt_epoch == 2 and Records.of(instance, 0).attempt_epoch == 0 + with pytest.raises(LookupError, match="no records of attempt 5"): + Records.of(instance, 5) From 6531f47b48e88bc5ff2f68ab2057d94e300bf071 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 30 Nov 2026 18:55:32 -0800 Subject: [PATCH 02/10] feat(task): an attempt records the steps it ran, and an entity only one attempt read is drift only when both ran them A resume runs only the rest of a task's steps, which read less, so an entity its first attempt read and it didn't is no difference. Each attempt now records the ids of the steps it was asked to run (`steps_run`, from its start step to its end step), and the comparator counts an entity only one attempt read as hard drift when both ran the same steps, as when the configured default agent changed between two full runs, and otherwise leaves such entities out, saying how many and why. `steps_run` itself is never drift. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 33 +++++++++++----------- src/agent_env/task/drift.py | 46 ++++++++++++++++++++++++++----- src/agent_env/task/run_lock.py | 22 +++++++++------ src/agent_env/task/run_records.py | 10 +++++-- src/agent_env/task/task.py | 3 +- tst/unit/cli/task_diff_test.py | 34 +++++++++++++++++++---- tst/unit/task/drift_test.py | 38 ++++++++++++++++++++++++- tst/unit/task/run_lock_test.py | 3 +- 8 files changed, 147 insertions(+), 42 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 131b079dc..c9e53829d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -490,22 +490,23 @@ orchestrators call it the same way. What callers rely on: `task/run_records.py` declares: `RunRuntime` (the core's and protocol's versions as `packages`, the Python version, each installed plugin's version and install kind, how the config file was found, and the distribution of each type the run used, from `agent_env.plugins`' `distribution_of`, its sandbox providers those of the deployments its context - records; never a path) and `RunLock` (its `intent`, the task's content hash, a hash of its steps as run, its pins, - each role's model and endpoint host as this process resolves them, the overrides without secrets and the result rules - version, computed as the eval plan computes its own, `eval/intent.py`; each verifier's settings and version at the - start and as graded, by the grades whose `attempt_epoch` is this attempt's or a retry's within it; and every entity - version the run read, each image with its `image_identity`). Each is written `started` and then `finished`, however - the run ends, by writer threads of their own (`task/record_writer.py`, never awaited; `flush_run_records` waits for - them, and an exit waits 10 s at most), under a counter of their own (`run_records_rev`) that the instance's other - writes don't check, nor these theirs (on DynamoDB, which conditions a write on the whole item, one still retries the - other); the store keeps the finished record whichever lands last, and a resume adds its own. An instance leaves out, - with a warning, a record this version can't read. A worker that runs a task's steps itself enters `run_recorded` - around them, once per attempt in the process that runs them all, as it sets `run_pins`. `task/drift.py` classes every - difference between two attempts' records by the lock table (`compare`, its rows `ROWS`, every record field in one or - in `NOT_COMPARED`): `hard` when they ran different things, `regrade` too for the result rules or a verifier's - settings, `soft` for code meant to change under a run, as an upgraded package, and `never`, as how a version was asked - for; an image's identity, not its artifact's version, says whether it changed. `agent-env task diff` lists the - differences, exiting 1 on hard drift. + records; never a path) and `RunLock` (its `intent`, the task's content hash, a hash of its steps as run and the ids of + those it was asked to run (`steps_run`), its pins, each role's model and endpoint host as this process resolves them, + the overrides without secrets and the result rules version, computed as the eval plan computes its own, + `eval/intent.py`; each verifier's settings and version at the start and as graded, by the grades whose `attempt_epoch` + is this attempt's or a retry's within it; and every entity version the run read, each image with its + `image_identity`). Each is written `started` and then `finished`, however the run ends, by writer threads of their own + (`task/record_writer.py`, never awaited; `flush_run_records` waits for them, and an exit waits 10 s at most), under a + counter of their own (`run_records_rev`) that the instance's other writes don't check, nor these theirs (on DynamoDB, + which conditions a write on the whole item, one still retries the other); the store keeps the finished record + whichever lands last, and a resume adds its own. An instance leaves out, with a warning, a record this version can't + read. A worker that runs a task's steps itself enters `run_recorded` around them, once per attempt in the process that + runs them all, as it sets `run_pins`. `task/drift.py` classes every difference between two attempts' records by the + lock table (`compare`, its rows `ROWS`, every record field in one or in `NOT_COMPARED`): `hard` when they ran + different things, `regrade` too for the result rules or a verifier's settings, `soft` for code meant to change under a + run, as an upgraded package, and `never`, as how a version was asked for; an image's identity, not its artifact's + version, says whether it changed, and an entity only one attempt read is a difference only when both ran the same + steps. `agent-env task diff` lists the differences, exiting 1 on hard drift. - A runner that must hear from a long step puts a zero-argument callable at `context.metadata[HEARTBEAT_KEY]` (`task_step/context.py`); a step that blocks for long calls `context.heartbeat()`, a no-op without one. The key is in `_REDACTED_KEYS`, so it is never persisted. diff --git a/src/agent_env/task/drift.py b/src/agent_env/task/drift.py index 203cbe830..f44765238 100644 --- a/src/agent_env/task/drift.py +++ b/src/agent_env/task/drift.py @@ -7,8 +7,9 @@ An image's identity, not its artifact's version, says whether it changed: an image read at another version with the same identity is the same image, so its version's change is ``never``. A row that reports a thing added or removed, a -verifier, a role or a plugin, is the only one that does; the rows of that thing's other fields compare it only where -both attempts have it. +verifier, a role, a plugin or an entity read, is the only one that does; the rows of that thing's other fields compare +it only where both attempts have it. An entity only one attempt read is a difference only when both ran the same steps +(``RunIntent.steps_run``): a resume runs only the rest, which read less, and what it didn't read isn't compared. """ from __future__ import annotations @@ -148,9 +149,36 @@ def compare(a: Records, b: Records) -> Comparison: differences.append(Difference(row.name, key, before, after, drift, row.regrade and drift is Drift.HARD)) not_compared = [f"what each read: attempt {r.attempt_epoch} of {r.instance_id} didn't finish, so its reads aren't " "recorded" for r in unread] + if not unread and not _same_steps(a, b) and (only := _read(a) ^ _read(b)): + not_compared.append(f"the {len(only)} entit{'y' if len(only) == 1 else 'ies'} only one of them read: " + f"{_ran(a)} and {_ran(b)}, so they ran different steps") return Comparison(a, b, differences, not_compared) +def _read(records: Records) -> set[Key]: + return {(read.kind, read.id) for read in records.lock.reads or ()} + + +def _same_steps(a: Records, b: Records) -> bool: + return a.lock.intent.steps_run is not None and a.lock.intent.steps_run == b.lock.intent.steps_run + + +def _read_by_both(key: Key, a: Records, b: Records) -> bool: + return key in _read(a) and key in _read(b) + + +def _read_by_both_or_same_steps(key: Key, a: Records, b: Records) -> bool: + return _same_steps(a, b) or _read_by_both(key, a, b) + + +def _ran(records: Records) -> str: + steps = records.lock.intent.steps_run + where = f"attempt {records.attempt_epoch} of {records.instance_id}" + if steps is None: + return f"{where} doesn't record which steps it ran" + return f"{where} ran {len(steps)} step{'s' * (len(steps) != 1)}" + + def _one(value: Any) -> dict[Key, Any]: return {(): value} @@ -230,13 +258,17 @@ def _set_while_grading(records: Records) -> dict[Key, Any]: _Row("task version", ("RunIntent.task_version",), Drift.HARD, lambda r: _one(r.lock.intent.task_version)), _Row("task content", ("RunIntent.content_hash",), Drift.HARD, lambda r: _one(r.lock.intent.content_hash)), _Row("steps as run", ("RunIntent.steps_hash",), Drift.HARD, lambda r: _one(r.lock.intent.steps_hash)), + _Row("steps it ran", ("RunIntent.steps_run",), Drift.NEVER, + lambda r: _one(None if r.lock.intent.steps_run is None else tuple(r.lock.intent.steps_run))), _Row("entity version", ("ReadRecord.kind", "ReadRecord.id", "ReadRecord.version"), Drift.HARD, - lambda r: _by_entity(r, "version"), classify=_version_drift), - _Row("entity type", ("ReadRecord.type",), Drift.HARD, lambda r: _by_entity(r, "type")), + lambda r: _by_entity(r, "version"), classify=_version_drift, compared=_read_by_both_or_same_steps), + _Row("entity type", ("ReadRecord.type",), Drift.HARD, lambda r: _by_entity(r, "type"), compared=_read_by_both), _Row("image identity", ("ReadRecord.image_identity",), Drift.HARD, - lambda r: _by_entity(r, "image_identity", known=True)), - _Row("read at its latest", ("ReadRecord.latest",), Drift.NEVER, lambda r: _by_entity(r, "latest")), - _Row("read through an alias", ("ReadRecord.alias",), Drift.NEVER, lambda r: _by_entity(r, "alias")), + lambda r: _by_entity(r, "image_identity", known=True), compared=_read_by_both), + _Row("read at its latest", ("ReadRecord.latest",), Drift.NEVER, lambda r: _by_entity(r, "latest"), + compared=_read_by_both), + _Row("read through an alias", ("ReadRecord.alias",), Drift.NEVER, lambda r: _by_entity(r, "alias"), + compared=_read_by_both), _Row("role model", ("RoleModel.model",), Drift.HARD, lambda r: {(name,): role.model for name, role in r.lock.intent.roles.items()}), _Row("role endpoint host", ("RoleModel.endpoint_host",), Drift.SOFT, diff --git a/src/agent_env/task/run_lock.py b/src/agent_env/task/run_lock.py index d4bcf48e7..f7cca5fa5 100644 --- a/src/agent_env/task/run_lock.py +++ b/src/agent_env/task/run_lock.py @@ -89,9 +89,11 @@ def started_runtime(attempt_epoch: int, steps: Sequence[TaskStep]) -> RunRuntime ) -def started_lock(task: "Task", steps: Sequence[TaskStep], context: TaskStepContext, attempt_epoch: int) -> RunLock: +def started_lock(task: "Task", steps: Sequence[TaskStep], context: TaskStepContext, attempt_epoch: int, + start_step: int = 0, end_step: Optional[int] = None) -> RunLock: """The lock of an attempt this process starts: its intent and its verifiers as they stand at the start. ``steps`` - are the steps it runs, its seed applied; ``task`` the task as stored, whose content its hash names.""" + are the task's steps, its seed applied, of which the attempt runs ``start_step`` to ``end_step``; ``task`` the task + as stored, whose content its hash names.""" user_overrides = context.metadata.get("user_overrides") or {} overrides = run_overrides(user_overrides, agent_model=context.agent_model, agent_artifact_id=context.agent_artifact_id) @@ -102,6 +104,7 @@ def started_lock(task: "Task", steps: Sequence[TaskStep], context: TaskStepConte task_version=task.version, content_hash=content_hash(task), steps_hash=steps_hash(steps), + steps_run=[step.id for step in steps[start_step:end_step]], pins=checked_pins(user_overrides.get(PINS_KEY)), roles=role_models(overrides), overrides=recorded_overrides(overrides), @@ -159,11 +162,13 @@ def read_records(reads: Iterable[Read]) -> list[ReadRecord]: @contextlib.asynccontextmanager async def run_recorded(instance_id: Optional[str], task: "Task", steps: Sequence[TaskStep], - context: TaskStepContext, attempt_epoch: int) -> AsyncIterator[None]: + context: TaskStepContext, attempt_epoch: int, *, start_step: int = 0, + end_step: Optional[int] = None) -> AsyncIterator[None]: """Record the attempt's start on ``instance_id``, list every entity the block reads, and record that when the block - ends, however it ends. Without an instance, as when registering the run failed, the block runs unrecorded. Neither - write is awaited, so the block's cancel and its end are the run's own.""" - started = _started(instance_id, task, steps, context, attempt_epoch) if instance_id else None + ends, however it ends. The block runs ``steps[start_step:end_step]``, which its lock names. Without an instance, as + when registering the run failed, the block runs unrecorded. Neither write is awaited, so the block's cancel and its + end are the run's own.""" + started = _started(instance_id, task, steps, context, attempt_epoch, start_step, end_step) if instance_id else None if started is None: yield return @@ -197,11 +202,12 @@ def _write(instance_id: str, runtime: RunRuntime, lock: RunLock) -> None: def _started(instance_id: str, task: "Task", steps: Sequence[TaskStep], context: TaskStepContext, - attempt_epoch: int) -> Optional[tuple[RunRuntime, RunLock]]: + attempt_epoch: int, start_step: int, end_step: Optional[int]) -> Optional[tuple[RunRuntime, RunLock]]: """The attempt's started records, made on the event loop, which reads installed metadata and the context but no store; None, logged, when they can't be made, so the run goes on unrecorded.""" try: - return started_runtime(attempt_epoch, steps), started_lock(task, steps, context, attempt_epoch) + return (started_runtime(attempt_epoch, steps), + started_lock(task, steps, context, attempt_epoch, start_step, end_step)) except Exception: logger.warning("What attempt %s of %s runs couldn't be recorded", attempt_epoch, instance_id, exc_info=True) return None diff --git a/src/agent_env/task/run_records.py b/src/agent_env/task/run_records.py index f50820709..f96c67041 100644 --- a/src/agent_env/task/run_records.py +++ b/src/agent_env/task/run_records.py @@ -97,9 +97,10 @@ def from_dict(cls, data: dict) -> RunRuntime: @dataclass class RunIntent: """What an attempt was asked to do, computed as an eval plan computes its own (``agent_env.eval.intent``): the task's - id, version and content hash; ``steps_hash``, of its steps as this run runs them, its seed applied; its pins; each - role's model and endpoint host as this process's config resolves them; its overrides without secrets; and the - result rules version.""" + id, version and content hash; ``steps_hash``, of its steps as this run runs them, its seed applied; ``steps_run``, + the ids of the steps it was asked to run, from its start step to its end step, as a resume runs only the rest, None + for a record that predates it; its pins; each role's model and endpoint host as this process's config resolves + them; its overrides without secrets; and the result rules version.""" task_id: str task_version: int @@ -109,6 +110,7 @@ class RunIntent: roles: dict[str, RoleModel] = field(default_factory=dict) overrides: dict[str, Any] = field(default_factory=dict) result_rules_version: int = 0 + steps_run: Optional[list[str]] = None def to_dict(self) -> dict: return { @@ -116,6 +118,7 @@ def to_dict(self) -> dict: "task_version": self.task_version, "content_hash": self.content_hash, "steps_hash": self.steps_hash, + "steps_run": None if self.steps_run is None else list(self.steps_run), "pins": self.pins, "roles": {name: role.to_dict() for name, role in self.roles.items()}, "overrides": self.overrides, @@ -129,6 +132,7 @@ def from_dict(cls, data: dict) -> RunIntent: task_version=data["task_version"], content_hash=data["content_hash"], steps_hash=data.get("steps_hash", ""), + steps_run=None if data.get("steps_run") is None else list(data["steps_run"]), pins=data.get("pins") or {}, roles={name: RoleModel.from_dict(role) for name, role in (data.get("roles") or {}).items()}, overrides=data.get("overrides") or {}, diff --git a/src/agent_env/task/task.py b/src/agent_env/task/task.py index 00b6f50c4..2225f9a2c 100644 --- a/src/agent_env/task/task.py +++ b/src/agent_env/task/task.py @@ -613,7 +613,8 @@ async def _run( state = self._build_scheduler_state(steps, start_step, end_step) if instance: state.epoch = instance.attempt_epoch - async with run_recorded(instance_id, self, steps, context, state.epoch): + async with run_recorded(instance_id, self, steps, context, state.epoch, start_step=start_step, + end_step=end_step): # _drive_dag drains in-flight steps and records the failure itself if it raises. first_error, first_error_step_id = await self._drive_dag( steps, state, total, context, instance_id, diff --git a/tst/unit/cli/task_diff_test.py b/tst/unit/cli/task_diff_test.py index 2ca026269..1cfac8e3d 100644 --- a/tst/unit/cli/task_diff_test.py +++ b/tst/unit/cli/task_diff_test.py @@ -7,14 +7,33 @@ import pytest from click.testing import CliRunner +from agent_env.a2a_agent import A2AAgent from agent_env.cli.task.diff import _parse, diff +from agent_env.env.env import Env from agent_env.eval.lock import RoleModel from agent_env.task import Task from agent_env.task.record_writer import flush_run_records from agent_env.task.run_records import RunIntent, RunLock, RunRuntime, Stage, VerifierRecord from agent_env.task.store import get_task_instance_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 Verification, VerifierTaskStep +from tst.util import entities + + +class _Reads(TaskStep): + """Reads an env and an agent at their latest, as a deploy does.""" + + type = "task_diff_test_reads" + entity_refs = () + + @classmethod + def from_dict(cls, data): + return cls(**cls._base_from_dict(data)) + + async def execute(self, context): + await asyncio.to_thread(lambda: (Env.get("office"), A2AAgent.get("solver"))) + return context class _Score(VerifierTaskStep): @@ -117,10 +136,13 @@ def test_what_cant_be_compared_exits_2_and_says_why(args, message): assert result.exit_code == 2 and message in result.output -def test_two_runs_of_a_task_with_different_step_params_and_a_resume_of_one(monkeypatch): - """Records a real run wrote, through Task.run: a run with another verifier threshold differs in its override and - its verifier's settings; a resume that reruns only the verifier ran the same thing as its first attempt.""" - task = Task(id="t", version=1, steps=[_Score(id="score", version=None, verifier_id="score")]) +def test_two_runs_of_a_task_with_different_step_params_and_a_resume_of_one(): + """Records real runs wrote, through Task.run: a run with another verifier threshold differs in its override and + its verifier's settings; a resume that reruns only the verifier, reading nothing, ran the same thing as its first + attempt, what only the first read not compared.""" + entities.office() + task = Task(id="t", version=1, steps=[_Reads(id="reads", version=None), + _Score(id="score", version=None, verifier_id="score")]) def run(**kwargs): context = TaskStepContext(metadata={"user_overrides": kwargs.pop("overrides", {})}) @@ -130,7 +152,7 @@ def run(**kwargs): first = run() other = run(overrides={"step_params": {"score": {"threshold": 0.9}}}) - run(instance_id=first, start_step=0) + run(instance_id=first, start_step=1) differs = _diff(first, other) resumed = _diff(first) @@ -139,3 +161,5 @@ def run(**kwargs): assert "hard override step_params score:" in differs.output assert "verifier settings score threshold: 0.5 -> 0.9 (regrade)" in differs.output assert resumed.exit_code == 0 and f"attempt 0 of {first} -> attempt 1 of {first}" in resumed.output + assert 'never steps it ran: ["reads", "score"] -> ["score"]' in resumed.output + assert "not compared: the 7 entities only one of them read: attempt 0" in resumed.output diff --git a/tst/unit/task/drift_test.py b/tst/unit/task/drift_test.py index a81741686..c563717ea 100644 --- a/tst/unit/task/drift_test.py +++ b/tst/unit/task/drift_test.py @@ -33,7 +33,7 @@ def _records(instance_id="first", epoch=0) -> Records: config_selected_by="discovered", types={"task_steps": {"grade": "acme-steps"}}, stage=Stage.FINISHED) intent = RunIntent(task_id="t", task_version=1, content_hash="sha256:c", steps_hash="sha256:s", - pins={"env": {"office": 1}}, + steps_run=["deploy", "score"], pins={"env": {"office": 1}}, roles={"solver": RoleModel("m", "run", "models.example"), "judge": RoleModel("j", "config_role", "models.example")}, overrides={"judge_model": "j", "agent_sandbox": "local", @@ -93,6 +93,7 @@ def change(records): Case("task version", _set("lock.intent.task_version", 2), (), HARD), Case("task content", _set("lock.intent.content_hash", "sha256:d"), (), HARD), Case("steps as run", _set("lock.intent.steps_hash", "sha256:t"), (), HARD), + Case("steps it ran", _set("lock.intent.steps_run", ["score"]), (), NEVER), Case("entity version", lambda r: _read(r, "office", version=2), ("env", "office"), HARD), Case("entity type", lambda r: _read(r, "office", type="mcp_server"), ("env", "office"), HARD), Case("image identity", lambda r: _read(r, "solver-image", image_identity="registry:sha256:h2"), @@ -177,6 +178,41 @@ def change(records): ("read at its latest", True, (False, True))] +def test_an_entity_only_one_attempt_read_is_hard_drift_when_both_ran_the_same_steps(): + """As when the configured default agent changed: the same steps read another agent.""" + def change(records): + records.lock.reads[:] = [r for r in records.lock.reads if r.id != "solver"] + + [difference] = compare(_records(), _changed(change)).differences + assert (difference.row, difference.key, difference.old, difference.new, difference.drift) == ( + "entity version", ("agent", "solver"), 2, None, HARD) + + +def test_a_resume_that_ran_the_rest_is_compared_on_what_both_read(): + def change(records): + records.lock.intent.steps_run = ["score"] + records.lock.reads[:] = [r for r in records.lock.reads if r.id == "office"] + + comparison = compare(_records(), _changed(change)) + + assert [(d.row, d.drift) for d in comparison.differences] == [("steps it ran", NEVER)] + assert comparison.not_compared == ["the 3 entities only one of them read: attempt 0 of first ran 2 steps and " + "attempt 0 of second ran 1 step, so they ran different steps"] + assert comparison.like_for_like + + +def test_an_attempt_that_doesnt_record_its_steps_is_compared_on_what_both_read(): + def change(records): + records.lock.intent.steps_run = None + records.lock.reads.pop() + + comparison = compare(_records(), _changed(change)) + + assert [d.row for d in comparison.differences] == ["steps it ran"] + assert comparison.not_compared == ["the 1 entity only one of them read: attempt 0 of first ran 2 steps and attempt " + "0 of second doesn't record which steps it ran, so they ran different steps"] + + def test_where_a_run_ran_is_soft_and_each_steps_params_are_their_own_override(): def change(records): records.lock.intent.overrides.update(agent_sandbox="modal", step_params={"score": {"threshold": 0.9}}) diff --git a/tst/unit/task/run_lock_test.py b/tst/unit/task/run_lock_test.py index c8b832f5c..e089d581d 100644 --- a/tst/unit/task/run_lock_test.py +++ b/tst/unit/task/run_lock_test.py @@ -218,6 +218,7 @@ def test_a_resume_in_another_process_adds_its_own_records_and_keeps_the_first(): assert [r.attempt_epoch for r in instance.runtimes] == [r.attempt_epoch for r in instance.run_locks] == [0, 1] assert instance.run_locks[0].reads and instance.run_locks[1].reads == [] + assert [lock.intent.steps_run for lock in instance.run_locks] == [["reads", "score"], ["score"]] def test_a_resume_names_the_settings_only_of_the_verifiers_it_graded_though_a_retry_rebuilds_its_context(): @@ -385,7 +386,7 @@ def test_every_field_of_the_records_survives_a_round_trip(): plugins={"acme-steps": plugin}, config_selected_by="environment", types={"task_steps": {"grade": "acme-steps"}}, stage=Stage.FINISHED, record_version=7) intent = RunIntent(task_id="t", task_version=3, content_hash="sha256:c", steps_hash="sha256:s", - pins={"env": {"office": 2}}, roles={"judge": RoleModel("j", "run", "models.example")}, + steps_run=["reads", "score"], pins={"env": {"office": 2}}, roles={"judge": RoleModel("j", "run", "models.example")}, overrides={"judge_model": "j"}, result_rules_version=4) verifier = VerifierRecord(type="score", distribution="acme-steps", version="1.2.0", settings={"a": 1}, graded_settings={"a": 2}) From fc1a05798095c5fb6af8e91d9e11ae0442f83531 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 30 Nov 2026 18:56:40 -0800 Subject: [PATCH 03/10] fix(cli): task diff exits 2, not 1, when the store can't be read, so 1 is only ever a verdict Co-Authored-By: Claude Opus 5.5 --- src/agent_env/cli/task/diff.py | 13 +++++++------ tst/unit/cli/task_diff_test.py | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/agent_env/cli/task/diff.py b/src/agent_env/cli/task/diff.py index b0ad2a5be..918c2dd07 100644 --- a/src/agent_env/cli/task/diff.py +++ b/src/agent_env/cli/task/diff.py @@ -21,12 +21,13 @@ def diff(first: str, second: Optional[str], as_json: bool): """List every difference between what two attempts of a task ran, as their run records keep it, each hard, soft or never drift by the lock table. FIRST and SECOND each name a task instance, for its latest attempt, or one of its attempts as INSTANCE@EPOCH. With FIRST alone, its first attempt is compared with its latest, as a run with its - resume. Exits 0 when the two ran the same thing, 1 when they didn't (hard drift), 2 when they can't be compared.""" - if second is None: - a, b = _first_and_latest(first) - else: - a, b = _records(first), _records(second) - comparison = compare(a, b) + resume. Exits 0 when the two ran the same thing, 1 when they didn't (hard drift), 2 when they can't be compared, + as when the store can't be read: so 1 is only ever a verdict.""" + try: + a, b = _first_and_latest(first) if second is None else (_records(first), _records(second)) + comparison = compare(a, b) + except Exception as e: + _fail(f"{type(e).__name__}: {e}") if as_json: click.echo(json.dumps(comparison.to_dict(), indent=2, default=str)) else: diff --git a/tst/unit/cli/task_diff_test.py b/tst/unit/cli/task_diff_test.py index 1cfac8e3d..17531ee6e 100644 --- a/tst/unit/cli/task_diff_test.py +++ b/tst/unit/cli/task_diff_test.py @@ -2,6 +2,7 @@ names what it can't compare.""" import asyncio +import importlib import json import pytest @@ -20,6 +21,9 @@ from agent_env.task_step.task_steps.verifiers.verifier import Verification, VerifierTaskStep from tst.util import entities +# The module, which the group's ``diff`` command shadows as an attribute of its package. +diff_module = importlib.import_module("agent_env.cli.task.diff") + class _Reads(TaskStep): """Reads an env and an agent at their latest, as a deploy does.""" @@ -136,6 +140,16 @@ def test_what_cant_be_compared_exits_2_and_says_why(args, message): assert result.exit_code == 2 and message in result.output +def test_a_store_that_fails_exits_2_never_1_which_is_a_verdict(monkeypatch): + def unreachable(instance_id): + raise ConnectionError("the store is unreachable") + + monkeypatch.setattr(diff_module, "find_task_instance", unreachable) + result = _diff("one", "two") + + assert result.exit_code == 2 and "ConnectionError: the store is unreachable" in result.output + + def test_two_runs_of_a_task_with_different_step_params_and_a_resume_of_one(): """Records real runs wrote, through Task.run: a run with another verifier threshold differs in its override and its verifier's settings; a resume that reruns only the verifier, reading nothing, ran the same thing as its first From b614987418d129adf43d83eba67e1d7eb80877dc Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 30 Nov 2026 19:23:19 -0800 Subject: [PATCH 04/10] fix(task): an attempt that didn't finish is compared by its step types alone, and what each read is indexed once An attempt records its env, artifact and provider types once it finishes, so a killed one's runtime lists its step types alone; those it didn't record aren't differences. Each attempt's reads are indexed once per comparison, so two attempts with 3,000 reads compare in tens of milliseconds rather than seconds. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task/drift.py | 76 +++++++++++++++++++++++++------------ tst/unit/task/drift_test.py | 14 ++++--- 2 files changed, 60 insertions(+), 30 deletions(-) diff --git a/src/agent_env/task/drift.py b/src/agent_env/task/drift.py index f44765238..7bbc0e6be 100644 --- a/src/agent_env/task/drift.py +++ b/src/agent_env/task/drift.py @@ -16,9 +16,11 @@ from dataclasses import dataclass from enum import StrEnum -from typing import Any, Callable, Iterable, Mapping, Optional +from functools import cached_property +from typing import Any, Callable, Mapping, Optional -from agent_env.task.run_records import ReadRecord, RunLock, RunRuntime +from agent_env.plugins import TASK_STEPS +from agent_env.task.run_records import RunLock, RunRuntime, Stage from agent_env.task.store import TaskInstance Key = tuple[str, ...] @@ -27,6 +29,9 @@ _PLACEMENT_OVERRIDES = frozenset({"agent_sandbox", "env_sandbox"}) # The override that holds each step's own, by step id (``TaskStep.step_param_overrides``). _STEP_PARAMS = "step_params" +# The registry of the types an attempt records from its start, its steps'; the others it records once it finishes. +_STEP_TYPES = TASK_STEPS.removeprefix("agent_env.") +_READ_FIELDS = ("version", "type", "image_identity", "latest", "alias") class Drift(StrEnum): @@ -37,7 +42,8 @@ class Drift(StrEnum): @dataclass(frozen=True) class Records: - """One attempt's records: the runtime and the lock it keeps on its instance, by its ``attempt_epoch``.""" + """One attempt's records: the runtime and the lock it keeps on its instance, by its ``attempt_epoch``. Compared as + they stand when first compared, as what it read is indexed then.""" instance_id: str runtime: RunRuntime @@ -65,6 +71,32 @@ def of(cls, instance: TaskInstance, attempt_epoch: Optional[int] = None) -> Reco lock = next(lock for lock in instance.run_locks if lock.attempt_epoch == epoch) return cls(instance.instance_id, runtime, lock) + @property + def finished(self) -> bool: + return self.lock.finished and self.runtime.stage == Stage.FINISHED + + @cached_property + def by_entity(self) -> Optional[dict[str, dict[Key, Any]]]: + """Each field of what the attempt read (``_READ_FIELDS``), by the entity's kind and id: the value, or the values + in order across the versions of it it read, an unknown image identity left out; None when its reads aren't + recorded.""" + if self.lock.reads is None: + return None + found: dict[str, dict[Key, set]] = {name: {} for name in _READ_FIELDS} + for read in self.lock.reads: + for name in _READ_FIELDS: + value = getattr(read, name) + if name != "image_identity" or value is not None: + found[name].setdefault((read.kind, read.id), set()).add(value) + return {name: {key: values.pop() if len(values) == 1 else tuple(sorted(values, key=lambda v: (v is None, v))) + for key, values in by_key.items()} + for name, by_key in found.items()} + + @cached_property + def entities(self) -> frozenset[Key]: + """Each entity the attempt read, by kind and id; none when its reads aren't recorded.""" + return frozenset((self.by_entity or {}).get("version", {})) + def to_dict(self) -> dict: return {"instance_id": self.instance_id, "attempt_epoch": self.attempt_epoch, "stage": str(self.lock.stage)} @@ -147,16 +179,16 @@ def compare(a: Records, b: Records) -> Comparison: continue drift = row.classify(key, a, b) if row.classify is not None else row.drift differences.append(Difference(row.name, key, before, after, drift, row.regrade and drift is Drift.HARD)) - not_compared = [f"what each read: attempt {r.attempt_epoch} of {r.instance_id} didn't finish, so its reads aren't " - "recorded" for r in unread] + not_compared = [f"attempt {r.attempt_epoch} of {r.instance_id} didn't finish, so what it read and the types it " + "used beyond its steps' aren't recorded" for r in unread] if not unread and not _same_steps(a, b) and (only := _read(a) ^ _read(b)): not_compared.append(f"the {len(only)} entit{'y' if len(only) == 1 else 'ies'} only one of them read: " f"{_ran(a)} and {_ran(b)}, so they ran different steps") return Comparison(a, b, differences, not_compared) -def _read(records: Records) -> set[Key]: - return {(read.kind, read.id) for read in records.lock.reads or ()} +def _read(records: Records) -> frozenset[Key]: + return records.entities def _same_steps(a: Records, b: Records) -> bool: @@ -183,27 +215,20 @@ def _one(value: Any) -> dict[Key, Any]: return {(): value} -def _by_entity(records: Records, field_name: str, *, known: bool = False) -> Optional[dict[Key, Any]]: - """Each entity the attempt read, by kind and id, with the value of ``field_name``, or the values, in order, across - the versions of it it read, those that are None left out when ``known``; None when its reads aren't recorded.""" - reads: Optional[Iterable[ReadRecord]] = records.lock.reads - if reads is None: - return None - found: dict[Key, set] = {} - for read in reads: - value = getattr(read, field_name) - if known and value is None: - continue - found.setdefault((read.kind, read.id), set()).add(value) - return {key: values.pop() if len(values) == 1 else tuple(sorted(values, key=lambda v: (v is None, v))) - for key, values in found.items()} +def _by_entity(records: Records, field_name: str) -> Optional[dict[Key, Any]]: + return None if records.by_entity is None else records.by_entity[field_name] def _version_drift(key: Key, a: Records, b: Records) -> Drift: - identities = [(_by_entity(records, "image_identity", known=True) or {}).get(key) for records in (a, b)] + identities = [(_by_entity(records, "image_identity") or {}).get(key) for records in (a, b)] return Drift.NEVER if identities[0] and identities[0] == identities[1] else Drift.HARD +def _types_recorded(key: Key, a: Records, b: Records) -> bool: + """A step type is recorded from an attempt's start, any other type once it finishes.""" + return key[0] == _STEP_TYPES or (a.finished and b.finished) + + def _overrides(records: Records) -> dict[Key, Any]: """The run's overrides by name, a step's ``step_params`` by the step's id.""" values: dict[Key, Any] = {} @@ -263,8 +288,8 @@ def _set_while_grading(records: Records) -> dict[Key, Any]: _Row("entity version", ("ReadRecord.kind", "ReadRecord.id", "ReadRecord.version"), Drift.HARD, lambda r: _by_entity(r, "version"), classify=_version_drift, compared=_read_by_both_or_same_steps), _Row("entity type", ("ReadRecord.type",), Drift.HARD, lambda r: _by_entity(r, "type"), compared=_read_by_both), - _Row("image identity", ("ReadRecord.image_identity",), Drift.HARD, - lambda r: _by_entity(r, "image_identity", known=True), compared=_read_by_both), + _Row("image identity", ("ReadRecord.image_identity",), Drift.HARD, lambda r: _by_entity(r, "image_identity"), + compared=_read_by_both), _Row("read at its latest", ("ReadRecord.latest",), Drift.NEVER, lambda r: _by_entity(r, "latest"), compared=_read_by_both), _Row("read through an alias", ("ReadRecord.alias",), Drift.NEVER, lambda r: _by_entity(r, "alias"), @@ -298,7 +323,8 @@ def _set_while_grading(records: Records) -> dict[Key, Any]: lambda r: {(name,): plugin.origin for name, plugin in r.runtime.plugins.items()}, compared=_in_both(_plugins)), _Row("type's package", ("RunRuntime.types",), Drift.SOFT, - lambda r: {(group, name): found for group, types in r.runtime.types.items() for name, found in types.items()}), + lambda r: {(group, name): found for group, types in r.runtime.types.items() for name, found in types.items()}, + compared=_types_recorded), _Row("config found by", ("RunRuntime.config_selected_by",), Drift.NEVER, lambda r: _one(r.runtime.config_selected_by)), ) diff --git a/tst/unit/task/drift_test.py b/tst/unit/task/drift_test.py index c563717ea..cd91747b5 100644 --- a/tst/unit/task/drift_test.py +++ b/tst/unit/task/drift_test.py @@ -239,16 +239,20 @@ def change(records): assert compare(_records(), _changed(change)).differences == [] -def test_an_attempt_that_didnt_finish_is_compared_without_its_reads(): +def test_an_attempt_that_didnt_finish_is_compared_without_its_reads_and_the_types_beyond_its_steps(): + """As a killed run leaves it: started records, its step types alone and no reads.""" def change(records): records.lock.reads = None - records.lock.stage = Stage.STARTED + records.lock.stage = records.runtime.stage = Stage.STARTED + records.runtime.types = {"task_steps": dict(records.runtime.types["task_steps"])} + first = _records() + first.runtime.types["envs"] = {"multi": "agentenv-framework"} - comparison = compare(_records(), _changed(change)) + comparison = compare(first, _changed(change)) assert comparison.differences == [] - assert comparison.not_compared == ["what each read: attempt 0 of second didn't finish, so its reads aren't " - "recorded"] + assert comparison.not_compared == ["attempt 0 of second didn't finish, so what it read and the types it used " + "beyond its steps' aren't recorded"] @pytest.mark.parametrize("gap, change, row", [ From 21af439eb7c6a60b823679a40fcbe56f137635a2 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 30 Nov 2026 21:42:18 -0800 Subject: [PATCH 05/10] feat(task): how a judge's grading went is compared apart from its settings, and a run records the formats it prescribes A rubrics judge's settings record the trajectory source of each turn it read, the host its calls reached and which settings a run's overrides changed. Compared as settings, two runs alike but for their conversations' length were hard drift with a regrade offered. Now each has a row of its own: the formats a judge read, however many turns, soft, as a copy that failed is read natively; the host its calls reached soft, as a role's endpoint host is; the names of the settings overrides changed never, as their values are compared. Each attempt records the trajectory formats it prescribes (`trajectory_formats`, from its overrides or else the config), hard, so a change of what judges are given stays hard, and the override itself isn't compared twice. The judges write these keys by the names the comparator reads them by. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 34 +++++++------- src/agent_env/task/drift.py | 45 ++++++++++++++++-- src/agent_env/task/run_lock.py | 2 + src/agent_env/task/run_records.py | 9 +++- .../task_steps/verifiers/rubrics_verifier.py | 15 ++++-- .../run_container_unit_tests_verifier.py | 4 +- .../task_steps/verifiers/verifier.py | 6 +++ tst/unit/task/drift_test.py | 47 +++++++++++++++++-- tst/unit/task/run_lock_test.py | 9 +++- 9 files changed, 138 insertions(+), 33 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c9e53829d..eee1cfb28 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -491,22 +491,24 @@ orchestrators call it the same way. What callers rely on: each installed plugin's version and install kind, how the config file was found, and the distribution of each type the run used, from `agent_env.plugins`' `distribution_of`, its sandbox providers those of the deployments its context records; never a path) and `RunLock` (its `intent`, the task's content hash, a hash of its steps as run and the ids of - those it was asked to run (`steps_run`), its pins, each role's model and endpoint host as this process resolves them, - the overrides without secrets and the result rules version, computed as the eval plan computes its own, - `eval/intent.py`; each verifier's settings and version at the start and as graded, by the grades whose `attempt_epoch` - is this attempt's or a retry's within it; and every entity version the run read, each image with its - `image_identity`). Each is written `started` and then `finished`, however the run ends, by writer threads of their own - (`task/record_writer.py`, never awaited; `flush_run_records` waits for them, and an exit waits 10 s at most), under a - counter of their own (`run_records_rev`) that the instance's other writes don't check, nor these theirs (on DynamoDB, - which conditions a write on the whole item, one still retries the other); the store keeps the finished record - whichever lands last, and a resume adds its own. An instance leaves out, with a warning, a record this version can't - read. A worker that runs a task's steps itself enters `run_recorded` around them, once per attempt in the process that - runs them all, as it sets `run_pins`. `task/drift.py` classes every difference between two attempts' records by the - lock table (`compare`, its rows `ROWS`, every record field in one or in `NOT_COMPARED`): `hard` when they ran - different things, `regrade` too for the result rules or a verifier's settings, `soft` for code meant to change under a - run, as an upgraded package, and `never`, as how a version was asked for; an image's identity, not its artifact's - version, says whether it changed, and an entity only one attempt read is a difference only when both ran the same - steps. `agent-env task diff` lists the differences, exiting 1 on hard drift. + those it was asked to run (`steps_run`), the trajectory formats it prescribes (`trajectory_formats`), its pins, each + role's model and endpoint host as this process resolves them, the overrides without secrets and the result rules + version, computed as the eval plan computes its own, `eval/intent.py`; each verifier's settings and version at the + start and as graded, by the grades whose `attempt_epoch` is this attempt's or a retry's within it; and every entity + version the run read, each image with its `image_identity`). Each is written `started` and then `finished`, however + the run ends, by writer threads of their own (`task/record_writer.py`, never awaited; `flush_run_records` waits for + them, and an exit waits 10 s at most), under a counter of their own (`run_records_rev`) that the instance's other + writes don't check, nor these theirs (on DynamoDB, which conditions a write on the whole item, one still retries the + other); the store keeps the finished record whichever lands last, and a resume adds its own. An instance leaves out, + with a warning, a record this version can't read. A worker that runs a task's steps itself enters `run_recorded` + around them, once per attempt in the process that runs them all, as it sets `run_pins`. `task/drift.py` classes every + difference between two attempts' records by the lock table (`compare`, its rows `ROWS`, every record field in one or + in `NOT_COMPARED`): `hard` when they ran different things, `regrade` too for the result rules or a verifier's + settings, `soft` for code meant to change under a run, as an upgraded package, and `never`, as how a version was asked + for; an image's identity, not its artifact's version, says whether it changed, and an entity only one attempt read is + a difference only when both ran the same steps; what a verifier's settings record of how its grading went (the formats + its judge read, the host its calls reached, which settings overrides changed) is compared apart from its settings. + `agent-env task diff` lists the differences, exiting 1 on hard drift. - A runner that must hear from a long step puts a zero-argument callable at `context.metadata[HEARTBEAT_KEY]` (`task_step/context.py`); a step that blocks for long calls `context.heartbeat()`, a no-op without one. The key is in `_REDACTED_KEYS`, so it is never persisted. diff --git a/src/agent_env/task/drift.py b/src/agent_env/task/drift.py index 7bbc0e6be..ebc77332d 100644 --- a/src/agent_env/task/drift.py +++ b/src/agent_env/task/drift.py @@ -10,6 +10,11 @@ verifier, a role, a plugin or an entity read, is the only one that does; the rows of that thing's other fields compare it only where both attempts have it. An entity only one attempt read is a difference only when both ran the same steps (``RunIntent.steps_run``): a resume runs only the rest, which read less, and what it didn't read isn't compared. + +A verifier's settings record how its grading went beside what it graded with: which trajectory formats its judge read, +the host its calls reached and which settings a run's overrides changed. Those aren't settings: each has a row of its +own, the formats a judge read soft, as a copy that failed is read natively, while the formats the run prescribed are +hard. """ from __future__ import annotations @@ -22,6 +27,11 @@ from agent_env.plugins import TASK_STEPS from agent_env.task.run_records import RunLock, RunRuntime, Stage from agent_env.task.store import TaskInstance +from agent_env.task_step.task_steps.verifiers.verifier import ( + JUDGE_ENDPOINT_HOST_SETTING, + OVERRIDDEN_SETTING, + TRAJECTORY_SOURCES_SETTING, +) Key = tuple[str, ...] @@ -29,6 +39,10 @@ _PLACEMENT_OVERRIDES = frozenset({"agent_sandbox", "env_sandbox"}) # The override that holds each step's own, by step id (``TaskStep.step_param_overrides``). _STEP_PARAMS = "step_params" +# The override of the trajectory formats a run prescribes, which the intent's own row compares as resolved. +_TRAJECTORY_FORMATS = "trajectory_formats" +# What a verifier's settings record of how its grading went, each compared by a row of its own, not as a setting. +_GRADING_EVIDENCE = frozenset({JUDGE_ENDPOINT_HOST_SETTING, TRAJECTORY_SOURCES_SETTING, OVERRIDDEN_SETTING}) # The registry of the types an attempt records from its start, its steps'; the others it records once it finishes. _STEP_TYPES = TASK_STEPS.removeprefix("agent_env.") _READ_FIELDS = ("version", "type", "image_identity", "latest", "alias") @@ -150,9 +164,10 @@ def to_dict(self) -> dict: @dataclass(frozen=True) class _Row: - """A lock-table row: the record ``fields`` it covers, as ``Class.field``; its class; its values in an attempt's - records by key, None when the attempt didn't record them; and, for a row whose class or reach depends on the key, - ``classify`` and ``compared``.""" + """A lock-table row: the record ``fields`` it covers, as ``Class.field``, none for a row of part of a field another + row covers, as how a verifier's grading went; its class; its values in an attempt's records by key, None when the + attempt didn't record them; and, for a row whose class or reach depends on the key, ``classify`` and + ``compared``.""" name: str fields: tuple[str, ...] @@ -233,6 +248,8 @@ def _overrides(records: Records) -> dict[Key, Any]: """The run's overrides by name, a step's ``step_params`` by the step's id.""" values: dict[Key, Any] = {} for name, value in records.lock.intent.overrides.items(): + if name == _TRAJECTORY_FORMATS: + continue if name == _STEP_PARAMS and isinstance(value, Mapping): values.update({(name, str(step)): params for step, params in value.items()}) else: @@ -267,7 +284,7 @@ def _plugins(records: Records) -> Mapping[str, Any]: def _settings(records: Records) -> dict[Key, Any]: return {(step, name): value for step, verifier in records.lock.verifiers.items() - for name, value in verifier.settings.items()} + for name, value in verifier.settings.items() if name not in _GRADING_EVIDENCE} def _set_while_grading(records: Records) -> dict[Key, Any]: @@ -275,7 +292,16 @@ def _set_while_grading(records: Records) -> dict[Key, Any]: grade records otherwise than it started with, which the starting settings' row already compares.""" return {(step, name): value for step, verifier in records.lock.verifiers.items() for name, value in (verifier.graded_settings or {}).items() - if name not in verifier.settings or verifier.settings[name] != value} + if name not in _GRADING_EVIDENCE and (name not in verifier.settings or verifier.settings[name] != value)} + + +def _formats_read(records: Records) -> dict[Key, Any]: + """The formats each judge read its turns as, each with the ATIF adapter version that built it, however many turns + it read: whether a turn was read natively is partly how the run went, as a copy that failed is read natively.""" + return {(step,): tuple(sorted({f"{source.get('format') or 'native'}" + + (f"@{source['adapter_version']}" if source.get("adapter_version") else "") + for source in verifier.graded_settings.get(TRAJECTORY_SOURCES_SETTING) or ()})) + for step, verifier in _graded(records).items()} ROWS: tuple[_Row, ...] = ( @@ -285,6 +311,8 @@ def _set_while_grading(records: Records) -> dict[Key, Any]: _Row("steps as run", ("RunIntent.steps_hash",), Drift.HARD, lambda r: _one(r.lock.intent.steps_hash)), _Row("steps it ran", ("RunIntent.steps_run",), Drift.NEVER, lambda r: _one(None if r.lock.intent.steps_run is None else tuple(r.lock.intent.steps_run))), + _Row("trajectory formats prescribed", ("RunIntent.trajectory_formats",), Drift.HARD, + lambda r: _one(None if r.lock.intent.trajectory_formats is None else tuple(r.lock.intent.trajectory_formats))), _Row("entity version", ("ReadRecord.kind", "ReadRecord.id", "ReadRecord.version"), Drift.HARD, lambda r: _by_entity(r, "version"), classify=_version_drift, compared=_read_by_both_or_same_steps), _Row("entity type", ("ReadRecord.type",), Drift.HARD, lambda r: _by_entity(r, "type"), compared=_read_by_both), @@ -310,6 +338,13 @@ def _set_while_grading(records: Records) -> dict[Key, Any]: compared=_in_both(_verifiers)), _Row("verifier settings set while grading", ("VerifierRecord.graded_settings",), Drift.HARD, _set_while_grading, regrade=True, compared=_in_both(_graded)), + _Row("trajectory formats a judge read", (), Drift.SOFT, _formats_read, compared=_in_both(_graded)), + _Row("judge endpoint host", (), Drift.SOFT, + lambda r: {(step,): v.graded_settings.get(JUDGE_ENDPOINT_HOST_SETTING) for step, v in _graded(r).items()}, + compared=_in_both(_graded)), + _Row("verifier settings overridden", (), Drift.NEVER, + lambda r: {(step,): tuple(v.settings.get(OVERRIDDEN_SETTING) or ()) for step, v in r.lock.verifiers.items()}, + compared=_in_both(_verifiers)), _Row("verifier package", ("VerifierRecord.distribution",), Drift.SOFT, lambda r: {(step,): v.distribution for step, v in r.lock.verifiers.items()}, compared=_in_both(_verifiers)), _Row("verifier package version", ("VerifierRecord.version",), Drift.SOFT, diff --git a/src/agent_env/task/run_lock.py b/src/agent_env/task/run_lock.py index f7cca5fa5..e8bd32fd8 100644 --- a/src/agent_env/task/run_lock.py +++ b/src/agent_env/task/run_lock.py @@ -59,6 +59,7 @@ from agent_env.task.store import record_run_records from agent_env.task_step.context import TaskStepContext from agent_env.task_step.task_step import TaskStep +from agent_env.task_step.task_steps.prompt_agent import prescribed_formats from agent_env.task_step.task_steps.verifiers.verifier import GRADES_KEY, VerifierTaskStep from agent_env.utils.canonical import canonical_json @@ -105,6 +106,7 @@ def started_lock(task: "Task", steps: Sequence[TaskStep], context: TaskStepConte content_hash=content_hash(task), steps_hash=steps_hash(steps), steps_run=[step.id for step in steps[start_step:end_step]], + trajectory_formats=list(prescribed_formats(context)), pins=checked_pins(user_overrides.get(PINS_KEY)), roles=role_models(overrides), overrides=recorded_overrides(overrides), diff --git a/src/agent_env/task/run_records.py b/src/agent_env/task/run_records.py index f96c67041..10b1f974d 100644 --- a/src/agent_env/task/run_records.py +++ b/src/agent_env/task/run_records.py @@ -99,8 +99,10 @@ class RunIntent: """What an attempt was asked to do, computed as an eval plan computes its own (``agent_env.eval.intent``): the task's id, version and content hash; ``steps_hash``, of its steps as this run runs them, its seed applied; ``steps_run``, the ids of the steps it was asked to run, from its start step to its end step, as a resume runs only the rest, None - for a record that predates it; its pins; each role's model and endpoint host as this process's config resolves - them; its overrides without secrets; and the result rules version.""" + for a record that predates it; ``trajectory_formats``, the formats beside native it prescribes to the agents whose + trajectories its judges read, from its overrides or else the config, None for a record that predates it; its pins; + each role's model and endpoint host as this process's config resolves them; its overrides without secrets; and the + result rules version.""" task_id: str task_version: int @@ -111,6 +113,7 @@ class RunIntent: overrides: dict[str, Any] = field(default_factory=dict) result_rules_version: int = 0 steps_run: Optional[list[str]] = None + trajectory_formats: Optional[list[str]] = None def to_dict(self) -> dict: return { @@ -119,6 +122,7 @@ def to_dict(self) -> dict: "content_hash": self.content_hash, "steps_hash": self.steps_hash, "steps_run": None if self.steps_run is None else list(self.steps_run), + "trajectory_formats": None if self.trajectory_formats is None else list(self.trajectory_formats), "pins": self.pins, "roles": {name: role.to_dict() for name, role in self.roles.items()}, "overrides": self.overrides, @@ -133,6 +137,7 @@ def from_dict(cls, data: dict) -> RunIntent: content_hash=data["content_hash"], steps_hash=data.get("steps_hash", ""), steps_run=None if data.get("steps_run") is None else list(data["steps_run"]), + trajectory_formats=None if data.get("trajectory_formats") is None else list(data["trajectory_formats"]), pins=data.get("pins") or {}, roles={name: RoleModel.from_dict(role) for name, role in (data.get("roles") or {}).items()}, overrides=data.get("overrides") or {}, diff --git a/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py b/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py index bf15d77e1..b8c7f0a92 100644 --- a/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py @@ -58,7 +58,14 @@ from agent_env.task_step.usage import StepUsage from agent_env.task_step.task_steps.verifiers.run_context import Run, load_run_context, render_run_context from agent_env.task_step.task_steps.verifiers.scoring import ScoreAggregator, aggregate_score -from agent_env.task_step.task_steps.verifiers.verifier import VERIFICATIONS_KEY, Verification, VerifierTaskStep +from agent_env.task_step.task_steps.verifiers.verifier import ( + JUDGE_ENDPOINT_HOST_SETTING, + OVERRIDDEN_SETTING, + TRAJECTORY_SOURCES_SETTING, + VERIFICATIONS_KEY, + Verification, + VerifierTaskStep, +) from agent_env.task_step.task_steps.sandbox_utils.sandbox_utils import ( agent_error_text, fetch_container_logs, @@ -1004,9 +1011,9 @@ def verifier_settings(self, context: TaskStepContext) -> dict[str, Any]: if judge.not_sent: settings["not_sent"] = dict(judge.not_sent) if judge.endpoint_host: - settings["judge_endpoint_host"] = judge.endpoint_host + settings[JUDGE_ENDPOINT_HOST_SETTING] = judge.endpoint_host if judge is not None and judge.sources: - settings["trajectory_sources"] = list(judge.sources) + settings[TRAJECTORY_SOURCES_SETTING] = list(judge.sources) asked, bar = values.get("judge_samples"), values.get("min_judge_agreement") if not self._spec().samplable: # A run-wide judge_samples reaches every judge; one whose format can't take it grades once. @@ -1019,7 +1026,7 @@ def verifier_settings(self, context: TaskStepContext) -> dict[str, Any]: settings["not_sent"] = {**(settings.get("not_sent") or {}), **refused} elif isinstance(asked, int) and asked > 1: settings["min_judge_agreement"] = judge_samples_rule.DEFAULT_MIN_AGREEMENT if bar is None else bar - return {**settings, "overridden": overridden} + return {**settings, OVERRIDDEN_SETTING: overridden} def grade_fields(self, context: TaskStepContext) -> dict[str, Any]: """``judge_calls``, the record of each model call the run's judge made, when it made any.""" diff --git a/src/agent_env/task_step/task_steps/verifiers/run_container_unit_tests_verifier.py b/src/agent_env/task_step/task_steps/verifiers/run_container_unit_tests_verifier.py index 34f189013..aa453c76c 100644 --- a/src/agent_env/task_step/task_steps/verifiers/run_container_unit_tests_verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/run_container_unit_tests_verifier.py @@ -54,7 +54,7 @@ from agent_env.task_step.task_step import TaskStepDependency from agent_env.task_step.task_steps.run_code import _DriverTarget from agent_env.task_step.task_steps.verifiers.scoring import ScoreAggregator -from agent_env.task_step.task_steps.verifiers.verifier import Verification, VerifierTaskStep +from agent_env.task_step.task_steps.verifiers.verifier import OVERRIDDEN_SETTING, Verification, VerifierTaskStep logger = logging.getLogger(__name__) @@ -218,7 +218,7 @@ def verifier_settings(self, context: TaskStepContext) -> dict[str, Any]: ) if changed] settings["command"] = overrides.get("command", self.command) settings["env_vars"] = sorted({*self.env_vars, *override_env}) - return {**settings, "overridden": overridden} + return {**settings, OVERRIDDEN_SETTING: overridden} def _resolve_command(self, context: TaskStepContext) -> tuple[str, dict[str, str]]: """Resolve ``(command, extra_env)`` for this run, so a value can vary without a diff --git a/src/agent_env/task_step/task_steps/verifiers/verifier.py b/src/agent_env/task_step/task_steps/verifiers/verifier.py index 0759e739e..6fa223187 100644 --- a/src/agent_env/task_step/task_steps/verifiers/verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/verifier.py @@ -29,6 +29,12 @@ # The version of the rules the base applies to every verifier's rows and pass rule; a change that can move a grade # bumps it, and every grade records it in its verifier_settings. SCORING_RULES = 1 +# Keys a verifier's settings may hold that record how its grading went, not what it graded with: the host its judge's +# calls reached, the trajectory source of each turn it read, and which settings a run's overrides changed, whose values +# the settings hold too. A comparison of two runs' settings reads these apart (``agent_env.task.drift``). +JUDGE_ENDPOINT_HOST_SETTING = "judge_endpoint_host" +TRAJECTORY_SOURCES_SETTING = "trajectory_sources" +OVERRIDDEN_SETTING = "overridden" DEFAULT_MIN_PASSING_SCORE = 1.0 OUTPUT_INLINE_BYTES = 16 * 1024 SETTING_INLINE_BYTES = 1024 diff --git a/tst/unit/task/drift_test.py b/tst/unit/task/drift_test.py index cd91747b5..efbde9462 100644 --- a/tst/unit/task/drift_test.py +++ b/tst/unit/task/drift_test.py @@ -33,14 +33,16 @@ def _records(instance_id="first", epoch=0) -> Records: config_selected_by="discovered", types={"task_steps": {"grade": "acme-steps"}}, stage=Stage.FINISHED) intent = RunIntent(task_id="t", task_version=1, content_hash="sha256:c", steps_hash="sha256:s", - steps_run=["deploy", "score"], pins={"env": {"office": 1}}, + steps_run=["deploy", "score"], trajectory_formats=["atif/1"], pins={"env": {"office": 1}}, roles={"solver": RoleModel("m", "run", "models.example"), "judge": RoleModel("j", "config_role", "models.example")}, overrides={"judge_model": "j", "agent_sandbox": "local", "step_params": {"score": {"threshold": 0.5}}}, result_rules_version=1) - verifiers = {"score": VerifierRecord("grade", "acme-steps", "1.2.0", {"threshold": 0.5}, - {"threshold": 0.5, "model": "j"})} + verifiers = {"score": VerifierRecord("grade", "acme-steps", "1.2.0", {"threshold": 0.5, "overridden": []}, + {"threshold": 0.5, "model": "j", "overridden": [], + "judge_endpoint_host": "models.example", + "trajectory_sources": [{"turn": 1, "format": "atif/1", "adapter_version": "1"}]})} reads = [ReadRecord("env", "office", 1, "multi", latest=True), ReadRecord("artifact", "office-image", 3, "docker_image", image_identity="source:sha256:x"), ReadRecord("agent", "solver", 2, "a2a_agent", latest=True), @@ -94,6 +96,7 @@ def change(records): Case("task content", _set("lock.intent.content_hash", "sha256:d"), (), HARD), Case("steps as run", _set("lock.intent.steps_hash", "sha256:t"), (), HARD), Case("steps it ran", _set("lock.intent.steps_run", ["score"]), (), NEVER), + Case("trajectory formats prescribed", _set("lock.intent.trajectory_formats", []), (), HARD), Case("entity version", lambda r: _read(r, "office", version=2), ("env", "office"), HARD), Case("entity type", lambda r: _read(r, "office", type="mcp_server"), ("env", "office"), HARD), Case("image identity", lambda r: _read(r, "solver-image", image_identity="registry:sha256:h2"), @@ -113,6 +116,14 @@ def change(records): Case("verifier settings", lambda r: _threshold(r, 0.9), ("score", "threshold"), HARD, regrade=True), Case("verifier settings set while grading", lambda r: r.lock.verifiers["score"].graded_settings.update(model="k"), ("score", "model"), HARD, regrade=True), + Case("trajectory formats a judge read", + lambda r: r.lock.verifiers["score"].graded_settings.update(trajectory_sources=[{"turn": 1, "format": "native"}]), + ("score",), SOFT), + Case("judge endpoint host", + lambda r: r.lock.verifiers["score"].graded_settings.update(judge_endpoint_host="fallback.example"), + ("score",), SOFT), + Case("verifier settings overridden", + lambda r: r.lock.verifiers["score"].settings.update(overridden=["threshold"]), ("score",), NEVER), Case("verifier package", lambda r: r.lock.verifiers.update(score=replace(r.lock.verifiers["score"], distribution="acme-grades")), ("score",), SOFT), @@ -132,6 +143,7 @@ def change(records): def test_every_row_has_a_case_and_every_record_field_a_row_or_a_reason(): assert {case.row for case in CASES} == {row.name for row in ROWS} + assert len({row.name for row in ROWS}) == len(ROWS) fields = {f"{cls.__name__}.{f.name}" for cls in RECORD_CLASSES for f in dataclasses.fields(cls)} in_rows = [name for row in ROWS for name in row.fields] assert len(in_rows) == len(set(in_rows)) and not set(in_rows) & set(NOT_COMPARED) @@ -213,6 +225,35 @@ def change(records): "0 of second doesn't record which steps it ran, so they ran different steps"] +def test_a_judge_that_read_more_turns_of_the_same_formats_read_the_same_thing(): + """Two runs alike but for how long their conversations went.""" + def change(records): + records.lock.verifiers["score"].graded_settings["trajectory_sources"] = [ + {"turn": turn, "format": "atif/1", "adapter_version": "1"} for turn in (1, 2, 3, 4, 5)] + + assert compare(_records(), _changed(change)).differences == [] + + +def test_a_change_the_overrides_made_to_a_judge_is_its_settings_hard_and_their_names_never(): + def change(records): + verifier = records.lock.verifiers["score"] + verifier.settings.update(threshold=0.9, overridden=["threshold"]) + verifier.graded_settings.update(threshold=0.9, overridden=["threshold"]) + + differences = compare(_records(), _changed(change)).differences + assert [(d.row, d.key, d.drift) for d in differences] == [ + ("verifier settings", ("score", "threshold"), HARD), ("verifier settings overridden", ("score",), NEVER)] + + +def test_prescribed_formats_given_as_an_override_are_compared_once_as_prescribed(): + def change(records): + records.lock.intent.overrides["trajectory_formats"] = [] + records.lock.intent.trajectory_formats = [] + + [difference] = compare(_records(), _changed(change)).differences + assert (difference.row, difference.drift) == ("trajectory formats prescribed", HARD) + + def test_where_a_run_ran_is_soft_and_each_steps_params_are_their_own_override(): def change(records): records.lock.intent.overrides.update(agent_sandbox="modal", step_params={"score": {"threshold": 0.9}}) diff --git a/tst/unit/task/run_lock_test.py b/tst/unit/task/run_lock_test.py index e089d581d..5ab6eb0ee 100644 --- a/tst/unit/task/run_lock_test.py +++ b/tst/unit/task/run_lock_test.py @@ -172,6 +172,13 @@ def test_a_run_records_what_ran_it_and_what_it_was_asked_and_read(): "data": None} +@pytest.mark.parametrize("overrides, formats", [({}, []), ({"trajectory_formats": ["atif/1"]}, ["atif/1"])], + ids=["the config's", "the run's"]) +def test_a_run_records_the_trajectory_formats_it_prescribes(overrides, formats): + _, context = _run(_task(), overrides) + assert find_task_instance(context.instance_id).run_locks[0].intent.trajectory_formats == formats + + def test_the_grades_verifier_version_and_settings_are_the_locks(): task = _task(_Score(id="score", version=None, verifier_id="score"), AggregateVerifiersTaskStep(id="total", version=None, sources=["score"])) @@ -386,7 +393,7 @@ def test_every_field_of_the_records_survives_a_round_trip(): plugins={"acme-steps": plugin}, config_selected_by="environment", types={"task_steps": {"grade": "acme-steps"}}, stage=Stage.FINISHED, record_version=7) intent = RunIntent(task_id="t", task_version=3, content_hash="sha256:c", steps_hash="sha256:s", - steps_run=["reads", "score"], pins={"env": {"office": 2}}, roles={"judge": RoleModel("j", "run", "models.example")}, + steps_run=["reads", "score"], trajectory_formats=["atif/1"], pins={"env": {"office": 2}}, roles={"judge": RoleModel("j", "run", "models.example")}, overrides={"judge_model": "j"}, result_rules_version=4) verifier = VerifierRecord(type="score", distribution="acme-steps", version="1.2.0", settings={"a": 1}, graded_settings={"a": 2}) From 48a18ae39951b1c7a30b3d43b51e32be077def15 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 30 Nov 2026 22:09:09 -0800 Subject: [PATCH 06/10] fix(task): a long conversation's judge formats and an older record's prescribed formats compare without false drift A judge's per-turn trajectory sources past the settings' inline cap are kept as their hash, so the comparator couldn't read them. The judge now also records the distinct formats it read (`trajectory_formats_read`), a few names, which the comparator reads; a record that keeps only the hash, and no summary, isn't compared on them, and the listing says so. An attempt recorded before its prescribed formats were is compared by its own `trajectory_formats` override, and one that records neither isn't compared on them, with a note, rather than counted as a change. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task/drift.py | 57 +++++++++++++++---- .../task_steps/verifiers/rubrics_verifier.py | 3 + .../task_steps/verifiers/verifier.py | 16 +++++- tst/unit/task/drift_test.py | 46 +++++++++++++++ .../verifiers/test_judge_inputs_stored.py | 1 + 5 files changed, 110 insertions(+), 13 deletions(-) diff --git a/src/agent_env/task/drift.py b/src/agent_env/task/drift.py index ebc77332d..8f83f1a86 100644 --- a/src/agent_env/task/drift.py +++ b/src/agent_env/task/drift.py @@ -30,7 +30,9 @@ from agent_env.task_step.task_steps.verifiers.verifier import ( JUDGE_ENDPOINT_HOST_SETTING, OVERRIDDEN_SETTING, + TRAJECTORY_FORMATS_READ_SETTING, TRAJECTORY_SOURCES_SETTING, + trajectory_formats_read, ) Key = tuple[str, ...] @@ -42,7 +44,8 @@ # The override of the trajectory formats a run prescribes, which the intent's own row compares as resolved. _TRAJECTORY_FORMATS = "trajectory_formats" # What a verifier's settings record of how its grading went, each compared by a row of its own, not as a setting. -_GRADING_EVIDENCE = frozenset({JUDGE_ENDPOINT_HOST_SETTING, TRAJECTORY_SOURCES_SETTING, OVERRIDDEN_SETTING}) +_GRADING_EVIDENCE = frozenset({JUDGE_ENDPOINT_HOST_SETTING, TRAJECTORY_SOURCES_SETTING, TRAJECTORY_FORMATS_READ_SETTING, + OVERRIDDEN_SETTING}) # The registry of the types an attempt records from its start, its steps'; the others it records once it finishes. _STEP_TYPES = TASK_STEPS.removeprefix("agent_env.") _READ_FIELDS = ("version", "type", "image_identity", "latest", "alias") @@ -106,6 +109,34 @@ def by_entity(self) -> Optional[dict[str, dict[Key, Any]]]: for key, values in by_key.items()} for name, by_key in found.items()} + @cached_property + def formats_read(self) -> dict[str, tuple[str, ...]]: + """The formats each verifier that graded read its turns as (``trajectory_formats_read``), none for one that read + no trajectory; a verifier whose record keeps only the hash of its per-turn list, and no summary, as one written + before the summary was, isn't here.""" + found = {} + for step, verifier in self.lock.verifiers.items(): + settings = verifier.graded_settings + if settings is None: + continue + summary, sources = settings.get(TRAJECTORY_FORMATS_READ_SETTING), settings.get(TRAJECTORY_SOURCES_SETTING) + if isinstance(summary, list): + found[step] = tuple(sorted(summary)) + elif sources is None: + found[step] = () + elif isinstance(sources, list) and all(isinstance(source, Mapping) for source in sources): + found[step] = tuple(trajectory_formats_read(sources)) + return found + + @cached_property + def prescribed_formats(self) -> Optional[tuple[str, ...]]: + """The trajectory formats the attempt prescribed, or, for one recorded before they were, its own override of + them; None when it records neither.""" + intent = self.lock.intent + formats = intent.trajectory_formats if intent.trajectory_formats is not None else intent.overrides.get( + _TRAJECTORY_FORMATS) + return tuple(formats) if isinstance(formats, list) else None + @cached_property def entities(self) -> frozenset[Key]: """Each entity the attempt read, by kind and id; none when its reads aren't recorded.""" @@ -199,6 +230,12 @@ def compare(a: Records, b: Records) -> Comparison: if not unread and not _same_steps(a, b) and (only := _read(a) ^ _read(b)): not_compared.append(f"the {len(only)} entit{'y' if len(only) == 1 else 'ies'} only one of them read: " f"{_ran(a)} and {_ran(b)}, so they ran different steps") + not_compared += [f"the trajectory formats attempt {r.attempt_epoch} of {r.instance_id} prescribed: it records " + "neither them nor an override of them" for r in (a, b) if r.prescribed_formats is None] + graded_both = _graded(a).keys() & _graded(b).keys() + not_compared += [f"the trajectory formats verifier {step} read in attempt {r.attempt_epoch} of {r.instance_id}: " + "its record keeps only a hash of them" for r in (a, b) + for step in sorted(graded_both - r.formats_read.keys())] return Comparison(a, b, differences, not_compared) @@ -295,13 +332,12 @@ def _set_while_grading(records: Records) -> dict[Key, Any]: if name not in _GRADING_EVIDENCE and (name not in verifier.settings or verifier.settings[name] != value)} -def _formats_read(records: Records) -> dict[Key, Any]: - """The formats each judge read its turns as, each with the ATIF adapter version that built it, however many turns - it read: whether a turn was read natively is partly how the run went, as a copy that failed is read natively.""" - return {(step,): tuple(sorted({f"{source.get('format') or 'native'}" - + (f"@{source['adapter_version']}" if source.get("adapter_version") else "") - for source in verifier.graded_settings.get(TRAJECTORY_SOURCES_SETTING) or ()})) - for step, verifier in _graded(records).items()} +def _formats_known(key: Key, a: Records, b: Records) -> bool: + return key[0] in a.formats_read and key[0] in b.formats_read + + +def _prescriptions_known(key: Key, a: Records, b: Records) -> bool: + return a.prescribed_formats is not None and b.prescribed_formats is not None ROWS: tuple[_Row, ...] = ( @@ -312,7 +348,7 @@ def _formats_read(records: Records) -> dict[Key, Any]: _Row("steps it ran", ("RunIntent.steps_run",), Drift.NEVER, lambda r: _one(None if r.lock.intent.steps_run is None else tuple(r.lock.intent.steps_run))), _Row("trajectory formats prescribed", ("RunIntent.trajectory_formats",), Drift.HARD, - lambda r: _one(None if r.lock.intent.trajectory_formats is None else tuple(r.lock.intent.trajectory_formats))), + lambda r: _one(r.prescribed_formats), compared=_prescriptions_known), _Row("entity version", ("ReadRecord.kind", "ReadRecord.id", "ReadRecord.version"), Drift.HARD, lambda r: _by_entity(r, "version"), classify=_version_drift, compared=_read_by_both_or_same_steps), _Row("entity type", ("ReadRecord.type",), Drift.HARD, lambda r: _by_entity(r, "type"), compared=_read_by_both), @@ -338,7 +374,8 @@ def _formats_read(records: Records) -> dict[Key, Any]: compared=_in_both(_verifiers)), _Row("verifier settings set while grading", ("VerifierRecord.graded_settings",), Drift.HARD, _set_while_grading, regrade=True, compared=_in_both(_graded)), - _Row("trajectory formats a judge read", (), Drift.SOFT, _formats_read, compared=_in_both(_graded)), + _Row("trajectory formats a judge read", (), Drift.SOFT, + lambda r: {(step,): formats for step, formats in r.formats_read.items()}, compared=_formats_known), _Row("judge endpoint host", (), Drift.SOFT, lambda r: {(step,): v.graded_settings.get(JUDGE_ENDPOINT_HOST_SETTING) for step, v in _graded(r).items()}, compared=_in_both(_graded)), diff --git a/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py b/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py index b8c7f0a92..9253559db 100644 --- a/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py @@ -61,10 +61,12 @@ from agent_env.task_step.task_steps.verifiers.verifier import ( JUDGE_ENDPOINT_HOST_SETTING, OVERRIDDEN_SETTING, + TRAJECTORY_FORMATS_READ_SETTING, TRAJECTORY_SOURCES_SETTING, VERIFICATIONS_KEY, Verification, VerifierTaskStep, + trajectory_formats_read, ) from agent_env.task_step.task_steps.sandbox_utils.sandbox_utils import ( agent_error_text, @@ -1014,6 +1016,7 @@ def verifier_settings(self, context: TaskStepContext) -> dict[str, Any]: settings[JUDGE_ENDPOINT_HOST_SETTING] = judge.endpoint_host if judge is not None and judge.sources: settings[TRAJECTORY_SOURCES_SETTING] = list(judge.sources) + settings[TRAJECTORY_FORMATS_READ_SETTING] = trajectory_formats_read(judge.sources) asked, bar = values.get("judge_samples"), values.get("min_judge_agreement") if not self._spec().samplable: # A run-wide judge_samples reaches every judge; one whose format can't take it grades once. diff --git a/src/agent_env/task_step/task_steps/verifiers/verifier.py b/src/agent_env/task_step/task_steps/verifiers/verifier.py index 6fa223187..55f271447 100644 --- a/src/agent_env/task_step/task_steps/verifiers/verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/verifier.py @@ -12,7 +12,7 @@ from abc import abstractmethod from dataclasses import dataclass, field from enum import Enum -from typing import Any, ClassVar, Optional, TypedDict +from typing import Any, ClassVar, Iterable, Mapping, Optional, TypedDict from agent_env.config import get_config from agent_env.plugins import distribution_version @@ -30,10 +30,12 @@ # bumps it, and every grade records it in its verifier_settings. SCORING_RULES = 1 # Keys a verifier's settings may hold that record how its grading went, not what it graded with: the host its judge's -# calls reached, the trajectory source of each turn it read, and which settings a run's overrides changed, whose values -# the settings hold too. A comparison of two runs' settings reads these apart (``agent_env.task.drift``). +# calls reached, the trajectory source of each turn it read and the formats those were, and which settings a run's +# overrides changed, whose values the settings hold too. A comparison of two runs' settings reads these apart +# (``agent_env.task.drift``). JUDGE_ENDPOINT_HOST_SETTING = "judge_endpoint_host" TRAJECTORY_SOURCES_SETTING = "trajectory_sources" +TRAJECTORY_FORMATS_READ_SETTING = "trajectory_formats_read" OVERRIDDEN_SETTING = "overridden" DEFAULT_MIN_PASSING_SCORE = 1.0 OUTPUT_INLINE_BYTES = 16 * 1024 @@ -295,6 +297,14 @@ def _capped(text: Optional[str]) -> Optional[str]: return f"{text[:REASONING_CHARS]}… ({len(text)} characters)" +def trajectory_formats_read(sources: Iterable[Mapping[str, Any]]) -> list[str]: + """The distinct formats a judge's ``trajectory_sources`` read its turns as, an ATIF copy's with its adapter's + version, however many turns it read: a few names, which stay whole where the per-turn list, past + ``SETTING_INLINE_BYTES``, is kept as its hash.""" + return sorted({f"{source.get('format')}@{source['adapter_version']}" if source.get("adapter_version") + else str(source.get("format")) for source in sources}) + + def _compact(value: Any) -> Any: body = canonical_json(value) if len(body) <= SETTING_INLINE_BYTES: diff --git a/tst/unit/task/drift_test.py b/tst/unit/task/drift_test.py index efbde9462..f8da85637 100644 --- a/tst/unit/task/drift_test.py +++ b/tst/unit/task/drift_test.py @@ -234,6 +234,52 @@ def change(records): assert compare(_records(), _changed(change)).differences == [] +HASHED = {"sha256": "f" * 64, "bytes": 4096} + + +@pytest.mark.parametrize("summary, rows", [(["atif/1@1"], []), (["atif/1@1", "native-stream"], [ + ("trajectory formats a judge read", SOFT)])], ids=["the same formats", "another format too"]) +def test_a_long_conversations_formats_are_compared_by_their_summary_when_its_turns_are_kept_as_a_hash(summary, rows): + def change(records): + records.lock.verifiers["score"].graded_settings.update(trajectory_sources=HASHED, + trajectory_formats_read=summary) + + comparison = compare(_records(), _changed(change)) + assert [(d.row, d.drift) for d in comparison.differences] == rows and comparison.not_compared == [] + + +def test_formats_kept_only_as_a_hash_arent_compared_and_the_listing_says_so(): + def change(records): + records.lock.verifiers["score"].graded_settings["trajectory_sources"] = HASHED + + comparison = compare(_records(), _changed(change)) + + assert comparison.differences == [] + assert comparison.not_compared == ["the trajectory formats verifier score read in attempt 0 of second: its record " + "keeps only a hash of them"] + + +@pytest.mark.parametrize("override, rows", [(["atif/1"], []), ([], [("trajectory formats prescribed", HARD)])], + ids=["the same formats", "other formats"]) +def test_an_attempt_recorded_before_its_prescribed_formats_is_compared_by_its_override_of_them(override, rows): + def change(records): + records.lock.intent.trajectory_formats = None + records.lock.intent.overrides["trajectory_formats"] = override + + assert [(d.row, d.drift) for d in compare(_records(), _changed(change)).differences] == rows + + +def test_an_attempt_that_records_neither_its_prescribed_formats_nor_an_override_isnt_compared_on_them(): + def change(records): + records.lock.intent.trajectory_formats = None + + comparison = compare(_records(), _changed(change)) + + assert comparison.differences == [] + assert comparison.not_compared == ["the trajectory formats attempt 0 of second prescribed: it records neither them " + "nor an override of them"] + + def test_a_change_the_overrides_made_to_a_judge_is_its_settings_hard_and_their_names_never(): def change(records): verifier = records.lock.verifiers["score"] diff --git a/tst/unit/task_step/verifiers/test_judge_inputs_stored.py b/tst/unit/task_step/verifiers/test_judge_inputs_stored.py index 55c8e5a5c..ed2e61d1a 100644 --- a/tst/unit/task_step/verifiers/test_judge_inputs_stored.py +++ b/tst/unit/task_step/verifiers/test_judge_inputs_stored.py @@ -216,6 +216,7 @@ async def test_a_judge_that_reads_the_trajectory_records_its_sources_in_its_sett grade = await _grade(step, context) assert grade["verifier_settings"]["trajectory_sources"] == [{"turn": 1, "format": "claude-code-stream-json"}] + assert grade["verifier_settings"]["trajectory_formats_read"] == ["claude-code-stream-json"] def _answering_judge(monkeypatch) -> list[str]: From 5b43f759c5688ada3ede5b1606152a820c8dc7be Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 1 Dec 2026 07:09:08 -0800 Subject: [PATCH 07/10] fix(task): a failed run, where a run ran, and a credential's reference compare without false drift From a review of the comparator against runs that ran the same thing: - Each attempt records whether it completed the steps it ran (`completed`: none failed, tolerated or not, and no cancel). An entity only one attempt read, or a type only one used, is a difference only when both ran and completed the same steps, so a run that failed early is no longer hard drift for what it didn't reach. - Where a run's sandboxes run is soft by every key that says so (`SANDBOX_OVERRIDE_KEYS`, which `sandbox_overrides` sets, `sandbox` included), and a judge's `judge_sandbox_type` is compared as where it ran, soft. - The override row leaves out each role's model and endpoint, which the role rows compare as they resolve; a secret's reference, as an API key's, is never drift; a step's `step_params` are compared each by name, an endpoint among them soft. - A grade's settings are compared where both verifiers started with the same value, so a setting they started with otherwise is one difference and its graded value isn't misread. - Pins are compared when an attempt's reads aren't recorded, and the listing says "in what both recorded" when anything wasn't compared. - A trajectory formats value named wrongly records None for that field rather than dropping the attempt's records. - The grading-evidence and placement settings are sets in the verifier base, and the registry's name in a record is one helper (`registry_name`) the recorder and the comparator share. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 31 +++-- src/agent_env/cli/task/diff.py | 9 +- src/agent_env/task/drift.py | 128 +++++++++++++----- src/agent_env/task/run_lock.py | 52 ++++--- src/agent_env/task/run_records.py | 11 +- src/agent_env/task_step/context.py | 12 +- .../task_steps/verifiers/rubrics_verifier.py | 3 +- .../task_steps/verifiers/verifier.py | 5 + tst/unit/cli/task_diff_test.py | 5 +- tst/unit/task/drift_test.py | 113 ++++++++++++---- tst/unit/task/run_lock_test.py | 16 ++- 11 files changed, 279 insertions(+), 106 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index eee1cfb28..67f3ae0ca 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -494,20 +494,23 @@ orchestrators call it the same way. What callers rely on: those it was asked to run (`steps_run`), the trajectory formats it prescribes (`trajectory_formats`), its pins, each role's model and endpoint host as this process resolves them, the overrides without secrets and the result rules version, computed as the eval plan computes its own, `eval/intent.py`; each verifier's settings and version at the - start and as graded, by the grades whose `attempt_epoch` is this attempt's or a retry's within it; and every entity - version the run read, each image with its `image_identity`). Each is written `started` and then `finished`, however - the run ends, by writer threads of their own (`task/record_writer.py`, never awaited; `flush_run_records` waits for - them, and an exit waits 10 s at most), under a counter of their own (`run_records_rev`) that the instance's other - writes don't check, nor these theirs (on DynamoDB, which conditions a write on the whole item, one still retries the - other); the store keeps the finished record whichever lands last, and a resume adds its own. An instance leaves out, - with a warning, a record this version can't read. A worker that runs a task's steps itself enters `run_recorded` - around them, once per attempt in the process that runs them all, as it sets `run_pins`. `task/drift.py` classes every - difference between two attempts' records by the lock table (`compare`, its rows `ROWS`, every record field in one or - in `NOT_COMPARED`): `hard` when they ran different things, `regrade` too for the result rules or a verifier's - settings, `soft` for code meant to change under a run, as an upgraded package, and `never`, as how a version was asked - for; an image's identity, not its artifact's version, says whether it changed, and an entity only one attempt read is - a difference only when both ran the same steps; what a verifier's settings record of how its grading went (the formats - its judge read, the host its calls reached, which settings overrides changed) is compared apart from its settings. + start and as graded, by the grades whose `attempt_epoch` is this attempt's or a retry's within it; every entity + version the run read, each image with its `image_identity`, and whether it completed the steps it ran, none failing + and no cancel, `completed`). Each is written `started` and then `finished`, however the run ends, by writer threads of + their own (`task/record_writer.py`, never awaited; `flush_run_records` waits for them, and an exit waits 10 s at + most), under a counter of their own (`run_records_rev`) that the instance's other writes don't check, nor these theirs + (on DynamoDB, which conditions a write on the whole item, one still retries the other); the store keeps the finished + record whichever lands last, and a resume adds its own. An instance leaves out, with a warning, a record this version + can't read. A worker that runs a task's steps itself enters `run_recorded` around them, once per attempt in the + process that runs them all, as it sets `run_pins`. `task/drift.py` classes every difference between two attempts' + records by the lock table (`compare`, its rows `ROWS`, every record field in one or in `NOT_COMPARED`): `hard` when + they ran different things, `regrade` too for the result rules or a verifier's settings, `soft` for code meant to + change under a run, as an upgraded package, and `never`, as how a version was asked for; an image's identity, not its + artifact's version, says whether it changed, and an entity only one attempt read is a difference only when both ran + and completed the same steps; an override is compared by what it changes (a role's model and endpoint by the role + rows, a secret's reference never, where sandboxes run soft); what a verifier's settings record of how its grading went + (the formats its judge read, the host its calls reached, which settings overrides changed, where its judge ran; + `GRADING_EVIDENCE_SETTINGS` and `PLACEMENT_SETTINGS` in the verifier base) is compared apart from its settings. `agent-env task diff` lists the differences, exiting 1 on hard drift. - A runner that must hear from a long step puts a zero-argument callable at `context.metadata[HEARTBEAT_KEY]` (`task_step/context.py`); a step that blocks for long calls diff --git a/src/agent_env/cli/task/diff.py b/src/agent_env/cli/task/diff.py index 918c2dd07..6c5d4929a 100644 --- a/src/agent_env/cli/task/diff.py +++ b/src/agent_env/cli/task/diff.py @@ -65,7 +65,7 @@ def _parse(spec: str) -> tuple[str, Optional[int]]: """``INSTANCE@EPOCH`` as the instance and the epoch, else the instance alone: an id may start with ``@``, as a local one does, so only a last ``@`` followed by digits names an attempt.""" head, at, tail = spec.rpartition("@") - return (head, int(tail)) if at and head and tail.isdigit() else (spec, None) + return (head, int(tail)) if at and head and tail.isascii() and tail.isdigit() else (spec, None) def _fail(message: str) -> NoReturn: @@ -81,8 +81,11 @@ def _echo(comparison: Comparison) -> None: for note in comparison.not_compared: click.echo(f" not compared: {note}") counts = ", ".join(f"{len(comparison.of(drift))} {drift}" for drift in Drift) - verdict = ("the same thing ran" if comparison.like_for_like else "they didn't run the same thing") - click.echo(f"{counts}: {verdict}" if comparison.differences else "no differences: the same thing ran") + if not comparison.like_for_like: + verdict = "they didn't run the same thing" + else: + verdict = "the same thing ran" + (", in what both recorded" if comparison.not_compared else "") + click.echo(f"{counts}: {verdict}" if comparison.differences else f"no differences: {verdict}") if comparison.regrade: click.echo("Their grades are under different result rules or verifier settings: regrade one under the other's " "before comparing their scores.") diff --git a/src/agent_env/task/drift.py b/src/agent_env/task/drift.py index 8f83f1a86..d5ff5ec3e 100644 --- a/src/agent_env/task/drift.py +++ b/src/agent_env/task/drift.py @@ -9,12 +9,18 @@ identity is the same image, so its version's change is ``never``. A row that reports a thing added or removed, a verifier, a role, a plugin or an entity read, is the only one that does; the rows of that thing's other fields compare it only where both attempts have it. An entity only one attempt read is a difference only when both ran the same steps -(``RunIntent.steps_run``): a resume runs only the rest, which read less, and what it didn't read isn't compared. +(``RunIntent.steps_run``) and completed them (``RunLock.completed``): a resume runs only the rest, which read less, and +a run that failed stopped short of what the other read, so what one didn't read isn't compared. + +An override is compared by what it changes: the role rows compare a role's model and endpoint as they resolve, so +the overrides naming them aren't listed again; one naming a secret, as an API key's reference, is never drift; one of +where a run's sandboxes run is soft, as is an endpoint a step's ``step_params`` name. A verifier's settings record how its grading went beside what it graded with: which trajectory formats its judge read, -the host its calls reached and which settings a run's overrides changed. Those aren't settings: each has a row of its -own, the formats a judge read soft, as a copy that failed is read natively, while the formats the run prescribed are -hard. +the host its calls reached and which settings a run's overrides changed, and where its judge ran. Those aren't settings: +each has a row of its own, the formats a judge read soft, as a copy that failed is read natively, while the formats the +run prescribed are hard. Settings its grade records are compared where both attempts started with the same; where they +started otherwise, the starting settings' row says so. """ from __future__ import annotations @@ -24,12 +30,16 @@ from functools import cached_property from typing import Any, Callable, Mapping, Optional +from agent_env.config.model import RUN_ENDPOINT_KEYS, RUN_MODEL_KEYS from agent_env.plugins import TASK_STEPS -from agent_env.task.run_records import RunLock, RunRuntime, Stage +from agent_env.task.run_records import RunLock, RunRuntime, Stage, registry_name from agent_env.task.store import TaskInstance +from agent_env.task_step.context import SANDBOX_OVERRIDE_KEYS, redacted_key from agent_env.task_step.task_steps.verifiers.verifier import ( + GRADING_EVIDENCE_SETTINGS, JUDGE_ENDPOINT_HOST_SETTING, OVERRIDDEN_SETTING, + PLACEMENT_SETTINGS, TRAJECTORY_FORMATS_READ_SETTING, TRAJECTORY_SOURCES_SETTING, trajectory_formats_read, @@ -37,17 +47,17 @@ Key = tuple[str, ...] -# Overrides of where a run's sandboxes run, not of what runs in them, which the image identities record. -_PLACEMENT_OVERRIDES = frozenset({"agent_sandbox", "env_sandbox"}) # The override that holds each step's own, by step id (``TaskStep.step_param_overrides``). _STEP_PARAMS = "step_params" # The override of the trajectory formats a run prescribes, which the intent's own row compares as resolved. _TRAJECTORY_FORMATS = "trajectory_formats" -# What a verifier's settings record of how its grading went, each compared by a row of its own, not as a setting. -_GRADING_EVIDENCE = frozenset({JUDGE_ENDPOINT_HOST_SETTING, TRAJECTORY_SOURCES_SETTING, TRAJECTORY_FORMATS_READ_SETTING, - OVERRIDDEN_SETTING}) +_ENDPOINT_OVERRIDES = frozenset(key for keys in RUN_ENDPOINT_KEYS.values() for key in keys) +# A run's overrides of each role's model and endpoint, which the role rows compare as they resolve. +_ROLE_OVERRIDES = frozenset(RUN_MODEL_KEYS.values()) | _ENDPOINT_OVERRIDES +# What a verifier's settings record that isn't what it graded with, each compared by a row of its own. +_NOT_GRADING_SETTINGS = GRADING_EVIDENCE_SETTINGS | PLACEMENT_SETTINGS # The registry of the types an attempt records from its start, its steps'; the others it records once it finishes. -_STEP_TYPES = TASK_STEPS.removeprefix("agent_env.") +_STEP_TYPES = registry_name(TASK_STEPS) _READ_FIELDS = ("version", "type", "image_identity", "latest", "alias") @@ -73,7 +83,8 @@ def attempt_epoch(self) -> int: @staticmethod def epochs(instance: TaskInstance) -> list[int]: """The attempts of ``instance`` that recorded both a runtime and a lock, oldest first.""" - return sorted({r.attempt_epoch for r in instance.runtimes} & {lock.attempt_epoch for lock in instance.run_locks}) + runtimes = {runtime.attempt_epoch for runtime in instance.runtimes} + return sorted(runtimes & {lock.attempt_epoch for lock in instance.run_locks}) @classmethod def of(cls, instance: TaskInstance, attempt_epoch: Optional[int] = None) -> Records: @@ -228,8 +239,8 @@ def compare(a: Records, b: Records) -> Comparison: not_compared = [f"attempt {r.attempt_epoch} of {r.instance_id} didn't finish, so what it read and the types it " "used beyond its steps' aren't recorded" for r in unread] if not unread and not _same_steps(a, b) and (only := _read(a) ^ _read(b)): - not_compared.append(f"the {len(only)} entit{'y' if len(only) == 1 else 'ies'} only one of them read: " - f"{_ran(a)} and {_ran(b)}, so they ran different steps") + not_compared.append(f"the {len(only)} entit{'y' if len(only) == 1 else 'ies'} only one of them read, as they " + f"didn't both run and complete the same steps: {_ran(a)}, and {_ran(b)}") not_compared += [f"the trajectory formats attempt {r.attempt_epoch} of {r.instance_id} prescribed: it records " "neither them nor an override of them" for r in (a, b) if r.prescribed_formats is None] graded_both = _graded(a).keys() & _graded(b).keys() @@ -244,7 +255,9 @@ def _read(records: Records) -> frozenset[Key]: def _same_steps(a: Records, b: Records) -> bool: - return a.lock.intent.steps_run is not None and a.lock.intent.steps_run == b.lock.intent.steps_run + """Whether both attempts ran the same steps, and each completed them.""" + return (a.lock.intent.steps_run is not None and a.lock.intent.steps_run == b.lock.intent.steps_run + and a.lock.completed is True and b.lock.completed is True) def _read_by_both(key: Key, a: Records, b: Records) -> bool: @@ -256,11 +269,13 @@ def _read_by_both_or_same_steps(key: Key, a: Records, b: Records) -> bool: def _ran(records: Records) -> str: - steps = records.lock.intent.steps_run + steps, completed = records.lock.intent.steps_run, records.lock.completed where = f"attempt {records.attempt_epoch} of {records.instance_id}" if steps is None: return f"{where} doesn't record which steps it ran" - return f"{where} ran {len(steps)} step{'s' * (len(steps) != 1)}" + ran = f"{where} ran {len(steps)} step{'s' * (len(steps) != 1)}" + return (f"{ran} and completed them" if completed is True else f"{ran} and didn't complete them" + if completed is False else f"{ran} and doesn't record whether it completed them") def _one(value: Any) -> dict[Key, Any]: @@ -277,25 +292,44 @@ def _version_drift(key: Key, a: Records, b: Records) -> Drift: def _types_recorded(key: Key, a: Records, b: Records) -> bool: - """A step type is recorded from an attempt's start, any other type once it finishes.""" - return key[0] == _STEP_TYPES or (a.finished and b.finished) + """A step type is recorded from an attempt's start, any other type once it finishes, from what it read: so one + only one attempt used is a difference only where an entity only one read is.""" + if key[0] == _STEP_TYPES: + return True + return a.finished and b.finished and (_same_steps(a, b) or (key in _types(a) and key in _types(b))) + + +def _types(records: Records) -> dict[Key, Any]: + return {(group, name): found for group, types in records.runtime.types.items() for name, found in types.items()} def _overrides(records: Records) -> dict[Key, Any]: - """The run's overrides by name, a step's ``step_params`` by the step's id.""" + """The run's overrides by name, each of a step's ``step_params`` by the step's id and its name, but those another + row compares: each role's model and endpoint, and the trajectory formats.""" values: dict[Key, Any] = {} for name, value in records.lock.intent.overrides.items(): - if name == _TRAJECTORY_FORMATS: + if name == _TRAJECTORY_FORMATS or name in _ROLE_OVERRIDES: continue if name == _STEP_PARAMS and isinstance(value, Mapping): - values.update({(name, str(step)): params for step, params in value.items()}) + for step, params in value.items(): + if isinstance(params, Mapping): + values.update({(name, str(step), str(param)): set_to for param, set_to in params.items()}) + else: + values[(name, str(step))] = params else: values[(name,)] = value return values def _override_drift(key: Key, a: Records, b: Records) -> Drift: - return Drift.SOFT if key[0] in _PLACEMENT_OVERRIDES else Drift.HARD + """A secret's reference is never drift, where a run's sandboxes run and the endpoint a step names are soft, and + anything else an override changes is hard.""" + name = key[-1] + if redacted_key(name): + return Drift.NEVER + if (len(key) == 1 and name in SANDBOX_OVERRIDE_KEYS) or (len(key) == 3 and name in _ENDPOINT_OVERRIDES): + return Drift.SOFT + return Drift.HARD def _in_both(of: Callable[[Records], Mapping[str, Any]]) -> Callable[[Key, Records, Records], bool]: @@ -321,15 +355,36 @@ def _plugins(records: Records) -> Mapping[str, Any]: def _settings(records: Records) -> dict[Key, Any]: return {(step, name): value for step, verifier in records.lock.verifiers.items() - for name, value in verifier.settings.items() if name not in _GRADING_EVIDENCE} + for name, value in verifier.settings.items() if name not in _NOT_GRADING_SETTINGS} -def _set_while_grading(records: Records) -> dict[Key, Any]: - """Each verifier's settings its grading set or changed, as a judge's model it resolves as it calls: those its - grade records otherwise than it started with, which the starting settings' row already compares.""" - return {(step, name): value for step, verifier in records.lock.verifiers.items() - for name, value in (verifier.graded_settings or {}).items() - if name not in _GRADING_EVIDENCE and (name not in verifier.settings or verifier.settings[name] != value)} +def _as_graded(records: Records) -> dict[Key, Any]: + return {(step, name): value for step, verifier in _graded(records).items() + for name, value in verifier.graded_settings.items() if name not in _NOT_GRADING_SETTINGS} + + +def _started_alike(key: Key, a: Records, b: Records) -> bool: + """A setting a grade records is compared where both verifiers graded and started with the same value of it, as + a judge's model it resolves as it calls; one they started with otherwise is the starting settings' row's.""" + step, name = key + if step not in _graded(a) or step not in _graded(b): + return False + return a.lock.verifiers[step].settings.get(name) == b.lock.verifiers[step].settings.get(name) + + +def _placement(records: Records) -> dict[Key, Any]: + return {(step, name): verifier.settings[name] for step, verifier in records.lock.verifiers.items() + for name in sorted(PLACEMENT_SETTINGS) if name in verifier.settings} + + +def _pins(records: Records) -> dict[Key, Any]: + return {(kind, entity_id): version for kind, ids in records.lock.intent.pins.items() + for entity_id, version in ids.items()} + + +def _either_unread(key: Key, a: Records, b: Records) -> bool: + """Pins are compared where an attempt's reads, which show what it read, aren't recorded.""" + return a.lock.reads is None or b.lock.reads is None def _formats_known(key: Key, a: Records, b: Records) -> bool: @@ -349,6 +404,9 @@ def _prescriptions_known(key: Key, a: Records, b: Records) -> bool: lambda r: _one(None if r.lock.intent.steps_run is None else tuple(r.lock.intent.steps_run))), _Row("trajectory formats prescribed", ("RunIntent.trajectory_formats",), Drift.HARD, lambda r: _one(r.prescribed_formats), compared=_prescriptions_known), + _Row("pins", ("RunIntent.pins",), Drift.HARD, _pins, compared=_either_unread), + _Row("completed its steps", ("RunLock.completed",), Drift.NEVER, lambda r: _one(r.lock.completed), + compared=lambda key, a, b: a.lock.completed is not None and b.lock.completed is not None), _Row("entity version", ("ReadRecord.kind", "ReadRecord.id", "ReadRecord.version"), Drift.HARD, lambda r: _by_entity(r, "version"), classify=_version_drift, compared=_read_by_both_or_same_steps), _Row("entity type", ("ReadRecord.type",), Drift.HARD, lambda r: _by_entity(r, "type"), compared=_read_by_both), @@ -372,8 +430,9 @@ def _prescriptions_known(key: Key, a: Records, b: Records) -> bool: lambda r: {(step,): v.type for step, v in r.lock.verifiers.items()}), _Row("verifier settings", ("VerifierRecord.settings",), Drift.HARD, _settings, regrade=True, compared=_in_both(_verifiers)), - _Row("verifier settings set while grading", ("VerifierRecord.graded_settings",), Drift.HARD, _set_while_grading, - regrade=True, compared=_in_both(_graded)), + _Row("verifier settings as graded", ("VerifierRecord.graded_settings",), Drift.HARD, _as_graded, regrade=True, + compared=_started_alike), + _Row("where a verifier's judge ran", (), Drift.SOFT, _placement, compared=_in_both(_verifiers)), _Row("trajectory formats a judge read", (), Drift.SOFT, lambda r: {(step,): formats for step, formats in r.formats_read.items()}, compared=_formats_known), _Row("judge endpoint host", (), Drift.SOFT, @@ -394,9 +453,7 @@ def _prescriptions_known(key: Key, a: Records, b: Records) -> bool: _Row("plugin install", ("InstalledPlugin.origin",), Drift.SOFT, lambda r: {(name,): plugin.origin for name, plugin in r.runtime.plugins.items()}, compared=_in_both(_plugins)), - _Row("type's package", ("RunRuntime.types",), Drift.SOFT, - lambda r: {(group, name): found for group, types in r.runtime.types.items() for name, found in types.items()}, - compared=_types_recorded), + _Row("type's package", ("RunRuntime.types",), Drift.SOFT, _types, compared=_types_recorded), _Row("config found by", ("RunRuntime.config_selected_by",), Drift.NEVER, lambda r: _one(r.runtime.config_selected_by)), ) @@ -409,7 +466,6 @@ def _prescriptions_known(key: Key, a: Records, b: Records) -> bool: "RunLock.stage": "whether the attempt finished says what was recorded, not what ran", "RunRuntime.record_version": "the shape the record was written in", "RunLock.record_version": "the shape the record was written in", - "RunIntent.pins": "the versions the run was told to read, which its reads show", "RunRuntime.plugins": "compared by each plugin's fields", "RunLock.intent": "compared by its fields", "RunIntent.roles": "compared by each role's fields", diff --git a/src/agent_env/task/run_lock.py b/src/agent_env/task/run_lock.py index e8bd32fd8..2040a6483 100644 --- a/src/agent_env/task/run_lock.py +++ b/src/agent_env/task/run_lock.py @@ -31,6 +31,7 @@ from typing import TYPE_CHECKING, Any, AsyncIterator, Iterable, Optional, Sequence from agent_env.config import get_config +from agent_env.config.errors import ConfigError from agent_env.entity.pins import PINS_KEY, Read, checked_pins, recording from agent_env.eval.intent import content_hash, recorded_overrides, role_models, run_overrides from agent_env.plugins import ( @@ -55,9 +56,10 @@ RunRuntime, Stage, VerifierRecord, + registry_name, ) from agent_env.task.store import record_run_records -from agent_env.task_step.context import TaskStepContext +from agent_env.task_step.context import StepContextError, TaskStepContext from agent_env.task_step.task_step import TaskStep from agent_env.task_step.task_steps.prompt_agent import prescribed_formats from agent_env.task_step.task_steps.verifiers.verifier import GRADES_KEY, VerifierTaskStep @@ -69,12 +71,7 @@ logger = logging.getLogger(__name__) -def _group(entry_point_group: str) -> str: - """A registry's name in a record: its entry-point group's without the ``agent_env.`` prefix (``task_steps``).""" - return entry_point_group.removeprefix("agent_env.") - - -_READ_KINDS = {"env": _group(ENVS), "artifact": _group(ARTIFACTS)} +_READ_KINDS = {"env": registry_name(ENVS), "artifact": registry_name(ARTIFACTS)} def started_runtime(attempt_epoch: int, steps: Sequence[TaskStep]) -> RunRuntime: @@ -86,7 +83,7 @@ def started_runtime(attempt_epoch: int, steps: Sequence[TaskStep]) -> RunRuntime python=platform.python_version(), plugins={name: InstalledPlugin(version, install_origin(name)) for name, version in installed_plugins().items()}, config_selected_by=get_config().config_found_by(), - types={_group(TASK_STEPS): {step.type: distribution_of(type(step)) for step in steps}}, + types={registry_name(TASK_STEPS): {step.type: distribution_of(type(step)) for step in steps}}, ) @@ -106,7 +103,7 @@ def started_lock(task: "Task", steps: Sequence[TaskStep], context: TaskStepConte content_hash=content_hash(task), steps_hash=steps_hash(steps), steps_run=[step.id for step in steps[start_step:end_step]], - trajectory_formats=list(prescribed_formats(context)), + trajectory_formats=_prescribed(context), pins=checked_pins(user_overrides.get(PINS_KEY)), roles=role_models(overrides), overrides=recorded_overrides(overrides), @@ -118,6 +115,15 @@ def started_lock(task: "Task", steps: Sequence[TaskStep], context: TaskStepConte ) +def _prescribed(context: TaskStepContext) -> Optional[list[str]]: + """The trajectory formats the run prescribes; None when its override or config names them wrongly, which fails the + step that prescribes them, not the record of the rest.""" + try: + return list(prescribed_formats(context)) + except (StepContextError, ConfigError): + return None + + def steps_hash(steps: Sequence[TaskStep]) -> str: """A hash of the steps as this run runs them, its seed applied, beside the task's own content hash: two runs of one task with different seeds ask different things of their agents, which this tells apart without recording the @@ -125,18 +131,19 @@ def steps_hash(steps: Sequence[TaskStep]) -> str: return "sha256:" + hashlib.sha256(canonical_json([step.to_dict() for step in steps])).hexdigest() -def finished_records(runtime: RunRuntime, lock: RunLock, reads: Iterable[Read], - context: TaskStepContext) -> tuple[RunRuntime, RunLock]: +def finished_records(runtime: RunRuntime, lock: RunLock, reads: Iterable[Read], context: TaskStepContext, + raised: bool = False) -> tuple[RunRuntime, RunLock]: """The attempt's records once its run ends: in its lock, ``reads``, every entity version it read, and each verifier - it graded with the settings its grade records (``graded_settings``), which a judge completes as it calls; in its - runtime, the types of the envs, artifacts and providers it used.""" + it graded with the settings its grade records (``graded_settings``), which a judge completes as it calls, and + whether it completed the steps it was asked to run (``raised`` when the block ended by an exception or a cancel); + in its runtime, the types of the envs, artifacts and providers it used.""" reads = list(reads) types = {group: dict(found) for group, found in runtime.types.items()} for read in reads: if (group := _READ_KINDS.get(str(read.kind))) and read.type and read.cls is not None: types.setdefault(group, {})[read.type] = distribution_of(read.cls) - for group, used in ((_group(SANDBOX_PROVIDERS), _sandbox_types(context)), - (_group(ENV_PROVIDERS), _env_provider_types(context))): + for group, used in ((registry_name(SANDBOX_PROVIDERS), _sandbox_types(context)), + (registry_name(ENV_PROVIDERS), _env_provider_types(context))): for name, impl in used.items(): types.setdefault(group, {})[name] = distribution_of(impl) if impl is not None else None grades = context.metadata.get(GRADES_KEY) or {} @@ -144,7 +151,16 @@ def finished_records(runtime: RunRuntime, lock: RunLock, reads: Iterable[Read], if _graded_in(grades.get(step_id), lock.attempt_epoch) else verifier) for step_id, verifier in lock.verifiers.items()} return (dataclasses.replace(runtime, types=types, stage=Stage.FINISHED), - dataclasses.replace(lock, verifiers=verifiers, reads=read_records(reads), stage=Stage.FINISHED)) + dataclasses.replace(lock, verifiers=verifiers, reads=read_records(reads), + completed=not raised and not _failed_in(context, lock.intent.steps_run), + stage=Stage.FINISHED)) + + +def _failed_in(context: TaskStepContext, steps_run: Optional[Sequence[str]]) -> bool: + """Whether a step the attempt ran failed and wasn't retried, as one whose failure the task tolerates.""" + ran = set(steps_run or ()) + return any(isinstance(failed, dict) and failed.get("step_id") in ran and not failed.get("retried") + for failed in context.metadata.get("failed_steps") or ()) def _graded_in(grade: Any, attempt_epoch: int) -> bool: @@ -177,11 +193,13 @@ async def run_recorded(instance_id: Optional[str], task: "Task", steps: Sequence runtime, lock = started _write(instance_id, runtime, lock) with recording() as reads: + raised = True try: yield + raised = False finally: try: - runtime, lock = finished_records(runtime, lock, reads, context) + runtime, lock = finished_records(runtime, lock, reads, context, raised) except Exception: logger.warning("The reads of attempt %s of %s couldn't be recorded", attempt_epoch, instance_id, exc_info=True) diff --git a/src/agent_env/task/run_records.py b/src/agent_env/task/run_records.py index 10b1f974d..041a7b2e8 100644 --- a/src/agent_env/task/run_records.py +++ b/src/agent_env/task/run_records.py @@ -21,6 +21,11 @@ RUN_RECORD_VERSION = 1 +def registry_name(entry_point_group: str) -> str: + """A registry's name in a record: its entry-point group's without the ``agent_env.`` prefix (``task_steps``).""" + return entry_point_group.removeprefix("agent_env.") + + class Stage(StrEnum): """``started`` when the attempt began; ``finished`` once it ended, however it ended, with what it read.""" @@ -194,12 +199,14 @@ def from_dict(cls, data: dict) -> ReadRecord: @dataclass class RunLock: """What an attempt was asked to do (``intent``) and what it resolved: each verifier's record by step id, and, once - ``finished``, every entity version it read (``reads``), children included; None while ``started``.""" + ``finished``, every entity version it read (``reads``), children included, and whether it ``completed`` the steps + it was asked to run, none failing it, raising or tolerated, and no cancel; both None while ``started``.""" attempt_epoch: int intent: RunIntent verifiers: dict[str, VerifierRecord] = field(default_factory=dict) reads: Optional[list[ReadRecord]] = None + completed: Optional[bool] = None stage: Stage | str = Stage.STARTED record_version: int = RUN_RECORD_VERSION @@ -216,6 +223,7 @@ def to_dict(self) -> dict: "resolved": { "verifiers": {step_id: verifier.to_dict() for step_id, verifier in self.verifiers.items()}, "reads": None if self.reads is None else [read.to_dict() for read in self.reads], + "completed": self.completed, }, } @@ -229,6 +237,7 @@ def from_dict(cls, data: dict) -> RunLock: verifiers={step_id: VerifierRecord.from_dict(verifier) for step_id, verifier in (resolved.get("verifiers") or {}).items()}, reads=None if reads is None else [ReadRecord.from_dict(read) for read in reads], + completed=resolved.get("completed"), stage=_stage(data.get("stage", Stage.STARTED)), record_version=data.get("record_version", RUN_RECORD_VERSION), ) diff --git a/src/agent_env/task_step/context.py b/src/agent_env/task_step/context.py index a02304790..183bd9cd6 100644 --- a/src/agent_env/task_step/context.py +++ b/src/agent_env/task_step/context.py @@ -71,6 +71,12 @@ class VerifierNotPassingError(RuntimeError): } +def redacted_key(key: str) -> bool: + """Whether ``key`` names a secret kept out of storage, as a run's API key: a bare reference to one is kept, naming + which secret a run used rather than what it ran.""" + return key in _REDACTED_KEYS + + def _is_redacted(key: str, value: Any) -> bool: """Whether ``key`` holds a secret kept out of storage. A bare ``env:`` / ``secret:`` reference names one rather than holding it, so it is kept; one with a ``?default`` may carry the secret itself, so it is not.""" @@ -220,10 +226,14 @@ def read_dual_keyed(data: dict[str, Any], legacy: str, neutral: str) -> Any: return value if value is not None else data.get(neutral) +# The ``user_overrides`` that say which sandbox provider a run's envs, agents and sandboxes run on. +SANDBOX_OVERRIDE_KEYS = ("env_sandbox", "agent_sandbox", "sandbox") + + def sandbox_overrides(sandbox: str) -> dict[str, str]: """The ``user_overrides`` that deploy a run's envs, agents, sandboxes and judge on ``sandbox``, as ``agent-env run --sandbox`` sets them.""" - return {"env_sandbox": sandbox, "agent_sandbox": sandbox, "sandbox": sandbox} + return {key: sandbox for key in SANDBOX_OVERRIDE_KEYS} # (legacy, neutral) keys of the PromptResponse fields that were renamed. Stored documents and raw-doc readers use the diff --git a/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py b/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py index 9253559db..bd53d9fe9 100644 --- a/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py @@ -60,6 +60,7 @@ from agent_env.task_step.task_steps.verifiers.scoring import ScoreAggregator, aggregate_score from agent_env.task_step.task_steps.verifiers.verifier import ( JUDGE_ENDPOINT_HOST_SETTING, + JUDGE_SANDBOX_TYPE_SETTING, OVERRIDDEN_SETTING, TRAJECTORY_FORMATS_READ_SETTING, TRAJECTORY_SOURCES_SETTING, @@ -974,7 +975,7 @@ def _run_values(self, context: TaskStepContext) -> dict[str, Any]: "judge_batch_concurrency": _override_or(overrides, "judge_batch_concurrency", self.judge_batch_concurrency), "judge_samples": _override_or(overrides, "judge_samples", self.judge_samples), "min_judge_agreement": _override_or(overrides, "min_judge_agreement", self.min_judge_agreement), - "judge_sandbox_type": (overrides.get("agent_sandbox") or self.judge_sandbox_type) + JUDGE_SANDBOX_TYPE_SETTING: (overrides.get("agent_sandbox") or self.judge_sandbox_type) if use_agent_judge and self.agent_name is None else self.judge_sandbox_type, } diff --git a/src/agent_env/task_step/task_steps/verifiers/verifier.py b/src/agent_env/task_step/task_steps/verifiers/verifier.py index 55f271447..795d9dd3e 100644 --- a/src/agent_env/task_step/task_steps/verifiers/verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/verifier.py @@ -37,6 +37,11 @@ TRAJECTORY_SOURCES_SETTING = "trajectory_sources" TRAJECTORY_FORMATS_READ_SETTING = "trajectory_formats_read" OVERRIDDEN_SETTING = "overridden" +GRADING_EVIDENCE_SETTINGS = frozenset({JUDGE_ENDPOINT_HOST_SETTING, TRAJECTORY_SOURCES_SETTING, + TRAJECTORY_FORMATS_READ_SETTING, OVERRIDDEN_SETTING}) +# Settings that say where a verifier's judge runs, as a run's sandbox overrides do, not what it grades with. +JUDGE_SANDBOX_TYPE_SETTING = "judge_sandbox_type" +PLACEMENT_SETTINGS = frozenset({JUDGE_SANDBOX_TYPE_SETTING}) DEFAULT_MIN_PASSING_SCORE = 1.0 OUTPUT_INLINE_BYTES = 16 * 1024 SETTING_INLINE_BYTES = 1024 diff --git a/tst/unit/cli/task_diff_test.py b/tst/unit/cli/task_diff_test.py index 17531ee6e..2ae752933 100644 --- a/tst/unit/cli/task_diff_test.py +++ b/tst/unit/cli/task_diff_test.py @@ -172,8 +172,9 @@ def run(**kwargs): resumed = _diff(first) assert differs.exit_code == 1, differs.output - assert "hard override step_params score:" in differs.output + assert "hard override step_params score threshold: - -> 0.9" in differs.output assert "verifier settings score threshold: 0.5 -> 0.9 (regrade)" in differs.output assert resumed.exit_code == 0 and f"attempt 0 of {first} -> attempt 1 of {first}" in resumed.output assert 'never steps it ran: ["reads", "score"] -> ["score"]' in resumed.output - assert "not compared: the 7 entities only one of them read: attempt 0" in resumed.output + assert "not compared: the 7 entities only one of them read, as they didn't both run and complete" in resumed.output + assert "0 hard, 0 soft, 1 never: the same thing ran, in what both recorded" in resumed.output diff --git a/tst/unit/task/drift_test.py b/tst/unit/task/drift_test.py index f8da85637..00dc65e74 100644 --- a/tst/unit/task/drift_test.py +++ b/tst/unit/task/drift_test.py @@ -28,7 +28,8 @@ def _records(instance_id="first", epoch=0) -> Records: """An attempt whose every field is set, the base each case changes one thing of.""" - runtime = RunRuntime(attempt_epoch=epoch, packages={"agentenv-framework": "1.0", "agentenv-framework-protocol": "1.0"}, + runtime = RunRuntime(attempt_epoch=epoch, + packages={"agentenv-framework": "1.0", "agentenv-framework-protocol": "1.0"}, python="3.12.4", plugins={"acme-steps": InstalledPlugin("1.2.0", "index")}, config_selected_by="discovered", types={"task_steps": {"grade": "acme-steps"}}, stage=Stage.FINISHED) @@ -36,18 +37,21 @@ def _records(instance_id="first", epoch=0) -> Records: steps_run=["deploy", "score"], trajectory_formats=["atif/1"], pins={"env": {"office": 1}}, roles={"solver": RoleModel("m", "run", "models.example"), "judge": RoleModel("j", "config_role", "models.example")}, - overrides={"judge_model": "j", "agent_sandbox": "local", + overrides={"judge_model": "j", "judge_samples": 1, "agent_sandbox": "local", "step_params": {"score": {"threshold": 0.5}}}, result_rules_version=1) - verifiers = {"score": VerifierRecord("grade", "acme-steps", "1.2.0", {"threshold": 0.5, "overridden": []}, + verifiers = {"score": VerifierRecord("grade", "acme-steps", "1.2.0", + {"threshold": 0.5, "overridden": [], "judge_sandbox_type": "local"}, {"threshold": 0.5, "model": "j", "overridden": [], - "judge_endpoint_host": "models.example", - "trajectory_sources": [{"turn": 1, "format": "atif/1", "adapter_version": "1"}]})} + "judge_sandbox_type": "local", "judge_endpoint_host": "models.example", + "trajectory_sources": [ + {"turn": 1, "format": "atif/1", "adapter_version": "1"}]})} reads = [ReadRecord("env", "office", 1, "multi", latest=True), ReadRecord("artifact", "office-image", 3, "docker_image", image_identity="source:sha256:x"), ReadRecord("agent", "solver", 2, "a2a_agent", latest=True), - ReadRecord("artifact", "solver-image", 1, "docker_image", image_identity="registry:sha256:h1")] - return Records(instance_id, runtime, RunLock(epoch, intent, verifiers, reads, stage=Stage.FINISHED)) + ReadRecord("artifact", "solver-image", 1, "docker_image", image_identity="registry:sha256:h1"), + ReadRecord("artifact", "macos-15", 1, "computer")] + return Records(instance_id, runtime, RunLock(epoch, intent, verifiers, reads, completed=True, stage=Stage.FINISHED)) def _changed(change: Callable[[Records], None]) -> Records: @@ -60,6 +64,12 @@ def _read(records: Records, entity_id: str, **fields) -> None: records.lock.reads[:] = [replace(r, **fields) if r.id == entity_id else r for r in records.lock.reads] +def _unfinished(records: Records) -> None: + """As a killed attempt leaves its records: started, its reads not recorded.""" + records.lock.reads, records.lock.completed = None, None + records.lock.stage = records.runtime.stage = Stage.STARTED + + def _threshold(records: Records, value: float) -> None: """A starting setting changed as a run changes it: its grade records it too, which is still one difference.""" verifier = records.lock.verifiers["score"] @@ -97,6 +107,8 @@ def change(records): Case("steps as run", _set("lock.intent.steps_hash", "sha256:t"), (), HARD), Case("steps it ran", _set("lock.intent.steps_run", ["score"]), (), NEVER), Case("trajectory formats prescribed", _set("lock.intent.trajectory_formats", []), (), HARD), + Case("pins", lambda r: (_unfinished(r), r.lock.intent.pins["env"].update(office=2)), ("env", "office"), HARD), + Case("completed its steps", _set("lock.completed", False), (), NEVER), Case("entity version", lambda r: _read(r, "office", version=2), ("env", "office"), HARD), Case("entity type", lambda r: _read(r, "office", type="mcp_server"), ("env", "office"), HARD), Case("image identity", lambda r: _read(r, "solver-image", image_identity="registry:sha256:h2"), @@ -109,15 +121,19 @@ def change(records): lambda r: r.lock.intent.roles.update(judge=RoleModel("j", "config_role", "other.example")), ("judge",), SOFT), Case("role model's source", lambda r: r.lock.intent.roles.update(judge=RoleModel("j", "run", "models.example")), ("judge",), NEVER), - Case("override", _set("lock.intent.overrides.judge_model", "k"), ("judge_model",), HARD), + Case("override", _set("lock.intent.overrides.judge_samples", 3), ("judge_samples",), HARD), Case("result rules", _set("lock.intent.result_rules_version", 2), (), HARD, regrade=True), Case("verifier", lambda r: r.lock.verifiers.update(score=replace(r.lock.verifiers["score"], type="rubric")), ("score",), HARD), Case("verifier settings", lambda r: _threshold(r, 0.9), ("score", "threshold"), HARD, regrade=True), - Case("verifier settings set while grading", + Case("verifier settings as graded", lambda r: r.lock.verifiers["score"].graded_settings.update(model="k"), ("score", "model"), HARD, regrade=True), + Case("where a verifier's judge ran", lambda r: [settings.update(judge_sandbox_type="modal") for settings in ( + r.lock.verifiers["score"].settings, r.lock.verifiers["score"].graded_settings)], + ("score", "judge_sandbox_type"), SOFT), Case("trajectory formats a judge read", - lambda r: r.lock.verifiers["score"].graded_settings.update(trajectory_sources=[{"turn": 1, "format": "native"}]), + lambda r: r.lock.verifiers["score"].graded_settings.update( + trajectory_sources=[{"turn": 1, "format": "native"}]), ("score",), SOFT), Case("judge endpoint host", lambda r: r.lock.verifiers["score"].graded_settings.update(judge_endpoint_host="fallback.example"), @@ -128,7 +144,8 @@ def change(records): distribution="acme-grades")), ("score",), SOFT), Case("verifier package version", - lambda r: r.lock.verifiers.update(score=replace(r.lock.verifiers["score"], version="1.3.0")), ("score",), SOFT), + lambda r: r.lock.verifiers.update(score=replace(r.lock.verifiers["score"], version="1.3.0")), + ("score",), SOFT), Case("core package", _set("runtime.packages.agentenv-framework", "1.1"), ("agentenv-framework",), SOFT), Case("python", _set("runtime.python", "3.13.1"), (), SOFT), Case("plugin", lambda r: r.runtime.plugins.update({"acme-steps": InstalledPlugin("1.3.0", "index")}), @@ -208,8 +225,9 @@ def change(records): comparison = compare(_records(), _changed(change)) assert [(d.row, d.drift) for d in comparison.differences] == [("steps it ran", NEVER)] - assert comparison.not_compared == ["the 3 entities only one of them read: attempt 0 of first ran 2 steps and " - "attempt 0 of second ran 1 step, so they ran different steps"] + assert comparison.not_compared == ["the 4 entities only one of them read, as they didn't both run and complete the " + "same steps: attempt 0 of first ran 2 steps and completed them, and attempt 0 " + "of second ran 1 step and completed them"] assert comparison.like_for_like @@ -221,8 +239,9 @@ def change(records): comparison = compare(_records(), _changed(change)) assert [d.row for d in comparison.differences] == ["steps it ran"] - assert comparison.not_compared == ["the 1 entity only one of them read: attempt 0 of first ran 2 steps and attempt " - "0 of second doesn't record which steps it ran, so they ran different steps"] + assert comparison.not_compared == ["the 1 entity only one of them read, as they didn't both run and complete the " + "same steps: attempt 0 of first ran 2 steps and completed them, and attempt 0 " + "of second doesn't record which steps it ran"] def test_a_judge_that_read_more_turns_of_the_same_formats_read_the_same_thing(): @@ -300,14 +319,61 @@ def change(records): assert (difference.row, difference.drift) == ("trajectory formats prescribed", HARD) -def test_where_a_run_ran_is_soft_and_each_steps_params_are_their_own_override(): +def test_a_failed_run_and_a_passing_one_differ_only_in_whether_they_completed_their_steps(): + """The failed one stopped before it read the agent or used an env, which isn't a difference in what they were asked + to run.""" + def change(records): + records.lock.completed = False + records.lock.reads[:] = [r for r in records.lock.reads if r.id not in ("solver", "solver-image")] + records.runtime.types.pop("envs", None) + first = _records() + first.runtime.types["envs"] = {"multi": "agentenv-framework"} + + comparison = compare(first, _changed(change)) + + assert [(d.row, d.drift) for d in comparison.differences] == [("completed its steps", NEVER)] + assert comparison.not_compared == ["the 2 entities only one of them read, as they didn't both run and complete the " + "same steps: attempt 0 of first ran 2 steps and completed them, and attempt 0 " + "of second ran 2 steps and didn't complete them"] + assert comparison.like_for_like + + +def test_where_a_run_ran_is_soft_and_each_of_a_steps_params_is_its_own_override(): + def change(records): + records.lock.intent.overrides.update(agent_sandbox="modal", sandbox="modal", + step_params={"score": {"threshold": 0.9}}) + + comparison = compare(_records(), _changed(change)) + + assert [(d.key, d.drift) for d in comparison.differences] == [ + (("agent_sandbox",), SOFT), (("sandbox",), SOFT), (("step_params", "score", "threshold"), HARD)] + + +def test_overrides_of_a_roles_model_or_endpoint_are_the_role_rows_and_a_secrets_reference_is_never_drift(): def change(records): - records.lock.intent.overrides.update(agent_sandbox="modal", step_params={"score": {"threshold": 0.9}}) + records.lock.intent.overrides.update( + judge_model="k", litellm_base_url="other.example", litellm_api_key="env:ANOTHER_KEY", + step_params={"score": {"threshold": 0.5, "litellm_base_url": "127.0.0.1:41234", + "litellm_api_key": "env:EPISODE_KEY"}}) comparison = compare(_records(), _changed(change)) - assert [(d.key, d.drift) for d in comparison.differences] == [(("agent_sandbox",), SOFT), - (("step_params", "score"), HARD)] + assert [(d.key, d.drift) for d in comparison.differences] == [ + (("litellm_api_key",), NEVER), (("step_params", "score", "litellm_api_key"), NEVER), + (("step_params", "score", "litellm_base_url"), SOFT)] + + +def test_a_setting_two_judges_started_with_otherwise_is_one_difference_however_they_graded(): + """One started with no effort and its judge resolved one; the other was given that effort from the start.""" + def change(records): + verifier = records.lock.verifiers["score"] + verifier.settings["effort"] = verifier.graded_settings["effort"] = "high" + first = _records() + first.lock.verifiers["score"].graded_settings["effort"] = "high" + + [difference] = compare(first, _changed(change)).differences + assert (difference.row, difference.key, difference.old, difference.new) == ( + "verifier settings", ("score", "effort"), None, "high") def test_a_verifier_added_is_one_difference_however_many_fields_it_has(): @@ -347,13 +413,12 @@ def change(records): lambda r: _read(r, "solver-image", image_identity="registry:sha256:h2"), "image identity"), ("an unpinned effort: one run pins it", lambda r: r.lock.intent.overrides.update(agent_effort="high"), "override"), - ("an unrecorded macOS build: the computer's image differs", - lambda r: r.lock.reads.append(ReadRecord("artifact", "macos-15", 1, "computer", image_identity="registry:sha256:m")), - "entity version"), + ("an unrecorded macOS build: the computer, built from another base image, is a new version of its artifact", + lambda r: _read(r, "macos-15", version=2), "entity version"), ], ids=["harness version", "effort", "macos build"]) def test_the_run_manifest_gaps_each_show_up_as_a_hard_difference(gap, change, row): - comparison = compare(_records(), _changed(change)) - assert row in {d.row for d in comparison.differences} and not comparison.like_for_like, gap + [difference] = compare(_records(), _changed(change)).differences + assert (difference.row, difference.drift) == (row, HARD), gap def test_an_instances_records_by_attempt_and_its_latest_by_default(): diff --git a/tst/unit/task/run_lock_test.py b/tst/unit/task/run_lock_test.py index 5ab6eb0ee..6229d3c08 100644 --- a/tst/unit/task/run_lock_test.py +++ b/tst/unit/task/run_lock_test.py @@ -153,7 +153,7 @@ def test_a_run_records_what_ran_it_and_what_it_was_asked_and_read(): assert runtime.types["task_steps"] == {"run_lock_test_reads": None, "run_lock_test_score": None} assert runtime.types["envs"] == {"multi": "agentenv-framework", "mcp_server": "agentenv-framework"} assert runtime.types["artifacts"] == {"docker_image": "agentenv-framework"} - assert lock.finished + assert lock.finished and lock.completed is True intent = lock.intent assert (intent.task_id, intent.task_version, intent.content_hash, intent.result_rules_version) == ( "t", 1, content_hash(task), RESULT_RULES_VERSION) @@ -172,8 +172,9 @@ def test_a_run_records_what_ran_it_and_what_it_was_asked_and_read(): "data": None} -@pytest.mark.parametrize("overrides, formats", [({}, []), ({"trajectory_formats": ["atif/1"]}, ["atif/1"])], - ids=["the config's", "the run's"]) +@pytest.mark.parametrize("overrides, formats", [({}, []), ({"trajectory_formats": ["atif/1"]}, ["atif/1"]), + ({"trajectory_formats": "atif/1"}, None)], + ids=["the config's", "the run's", "named wrongly, the rest recorded"]) def test_a_run_records_the_trajectory_formats_it_prescribes(overrides, formats): _, context = _run(_task(), overrides) assert find_task_instance(context.instance_id).run_locks[0].intent.trajectory_formats == formats @@ -250,7 +251,7 @@ def test_a_run_that_fails_records_what_it_read(): assert record_writer.flush_run_records(10) [lock] = find_task_instance(context.instance_id).run_locks - assert lock.finished and {r.id for r in lock.reads} >= {"office", "solver", "data"} + assert lock.finished and lock.completed is False and {r.id for r in lock.reads} >= {"office", "solver", "data"} def test_a_cancelled_run_records_what_it_read_before_the_cancel(): @@ -393,14 +394,15 @@ def test_every_field_of_the_records_survives_a_round_trip(): plugins={"acme-steps": plugin}, config_selected_by="environment", types={"task_steps": {"grade": "acme-steps"}}, stage=Stage.FINISHED, record_version=7) intent = RunIntent(task_id="t", task_version=3, content_hash="sha256:c", steps_hash="sha256:s", - steps_run=["reads", "score"], trajectory_formats=["atif/1"], pins={"env": {"office": 2}}, roles={"judge": RoleModel("j", "run", "models.example")}, + steps_run=["reads", "score"], trajectory_formats=["atif/1"], pins={"env": {"office": 2}}, + roles={"judge": RoleModel("j", "run", "models.example")}, overrides={"judge_model": "j"}, result_rules_version=4) verifier = VerifierRecord(type="score", distribution="acme-steps", version="1.2.0", settings={"a": 1}, graded_settings={"a": 2}) read = ReadRecord(kind="env", id="office", version=2, type="multi", latest=True, alias=True, image_identity="source:sha256:x") - lock = RunLock(attempt_epoch=2, intent=intent, verifiers={"score": verifier}, reads=[read], stage=Stage.FINISHED, - record_version=7) + lock = RunLock(attempt_epoch=2, intent=intent, verifiers={"score": verifier}, reads=[read], completed=True, + stage=Stage.FINISHED, record_version=7) for sample in (plugin, runtime, intent, verifier, read, lock): for f in dataclasses.fields(sample): default = f.default_factory() if f.default_factory is not dataclasses.MISSING else f.default From ae1ca52d9d2642cf9ef3054db33d342e99d0b823 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 1 Dec 2026 11:31:05 -0800 Subject: [PATCH 08/10] fix(task): an attempt records the steps it actually ran, and a model override or a failed grade compares without missing or false drift - `Task.run` notes each step it dispatches and whether it reached its end, a verdict that fails the step included (`step_dispatched`, `step_ended`). `steps_run` (now on the lock beside `completed`) is the steps it ran, in the task's order, a retry's included, so a resume whose retry reruns an earlier step says so; `completed` is that each reached its end, so a verifier that graded "not passing" no longer makes its attempt incomplete. - Model overrides (`agent_model`, `user_model`, `judge_model`) are compared again, hard: a role's model is resolved where no step names one, so a run given the config's model where the task's step names another read as alike. Only endpoint overrides are left to the role rows. - A failed grade's settings aren't the attempt's graded settings: its calls hadn't filled in what they fill in. - What a row can't compare it says why: each row declares its own reason, and the comparison gathers them, so a type only one attempt used is now said, and a trajectory formats override that isn't a list is named as such. - `RUN_ENDPOINT_OVERRIDES` is exported from `config/model.py` and shared; the step-params check names `step_params`; AGENTS.md keeps the comparator's invariants and points at `ROWS`. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 42 ++++---- src/agent_env/config/model.py | 5 +- src/agent_env/task/drift.py | 167 ++++++++++++++++++------------ src/agent_env/task/run_lock.py | 104 ++++++++++++------- src/agent_env/task/run_records.py | 20 ++-- src/agent_env/task/task.py | 8 +- tst/unit/cli/task_diff_test.py | 2 +- tst/unit/task/drift_test.py | 74 +++++++++---- tst/unit/task/run_lock_test.py | 78 ++++++++++++-- 9 files changed, 329 insertions(+), 171 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 67f3ae0ca..fd34c0154 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -490,28 +490,26 @@ orchestrators call it the same way. What callers rely on: `task/run_records.py` declares: `RunRuntime` (the core's and protocol's versions as `packages`, the Python version, each installed plugin's version and install kind, how the config file was found, and the distribution of each type the run used, from `agent_env.plugins`' `distribution_of`, its sandbox providers those of the deployments its context - records; never a path) and `RunLock` (its `intent`, the task's content hash, a hash of its steps as run and the ids of - those it was asked to run (`steps_run`), the trajectory formats it prescribes (`trajectory_formats`), its pins, each - role's model and endpoint host as this process resolves them, the overrides without secrets and the result rules - version, computed as the eval plan computes its own, `eval/intent.py`; each verifier's settings and version at the - start and as graded, by the grades whose `attempt_epoch` is this attempt's or a retry's within it; every entity - version the run read, each image with its `image_identity`, and whether it completed the steps it ran, none failing - and no cancel, `completed`). Each is written `started` and then `finished`, however the run ends, by writer threads of - their own (`task/record_writer.py`, never awaited; `flush_run_records` waits for them, and an exit waits 10 s at - most), under a counter of their own (`run_records_rev`) that the instance's other writes don't check, nor these theirs - (on DynamoDB, which conditions a write on the whole item, one still retries the other); the store keeps the finished - record whichever lands last, and a resume adds its own. An instance leaves out, with a warning, a record this version - can't read. A worker that runs a task's steps itself enters `run_recorded` around them, once per attempt in the - process that runs them all, as it sets `run_pins`. `task/drift.py` classes every difference between two attempts' - records by the lock table (`compare`, its rows `ROWS`, every record field in one or in `NOT_COMPARED`): `hard` when - they ran different things, `regrade` too for the result rules or a verifier's settings, `soft` for code meant to - change under a run, as an upgraded package, and `never`, as how a version was asked for; an image's identity, not its - artifact's version, says whether it changed, and an entity only one attempt read is a difference only when both ran - and completed the same steps; an override is compared by what it changes (a role's model and endpoint by the role - rows, a secret's reference never, where sandboxes run soft); what a verifier's settings record of how its grading went - (the formats its judge read, the host its calls reached, which settings overrides changed, where its judge ran; - `GRADING_EVIDENCE_SETTINGS` and `PLACEMENT_SETTINGS` in the verifier base) is compared apart from its settings. - `agent-env task diff` lists the differences, exiting 1 on hard drift. + records; never a path) and `RunLock` (its `intent`, the task's content hash, a hash of its steps as run, the + trajectory formats it prescribes, its pins, each role's model and endpoint host as this process resolves them, the + overrides without secrets and the result rules version, computed as the eval plan computes its own, `eval/intent.py`; + each verifier's settings and version at the start and as graded, by the grades, not failed, whose `attempt_epoch` is + this attempt's or a retry's within it; every entity version the run read, each image with its `image_identity`; and + the steps it ran, `steps_run`, and whether each reached its end, a verdict included, `completed`, from what `Task.run` + notes as it dispatches each step, `step_dispatched` and `step_ended`). Each is written `started` and then `finished`, + however the run ends, by writer threads of their own (`task/record_writer.py`, never awaited; `flush_run_records` + waits for them, and an exit waits 10 s at most), under a counter of their own (`run_records_rev`) that the instance's + other writes don't check, nor these theirs (on DynamoDB, which conditions a write on the whole item, one still retries + the other); the store keeps the finished record whichever lands last, and a resume adds its own. An instance leaves + out, with a warning, a record this version can't read. A worker that runs a task's steps itself enters `run_recorded` + around them, once per attempt in the process that runs them all, and notes each step as `Task.run` does, as it sets + `run_pins`. +- `task/drift.py` (`compare`) classes every difference between two attempts' records by the lock table, its rows `ROWS`: + `hard` when they ran different things, `regrade` too for the result rules or a verifier's settings; `soft` for what's + meant to change under a run, as an upgraded package or where its sandboxes ran; `never`, recorded only. Every record + field is in a row or in `NOT_COMPARED`, and what a row can't compare it says why (`Comparison.not_compared`). + `agent-env task diff` lists them, exiting 0 when the two ran the same thing, 1 on hard drift and 2 when they can't be + compared. - A runner that must hear from a long step puts a zero-argument callable at `context.metadata[HEARTBEAT_KEY]` (`task_step/context.py`); a step that blocks for long calls `context.heartbeat()`, a no-op without one. The key is in `_REDACTED_KEYS`, so it is never persisted. diff --git a/src/agent_env/config/model.py b/src/agent_env/config/model.py index 030e8aef6..d3574815a 100644 --- a/src/agent_env/config/model.py +++ b/src/agent_env/config/model.py @@ -357,7 +357,8 @@ def endpoint_host(url: object) -> Optional[str]: return None -_ENDPOINT_KEYS = frozenset(key for keys in RUN_ENDPOINT_KEYS.values() for key in keys) +# Every override that names an endpoint for some role's calls. +RUN_ENDPOINT_OVERRIDES = frozenset(key for keys in RUN_ENDPOINT_KEYS.values() for key in keys) def without_credentials(value: Any, key: Optional[str] = None) -> Any: @@ -370,7 +371,7 @@ def without_credentials(value: Any, key: Optional[str] = None) -> Any: return [without_credentials(v) for v in value] if not isinstance(value, str): return value - if key in _ENDPOINT_KEYS and (host := endpoint_host(value)): + if key in RUN_ENDPOINT_OVERRIDES and (host := endpoint_host(value)): return host try: parts = urlsplit(value) diff --git a/src/agent_env/task/drift.py b/src/agent_env/task/drift.py index d5ff5ec3e..585283e9f 100644 --- a/src/agent_env/task/drift.py +++ b/src/agent_env/task/drift.py @@ -8,13 +8,16 @@ An image's identity, not its artifact's version, says whether it changed: an image read at another version with the same identity is the same image, so its version's change is ``never``. A row that reports a thing added or removed, a verifier, a role, a plugin or an entity read, is the only one that does; the rows of that thing's other fields compare -it only where both attempts have it. An entity only one attempt read is a difference only when both ran the same steps -(``RunIntent.steps_run``) and completed them (``RunLock.completed``): a resume runs only the rest, which read less, and -a run that failed stopped short of what the other read, so what one didn't read isn't compared. +it only where both attempts have it. An entity only one attempt read, or a type only one used, is a difference only when +both ran the same steps (``RunLock.steps_run``) and completed them (``RunLock.completed``): a resume runs only the rest, +which read less, and a run that failed stopped short of what the other read. A step that reads only on some data, as a +user simulator's judge that skips with no graded turns doesn't read its agent, is the limit of that rule. -An override is compared by what it changes: the role rows compare a role's model and endpoint as they resolve, so -the overrides naming them aren't listed again; one naming a secret, as an API key's reference, is never drift; one of -where a run's sandboxes run is soft, as is an endpoint a step's ``step_params`` name. +An override is compared by what it changes: one naming a secret, as an API key's reference, is never drift; one of where +a run's sandboxes run, and an endpoint, are soft, as a role's endpoint host is, which the role rows compare as it +resolves; any other is hard, a role's model among them, which the role rows can't tell from a step's own. + +What a row can't compare it says why in the comparison's ``not_compared``. A verifier's settings record how its grading went beside what it graded with: which trajectory formats its judge read, the host its calls reached and which settings a run's overrides changed, and where its judge ran. Those aren't settings: @@ -30,7 +33,7 @@ from functools import cached_property from typing import Any, Callable, Mapping, Optional -from agent_env.config.model import RUN_ENDPOINT_KEYS, RUN_MODEL_KEYS +from agent_env.config.model import RUN_ENDPOINT_OVERRIDES from agent_env.plugins import TASK_STEPS from agent_env.task.run_records import RunLock, RunRuntime, Stage, registry_name from agent_env.task.store import TaskInstance @@ -51,9 +54,6 @@ _STEP_PARAMS = "step_params" # The override of the trajectory formats a run prescribes, which the intent's own row compares as resolved. _TRAJECTORY_FORMATS = "trajectory_formats" -_ENDPOINT_OVERRIDES = frozenset(key for keys in RUN_ENDPOINT_KEYS.values() for key in keys) -# A run's overrides of each role's model and endpoint, which the role rows compare as they resolve. -_ROLE_OVERRIDES = frozenset(RUN_MODEL_KEYS.values()) | _ENDPOINT_OVERRIDES # What a verifier's settings record that isn't what it graded with, each compared by a row of its own. _NOT_GRADING_SETTINGS = GRADING_EVIDENCE_SETTINGS | PLACEMENT_SETTINGS # The registry of the types an attempt records from its start, its steps'; the others it records once it finishes. @@ -142,12 +142,16 @@ def formats_read(self) -> dict[str, tuple[str, ...]]: @cached_property def prescribed_formats(self) -> Optional[tuple[str, ...]]: """The trajectory formats the attempt prescribed, or, for one recorded before they were, its own override of - them; None when it records neither.""" + them; None when it records neither, or names them by an override that isn't a list of them.""" intent = self.lock.intent formats = intent.trajectory_formats if intent.trajectory_formats is not None else intent.overrides.get( _TRAJECTORY_FORMATS) return tuple(formats) if isinstance(formats, list) else None + @property + def where(self) -> str: + return f"attempt {self.attempt_epoch} of {self.instance_id}" + @cached_property def entities(self) -> frozenset[Key]: """Each entity the attempt read, by kind and id; none when its reads aren't recorded.""" @@ -177,8 +181,8 @@ def to_dict(self) -> dict: @dataclass(frozen=True) class Comparison: - """Every difference between attempts ``a`` and ``b``, in lock-table order, and what couldn't be compared, as what - an attempt that didn't finish read.""" + """Every difference between attempts ``a`` and ``b``, in lock-table order, and what couldn't be compared and why, + as what an attempt that didn't finish read.""" a: Records b: Records @@ -208,8 +212,8 @@ def to_dict(self) -> dict: class _Row: """A lock-table row: the record ``fields`` it covers, as ``Class.field``, none for a row of part of a field another row covers, as how a verifier's grading went; its class; its values in an attempt's records by key, None when the - attempt didn't record them; and, for a row whose class or reach depends on the key, ``classify`` and - ``compared``.""" + attempt didn't record them; and, for a row whose class or reach depends on the key, ``classify``, ``compared``, for + a key it leaves to another row, and ``unknown``, why a key can't be compared, which the comparison says.""" name: str fields: tuple[str, ...] @@ -218,17 +222,22 @@ class _Row: regrade: bool = False classify: Optional[Callable[[Key, Records, Records], Drift]] = None compared: Optional[Callable[[Key, Records, Records], bool]] = None + unknown: Optional[Callable[[Key, Records, Records], Optional[str]]] = None def compare(a: Records, b: Records) -> Comparison: - """Every difference between the records of attempts ``a`` and ``b``, each classed by its lock-table row.""" + """Every difference between the records of attempts ``a`` and ``b``, each classed by its lock-table row, and each + key a row couldn't compare, by why.""" differences: list[Difference] = [] - unread = [records for records in (a, b) if records.lock.reads is None] + unknown: dict[tuple[str, str], list[Key]] = {} for row in ROWS: old, new = row.values(a), row.values(b) if old is None or new is None: continue for key in sorted(old.keys() | new.keys()): + if row.unknown is not None and (why := row.unknown(key, a, b)): + unknown.setdefault((row.name, why), []).append(key) + continue if row.compared is not None and not row.compared(key, a, b): continue before, after = old.get(key), new.get(key) @@ -236,46 +245,53 @@ def compare(a: Records, b: Records) -> Comparison: continue drift = row.classify(key, a, b) if row.classify is not None else row.drift differences.append(Difference(row.name, key, before, after, drift, row.regrade and drift is Drift.HARD)) - not_compared = [f"attempt {r.attempt_epoch} of {r.instance_id} didn't finish, so what it read and the types it " - "used beyond its steps' aren't recorded" for r in unread] - if not unread and not _same_steps(a, b) and (only := _read(a) ^ _read(b)): - not_compared.append(f"the {len(only)} entit{'y' if len(only) == 1 else 'ies'} only one of them read, as they " - f"didn't both run and complete the same steps: {_ran(a)}, and {_ran(b)}") - not_compared += [f"the trajectory formats attempt {r.attempt_epoch} of {r.instance_id} prescribed: it records " - "neither them nor an override of them" for r in (a, b) if r.prescribed_formats is None] - graded_both = _graded(a).keys() & _graded(b).keys() - not_compared += [f"the trajectory formats verifier {step} read in attempt {r.attempt_epoch} of {r.instance_id}: " - "its record keeps only a hash of them" for r in (a, b) - for step in sorted(graded_both - r.formats_read.keys())] + not_compared = [f"{r.where} didn't finish, so what it read and the types it used beyond its steps' aren't recorded" + for r in (a, b) if r.lock.reads is None] + not_compared += [f"{row}{_listed(keys)}: not compared, as {why}" for (row, why), keys in unknown.items()] return Comparison(a, b, differences, not_compared) -def _read(records: Records) -> frozenset[Key]: - return records.entities +def _listed(keys: list[Key]) -> str: + shown = [" ".join(key) for key in keys if key] + if not shown: + return "" + more = f" and {len(shown) - 3} more" if len(shown) > 3 else "" + return f" of {', '.join(shown[:3])}{more}" def _same_steps(a: Records, b: Records) -> bool: """Whether both attempts ran the same steps, and each completed them.""" - return (a.lock.intent.steps_run is not None and a.lock.intent.steps_run == b.lock.intent.steps_run + return (a.lock.steps_run is not None and a.lock.steps_run == b.lock.steps_run and a.lock.completed is True and b.lock.completed is True) -def _read_by_both(key: Key, a: Records, b: Records) -> bool: - return key in _read(a) and key in _read(b) +def _ran(records: Records) -> str: + steps = records.lock.steps_run + if steps is None: + return f"{records.where} doesn't record which steps it ran" + ran = f"{records.where} ran {len(steps)} step{'s' * (len(steps) != 1)}" + return f"{ran} and completed them" if records.lock.completed else f"{ran} and didn't complete them" -def _read_by_both_or_same_steps(key: Key, a: Records, b: Records) -> bool: - return _same_steps(a, b) or _read_by_both(key, a, b) +def _one_sided(read: str) -> Callable[[Key, Records, Records], Optional[str]]: + """Why a key only one attempt has, as an entity it read, isn't compared: they didn't both run and complete the same + steps, so one may not have reached what read it.""" + def why(key: Key, a: Records, b: Records) -> Optional[str]: + if (key in _has(read, a)) == (key in _has(read, b)) or _same_steps(a, b): + return None + return (f"only one of them {read} it, and they didn't both run and complete the same steps: {_ran(a)}, and " + f"{_ran(b)}") + return why -def _ran(records: Records) -> str: - steps, completed = records.lock.intent.steps_run, records.lock.completed - where = f"attempt {records.attempt_epoch} of {records.instance_id}" - if steps is None: - return f"{where} doesn't record which steps it ran" - ran = f"{where} ran {len(steps)} step{'s' * (len(steps) != 1)}" - return (f"{ran} and completed them" if completed is True else f"{ran} and didn't complete them" - if completed is False else f"{ran} and doesn't record whether it completed them") +def _has(read: str, records: Records) -> Any: + return records.entities if read == "read" else _types(records) + + +def _read_by_both(key: Key, a: Records, b: Records) -> bool: + """Another row of what an attempt read than its version compares an entity both read; the version's row reports + one only one read.""" + return key in a.entities and key in b.entities def _one(value: Any) -> dict[Key, Any]: @@ -291,24 +307,30 @@ def _version_drift(key: Key, a: Records, b: Records) -> Drift: return Drift.NEVER if identities[0] and identities[0] == identities[1] else Drift.HARD +def _types(records: Records) -> dict[Key, Any]: + return {(group, name): found for group, types in records.runtime.types.items() for name, found in types.items()} + + def _types_recorded(key: Key, a: Records, b: Records) -> bool: - """A step type is recorded from an attempt's start, any other type once it finishes, from what it read: so one - only one attempt used is a difference only where an entity only one read is.""" - if key[0] == _STEP_TYPES: - return True - return a.finished and b.finished and (_same_steps(a, b) or (key in _types(a) and key in _types(b))) + """A step type is recorded from an attempt's start, any other type once it finishes, which an attempt that didn't + finish says it hasn't.""" + return key[0] == _STEP_TYPES or (a.finished and b.finished) -def _types(records: Records) -> dict[Key, Any]: - return {(group, name): found for group, types in records.runtime.types.items() for name, found in types.items()} +def _types_one_sided(key: Key, a: Records, b: Records) -> Optional[str]: + return None if key[0] == _STEP_TYPES or not (a.finished and b.finished) else _one_sided("used")(key, a, b) + + +def _both_recorded(of: Callable[[RunLock], Any]) -> Callable[[Key, Records, Records], bool]: + return lambda key, a, b: of(a.lock) is not None and of(b.lock) is not None def _overrides(records: Records) -> dict[Key, Any]: """The run's overrides by name, each of a step's ``step_params`` by the step's id and its name, but those another - row compares: each role's model and endpoint, and the trajectory formats.""" + row compares as they resolve: an endpoint, by the role rows, and the trajectory formats.""" values: dict[Key, Any] = {} for name, value in records.lock.intent.overrides.items(): - if name == _TRAJECTORY_FORMATS or name in _ROLE_OVERRIDES: + if name == _TRAJECTORY_FORMATS or name in RUN_ENDPOINT_OVERRIDES: continue if name == _STEP_PARAMS and isinstance(value, Mapping): for step, params in value.items(): @@ -322,12 +344,12 @@ def _overrides(records: Records) -> dict[Key, Any]: def _override_drift(key: Key, a: Records, b: Records) -> Drift: - """A secret's reference is never drift, where a run's sandboxes run and the endpoint a step names are soft, and + """A secret's reference is never drift; where a run's sandboxes run, and an endpoint a step names, are soft; and anything else an override changes is hard.""" - name = key[-1] + in_step, name = key[0] == _STEP_PARAMS and len(key) == 3, key[-1] if redacted_key(name): return Drift.NEVER - if (len(key) == 1 and name in SANDBOX_OVERRIDE_KEYS) or (len(key) == 3 and name in _ENDPOINT_OVERRIDES): + if (name in RUN_ENDPOINT_OVERRIDES) if in_step else (name in SANDBOX_OVERRIDE_KEYS): return Drift.SOFT return Drift.HARD @@ -387,12 +409,20 @@ def _either_unread(key: Key, a: Records, b: Records) -> bool: return a.lock.reads is None or b.lock.reads is None -def _formats_known(key: Key, a: Records, b: Records) -> bool: - return key[0] in a.formats_read and key[0] in b.formats_read +def _prescription_unknown(key: Key, a: Records, b: Records) -> Optional[str]: + whys = [f"{r.where} " + ("names them by an override that isn't a list of formats" + if r.lock.intent.overrides.get(_TRAJECTORY_FORMATS) is not None + else "records neither them nor an override of them") + for r in (a, b) if r.prescribed_formats is None] + return "; ".join(whys) or None -def _prescriptions_known(key: Key, a: Records, b: Records) -> bool: - return a.prescribed_formats is not None and b.prescribed_formats is not None +def _formats_unknown(key: Key, a: Records, b: Records) -> Optional[str]: + step = key[0] + if step not in _graded(a) or step not in _graded(b): + return None + whys = [f"{r.where} keeps only a hash of them" for r in (a, b) if step not in r.formats_read] + return "; ".join(whys) or None ROWS: tuple[_Row, ...] = ( @@ -400,15 +430,16 @@ def _prescriptions_known(key: Key, a: Records, b: Records) -> bool: _Row("task version", ("RunIntent.task_version",), Drift.HARD, lambda r: _one(r.lock.intent.task_version)), _Row("task content", ("RunIntent.content_hash",), Drift.HARD, lambda r: _one(r.lock.intent.content_hash)), _Row("steps as run", ("RunIntent.steps_hash",), Drift.HARD, lambda r: _one(r.lock.intent.steps_hash)), - _Row("steps it ran", ("RunIntent.steps_run",), Drift.NEVER, - lambda r: _one(None if r.lock.intent.steps_run is None else tuple(r.lock.intent.steps_run))), + _Row("steps it ran", ("RunLock.steps_run",), Drift.NEVER, + lambda r: _one(None if r.lock.steps_run is None else tuple(r.lock.steps_run)), + compared=_both_recorded(lambda lock: lock.steps_run)), + _Row("completed its steps", ("RunLock.completed",), Drift.NEVER, lambda r: _one(r.lock.completed), + compared=_both_recorded(lambda lock: lock.completed)), _Row("trajectory formats prescribed", ("RunIntent.trajectory_formats",), Drift.HARD, - lambda r: _one(r.prescribed_formats), compared=_prescriptions_known), + lambda r: _one(r.prescribed_formats), unknown=_prescription_unknown), _Row("pins", ("RunIntent.pins",), Drift.HARD, _pins, compared=_either_unread), - _Row("completed its steps", ("RunLock.completed",), Drift.NEVER, lambda r: _one(r.lock.completed), - compared=lambda key, a, b: a.lock.completed is not None and b.lock.completed is not None), _Row("entity version", ("ReadRecord.kind", "ReadRecord.id", "ReadRecord.version"), Drift.HARD, - lambda r: _by_entity(r, "version"), classify=_version_drift, compared=_read_by_both_or_same_steps), + lambda r: _by_entity(r, "version"), classify=_version_drift, unknown=_one_sided("read")), _Row("entity type", ("ReadRecord.type",), Drift.HARD, lambda r: _by_entity(r, "type"), compared=_read_by_both), _Row("image identity", ("ReadRecord.image_identity",), Drift.HARD, lambda r: _by_entity(r, "image_identity"), compared=_read_by_both), @@ -434,7 +465,8 @@ def _prescriptions_known(key: Key, a: Records, b: Records) -> bool: compared=_started_alike), _Row("where a verifier's judge ran", (), Drift.SOFT, _placement, compared=_in_both(_verifiers)), _Row("trajectory formats a judge read", (), Drift.SOFT, - lambda r: {(step,): formats for step, formats in r.formats_read.items()}, compared=_formats_known), + lambda r: {(step,): formats for step, formats in r.formats_read.items()}, + compared=_in_both(lambda r: r.formats_read), unknown=_formats_unknown), _Row("judge endpoint host", (), Drift.SOFT, lambda r: {(step,): v.graded_settings.get(JUDGE_ENDPOINT_HOST_SETTING) for step, v in _graded(r).items()}, compared=_in_both(_graded)), @@ -453,7 +485,8 @@ def _prescriptions_known(key: Key, a: Records, b: Records) -> bool: _Row("plugin install", ("InstalledPlugin.origin",), Drift.SOFT, lambda r: {(name,): plugin.origin for name, plugin in r.runtime.plugins.items()}, compared=_in_both(_plugins)), - _Row("type's package", ("RunRuntime.types",), Drift.SOFT, _types, compared=_types_recorded), + _Row("type's package", ("RunRuntime.types",), Drift.SOFT, _types, compared=_types_recorded, + unknown=_types_one_sided), _Row("config found by", ("RunRuntime.config_selected_by",), Drift.NEVER, lambda r: _one(r.runtime.config_selected_by)), ) diff --git a/src/agent_env/task/run_lock.py b/src/agent_env/task/run_lock.py index 2040a6483..b7a951d54 100644 --- a/src/agent_env/task/run_lock.py +++ b/src/agent_env/task/run_lock.py @@ -28,6 +28,7 @@ import hashlib import logging import platform +from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, AsyncIterator, Iterable, Optional, Sequence from agent_env.config import get_config @@ -59,10 +60,11 @@ registry_name, ) from agent_env.task.store import record_run_records -from agent_env.task_step.context import StepContextError, TaskStepContext +from agent_env.task_step.context import StepContextError, TaskStepContext, VerifierNotPassingError from agent_env.task_step.task_step import TaskStep from agent_env.task_step.task_steps.prompt_agent import prescribed_formats -from agent_env.task_step.task_steps.verifiers.verifier import GRADES_KEY, VerifierTaskStep +from agent_env.task_step.task_steps.verifiers.judge_utils.judge_samples import JudgeDisagreementError +from agent_env.task_step.task_steps.verifiers.verifier import GRADES_KEY, VerifierStatus, VerifierTaskStep from agent_env.utils.canonical import canonical_json if TYPE_CHECKING: @@ -70,6 +72,35 @@ logger = logging.getLogger(__name__) +# What a verifier raises once it has graded, for a verdict that fails its step: such a step ran to its end. +VERDICTS = (VerifierNotPassingError, JudgeDisagreementError) + + +@dataclass +class StepsRan: + """The steps the attempt a ``run_recorded`` block records dispatched, and those whose latest dispatch reached its + end: it returned, or raised a verdict (``VERDICTS``).""" + + dispatched: set[str] = field(default_factory=set) + ended: set[str] = field(default_factory=set) + + +_STEPS_RAN: contextvars.ContextVar[Optional[StepsRan]] = contextvars.ContextVar("agentenv_steps_ran", default=None) + + +def step_dispatched(step_id: str) -> None: + """Note that the attempt the running ``run_recorded`` block records dispatched ``step_id``, again for a retry. A + worker that runs a task's steps itself calls this and ``step_ended`` around each, as ``Task.run`` does.""" + if (ran := _STEPS_RAN.get()) is not None: + ran.dispatched.add(step_id) + ran.ended.discard(step_id) + + +def step_ended(step_id: str, raised: Optional[BaseException] = None) -> None: + """Note how ``step_id``'s dispatch ended: it reached its end unless it ``raised`` other than a verdict.""" + if (ran := _STEPS_RAN.get()) is not None and (raised is None or isinstance(raised, VERDICTS)): + ran.ended.add(step_id) + _READ_KINDS = {"env": registry_name(ENVS), "artifact": registry_name(ARTIFACTS)} @@ -87,11 +118,9 @@ def started_runtime(attempt_epoch: int, steps: Sequence[TaskStep]) -> RunRuntime ) -def started_lock(task: "Task", steps: Sequence[TaskStep], context: TaskStepContext, attempt_epoch: int, - start_step: int = 0, end_step: Optional[int] = None) -> RunLock: +def started_lock(task: "Task", steps: Sequence[TaskStep], context: TaskStepContext, attempt_epoch: int) -> RunLock: """The lock of an attempt this process starts: its intent and its verifiers as they stand at the start. ``steps`` - are the task's steps, its seed applied, of which the attempt runs ``start_step`` to ``end_step``; ``task`` the task - as stored, whose content its hash names.""" + are the task's steps, its seed applied; ``task`` the task as stored, whose content its hash names.""" user_overrides = context.metadata.get("user_overrides") or {} overrides = run_overrides(user_overrides, agent_model=context.agent_model, agent_artifact_id=context.agent_artifact_id) @@ -102,7 +131,6 @@ def started_lock(task: "Task", steps: Sequence[TaskStep], context: TaskStepConte task_version=task.version, content_hash=content_hash(task), steps_hash=steps_hash(steps), - steps_run=[step.id for step in steps[start_step:end_step]], trajectory_formats=_prescribed(context), pins=checked_pins(user_overrides.get(PINS_KEY)), roles=role_models(overrides), @@ -132,11 +160,14 @@ def steps_hash(steps: Sequence[TaskStep]) -> str: def finished_records(runtime: RunRuntime, lock: RunLock, reads: Iterable[Read], context: TaskStepContext, - raised: bool = False) -> tuple[RunRuntime, RunLock]: - """The attempt's records once its run ends: in its lock, ``reads``, every entity version it read, and each verifier - it graded with the settings its grade records (``graded_settings``), which a judge completes as it calls, and - whether it completed the steps it was asked to run (``raised`` when the block ended by an exception or a cancel); - in its runtime, the types of the envs, artifacts and providers it used.""" + ran: Optional[StepsRan] = None, steps: Sequence[TaskStep] = (), + stopped: bool = False) -> tuple[RunRuntime, RunLock]: + """The attempt's records once its run ends: in its lock, ``reads``, every entity version it read; each verifier + that graded, its grade not failed, with the settings its grade records (``graded_settings``), which a judge + completes as it calls; and, from ``ran``, the steps it ran in the order of ``steps`` and whether each reached its + end, which it didn't when the block was ``stopped`` (an exception other than a verdict, or a cancel), both left + None when no step was noted and the block wasn't stopped, as for a worker that doesn't note its steps. In its + runtime, the types of the envs, artifacts and providers it used.""" reads = list(reads) types = {group: dict(found) for group, found in runtime.types.items()} for read in reads: @@ -150,23 +181,21 @@ def finished_records(runtime: RunRuntime, lock: RunLock, reads: Iterable[Read], verifiers = {step_id: (dataclasses.replace(verifier, graded_settings=grades[step_id].get("verifier_settings")) if _graded_in(grades.get(step_id), lock.attempt_epoch) else verifier) for step_id, verifier in lock.verifiers.items()} + steps_run, completed = None, None + if ran is not None and (ran.dispatched or stopped): + steps_run = [step.id for step in steps if step.id in ran.dispatched] + completed = not stopped and ran.dispatched <= ran.ended return (dataclasses.replace(runtime, types=types, stage=Stage.FINISHED), - dataclasses.replace(lock, verifiers=verifiers, reads=read_records(reads), - completed=not raised and not _failed_in(context, lock.intent.steps_run), - stage=Stage.FINISHED)) - - -def _failed_in(context: TaskStepContext, steps_run: Optional[Sequence[str]]) -> bool: - """Whether a step the attempt ran failed and wasn't retried, as one whose failure the task tolerates.""" - ran = set(steps_run or ()) - return any(isinstance(failed, dict) and failed.get("step_id") in ran and not failed.get("retried") - for failed in context.metadata.get("failed_steps") or ()) + dataclasses.replace(lock, verifiers=verifiers, reads=read_records(reads), steps_run=steps_run, + completed=completed, stage=Stage.FINISHED)) def _graded_in(grade: Any, attempt_epoch: int) -> bool: """Whether ``grade`` was written by the attempt that started under ``attempt_epoch`` or a retry within it, which runs under a later epoch; not one a resume restored from an earlier attempt, nor one that names no epoch.""" - epoch = grade.get("attempt_epoch") if isinstance(grade, dict) else None + if not isinstance(grade, dict) or grade.get("verifier_status") == VerifierStatus.FAILED.value: + return False # a failed grade records only the settings its calls had filled in by then + epoch = grade.get("attempt_epoch") return isinstance(epoch, int) and epoch >= attempt_epoch @@ -180,26 +209,30 @@ def read_records(reads: Iterable[Read]) -> list[ReadRecord]: @contextlib.asynccontextmanager async def run_recorded(instance_id: Optional[str], task: "Task", steps: Sequence[TaskStep], - context: TaskStepContext, attempt_epoch: int, *, start_step: int = 0, - end_step: Optional[int] = None) -> AsyncIterator[None]: - """Record the attempt's start on ``instance_id``, list every entity the block reads, and record that when the block - ends, however it ends. The block runs ``steps[start_step:end_step]``, which its lock names. Without an instance, as - when registering the run failed, the block runs unrecorded. Neither write is awaited, so the block's cancel and its - end are the run's own.""" - started = _started(instance_id, task, steps, context, attempt_epoch, start_step, end_step) if instance_id else None + context: TaskStepContext, attempt_epoch: int) -> AsyncIterator[None]: + """Record the attempt's start on ``instance_id``, list every entity the block reads and every step it notes + (``step_dispatched``, ``step_ended``), and record those when the block ends, however it ends. Without an instance, + as when registering the run failed, the block runs unrecorded. Neither write is awaited, so the block's cancel and + its end are the run's own.""" + started = _started(instance_id, task, steps, context, attempt_epoch) if instance_id else None if started is None: yield return runtime, lock = started _write(instance_id, runtime, lock) + ran, stopped = StepsRan(), True + token = _STEPS_RAN.set(ran) with recording() as reads: - raised = True try: yield - raised = False + stopped = False + except VERDICTS: + stopped = False + raise finally: + _STEPS_RAN.reset(token) try: - runtime, lock = finished_records(runtime, lock, reads, context, raised) + runtime, lock = finished_records(runtime, lock, reads, context, ran, steps, stopped) except Exception: logger.warning("The reads of attempt %s of %s couldn't be recorded", attempt_epoch, instance_id, exc_info=True) @@ -222,12 +255,11 @@ def _write(instance_id: str, runtime: RunRuntime, lock: RunLock) -> None: def _started(instance_id: str, task: "Task", steps: Sequence[TaskStep], context: TaskStepContext, - attempt_epoch: int, start_step: int, end_step: Optional[int]) -> Optional[tuple[RunRuntime, RunLock]]: + attempt_epoch: int) -> Optional[tuple[RunRuntime, RunLock]]: """The attempt's started records, made on the event loop, which reads installed metadata and the context but no store; None, logged, when they can't be made, so the run goes on unrecorded.""" try: - return (started_runtime(attempt_epoch, steps), - started_lock(task, steps, context, attempt_epoch, start_step, end_step)) + return started_runtime(attempt_epoch, steps), started_lock(task, steps, context, attempt_epoch) except Exception: logger.warning("What attempt %s of %s runs couldn't be recorded", attempt_epoch, instance_id, exc_info=True) return None diff --git a/src/agent_env/task/run_records.py b/src/agent_env/task/run_records.py index 041a7b2e8..da5c209e9 100644 --- a/src/agent_env/task/run_records.py +++ b/src/agent_env/task/run_records.py @@ -102,10 +102,10 @@ def from_dict(cls, data: dict) -> RunRuntime: @dataclass class RunIntent: """What an attempt was asked to do, computed as an eval plan computes its own (``agent_env.eval.intent``): the task's - id, version and content hash; ``steps_hash``, of its steps as this run runs them, its seed applied; ``steps_run``, - the ids of the steps it was asked to run, from its start step to its end step, as a resume runs only the rest, None - for a record that predates it; ``trajectory_formats``, the formats beside native it prescribes to the agents whose - trajectories its judges read, from its overrides or else the config, None for a record that predates it; its pins; + id, version and content hash; ``steps_hash``, of its steps as this run runs them, its seed applied; + ``trajectory_formats``, the formats beside native it prescribes to the agents whose trajectories its judges read, + from its overrides or else the config, None for a record that predates it or when the value names them wrongly; + its pins; each role's model and endpoint host as this process's config resolves them; its overrides without secrets; and the result rules version.""" @@ -117,7 +117,6 @@ class RunIntent: roles: dict[str, RoleModel] = field(default_factory=dict) overrides: dict[str, Any] = field(default_factory=dict) result_rules_version: int = 0 - steps_run: Optional[list[str]] = None trajectory_formats: Optional[list[str]] = None def to_dict(self) -> dict: @@ -126,7 +125,6 @@ def to_dict(self) -> dict: "task_version": self.task_version, "content_hash": self.content_hash, "steps_hash": self.steps_hash, - "steps_run": None if self.steps_run is None else list(self.steps_run), "trajectory_formats": None if self.trajectory_formats is None else list(self.trajectory_formats), "pins": self.pins, "roles": {name: role.to_dict() for name, role in self.roles.items()}, @@ -141,7 +139,6 @@ def from_dict(cls, data: dict) -> RunIntent: task_version=data["task_version"], content_hash=data["content_hash"], steps_hash=data.get("steps_hash", ""), - steps_run=None if data.get("steps_run") is None else list(data["steps_run"]), trajectory_formats=None if data.get("trajectory_formats") is None else list(data["trajectory_formats"]), pins=data.get("pins") or {}, roles={name: RoleModel.from_dict(role) for name, role in (data.get("roles") or {}).items()}, @@ -199,13 +196,16 @@ def from_dict(cls, data: dict) -> ReadRecord: @dataclass class RunLock: """What an attempt was asked to do (``intent``) and what it resolved: each verifier's record by step id, and, once - ``finished``, every entity version it read (``reads``), children included, and whether it ``completed`` the steps - it was asked to run, none failing it, raising or tolerated, and no cancel; both None while ``started``.""" + ``finished``, every entity version it read (``reads``), children included; the ids of the steps it ran + (``steps_run``), in the task's order, a retry's included, as a resume runs only the rest; and whether it + ``completed`` them, each reaching its end, a verdict that fails its step included; each None while ``started``, + and the last two for a record without them.""" attempt_epoch: int intent: RunIntent verifiers: dict[str, VerifierRecord] = field(default_factory=dict) reads: Optional[list[ReadRecord]] = None + steps_run: Optional[list[str]] = None completed: Optional[bool] = None stage: Stage | str = Stage.STARTED record_version: int = RUN_RECORD_VERSION @@ -223,6 +223,7 @@ def to_dict(self) -> dict: "resolved": { "verifiers": {step_id: verifier.to_dict() for step_id, verifier in self.verifiers.items()}, "reads": None if self.reads is None else [read.to_dict() for read in self.reads], + "steps_run": None if self.steps_run is None else list(self.steps_run), "completed": self.completed, }, } @@ -237,6 +238,7 @@ def from_dict(cls, data: dict) -> RunLock: verifiers={step_id: VerifierRecord.from_dict(verifier) for step_id, verifier in (resolved.get("verifiers") or {}).items()}, reads=None if reads is None else [ReadRecord.from_dict(read) for read in reads], + steps_run=None if resolved.get("steps_run") is None else list(resolved["steps_run"]), completed=resolved.get("completed"), stage=_stage(data.get("stage", Stage.STARTED)), record_version=data.get("record_version", RUN_RECORD_VERSION), diff --git a/src/agent_env/task/task.py b/src/agent_env/task/task.py index 2225f9a2c..fcf7feabe 100644 --- a/src/agent_env/task/task.py +++ b/src/agent_env/task/task.py @@ -27,7 +27,7 @@ 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.run_lock import run_recorded +from agent_env.task.run_lock import run_recorded, step_dispatched, step_ended 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 @@ -613,8 +613,7 @@ async def _run( state = self._build_scheduler_state(steps, start_step, end_step) if instance: state.epoch = instance.attempt_epoch - async with run_recorded(instance_id, self, steps, context, state.epoch, start_step=start_step, - end_step=end_step): + async with run_recorded(instance_id, self, steps, context, state.epoch): # _drive_dag drains in-flight steps and records the failure itself if it raises. first_error, first_error_step_id = await self._drive_dag( steps, state, total, context, instance_id, @@ -713,6 +712,7 @@ async def _run_one(step: TaskStep, idx: int, dispatch_epoch: int) -> None: started_utc = datetime.now(timezone.utc).isoformat() # This step's own asyncio task, so a sibling dispatched alongside it doesn't see it. ATTEMPT_EPOCH.set(dispatch_epoch) + step_dispatched(step.id) try: with protocol_v1.authorized({url: sent for d in context.deployed_envs for url, sent in d.control_grants.items()}): async with running_usage(instance_id, step.id, context): @@ -720,6 +720,7 @@ async def _run_one(step: TaskStep, idx: int, dispatch_epoch: int) -> None: except asyncio.CancelledError: raise except BaseException as exc: + step_ended(step.id, exc) duration = time.monotonic() - started_mono fatal = getattr(step, "fail_task_on_error", True) context.metadata.setdefault("failed_steps", []).append(FailedStep.from_exception( @@ -728,6 +729,7 @@ async def _run_one(step: TaskStep, idx: int, dispatch_epoch: int) -> None: if not fatal: await _heartbeat_step(step, pre_context, _store.TaskStepStatus.FAILURE, dispatch_epoch) raise + step_ended(step.id) duration = time.monotonic() - started_mono await _heartbeat_step(step, pre_context, _store.TaskStepStatus.SUCCESS, dispatch_epoch) logger.info( diff --git a/tst/unit/cli/task_diff_test.py b/tst/unit/cli/task_diff_test.py index 2ae752933..0daf9fe99 100644 --- a/tst/unit/cli/task_diff_test.py +++ b/tst/unit/cli/task_diff_test.py @@ -176,5 +176,5 @@ def run(**kwargs): assert "verifier settings score threshold: 0.5 -> 0.9 (regrade)" in differs.output assert resumed.exit_code == 0 and f"attempt 0 of {first} -> attempt 1 of {first}" in resumed.output assert 'never steps it ran: ["reads", "score"] -> ["score"]' in resumed.output - assert "not compared: the 7 entities only one of them read, as they didn't both run and complete" in resumed.output + assert "not compared, as only one of them read it, and they didn't both run and complete" in resumed.output assert "0 hard, 0 soft, 1 never: the same thing ran, in what both recorded" in resumed.output diff --git a/tst/unit/task/drift_test.py b/tst/unit/task/drift_test.py index 00dc65e74..174695e6a 100644 --- a/tst/unit/task/drift_test.py +++ b/tst/unit/task/drift_test.py @@ -34,7 +34,7 @@ def _records(instance_id="first", epoch=0) -> Records: config_selected_by="discovered", types={"task_steps": {"grade": "acme-steps"}}, stage=Stage.FINISHED) intent = RunIntent(task_id="t", task_version=1, content_hash="sha256:c", steps_hash="sha256:s", - steps_run=["deploy", "score"], trajectory_formats=["atif/1"], pins={"env": {"office": 1}}, + trajectory_formats=["atif/1"], pins={"env": {"office": 1}}, roles={"solver": RoleModel("m", "run", "models.example"), "judge": RoleModel("j", "config_role", "models.example")}, overrides={"judge_model": "j", "judge_samples": 1, "agent_sandbox": "local", @@ -51,7 +51,8 @@ def _records(instance_id="first", epoch=0) -> Records: ReadRecord("agent", "solver", 2, "a2a_agent", latest=True), ReadRecord("artifact", "solver-image", 1, "docker_image", image_identity="registry:sha256:h1"), ReadRecord("artifact", "macos-15", 1, "computer")] - return Records(instance_id, runtime, RunLock(epoch, intent, verifiers, reads, completed=True, stage=Stage.FINISHED)) + return Records(instance_id, runtime, RunLock(epoch, intent, verifiers, reads, steps_run=["deploy", "score"], + completed=True, stage=Stage.FINISHED)) def _changed(change: Callable[[Records], None]) -> Records: @@ -66,7 +67,7 @@ def _read(records: Records, entity_id: str, **fields) -> None: def _unfinished(records: Records) -> None: """As a killed attempt leaves its records: started, its reads not recorded.""" - records.lock.reads, records.lock.completed = None, None + records.lock.reads, records.lock.steps_run, records.lock.completed = None, None, None records.lock.stage = records.runtime.stage = Stage.STARTED @@ -105,7 +106,7 @@ def change(records): Case("task version", _set("lock.intent.task_version", 2), (), HARD), Case("task content", _set("lock.intent.content_hash", "sha256:d"), (), HARD), Case("steps as run", _set("lock.intent.steps_hash", "sha256:t"), (), HARD), - Case("steps it ran", _set("lock.intent.steps_run", ["score"]), (), NEVER), + Case("steps it ran", _set("lock.steps_run", ["score"]), (), NEVER), Case("trajectory formats prescribed", _set("lock.intent.trajectory_formats", []), (), HARD), Case("pins", lambda r: (_unfinished(r), r.lock.intent.pins["env"].update(office=2)), ("env", "office"), HARD), Case("completed its steps", _set("lock.completed", False), (), NEVER), @@ -219,29 +220,31 @@ def change(records): def test_a_resume_that_ran_the_rest_is_compared_on_what_both_read(): def change(records): - records.lock.intent.steps_run = ["score"] + records.lock.steps_run = ["score"] records.lock.reads[:] = [r for r in records.lock.reads if r.id == "office"] comparison = compare(_records(), _changed(change)) assert [(d.row, d.drift) for d in comparison.differences] == [("steps it ran", NEVER)] - assert comparison.not_compared == ["the 4 entities only one of them read, as they didn't both run and complete the " - "same steps: attempt 0 of first ran 2 steps and completed them, and attempt 0 " - "of second ran 1 step and completed them"] + assert comparison.not_compared == [ + "entity version of agent solver, artifact macos-15, artifact office-image and 1 more: not compared, as only one " + "of them read it, and they didn't both run and complete the same steps: attempt 0 of first ran 2 steps and " + "completed them, and attempt 0 of second ran 1 step and completed them"] assert comparison.like_for_like def test_an_attempt_that_doesnt_record_its_steps_is_compared_on_what_both_read(): def change(records): - records.lock.intent.steps_run = None + records.lock.steps_run = None records.lock.reads.pop() comparison = compare(_records(), _changed(change)) - assert [d.row for d in comparison.differences] == ["steps it ran"] - assert comparison.not_compared == ["the 1 entity only one of them read, as they didn't both run and complete the " - "same steps: attempt 0 of first ran 2 steps and completed them, and attempt 0 " - "of second doesn't record which steps it ran"] + assert comparison.differences == [] + assert comparison.not_compared == [ + "entity version of artifact macos-15: not compared, as only one of them read it, and they didn't both run and " + "complete the same steps: attempt 0 of first ran 2 steps and completed them, and attempt 0 of second doesn't " + "record which steps it ran"] def test_a_judge_that_read_more_turns_of_the_same_formats_read_the_same_thing(): @@ -274,7 +277,7 @@ def change(records): comparison = compare(_records(), _changed(change)) assert comparison.differences == [] - assert comparison.not_compared == ["the trajectory formats verifier score read in attempt 0 of second: its record " + assert comparison.not_compared == ["trajectory formats a judge read of score: not compared, as attempt 0 of second " "keeps only a hash of them"] @@ -295,8 +298,18 @@ def change(records): comparison = compare(_records(), _changed(change)) assert comparison.differences == [] - assert comparison.not_compared == ["the trajectory formats attempt 0 of second prescribed: it records neither them " - "nor an override of them"] + assert comparison.not_compared == ["trajectory formats prescribed: not compared, as attempt 0 of second records " + "neither them nor an override of them"] + + +def test_an_override_of_the_formats_that_isnt_a_list_is_said_to_be_so(): + def change(records): + records.lock.intent.trajectory_formats = None + records.lock.intent.overrides["trajectory_formats"] = "atif/1" + + assert compare(_records(), _changed(change)).not_compared == [ + "trajectory formats prescribed: not compared, as attempt 0 of second names them by an override that isn't a " + "list of formats"] def test_a_change_the_overrides_made_to_a_judge_is_its_settings_hard_and_their_names_never(): @@ -332,9 +345,11 @@ def change(records): comparison = compare(first, _changed(change)) assert [(d.row, d.drift) for d in comparison.differences] == [("completed its steps", NEVER)] - assert comparison.not_compared == ["the 2 entities only one of them read, as they didn't both run and complete the " - "same steps: attempt 0 of first ran 2 steps and completed them, and attempt 0 " - "of second ran 2 steps and didn't complete them"] + why = ("they didn't both run and complete the same steps: attempt 0 of first ran 2 steps and completed them, and " + "attempt 0 of second ran 2 steps and didn't complete them") + assert comparison.not_compared == [ + f"entity version of agent solver, artifact solver-image: not compared, as only one of them read it, and {why}", + f"type's package of envs multi: not compared, as only one of them used it, and {why}"] assert comparison.like_for_like @@ -349,10 +364,10 @@ def change(records): (("agent_sandbox",), SOFT), (("sandbox",), SOFT), (("step_params", "score", "threshold"), HARD)] -def test_overrides_of_a_roles_model_or_endpoint_are_the_role_rows_and_a_secrets_reference_is_never_drift(): +def test_an_endpoint_override_is_the_role_rows_and_soft_in_a_step_and_a_secrets_reference_is_never_drift(): def change(records): records.lock.intent.overrides.update( - judge_model="k", litellm_base_url="other.example", litellm_api_key="env:ANOTHER_KEY", + litellm_base_url="other.example", litellm_api_key="env:ANOTHER_KEY", step_params={"score": {"threshold": 0.5, "litellm_base_url": "127.0.0.1:41234", "litellm_api_key": "env:EPISODE_KEY"}}) @@ -363,6 +378,23 @@ def change(records): (("step_params", "score", "litellm_base_url"), SOFT)] +def test_a_model_override_is_hard_though_the_role_it_names_resolves_alike(): + """The config names model A and the task's prompt step names B: a plain run uses B, and one given the override of + A uses A, though the role's model, resolved where no step names one, is A in both.""" + def change(records): + records.lock.intent.overrides["agent_model"] = "A" + first = _records() + first.lock.intent.roles["solver"] = RoleModel("A", "config_role", "models.example") + second = _changed(change) + second.lock.intent.roles["solver"] = RoleModel("A", "run", "models.example") + + comparison = compare(first, second) + + assert [(d.row, d.key, d.drift) for d in comparison.differences] == [ + ("role model's source", ("solver",), NEVER), ("override", ("agent_model",), HARD)] + assert not comparison.like_for_like + + def test_a_setting_two_judges_started_with_otherwise_is_one_difference_however_they_graded(): """One started with no effort and its judge resolved one; the other was given that effort from the start.""" def change(records): diff --git a/tst/unit/task/run_lock_test.py b/tst/unit/task/run_lock_test.py index 6229d3c08..9d01a6b27 100644 --- a/tst/unit/task/run_lock_test.py +++ b/tst/unit/task/run_lock_test.py @@ -42,7 +42,7 @@ find_task_instance, get_task_instance_store, ) -from agent_env.task_step.context import TaskStepContext +from agent_env.task_step.context import TaskStepContext, VerifierNotPassingError from agent_env.task_step.task_step import RetryConfig, TaskStep from agent_env.task_step.task_steps.verifiers.aggregate_verifiers import AggregateVerifiersTaskStep from agent_env.task_step.task_steps.verifiers.verifier import Verification, VerifierTaskStep @@ -81,13 +81,15 @@ async def execute(self, context): class _Flaky(TaskStep): - """Fails ``fails`` times, then passes; it retries itself, as a step whose ``retry_config`` names it does.""" + """Fails ``fails`` times, then passes; a failure retries from ``retry_from``, itself by default, as a step whose + ``retry_config`` names it does, or, without ``retries``, is the end of the run, or is tolerated by the task.""" type = "run_lock_test_flaky" entity_refs = () - def __init__(self, *, fails=0, **kwargs): - super().__init__(**kwargs, retry_config=RetryConfig(retry_from_step_id=kwargs["id"])) + def __init__(self, *, fails=0, retry_from=None, retries=True, **kwargs): + retry = RetryConfig(retry_from_step_id=retry_from or kwargs["id"]) if retries else None + super().__init__(**kwargs, retry_config=retry) self.fails = fails @classmethod @@ -105,9 +107,9 @@ class _Score(VerifierTaskStep): type = "run_lock_test_score" entity_refs = () - def __init__(self, *, threshold=0.5, note="", **kwargs): + def __init__(self, *, threshold=0.5, note="", verdict=False, **kwargs): super().__init__(**kwargs) - self.threshold, self.note = threshold, note + self.threshold, self.note, self.verdict = threshold, note, verdict def to_dict(self): return {**super().to_dict(), "threshold": self.threshold, "note": self.note} @@ -117,6 +119,8 @@ def from_dict(cls, data): return cls(**cls._base_from_dict(data), threshold=data.get("threshold", 0.5), note=data.get("note", "")) async def verify(self, context): + if self.verdict: + return Verification(score=0.0, raise_after=VerifierNotPassingError(f"{self.id} didn't pass")) return Verification(score=1.0) @@ -226,7 +230,7 @@ def test_a_resume_in_another_process_adds_its_own_records_and_keeps_the_first(): assert [r.attempt_epoch for r in instance.runtimes] == [r.attempt_epoch for r in instance.run_locks] == [0, 1] assert instance.run_locks[0].reads and instance.run_locks[1].reads == [] - assert [lock.intent.steps_run for lock in instance.run_locks] == [["reads", "score"], ["score"]] + assert [lock.steps_run for lock in instance.run_locks] == [["reads", "score"], ["score"]] def test_a_resume_names_the_settings_only_of_the_verifiers_it_graded_though_a_retry_rebuilds_its_context(): @@ -269,6 +273,60 @@ async def cancelled(): assert record_writer.flush_run_records(10) # the record's write runs on past the cancel [lock] = find_task_instance(context.instance_id).run_locks assert {r.id for r in lock.reads} >= {"office", "solver", "data"} + assert (lock.steps_run, lock.completed) == (["reads"], False) + + +def _completed(*steps, **kwargs): + """What the one attempt of a run of ``steps`` records of the steps it ran and whether it completed them.""" + context = TaskStepContext() + try: + asyncio.run(_task(*steps).run(context=context, **kwargs)) + except (RuntimeError, VerifierNotPassingError): + pass + assert record_writer.flush_run_records(10) + [lock] = find_task_instance(context.instance_id).run_locks + return lock.steps_run, lock.completed + + +@pytest.mark.parametrize("steps, ran, completed", [ + (lambda: [_Score(id="score", version=None, verifier_id="score")], ["score"], True), + (lambda: [_Flaky(id="flaky", version=None, fails=1, retries=False), _Score(id="score", version=None, + verifier_id="score")], ["flaky"], False), + (lambda: [_Flaky(id="flaky", version=None, fails=1, retries=False, fail_task_on_error=False), + _Score(id="score", version=None, verifier_id="score")], ["flaky", "score"], False), + (lambda: [_Flaky(id="flaky", version=None, fails=1), _Score(id="score", version=None, verifier_id="score")], + ["flaky", "score"], True), + (lambda: [_Score(id="score", version=None, verifier_id="score", verdict=True)], ["score"], True), +], ids=["every step passing", "a step failing the run", "a step's failure tolerated", "a step retried, then passing", + "a verifier's verdict failing the run, as it graded"]) +def test_an_attempt_records_the_steps_it_ran_and_whether_each_reached_its_end(steps, ran, completed): + assert _completed(*steps()) == (ran, completed) + + +def test_a_retry_within_a_resume_that_reruns_an_earlier_step_records_it_as_run(): + flaky = _Flaky(id="flaky", version=None, retry_from="early") + task = _task(_Score(id="early", version=None, verifier_id="early"), flaky) + _, first = _run(task) + flaky.fails = 1 + restored = TaskStepContext.from_dict(find_task_instance(first.instance_id).context) + asyncio.run(task.run(context=restored, instance_id=first.instance_id, start_step=1)) + assert record_writer.flush_run_records(10) + + resumed = find_task_instance(first.instance_id).run_locks[1] + assert (resumed.steps_run, resumed.completed) == (["early", "flaky"], True) + + +def test_a_grade_that_failed_records_no_settings_it_graded_with(monkeypatch): + """Its calls hadn't filled in what they fill in, so its settings aren't those a grade that graded has.""" + async def verify(self, context): + raise RuntimeError("the judge couldn't be reached") + + monkeypatch.setattr(_Score, "verify", verify) + _, context = _run(_task(_Score(id="score", version=None, verifier_id="score", fail_task_on_error=False))) + + [lock] = find_task_instance(context.instance_id).run_locks + assert context.metadata["grades"]["score"]["verifier_status"] == "failed" + assert lock.verifiers["score"].graded_settings is None def test_a_run_whose_records_cant_be_made_runs_unrecorded(monkeypatch): @@ -394,15 +452,15 @@ def test_every_field_of_the_records_survives_a_round_trip(): plugins={"acme-steps": plugin}, config_selected_by="environment", types={"task_steps": {"grade": "acme-steps"}}, stage=Stage.FINISHED, record_version=7) intent = RunIntent(task_id="t", task_version=3, content_hash="sha256:c", steps_hash="sha256:s", - steps_run=["reads", "score"], trajectory_formats=["atif/1"], pins={"env": {"office": 2}}, + trajectory_formats=["atif/1"], pins={"env": {"office": 2}}, roles={"judge": RoleModel("j", "run", "models.example")}, overrides={"judge_model": "j"}, result_rules_version=4) verifier = VerifierRecord(type="score", distribution="acme-steps", version="1.2.0", settings={"a": 1}, graded_settings={"a": 2}) read = ReadRecord(kind="env", id="office", version=2, type="multi", latest=True, alias=True, image_identity="source:sha256:x") - lock = RunLock(attempt_epoch=2, intent=intent, verifiers={"score": verifier}, reads=[read], completed=True, - stage=Stage.FINISHED, record_version=7) + lock = RunLock(attempt_epoch=2, intent=intent, verifiers={"score": verifier}, reads=[read], + steps_run=["reads", "score"], completed=True, stage=Stage.FINISHED, record_version=7) for sample in (plugin, runtime, intent, verifier, read, lock): for f in dataclasses.fields(sample): default = f.default_factory() if f.default_factory is not dataclasses.MISSING else f.default From 2e82e39dc7e9de29a56bc5f89f08c0851af4c48f Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 1 Dec 2026 11:50:39 -0800 Subject: [PATCH 09/10] fix(task): a not-compared note doesn't repeat "not compared", which task diff puts before it Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task/drift.py | 2 +- tst/unit/cli/task_diff_test.py | 3 ++- tst/unit/task/drift_test.py | 14 +++++++------- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/agent_env/task/drift.py b/src/agent_env/task/drift.py index 585283e9f..ae0a5efb0 100644 --- a/src/agent_env/task/drift.py +++ b/src/agent_env/task/drift.py @@ -247,7 +247,7 @@ def compare(a: Records, b: Records) -> Comparison: differences.append(Difference(row.name, key, before, after, drift, row.regrade and drift is Drift.HARD)) not_compared = [f"{r.where} didn't finish, so what it read and the types it used beyond its steps' aren't recorded" for r in (a, b) if r.lock.reads is None] - not_compared += [f"{row}{_listed(keys)}: not compared, as {why}" for (row, why), keys in unknown.items()] + not_compared += [f"{row}{_listed(keys)}: {why}" for (row, why), keys in unknown.items()] return Comparison(a, b, differences, not_compared) diff --git a/tst/unit/cli/task_diff_test.py b/tst/unit/cli/task_diff_test.py index 0daf9fe99..416890d3a 100644 --- a/tst/unit/cli/task_diff_test.py +++ b/tst/unit/cli/task_diff_test.py @@ -176,5 +176,6 @@ def run(**kwargs): assert "verifier settings score threshold: 0.5 -> 0.9 (regrade)" in differs.output assert resumed.exit_code == 0 and f"attempt 0 of {first} -> attempt 1 of {first}" in resumed.output assert 'never steps it ran: ["reads", "score"] -> ["score"]' in resumed.output - assert "not compared, as only one of them read it, and they didn't both run and complete" in resumed.output + assert "not compared: entity version of " in resumed.output + assert "only one of them read it, and they didn't both run and complete" in resumed.output assert "0 hard, 0 soft, 1 never: the same thing ran, in what both recorded" in resumed.output diff --git a/tst/unit/task/drift_test.py b/tst/unit/task/drift_test.py index 174695e6a..cb3b96188 100644 --- a/tst/unit/task/drift_test.py +++ b/tst/unit/task/drift_test.py @@ -227,7 +227,7 @@ def change(records): assert [(d.row, d.drift) for d in comparison.differences] == [("steps it ran", NEVER)] assert comparison.not_compared == [ - "entity version of agent solver, artifact macos-15, artifact office-image and 1 more: not compared, as only one " + "entity version of agent solver, artifact macos-15, artifact office-image and 1 more: only one " "of them read it, and they didn't both run and complete the same steps: attempt 0 of first ran 2 steps and " "completed them, and attempt 0 of second ran 1 step and completed them"] assert comparison.like_for_like @@ -242,7 +242,7 @@ def change(records): assert comparison.differences == [] assert comparison.not_compared == [ - "entity version of artifact macos-15: not compared, as only one of them read it, and they didn't both run and " + "entity version of artifact macos-15: only one of them read it, and they didn't both run and " "complete the same steps: attempt 0 of first ran 2 steps and completed them, and attempt 0 of second doesn't " "record which steps it ran"] @@ -277,7 +277,7 @@ def change(records): comparison = compare(_records(), _changed(change)) assert comparison.differences == [] - assert comparison.not_compared == ["trajectory formats a judge read of score: not compared, as attempt 0 of second " + assert comparison.not_compared == ["trajectory formats a judge read of score: attempt 0 of second " "keeps only a hash of them"] @@ -298,7 +298,7 @@ def change(records): comparison = compare(_records(), _changed(change)) assert comparison.differences == [] - assert comparison.not_compared == ["trajectory formats prescribed: not compared, as attempt 0 of second records " + assert comparison.not_compared == ["trajectory formats prescribed: attempt 0 of second records " "neither them nor an override of them"] @@ -308,7 +308,7 @@ def change(records): records.lock.intent.overrides["trajectory_formats"] = "atif/1" assert compare(_records(), _changed(change)).not_compared == [ - "trajectory formats prescribed: not compared, as attempt 0 of second names them by an override that isn't a " + "trajectory formats prescribed: attempt 0 of second names them by an override that isn't a " "list of formats"] @@ -348,8 +348,8 @@ def change(records): why = ("they didn't both run and complete the same steps: attempt 0 of first ran 2 steps and completed them, and " "attempt 0 of second ran 2 steps and didn't complete them") assert comparison.not_compared == [ - f"entity version of agent solver, artifact solver-image: not compared, as only one of them read it, and {why}", - f"type's package of envs multi: not compared, as only one of them used it, and {why}"] + f"entity version of agent solver, artifact solver-image: only one of them read it, and {why}", + f"type's package of envs multi: only one of them used it, and {why}"] assert comparison.like_for_like From 550ddeb247bf96744d998772aeb0f03e3d2e60ba Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 1 Dec 2026 11:51:38 -0800 Subject: [PATCH 10/10] fix(task): a judge whose formats both attempts keep only as a hash is said not to be compared The formats row now lists every verifier both attempts graded, so its reason for one it can't compare is said even when neither attempt has a summary, rather than the listing saying "the same thing ran" unqualified. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task/drift.py | 2 +- tst/unit/task/drift_test.py | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/agent_env/task/drift.py b/src/agent_env/task/drift.py index ae0a5efb0..0276aa75d 100644 --- a/src/agent_env/task/drift.py +++ b/src/agent_env/task/drift.py @@ -465,7 +465,7 @@ def _formats_unknown(key: Key, a: Records, b: Records) -> Optional[str]: compared=_started_alike), _Row("where a verifier's judge ran", (), Drift.SOFT, _placement, compared=_in_both(_verifiers)), _Row("trajectory formats a judge read", (), Drift.SOFT, - lambda r: {(step,): formats for step, formats in r.formats_read.items()}, + lambda r: {(step,): r.formats_read.get(step) for step in _graded(r)}, compared=_in_both(lambda r: r.formats_read), unknown=_formats_unknown), _Row("judge endpoint host", (), Drift.SOFT, lambda r: {(step,): v.graded_settings.get(JUDGE_ENDPOINT_HOST_SETTING) for step, v in _graded(r).items()}, diff --git a/tst/unit/task/drift_test.py b/tst/unit/task/drift_test.py index cb3b96188..18283fb4a 100644 --- a/tst/unit/task/drift_test.py +++ b/tst/unit/task/drift_test.py @@ -281,6 +281,18 @@ def change(records): "keeps only a hash of them"] +def test_formats_both_attempts_keep_only_as_a_hash_are_said_not_to_be_compared(): + first = _records() + first.lock.verifiers["score"].graded_settings["trajectory_sources"] = HASHED + + comparison = compare(first, _changed(lambda r: r.lock.verifiers["score"].graded_settings.update( + trajectory_sources=HASHED))) + + assert comparison.differences == [] + assert comparison.not_compared == ["trajectory formats a judge read of score: attempt 0 of first keeps only a hash " + "of them; attempt 0 of second keeps only a hash of them"] + + @pytest.mark.parametrize("override, rows", [(["atif/1"], []), ([], [("trajectory formats prescribed", HARD)])], ids=["the same formats", "other formats"]) def test_an_attempt_recorded_before_its_prescribed_formats_is_compared_by_its_override_of_them(override, rows):