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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 20 additions & 11 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions src/agent_env/cli/task/__init__.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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)
Expand Down
104 changes: 104 additions & 0 deletions src/agent_env/cli/task/diff.py
Original file line number Diff line number Diff line change
@@ -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] + "…"
5 changes: 3 additions & 2 deletions src/agent_env/config/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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)
Expand Down
Loading
Loading