diff --git a/AGENTS.md b/AGENTS.md index 181ad45b9..fd34c0154 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -490,17 +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, 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`. + 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/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..6c5d4929a --- /dev/null +++ b/src/agent_env/cli/task/diff.py @@ -0,0 +1,104 @@ +"""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, + 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: + _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.isascii() 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) + 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.") + + +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/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 new file mode 100644 index 000000000..0276aa75d --- /dev/null +++ b/src/agent_env/task/drift.py @@ -0,0 +1,507 @@ +"""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, 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, 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: 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: +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 + +from dataclasses import dataclass +from enum import StrEnum +from functools import cached_property +from typing import Any, Callable, Mapping, Optional + +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 +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, +) + +Key = tuple[str, ...] + +# 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 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 = registry_name(TASK_STEPS) +_READ_FIELDS = ("version", "type", "image_identity", "latest", "alias") + + +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``. Compared as + they stand when first compared, as what it read is indexed then.""" + + 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.""" + 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: + """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) + + @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 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, 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.""" + 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)} + + +@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 and why, + 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``, 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``, ``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, ...] + 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 + 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, and each + key a row couldn't compare, by why.""" + differences: list[Difference] = [] + 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) + 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"{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)}: {why}" for (row, why), keys in unknown.items()] + return Comparison(a, b, differences, not_compared) + + +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.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 _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 _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 _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]: + return {(): value} + + +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") or {}).get(key) for records in (a, b)] + 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, which an attempt that didn't + finish says it hasn't.""" + return key[0] == _STEP_TYPES or (a.finished and b.finished) + + +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 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 RUN_ENDPOINT_OVERRIDES: + continue + if name == _STEP_PARAMS and isinstance(value, Mapping): + 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: + """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.""" + in_step, name = key[0] == _STEP_PARAMS and len(key) == 3, key[-1] + if redacted_key(name): + return Drift.NEVER + if (name in RUN_ENDPOINT_OVERRIDES) if in_step else (name in SANDBOX_OVERRIDE_KEYS): + return Drift.SOFT + return 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() if name not in _NOT_GRADING_SETTINGS} + + +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 _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 _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, ...] = ( + _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("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), unknown=_prescription_unknown), + _Row("pins", ("RunIntent.pins",), Drift.HARD, _pins, compared=_either_unread), + _Row("entity version", ("ReadRecord.kind", "ReadRecord.id", "ReadRecord.version"), Drift.HARD, + 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), + _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, + 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 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,): 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()}, + 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, + 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, _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)), +) + +# 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", + "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/src/agent_env/task/run_lock.py b/src/agent_env/task/run_lock.py index d4bcf48e7..b7a951d54 100644 --- a/src/agent_env/task/run_lock.py +++ b/src/agent_env/task/run_lock.py @@ -28,9 +28,11 @@ 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 +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,11 +57,14 @@ 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, VerifierNotPassingError from agent_env.task_step.task_step import TaskStep -from agent_env.task_step.task_steps.verifiers.verifier import GRADES_KEY, VerifierTaskStep +from agent_env.task_step.task_steps.prompt_agent import prescribed_formats +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: @@ -67,13 +72,37 @@ 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) -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.") +@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``).""" -_READ_KINDS = {"env": _group(ENVS), "artifact": _group(ARTIFACTS)} + 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)} def started_runtime(attempt_epoch: int, steps: Sequence[TaskStep]) -> RunRuntime: @@ -85,13 +114,13 @@ 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}}, ) 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 steps it runs, its seed applied; ``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,6 +131,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), + trajectory_formats=_prescribed(context), pins=checked_pins(user_overrides.get(PINS_KEY)), roles=role_models(overrides), overrides=recorded_overrides(overrides), @@ -113,6 +143,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 @@ -120,32 +159,43 @@ 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]: - """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 +def finished_records(runtime: RunRuntime, lock: RunLock, reads: Iterable[Read], context: TaskStepContext, + 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: 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 {} 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), stage=Stage.FINISHED)) + 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 @@ -160,21 +210,29 @@ 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]: - """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.""" + """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: try: yield + stopped = False + except VERDICTS: + stopped = False + raise finally: + _STEPS_RAN.reset(token) try: - runtime, lock = finished_records(runtime, lock, reads, context) + 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) diff --git a/src/agent_env/task/run_records.py b/src/agent_env/task/run_records.py index f50820709..da5c209e9 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.""" @@ -97,8 +102,11 @@ 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 + 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.""" task_id: str @@ -109,6 +117,7 @@ class RunIntent: roles: dict[str, RoleModel] = field(default_factory=dict) overrides: dict[str, Any] = field(default_factory=dict) result_rules_version: int = 0 + trajectory_formats: Optional[list[str]] = None def to_dict(self) -> dict: return { @@ -116,6 +125,7 @@ def to_dict(self) -> dict: "task_version": self.task_version, "content_hash": self.content_hash, "steps_hash": self.steps_hash, + "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, @@ -129,6 +139,7 @@ def from_dict(cls, data: dict) -> RunIntent: task_version=data["task_version"], content_hash=data["content_hash"], steps_hash=data.get("steps_hash", ""), + 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 {}, @@ -185,12 +196,17 @@ 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; 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 @@ -207,6 +223,8 @@ 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, }, } @@ -220,6 +238,8 @@ 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 00b6f50c4..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 @@ -712,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): @@ -719,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( @@ -727,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/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 bf15d77e1..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 @@ -58,7 +58,17 @@ 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, + JUDGE_SANDBOX_TYPE_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, fetch_container_logs, @@ -965,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, } @@ -1004,9 +1014,10 @@ 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) + 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. @@ -1019,7 +1030,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..795d9dd3e 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 @@ -29,6 +29,19 @@ # 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 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" +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 @@ -289,6 +302,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/cli/task_diff_test.py b/tst/unit/cli/task_diff_test.py new file mode 100644 index 000000000..416890d3a --- /dev/null +++ b/tst/unit/cli/task_diff_test.py @@ -0,0 +1,181 @@ +"""``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 importlib +import json + +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 + +# 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.""" + + 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): + 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_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 + 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", {})}) + 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=1) + + differs = _diff(first, other) + resumed = _diff(first) + + assert differs.exit_code == 1, 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: 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 new file mode 100644 index 000000000..18283fb4a --- /dev/null +++ b/tst/unit/task/drift_test.py @@ -0,0 +1,477 @@ +"""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", + 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", + "step_params": {"score": {"threshold": 0.5}}}, + result_rules_version=1) + verifiers = {"score": VerifierRecord("grade", "acme-steps", "1.2.0", + {"threshold": 0.5, "overridden": [], "judge_sandbox_type": "local"}, + {"threshold": 0.5, "model": "j", "overridden": [], + "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"), + ReadRecord("artifact", "macos-15", 1, "computer")] + 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: + 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 _unfinished(records: Records) -> None: + """As a killed attempt leaves its records: started, its reads not recorded.""" + records.lock.reads, records.lock.steps_run, records.lock.completed = None, 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"] + 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("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), + 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_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 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"}]), + ("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), + 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} + 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) + 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_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.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 == [ + "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 + + +def test_an_attempt_that_doesnt_record_its_steps_is_compared_on_what_both_read(): + def change(records): + records.lock.steps_run = None + records.lock.reads.pop() + + comparison = compare(_records(), _changed(change)) + + assert comparison.differences == [] + assert comparison.not_compared == [ + "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"] + + +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 == [] + + +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 == ["trajectory formats a judge read of score: attempt 0 of second " + "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): + 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 == ["trajectory formats prescribed: 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: 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(): + 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_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)] + 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: 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 + + +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_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( + 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] == [ + (("litellm_api_key",), NEVER), (("step_params", "score", "litellm_api_key"), NEVER), + (("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): + 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(): + 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_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 = 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(first, _changed(change)) + + assert comparison.differences == [] + 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", [ + ("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, 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): + [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(): + 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) diff --git a/tst/unit/task/run_lock_test.py b/tst/unit/task/run_lock_test.py index c8b832f5c..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) @@ -153,7 +157,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,6 +176,14 @@ 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"]), + ({"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 + + 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"])) @@ -218,6 +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.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(): @@ -242,7 +255,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(): @@ -260,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): @@ -385,14 +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", - pins={"env": {"office": 2}}, roles={"judge": RoleModel("j", "run", "models.example")}, + 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], + 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 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]: