From 7dc0e48457d8121f25778d4a443494b25ebb67d7 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 30 Nov 2026 09:55:12 -0800 Subject: [PATCH 01/10] feat(task): each attempt of a run records the code that ran it and what it was asked to do and read - task/run_lock.py: run_recorded writes, per attempt and by its attempt_epoch, a runtime entry (core, protocol and Python versions, installed plugins with their install kind, how the config file was found, the distribution of each type the run used; never a path) and a lock entry (intent: content hash, pins, each role's model and endpoint host, overrides without secrets, result rules version; resolved: each verifier's settings and version at the start and every entity version the run read, with each image's identity), at the start and again when the run ends. - agent_env.plugins: distribution_of, distribution_version, installed_plugins, install_origin, from metadata alone. - The config's found_by (environment, discovered, none); DockerImageArtifact.image_identity; recorded reads carry the entity's type, class and image identity. - eval/intent.py holds the intent helpers the eval plan and each run share; the verifier's grade takes its settings and version from the same functions the lock does. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 11 +- src/agent_env/a2a_agent/a2a_agent.py | 4 +- src/agent_env/artifact/artifact.py | 2 +- .../artifact/artifacts/docker_image.py | 10 + src/agent_env/config/loader.py | 16 +- src/agent_env/config/runtime.py | 4 + src/agent_env/config/snapshot.py | 15 +- src/agent_env/entity/pins.py | 18 +- src/agent_env/env/env.py | 4 +- src/agent_env/eval/intent.py | 59 +++++ src/agent_env/eval/resolve.py | 58 +---- src/agent_env/plugins/__init__.py | 8 +- src/agent_env/plugins/_provenance.py | 89 +++++++ src/agent_env/task/run_lock.py | 192 +++++++++++++++ src/agent_env/task/store.py | 35 +++ src/agent_env/task/task.py | 20 +- .../task_steps/verifiers/verifier.py | 27 +-- tst/unit/artifact/image_identity_test.py | 20 ++ tst/unit/config/config_found_by_test.py | 28 +++ tst/unit/eval/resolve_test.py | 3 +- tst/unit/plugins/__init__.py | 0 tst/unit/plugins/provenance_test.py | 52 ++++ tst/unit/task/run_lock_test.py | 226 ++++++++++++++++++ 23 files changed, 797 insertions(+), 104 deletions(-) create mode 100644 src/agent_env/eval/intent.py create mode 100644 src/agent_env/plugins/_provenance.py create mode 100644 src/agent_env/task/run_lock.py create mode 100644 tst/unit/artifact/image_identity_test.py create mode 100644 tst/unit/config/config_found_by_test.py create mode 100644 tst/unit/plugins/__init__.py create mode 100644 tst/unit/plugins/provenance_test.py create mode 100644 tst/unit/task/run_lock_test.py diff --git a/AGENTS.md b/AGENTS.md index 9b7a55c6c..8a64a850d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -191,7 +191,7 @@ and deserialized through a registry. | `training/` | One module per outside trainer, each behind its own extra, and the modules they share; [Training helpers](#training-helpers) lists them. | | `runner/` | The `[runner]` seam: `Runner.submit()` returns a `RunHandle` (`run_id`, `instance_id`) before the run starts; `LocalRunner` is built in. A runner declares `runs_outlive_submitter` (its runs keep going after the process that submitted them stops) and `retries_infra` (it runs a run again itself after an infrastructure failure), both False by default and for `LocalRunner`. `runner/store.py` is the run index every runner writes and the explorer reads. | | `bundle/` | A bundle is a folder of entities (`envs/`, `agents/`, `artifacts/`, `skills/`, `tasks/.json`, a JSON array of steps or `{"headline_verifiers": [...], "steps": [...]}`, `evals/.toml`) that runs without a registry: `agent-env run` plans it, writes it into the `@local` namespace (reusing each version whose inputs haven't changed) and runs its evals or tasks; `agent-env run hf:///[@][/]` (`bundle/hub.py`) runs one from a Hugging Face Hub dataset, picked from the commit's file list (the path, else `bundles/`, else the root) and downloaded alone with the card into a folder per commit, under ids rooted at `@hf//`, which only that path produces, each run's context recording the commit (`metadata["bundle_source"]`); `agent-env bundle init` writes a stored task or eval as one, with every env, agent and artifact it uses in its own folder (each image as its build context, pruned to what its Dockerfile reads and pinned to the Python and npm versions of the stored image, or, given `--image-ref ID=REF`, as that registry image pinned by digest with its context beside it, `image = { ref, dockerfile }`, which a run pulls and builds only when it can't; `task_images` lists the images an import writes, downloading nothing, so an export can push them first; a computer env as its base, driver and apps, each with its files, never what it composed, which a run of the folder composes, and an env or artifact of an installed bundle, there or anywhere an entity names one, by its id) so it runs with no store; `agent-env bundle register` writes a folder into the configured stores under registry ids (``, and an installed bundle's agent, env or artifact a reference pulls in under its alias, an env only into a shared store), each task and eval naming the versions it reads and each image it builds pushed, through a ledger in the target store so registering again writes only what changed. | -| `eval/` | `Eval` (`eval`), a versioned list of task references, and its store. `eval/instance.py` is the eval instance, the record of one eval run (`EvalInstance`, its status, source, settings and runner declarations), and its slots, one per task and replica (`task_id@version#i`), each with its attempts, the runs that filled it, oldest first, each with how it ended and its result; attempt n of a slot is submitted under the idempotency key `attempt_key(instance, slot, n)`. `eval/instance_store.py` keeps them in `eval_instances` and `eval_slots`, one document per slot, all in the eval's namespace, so the instance document never grows with tasks or runs: creation writes the slots first and the instance last, a retry finishing it. After creation one process at a time drives an instance, through the `DriverLease` `take_driver` gives it for a holder name from `new_driver_holder()` (renewed within `DRIVER_LEASE_SECONDS`); every write goes through the lease and names its `driver_epoch`, which moves on each take and release, and is refused (`LeaseLostError`) once the lease has moved on, a slot write also when the slot carries a later epoch. Every take gets an epoch of its own (the same holder taking again, as a resent take does, takes it anew), and taking over a lease someone held writes the new epoch into every slot before the take returns. A slot write is checked against the slot as read (a run is added once, only as the next attempt and only once the last has ended, an attempt ends once, and a result lands only for the last attempt), and every write can be sent again after its answer was lost. `DriverLease.release` sets the status the instance ends in and the final summary (always written, None clearing it) in the write that lets the lease go, refused (`WritesInFlightError`) while the lease's slot writes haven't ended, so `EvalInstance.final_summary` is the summary once no driver holds the instance. Records are stored as JSON without per-run secrets, read leniently, so a value a newer version wrote loads as stored, and written field by field, so a field this version doesn't know is kept. Nothing writes them yet. `eval/resolve.py` resolves an instance before its first run (`resolve`): for each task, every env, agent and artifact its runs read (its steps' `entity_refs` in the fields a run reads, `TaskStep.run_fields`, which a step whose overrides follow rules of their own, such as `deploy_agent`'s, overrides with the method its run uses; the default agent for an agent field left unset, an `agent_artifact_id`, and the infra envs of a task that deploys one), each read once per instance with the children it loads (`entity/pins.py` `recording`), the ones read at their latest pinned, except an id the task writes, an installed bundle's alias, or one missing from the store; it gives each task's runs their `pins` (`Resolution.run_overrides`), as `eval run` does. Its records (`eval/lock.py`) are the instance's `intent_lock` (each role's model and endpoint host, the overrides without secrets, the result rules version, the package versions) and each slot's `lock` (the task's content hash, whether its version floated, and what it reads). | +| `eval/` | `Eval` (`eval`), a versioned list of task references, and its store. `eval/instance.py` is the eval instance, the record of one eval run (`EvalInstance`, its status, source, settings and runner declarations), and its slots, one per task and replica (`task_id@version#i`), each with its attempts, the runs that filled it, oldest first, each with how it ended and its result; attempt n of a slot is submitted under the idempotency key `attempt_key(instance, slot, n)`. `eval/instance_store.py` keeps them in `eval_instances` and `eval_slots`, one document per slot, all in the eval's namespace, so the instance document never grows with tasks or runs: creation writes the slots first and the instance last, a retry finishing it. After creation one process at a time drives an instance, through the `DriverLease` `take_driver` gives it for a holder name from `new_driver_holder()` (renewed within `DRIVER_LEASE_SECONDS`); every write goes through the lease and names its `driver_epoch`, which moves on each take and release, and is refused (`LeaseLostError`) once the lease has moved on, a slot write also when the slot carries a later epoch. Every take gets an epoch of its own (the same holder taking again, as a resent take does, takes it anew), and taking over a lease someone held writes the new epoch into every slot before the take returns. A slot write is checked against the slot as read (a run is added once, only as the next attempt and only once the last has ended, an attempt ends once, and a result lands only for the last attempt), and every write can be sent again after its answer was lost. `DriverLease.release` sets the status the instance ends in and the final summary (always written, None clearing it) in the write that lets the lease go, refused (`WritesInFlightError`) while the lease's slot writes haven't ended, so `EvalInstance.final_summary` is the summary once no driver holds the instance. Records are stored as JSON without per-run secrets, read leniently, so a value a newer version wrote loads as stored, and written field by field, so a field this version doesn't know is kept. Nothing writes them yet. `eval/resolve.py` resolves an instance before its first run (`resolve`): for each task, every env, agent and artifact its runs read (its steps' `entity_refs` in the fields a run reads, `TaskStep.run_fields`, which a step whose overrides follow rules of their own, such as `deploy_agent`'s, overrides with the method its run uses; the default agent for an agent field left unset, an `agent_artifact_id`, and the infra envs of a task that deploys one), each read once per instance with the children it loads (`entity/pins.py` `recording`), the ones read at their latest pinned, except an id the task writes, an installed bundle's alias, or one missing from the store; it gives each task's runs their `pins` (`Resolution.run_overrides`), as `eval run` does. Its intent is computed by `eval/intent.py`, as each run's own (`task/run_lock.py`) is. Its records (`eval/lock.py`) are the instance's `intent_lock` (each role's model and endpoint host, the overrides without secrets, the result rules version, the package versions) and each slot's `lock` (the task's content hash, whether its version floated, and what it reads). | | `plugins/` | Entry-point plugins (see Extension points): the group names, `inventory()`, which `agent-env plugin list/show/check` report, `load_failures` and `settings`. The top level is public; the underscored modules are internal. | | `explorer/` | Optional local web UI: `agent-env up`, binds loopback `:8234`. | | `cli/` | Click CLI with the groups `a2a-agent`, `artifact`, `bundle`, `config`, `env`, `eval`, `plugin`, `run`, `task`, `up`. `task run`, `task run-batch` and `eval run` hand their runs to the configured `[runner]` and follow them. | @@ -474,6 +474,15 @@ orchestrators call it the same way. What callers rely on: references it did not create. - A run is resumable: pass a previously persisted `context`, a `start_step` and the existing `instance_id`; completed steps are seeded as SUCCESS. +- Each attempt a process starts records, on the instance and by its `attempt_epoch`, the code that ran it and what + it was asked to do and read (`task/run_lock.py`, `run_recorded`): `runtime` (the core, protocol and Python versions, + 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`; never a path) and `lock` (`intent`: the task's content + hash, pins, each role's model and endpoint host as this process resolves them, the overrides without secrets, the + result rules version, computed as the eval plan computes its own, `eval/intent.py`; `resolved`: each verifier's + settings and version at the start and every entity version the run read, each image with its `image_identity`). + Both are written at the start and again when the run ends, however it ends; a resume adds its own entries. A + worker that runs a task's steps itself enters `run_recorded` around them, as it sets `run_pins`. - 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/a2a_agent/a2a_agent.py b/src/agent_env/a2a_agent/a2a_agent.py index 70f7b80b5..ef8525e83 100644 --- a/src/agent_env/a2a_agent/a2a_agent.py +++ b/src/agent_env/a2a_agent/a2a_agent.py @@ -498,14 +498,14 @@ def get(cls, id: str, version: Optional[int] = None) -> A2AAgent: raise NotFoundError(f"{id!r} is an alias of {named.target_id}, which comes with " f"{named.declared_by}, so it has no fixed version; drop the pin") from None else: - note_read(EntityKind.AGENT, id, asked, agent.version) + note_read(EntityKind.AGENT, id, asked, agent) return agent try: agent = store.get(named.target_id) except NotFoundError: raise NotFoundError(f"{id!r} is an alias of {named.target_id}, which comes with {named.declared_by} and " "isn't in the store yet: an `agent-env run` of a bundle that uses it writes it") from None - note_read(EntityKind.AGENT, id, asked, agent.version, alias=True) + note_read(EntityKind.AGENT, id, asked, agent, alias=True) return agent @classmethod diff --git a/src/agent_env/artifact/artifact.py b/src/agent_env/artifact/artifact.py index 0a1ecb6f7..5f48c063e 100644 --- a/src/agent_env/artifact/artifact.py +++ b/src/agent_env/artifact/artifact.py @@ -72,7 +72,7 @@ def get(cls, id: str, version: Optional[int] = None) -> Self: artifact = get_artifact_store().get(id, pinned_version(EntityKind.ARTIFACT, id, version)) if not isinstance(artifact, cls): raise TypeError(f"artifact {id!r} is a {artifact.type!r} artifact, not a {cls.__name__}") - note_read(EntityKind.ARTIFACT, id, version, artifact.version) + note_read(EntityKind.ARTIFACT, id, version, artifact) return artifact @classmethod diff --git a/src/agent_env/artifact/artifacts/docker_image.py b/src/agent_env/artifact/artifacts/docker_image.py index 5aa938752..2f5663e78 100644 --- a/src/agent_env/artifact/artifacts/docker_image.py +++ b/src/agent_env/artifact/artifacts/docker_image.py @@ -303,6 +303,16 @@ def pinned_name(self) -> str: """What a sandbox pulls: ``image_name`` pinned to the ``image_digest`` when it records one.""" return f"{self.image_name}@{self.image_digest}" if self.image_digest else self.image_name + @property + def image_identity(self) -> str | None: + """What the image is, whichever build of it ran: ``source:``, its build context's content hash, when it + has one, so a rebuild of the same context is the same image; else ``registry:``, the digest it is + pinned to; None for an image held only as a tarball, which this artifact's version names.""" + if self.source_digest: + return f"source:{self.source_digest}" + digest = self.image_digest or self.image_name.partition("@")[2] + return f"registry:{digest}" if digest else None + @property def context_only(self) -> bool: """Whether only the image's build context is stored: no tar.gz, and an image name that names no registry, the diff --git a/src/agent_env/config/loader.py b/src/agent_env/config/loader.py index e6a903936..2320d5d15 100644 --- a/src/agent_env/config/loader.py +++ b/src/agent_env/config/loader.py @@ -41,6 +41,10 @@ SEAM_KEYS = ("impl", "config") +# How the config file in effect was found, as a run records it: never its path. +FOUND_BY_ENVIRONMENT, FOUND_BY_DISCOVERY, FOUND_BY_NONE = "environment", "discovered", "none" + + def discover_config_path(start: Optional[Path] = None) -> Optional[Path]: """Locate the config.toml: ``AGENT_ENV_CONFIG`` wins, else the nearest ``.agentenv/config.toml`` walking up from ``start`` (CWD by default). @@ -48,16 +52,22 @@ def discover_config_path(start: Optional[Path] = None) -> Optional[Path]: An explicit ``AGENT_ENV_CONFIG`` override must point to an existing file — fail loud rather than silently drop the whole config (and derive local-store paths from a non-existent directory) on a typo'd override path.""" + return discover_config(start)[0] + + +def discover_config(start: Optional[Path] = None) -> tuple[Optional[Path], str]: + """``discover_config_path``'s answer, and how it was found: ``environment`` (``AGENT_ENV_CONFIG``, which a plugin + may set), ``discovered`` (walking up) or ``none``.""" override = os.getenv(ENV_CONFIG_PATH) if override: path = Path(override) if not path.is_file(): raise ConfigError(f"{ENV_CONFIG_PATH}={override!r} does not point to an existing file") - return path + return path, FOUND_BY_ENVIRONMENT for candidate in _walk_up_candidates(start): if candidate.is_file(): - return candidate - return None + return candidate, FOUND_BY_DISCOVERY + return None, FOUND_BY_NONE def _walk_up_candidates(start: Optional[Path] = None) -> list[Path]: diff --git a/src/agent_env/config/runtime.py b/src/agent_env/config/runtime.py index 1967dd765..0d81aebce 100644 --- a/src/agent_env/config/runtime.py +++ b/src/agent_env/config/runtime.py @@ -701,6 +701,10 @@ def section(self, *names: str) -> Mapping[str, Any]: """The config table at ``names``: ``{}`` when absent, an error when mis-shaped.""" return self._document().section(*names) + def config_found_by(self) -> str: + """How the config file this Config reads was found (``loader.discover_config``), never its path.""" + return self._document().found_by + def config_path(self) -> Optional[Path]: """The config.toml this Config resolves against. The process resolves one document, so every section and every local-store path agree about which file they came from.""" diff --git a/src/agent_env/config/snapshot.py b/src/agent_env/config/snapshot.py index 6f9a6ef46..c7582506c 100644 --- a/src/agent_env/config/snapshot.py +++ b/src/agent_env/config/snapshot.py @@ -17,11 +17,12 @@ @dataclass(frozen=True) class Snapshot: - """Where the document came from, and what it said.""" + """Where the document came from, how it was found (``loader.discover_config``), and what it said.""" path: Optional[Path] _document: Mapping[str, Any] error: Optional[Exception] = None + found_by: str = loader.FOUND_BY_NONE def section(self, *names: str) -> Mapping[str, Any]: """The table at ``names`` as a copy; ``{}`` when absent, an error when mis-shaped. @@ -58,24 +59,24 @@ def _require_table(node: Any, walked: list) -> None: ) -def _parse(path: Optional[Path]) -> Snapshot: +def _parse(path: Optional[Path], found_by: str = loader.FOUND_BY_NONE) -> Snapshot: """A parse error rides on the snapshot so the path stays reportable — `config show` needs to name the file most when the file is the broken thing.""" if path is None: - return Snapshot(path=None, _document={}) + return Snapshot(path=None, _document={}, found_by=found_by) try: # A strict read, with no existence check in front of it: discovery returned this # path a moment ago, so a missing file is a race and must be loud. Checking first # and reading second would only narrow the window, which is not the same as closing # it — the open is the check. - return Snapshot(path=path, _document=loader.read_config_file(path)) + return Snapshot(path=path, _document=loader.read_config_file(path), found_by=found_by) except FileNotFoundError: - return Snapshot(path=path, _document={}, error=ConfigError( + return Snapshot(path=path, _document={}, found_by=found_by, error=ConfigError( f"config.toml at {path} vanished between discovery and read")) except (ConfigError, OSError) as e: - return Snapshot(path=path, _document={}, error=e) + return Snapshot(path=path, _document={}, found_by=found_by, error=e) def resolve() -> Snapshot: """Discover and parse, with no caching — the Config holds the result.""" - return _parse(loader.discover_config_path()) + return _parse(*loader.discover_config()) diff --git a/src/agent_env/entity/pins.py b/src/agent_env/entity/pins.py index 30ba467af..045f87a77 100644 --- a/src/agent_env/entity/pins.py +++ b/src/agent_env/entity/pins.py @@ -16,7 +16,7 @@ from collections.abc import Iterator, Mapping from contextlib import contextmanager from contextvars import ContextVar -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import Any, Optional from agent_env.entity.refs import EntityKind @@ -34,13 +34,17 @@ class Read: """One read of an entity: ``asked`` is the version asked for, None for the latest, and ``version`` the one read. ``alias`` marks an id that named an installed bundle's entity rather than one of the store's, which takes no - pin: its version is the installed bundle's.""" + pin: its version is the installed bundle's. ``type`` is the entity's type and ``cls`` its class, which says the + distribution that supplied it; ``image_identity`` is an image's (``DockerImageArtifact.image_identity``).""" kind: EntityKind id: str asked: Optional[int] version: int alias: bool = False + type: Optional[str] = None + cls: Optional[type] = field(default=None, compare=False) + image_identity: Optional[str] = None def checked_pins(value: Any) -> dict[str, dict[str, int]]: @@ -108,10 +112,12 @@ def recording(pins: Optional[dict[str, dict[str, int]]] = None) -> Iterator[list _RECORDING.reset(token) -def note_read(kind: EntityKind, entity_id: str, asked: Optional[int], version: int, *, alias: bool = False) -> None: - """Add a read to the block ``recording`` is listing, if any, pinning it there when it was read at its latest.""" +def note_read(kind: EntityKind, entity_id: str, asked: Optional[int], entity: Any, *, alias: bool = False) -> None: + """Add the read of ``entity`` to the block ``recording`` is listing, if any, pinning it there when it was read at + its latest.""" if (record := _RECORDING.get()) is None: return - record.reads.append(Read(kind, entity_id, asked, version, alias)) + record.reads.append(Read(kind, entity_id, asked, entity.version, alias, getattr(entity, "type", None), + type(entity), getattr(entity, "image_identity", None))) if record.pins is not None and asked is None and not alias: - record.pins.setdefault(str(kind), {}).setdefault(entity_id, version) + record.pins.setdefault(str(kind), {}).setdefault(entity_id, entity.version) diff --git a/src/agent_env/env/env.py b/src/agent_env/env/env.py index 7a63063b9..c097ee2ca 100644 --- a/src/agent_env/env/env.py +++ b/src/agent_env/env/env.py @@ -361,7 +361,7 @@ def get(cls, id: str, version: Optional[int] = None) -> "Env": if named is None: raise NotFoundError(refusal) from None else: - note_read(EntityKind.ENV, id, asked, env.version) + note_read(EntityKind.ENV, id, asked, env) return env if not namespace_routing_enabled(): raise NotFoundError(f"{id!r} is an alias of {named.target_id}, which comes with {named.declared_by}, and " @@ -374,7 +374,7 @@ def get(cls, id: str, version: Optional[int] = None) -> "Env": "isn't in the store yet: an `agent-env run` of a bundle that uses it writes it") from None env = copy.copy(env) env._stored_id, env.id = env.id, id - note_read(EntityKind.ENV, id, asked, env.version, alias=True) + note_read(EntityKind.ENV, id, asked, env, alias=True) return env @property diff --git a/src/agent_env/eval/intent.py b/src/agent_env/eval/intent.py new file mode 100644 index 000000000..b5258a447 --- /dev/null +++ b/src/agent_env/eval/intent.py @@ -0,0 +1,59 @@ +"""What a run of a task is asked to do, computed the same way by an eval's plan (``agent_env.eval.resolve``) and by +each run on the process that runs it (``agent_env.task.run_lock``), so the two compare: the task's content hash, the +overrides a run reads, each role's model and the host its calls go to, and those overrides as a record keeps them. +""" + +from __future__ import annotations + +import hashlib +from typing import TYPE_CHECKING, Any, Mapping, Optional + +from agent_env.config import get_config +from agent_env.config.errors import ConfigError +from agent_env.config.model import ModelRole, endpoint_host, run_endpoint, run_model, without_credentials +from agent_env.entity.pins import PINS_KEY +from agent_env.eval.lock import RoleModel +from agent_env.task_step.context import strip_redacted_keys +from agent_env.utils.canonical import canonical_json + +if TYPE_CHECKING: + from agent_env.task import Task + + +def content_hash(task: "Task") -> str: + """A hash of what the task runs, without its id and version, which a lock records beside it: a version that + republishes the same content hashes the same.""" + content = {key: value for key, value in task.to_dict().items() if key not in ("id", "version")} + return "sha256:" + hashlib.sha256(canonical_json(content)).hexdigest() + + +def run_overrides(user_overrides: Mapping[str, Any], *, agent_model: Optional[str] = None, + agent_artifact_id: Optional[str] = None) -> dict[str, Any]: + """The overrides a run reads, without its pins, which a lock records apart: ``user_overrides`` with the run's + ``agent_model`` and ``agent_artifact_id``, which ``Task.run`` takes beside them.""" + overrides = {key: value for key, value in user_overrides.items() if key != PINS_KEY} + overrides.update({key: value for key, value in (("agent_model", agent_model), + ("agent_artifact_id", agent_artifact_id)) if value}) + return overrides + + +def role_models(overrides: Mapping[str, Any]) -> dict[str, RoleModel]: + """Each role's model where no step or agent names one, as this process's config resolves it with ``overrides``, + and the host its calls go to, by the role's name.""" + config = get_config() + try: + configured = config.get_litellm_base_url() + except ConfigError: + configured = None + roles = {} + for role in ModelRole: + resolved = config.resolve_model(role, run=run_model(role, overrides)) + roles[role.value] = RoleModel(resolved.model, None if resolved.source is None else str(resolved.source), + endpoint_host(run_endpoint(role, overrides) or configured)) + return roles + + +def recorded_overrides(overrides: Mapping[str, Any]) -> dict[str, Any]: + """``overrides`` without secrets, at any depth (a step's ``step_params`` included): each endpoint override as its + host, and no URL with a user or password in it.""" + return without_credentials(strip_redacted_keys(dict(overrides))) diff --git a/src/agent_env/eval/resolve.py b/src/agent_env/eval/resolve.py index 1f125e671..c0a6aa4ee 100644 --- a/src/agent_env/eval/resolve.py +++ b/src/agent_env/eval/resolve.py @@ -14,29 +14,24 @@ from __future__ import annotations -import hashlib from dataclasses import dataclass -from importlib.metadata import PackageNotFoundError, version as package_version from typing import Any, Mapping, Optional, Sequence from agent_env.a2a_agent import A2AAgent from agent_env.artifact import Artifact from agent_env.config import get_config, run_env_ids -from agent_env.config.errors import ConfigError -from agent_env.config.model import ModelRole, endpoint_host, run_endpoint, run_model, without_credentials from agent_env.config.runtime import infra_env_ids from agent_env.entity.pins import PINNED_KINDS, PINS_KEY, Read, recording from agent_env.entity.refs import EntityKind, RefRole, default_agent_refs, ref_sites from agent_env.env.env import Env -from agent_env.eval.lock import IntentLock, LockedRead, RoleModel, TaskLock, Unread, UnreadRef +from agent_env.eval.intent import content_hash, recorded_overrides, role_models, run_overrides +from agent_env.eval.lock import IntentLock, LockedRead, TaskLock, Unread, UnreadRef +from agent_env.plugins._requirements import CORE, installed from agent_env.store.base import NotFoundError from agent_env.store.routing import local_namespace, run_scope from agent_env.task import Task from agent_env.task.result import RESULT_RULES_VERSION -from agent_env.task_step.context import TaskStepContext, strip_redacted_keys -from agent_env.utils.canonical import canonical_json - -PACKAGES = ("agentenv-framework", "agentenv-framework-protocol") +from agent_env.task_step.context import TaskStepContext _GETTERS = {EntityKind.ENV: Env.get, EntityKind.AGENT: A2AAgent.get, EntityKind.ARTIFACT: Artifact.get} @@ -66,52 +61,13 @@ def resolve(tasks: Sequence[tuple[Task, bool]], user_overrides: Mapping[str, Any locks) -def content_hash(task: Task) -> str: - """A hash of what the task runs, without its id and version, which its lock records beside it: a version that - republishes the same content hashes the same.""" - content = {key: value for key, value in task.to_dict().items() if key not in ("id", "version")} - return "sha256:" + hashlib.sha256(canonical_json(content)).hexdigest() - - def intent_lock(user_overrides: Mapping[str, Any], *, agent_model: Optional[str] = None, agent_artifact_id: Optional[str] = None) -> IntentLock: """The intent every run shares: each role's model and endpoint host, the overrides, the result rules version and the package versions.""" - overrides = {key: value for key, value in user_overrides.items() if key != PINS_KEY} - overrides.update({key: value for key, value in (("agent_model", agent_model), - ("agent_artifact_id", agent_artifact_id)) if value}) - return IntentLock(roles=_roles(overrides), overrides=_recorded_overrides(overrides), - result_rules_version=RESULT_RULES_VERSION, packages=_packages()) - - -def _roles(overrides: Mapping[str, Any]) -> dict[str, RoleModel]: - config = get_config() - try: - configured = config.get_litellm_base_url() - except ConfigError: - configured = None - roles = {} - for role in ModelRole: - resolved = config.resolve_model(role, run=run_model(role, overrides)) - roles[role.value] = RoleModel(resolved.model, None if resolved.source is None else str(resolved.source), - endpoint_host(run_endpoint(role, overrides) or configured)) - return roles - - -def _recorded_overrides(overrides: Mapping[str, Any]) -> dict[str, Any]: - """``overrides`` without secrets, at any depth (a step's ``step_params`` included): each endpoint override as its - host, and no URL with a user or password in it.""" - return without_credentials(strip_redacted_keys(dict(overrides))) - - -def _packages() -> dict[str, Optional[str]]: - versions = {} - for name in PACKAGES: - try: - versions[name] = package_version(name) - except PackageNotFoundError: - versions[name] = None - return versions + overrides = run_overrides(user_overrides, agent_model=agent_model, agent_artifact_id=agent_artifact_id) + return IntentLock(roles=role_models(overrides), overrides=recorded_overrides(overrides), + result_rules_version=RESULT_RULES_VERSION, packages={name: installed(name) for name in CORE}) class _Resolver: diff --git a/src/agent_env/plugins/__init__.py b/src/agent_env/plugins/__init__.py index 88b509e9e..a3bed7d0b 100644 --- a/src/agent_env/plugins/__init__.py +++ b/src/agent_env/plugins/__init__.py @@ -11,7 +11,8 @@ ``settings`` reads them. This package's top level is the public surface: the group names, ``load_failures``, ``settings``, -and ``inventory`` with the types it returns; its underscored modules are internal. The codes the +``inventory`` with the types it returns, and the provenance a run records (``distribution_of``, +``distribution_version``, ``installed_plugins``, ``install_origin``); its underscored modules are internal. The codes the inventory reports are stable; reason text is not. """ @@ -26,6 +27,7 @@ Status, inventory, ) +from agent_env.plugins._provenance import distribution_of, distribution_version, install_origin, installed_plugins from agent_env.plugins._registration import ( ARTIFACTS, ENV_PROVIDERS, @@ -52,6 +54,10 @@ "Inventory", "Replacement", "Status", + "distribution_of", + "distribution_version", + "install_origin", + "installed_plugins", "inventory", "load_failures", "settings", diff --git a/src/agent_env/plugins/_provenance.py b/src/agent_env/plugins/_provenance.py new file mode 100644 index 000000000..62b5afa1f --- /dev/null +++ b/src/agent_env/plugins/_provenance.py @@ -0,0 +1,89 @@ +"""Which installed distribution supplies a class, which agent-env plugins are installed, and how a distribution was +installed, read from installed metadata alone, so nothing is imported to answer. A run records these +(``agent_env.task.run_lock``) so two runs of a task can be told apart by the code that ran them.""" + +from __future__ import annotations + +import functools +import json +from importlib.metadata import Distribution, PackageNotFoundError, distribution, entry_points, packages_distributions +from typing import Optional, Union + +from packaging.utils import canonicalize_name + +from agent_env.plugins._requirements import CORE, distribution_holding, installed + +FRAMEWORK, PROTOCOL = CORE +_OWN = {"agent_env": FRAMEWORK, "agentenv_protocol": PROTOCOL} +_GROUP_PREFIX = "agent_env." + + +def distribution_of(target: Union[type, str]) -> Optional[str]: + """The distribution that supplies ``target``, a class or its ``module:Class`` path, as a registry holds it: + agent-env's own for its modules; else the one whose entry point names it; else the one whose files hold its module; + None when none can be told, as for a module on the path.""" + module, name = (target.split(":", 1) if isinstance(target, str) else (target.__module__, target.__qualname__)) + if own := _OWN.get(module.partition(".")[0]): + return own + if declared := _entry_point_classes().get(f"{module}:{name}"): + return declared + holder = distribution_holding(module, _packages()) + return canonicalize_name(holder) if holder else None + + +def distribution_version(target: Union[type, str]) -> Optional[str]: + """The installed version of the distribution that supplies ``target``; None when none can be told.""" + name = distribution_of(target) + return installed(name) if name else None + + +@functools.cache +def installed_plugins() -> dict[str, Optional[str]]: + """Every installed distribution declaring an agent-env entry point, by name, with its version.""" + plugins = {} + for point in entry_points(): + if point.group.startswith(_GROUP_PREFIX) and point.dist is not None: + name = canonicalize_name(point.dist.name) + if name not in CORE: + plugins.setdefault(name, point.dist.version) + return dict(sorted(plugins.items())) + + +def install_origin(name: str) -> Optional[str]: + """How ``name`` was installed, as a kind and never a path: ``index``, ``vcs@``, ``editable`` or ``local``; + None when it isn't installed.""" + try: + found = distribution(name) + except PackageNotFoundError: + return None + return _origin(found) + + +def _origin(found: Distribution) -> str: + text = found.read_text("direct_url.json") + if not text: + return "index" + try: + direct = json.loads(text) + except ValueError: + return "local" + if commit := (direct.get("vcs_info") or {}).get("commit_id"): + return f"vcs@{commit}" + if (direct.get("dir_info") or {}).get("editable"): + return "editable" + return "local" + + +@functools.cache +def _entry_point_classes() -> dict[str, str]: + """Each class an agent-env entry point names (``module:Class``), by the distribution declaring it.""" + classes: dict[str, str] = {} + for point in entry_points(): + if point.group.startswith(_GROUP_PREFIX) and point.dist is not None: + classes.setdefault(point.value.strip(), canonicalize_name(point.dist.name)) + return classes + + +@functools.cache +def _packages() -> dict: + return packages_distributions() diff --git a/src/agent_env/task/run_lock.py b/src/agent_env/task/run_lock.py new file mode 100644 index 000000000..0e8931d3b --- /dev/null +++ b/src/agent_env/task/run_lock.py @@ -0,0 +1,192 @@ +"""What each attempt of a run ran and was asked to do, recorded on its task instance by the process that runs its +steps, so two runs of a task, or a run and its resume, can be told apart and compared. + +Each attempt a process starts keeps an entry in each of two lists, by the ``attempt_epoch`` it started under; an attempt +a retry starts within the run belongs to the entry before it, since the same process runs it with the same code. + +- ``runtime``: the code that ran it. The core, protocol and Python versions; each installed agent-env plugin's version + and how it was installed (``index``, ``vcs@``, ``editable`` or ``local``); how the config file was found + (``loader.discover_config``); and the distribution supplying each type the run used, its steps' from the start and + the envs, artifacts and providers it used once it ends. Never a path. +- ``lock``: ``intent``, what it was asked to do, as the eval engine's plan computes it (``agent_env.eval.intent``): the + task's id, version and content hash, its pins, each role's model and the host its calls go to as this process's config + resolves them, its overrides without secrets, and the result rules version. And ``resolved``, what this process found: + each verifier's settings and version at the run's start, and, once the run ends, every entity version it read + (``entity.pins.recording``), each image with its identity, so a rebuild of an unchanged context reads as the same. + +Both are written when the run starts and again, with what it read, when it ends, however it ends, so a run that dies +midway keeps what it started with. A write that fails is logged, never failing the run. ``Task.run`` records them +through ``run_recorded``; a worker that runs a task's steps itself enters ``run_recorded`` around them the same way. +Reads made on a thread that doesn't carry the run's context, as the computer composer's pool, aren't listed. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import logging +import platform +from typing import TYPE_CHECKING, Any, AsyncIterator, Optional, Sequence + +from agent_env.config import get_config +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 ( + ARTIFACTS, + ENV_PROVIDERS, + ENVS, + SANDBOX_PROVIDERS, + TASK_STEPS, + distribution_of, + distribution_version, + install_origin, + installed_plugins, +) +from agent_env.plugins._provenance import FRAMEWORK, PROTOCOL +from agent_env.plugins._requirements import installed +from agent_env.task.result import RESULT_RULES_VERSION +from agent_env.task.store import record_run_lock +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 VerifierTaskStep + +if TYPE_CHECKING: + from agent_env.task import Task + +logger = logging.getLogger(__name__) + +RUN_LOCK_VERSION = 1 + + +def _group(entry_point_group: str) -> str: + """A registry's name in a record: its entry-point group's without the ``agent_env.`` prefix (``task_steps``).""" + return entry_point_group.removeprefix("agent_env.") + + +_READ_KINDS = {"env": _group(ENVS), "artifact": _group(ARTIFACTS)} + + +def runtime_entry(attempt_epoch: int, steps: Sequence[TaskStep]) -> dict[str, Any]: + """The ``runtime`` entry of an attempt this process starts, with its steps' types; ``finished_entries`` adds the + other types the run used.""" + return { + "attempt_epoch": attempt_epoch, + "agentenv_framework": installed(FRAMEWORK), + "agentenv_protocol": installed(PROTOCOL), + "python": platform.python_version(), + "plugins": {name: {"version": version, "origin": 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}}, + } + + +def lock_entry(task: "Task", steps: Sequence[TaskStep], context: TaskStepContext, attempt_epoch: int) -> dict[str, Any]: + """The ``lock`` entry of an attempt this process starts: its intent and what it resolved at the start. ``steps`` are + the steps it runs, 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) + return { + "attempt_epoch": attempt_epoch, + "lock_version": RUN_LOCK_VERSION, + "intent": { + "task_id": task.id, + "task_version": task.version, + "content_hash": content_hash(task), + "pins": checked_pins(user_overrides.get(PINS_KEY)), + "roles": {name: role.to_dict() for name, role in role_models(overrides).items()}, + "overrides": recorded_overrides(overrides), + "result_rules_version": RESULT_RULES_VERSION, + }, + "resolved": { + "verifiers": {step.id: {"type": step.type, "distribution": distribution_of(type(step)), + "version": distribution_version(type(step)), + "settings": step.recorded_settings(context)} + for step in steps if isinstance(step, VerifierTaskStep)}, + "reads": None, + }, + } + + +def finished_entries(runtime: dict[str, Any], lock: dict[str, Any], reads: Sequence[Read], + context: TaskStepContext) -> tuple[dict[str, Any], dict[str, Any]]: + """The attempt's entries once its run ends: ``reads``, every entity version it read, in its lock, and the types of + the envs, artifacts and providers it used in its runtime.""" + 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 name, impl in used.items(): + types.setdefault(group, {})[name] = distribution_of(impl) if impl is not None else None + return ({**runtime, "types": types}, + {**lock, "resolved": {**lock["resolved"], "reads": read_entries(reads)}}) + + +def read_entries(reads: Sequence[Read]) -> list[dict[str, Any]]: + """Each entity version ``reads`` name, once, in order: ``latest`` when any read asked for its latest, which the run's + pins answer when they name it; ``alias`` when it came through an installed bundle's alias.""" + entries: dict[tuple[str, str, int], dict[str, Any]] = {} + for read in reads: + key = (str(read.kind), read.id, read.version) + entry = entries.setdefault(key, {"kind": key[0], "id": read.id, "version": read.version, "type": read.type, + "latest": False, "alias": False}) + entry["latest"] = entry["latest"] or read.asked is None + entry["alias"] = entry["alias"] or read.alias + if read.image_identity: + entry["image_identity"] = read.image_identity + return [entries[key] for key in sorted(entries)] + + +@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.""" + started = await asyncio.to_thread(_started, instance_id, task, steps, context, attempt_epoch) if instance_id else None + if started is None: + yield + return + runtime, lock = started + with recording() as reads: + try: + yield + finally: + try: + runtime, lock = finished_entries(runtime, lock, list(reads), context) + except Exception: + logger.warning("The reads of attempt %s of %s couldn't be recorded", attempt_epoch, instance_id, + exc_info=True) + else: # a cancel can't stop the record: the write runs on, as the run's other end writes do + await asyncio.shield(asyncio.to_thread(record_run_lock, instance_id, runtime, lock)) + + +def _started(instance_id: str, task: "Task", steps: Sequence[TaskStep], context: TaskStepContext, + attempt_epoch: int) -> Optional[tuple[dict[str, Any], dict[str, Any]]]: + """The attempt's entries, recorded; None, logged, when they can't be made, so the run goes on unrecorded.""" + try: + runtime, lock = runtime_entry(attempt_epoch, steps), lock_entry(task, steps, context, attempt_epoch) + except Exception: + logger.warning("What attempt %s of %s runs couldn't be recorded", attempt_epoch, instance_id, exc_info=True) + return None + record_run_lock(instance_id, runtime, lock) + return runtime, lock + + +def _sandbox_types(context: TaskStepContext) -> dict[str, Any]: + """The sandbox types the run deployed on, each with its provider's ``module:Class`` or class as its registry holds + it; None for one this process doesn't register.""" + names = {d.sandbox_type for d in [*context.deployed_sandboxes, *context.deployed_agents] if d.sandbox_type} + names |= {d.sandbox_type for d in context.deployed_envs if getattr(d, "sandbox_type", None)} + registry = get_config().sandbox_registry() + return {name: (registry.get(name) or {}).get("impl") for name in sorted(names)} + + +def _env_provider_types(context: TaskStepContext) -> dict[str, Any]: + """The env provider types the run deployed through, each with its registered class; None for one this process + doesn't register.""" + names = sorted({d.env_provider_type for d in context.deployed_envs if d.env_provider_type}) + registry = get_config().env_provider_registry() + return {name: registry.get(name) for name in names} diff --git a/src/agent_env/task/store.py b/src/agent_env/task/store.py index 0999bcb66..a8c0a8cc5 100644 --- a/src/agent_env/task/store.py +++ b/src/agent_env/task/store.py @@ -49,6 +49,10 @@ _GENERATION = "run_generation" # The run's result, outside its context (``agent_env.task.result``): a grade version per grading, oldest first. RESULT_KEY = "result" +# What ran each attempt and what it read (``agent_env.task.run_lock``): an entry per attempt a process started, by its +# ``attempt_epoch``, kept across re-registers so a resume's entries sit beside the first run's. +RUNTIME_KEY = "runtime" +LOCK_KEY = "lock" # Where a submitter names the eval slot a run fills, in ``context.metadata``: ``{eval_instance_id, slot, attempt}``, # which registering the run keeps as the instance's own fields. EVAL_SLOT_KEY = "eval_slot" @@ -204,6 +208,9 @@ class TaskInstance: attempt: int | None = None # A grade version per grading of the run, oldest first; empty until the run ends. result: list[dict] = field(default_factory=list) + # An entry per attempt a process started, by attempt_epoch: the code that ran it and what it was asked and read. + runtime: list[dict] = field(default_factory=list) + lock: list[dict] = field(default_factory=list) @classmethod def from_dict(cls, data: dict) -> TaskInstance: @@ -228,6 +235,8 @@ def from_dict(cls, data: dict) -> TaskInstance: slot=data.get("slot"), attempt=data.get("attempt"), result=data.get(RESULT_KEY) or [], + runtime=data.get(RUNTIME_KEY) or [], + lock=data.get(LOCK_KEY) or [], ) @@ -295,6 +304,8 @@ def _new_instance_doc( _GENERATION: 0, LEDGER_KEY: [], TOTAL_KEY: total([]), + RUNTIME_KEY: [], + LOCK_KEY: [], **run_state, } @@ -889,6 +900,22 @@ def _mutate(doc: dict) -> UpdateSpec | None: return compare_and_swap(self._doc_store, TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id), _mutate, counter_field=_REV) is not None + def record_run_lock_sync(self, instance_id: str, runtime: dict, lock: dict) -> bool: + """Keep an attempt's ``runtime`` and ``lock`` entries, in place of any the attempt (their ``attempt_epoch``) + kept before, so the same write sent again, or a run's end replacing its start, keeps one of each; whether the + instance was found. Entries of other attempts stay, a later one's included, since each describes its own.""" + epoch = runtime["attempt_epoch"] + + def _mutate(doc: dict) -> UpdateSpec: + def replaced(entries: list | None, entry: dict) -> list[dict]: + kept = [e for e in entries or [] if e.get("attempt_epoch") != epoch] + return sorted([*kept, entry], key=lambda e: e.get("attempt_epoch", 0)) + return UpdateSpec(set={RUNTIME_KEY: replaced(doc.get(RUNTIME_KEY), runtime), + LOCK_KEY: replaced(doc.get(LOCK_KEY), lock)}) + + return compare_and_swap(self._doc_store, TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id), + _mutate, counter_field=_REV) is not None + def record_teardown_sync(self, instance_id: str, context: "TaskStepContext", attempt_epoch: int) -> None: """Keep the context a run's teardown ended with: what the run deployed, writes of a step a signal cut short included, and what the teardown took down and left up, unless an attempt later than ``attempt_epoch``, the @@ -1184,6 +1211,14 @@ def _retried(write: Callable[[], _T], failed: _T, what: str) -> _T: logger.warning("Failed to %s after %d attempts", what, _FAILURE_WRITE_MAX_ATTEMPTS, exc_info=last_exc) return failed +def record_run_lock(instance_id: str, runtime: dict, lock: dict) -> bool: + """``TaskInstanceStore.record_run_lock_sync``, retried like the run's other records; whether it was kept. A write + that keeps failing is logged rather than raised: a run isn't failed for its record of what ran.""" + store = get_task_instance_store() + return _retried(lambda: store.record_run_lock_sync(instance_id, runtime, lock), False, + f"record what attempt {runtime['attempt_epoch']} of instance_id={instance_id} ran") + + def record_result(instance_id: str, result: list[dict], attempt_epoch: int | None = None) -> bool: """``TaskInstanceStore.record_result_sync``, retried like ``record_task_failure``; whether it was set. A write that keeps failing is logged rather than raised: the run's own state is recorded either way, and a result left diff --git a/src/agent_env/task/task.py b/src/agent_env/task/task.py index 7132618fd..00b6f50c4 100644 --- a/src/agent_env/task/task.py +++ b/src/agent_env/task/task.py @@ -27,6 +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.teardown import env_record_ids from agent_env.task.usage.ledger import entries_of from agent_env.task.usage.running import running_usage @@ -612,15 +613,16 @@ async def _run( state = self._build_scheduler_state(steps, start_step, end_step) if instance: state.epoch = instance.attempt_epoch - # _drive_dag drains in-flight steps and records the failure itself if it raises. - first_error, first_error_step_id = await self._drive_dag( - steps, state, total, context, instance_id, - on_step_start, on_step_complete, log_prefix, - ) - if first_error is not None: - await self._handle_failure(first_error_step_id, first_error, steps, context, instance_id, state.epoch) - elif instance_id and (end_step is None or end_step == total): - await record_run_end(instance_id, steps, context, state.epoch) + async with run_recorded(instance_id, self, steps, context, state.epoch): + # _drive_dag drains in-flight steps and records the failure itself if it raises. + first_error, first_error_step_id = await self._drive_dag( + steps, state, total, context, instance_id, + on_step_start, on_step_complete, log_prefix, + ) + if first_error is not None: + await self._handle_failure(first_error_step_id, first_error, steps, context, instance_id, state.epoch) + elif instance_id and (end_step is None or end_step == total): + await record_run_end(instance_id, steps, context, state.epoch) return context async def _drive_dag( 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 11a21e3a9..af568a77f 100644 --- a/src/agent_env/task_step/task_steps/verifiers/verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/verifier.py @@ -12,13 +12,10 @@ from abc import abstractmethod from dataclasses import dataclass, field from enum import Enum -from importlib.metadata import packages_distributions from typing import Any, ClassVar, Optional, TypedDict -from packaging.utils import canonicalize_name - from agent_env.config import get_config -from agent_env.plugins import _requirements +from agent_env.plugins import distribution_version from agent_env.task_step.context import TaskStepContext from agent_env.task_step.task_step import RetryConfig, StepRole, TaskStep, TaskStepDependency from agent_env.task_step.task_steps.verifiers.scoring import ScoreAggregator, aggregate_score @@ -41,7 +38,6 @@ # min_passing_score, which the grade holds itself. _NOT_SETTINGS = ("id", "type", "version", "depends_on", "fail_task_on_error", "retry_config", "verifier_id", "min_passing_score") -_FRAMEWORK = "agentenv-framework" class VerifierStatus(str, Enum): @@ -221,8 +217,8 @@ def _grade(self, context: TaskStepContext, status: VerifierStatus, score: Option verifier_output=None, verifier_criteria=rows, verifier_type=self.type, - verifier_version=_providing_version(type(self).__module__), - verifier_settings=self._settings(context), + verifier_version=distribution_version(type(self)), + verifier_settings=self.recorded_settings(context), **self.grade_fields(context), ) @@ -233,9 +229,10 @@ def _score(self, verification: Verification) -> Optional[float]: return verification.score return aggregate_score(verification.criteria or [], self.score_aggregator) - def _settings(self, context: TaskStepContext) -> dict[str, Any]: - """``verifier_settings`` as the grade records it, compacted; a failing one is recorded rather than raised, since a - failed grade records settings too and must not lose the verifier's own error.""" + def recorded_settings(self, context: TaskStepContext) -> dict[str, Any]: + """``verifier_settings`` as a record keeps them, compacted: the grade, and a run's lock at its start + (``agent_env.task.run_lock``); a failing one is recorded rather than raised, since a failed grade records + settings too and must not lose the verifier's own error.""" try: settings = {k: _compact(v) for k, v in self.verifier_settings(context).items()} except Exception as exc: @@ -301,13 +298,3 @@ def _store_output(instance_id: Optional[str], step_id: str, body: bytes) -> str: key = (f"{config.get_artifact_key_prefix()}verifier-outputs/instance_id={instance_id}/" f"{step_id}-{uuid.uuid4().hex}.json") return config.get_object_store().put(key, body, content_type="application/json") - - -@functools.cache -def _providing_version(module: str) -> Optional[str]: - """The version of the installed package that holds ``module``: agentenv-framework's for agent_env's own; None when - no one package does, as for a module on the path or an editable plugin.""" - if module.partition(".")[0] == "agent_env": - return _requirements.installed(_FRAMEWORK) - name = _requirements.distribution_holding(module, packages_distributions()) - return _requirements.installed(canonicalize_name(name)) if name else None diff --git a/tst/unit/artifact/image_identity_test.py b/tst/unit/artifact/image_identity_test.py new file mode 100644 index 000000000..fae49e62c --- /dev/null +++ b/tst/unit/artifact/image_identity_test.py @@ -0,0 +1,20 @@ +"""An image's identity is what it is, whichever build of it ran: its build context's content hash, else the registry +digest it is pinned to; an image held only as a tarball has none beyond its artifact version.""" + +import pytest + +from agent_env.artifact.artifacts.docker_image import DockerImageArtifact + +SOURCE, DIGEST = "sha256:" + "a" * 64, "sha256:" + "b" * 64 + + +@pytest.mark.parametrize("fields, identity", [ + ({"source_digest": SOURCE, "image_digest": DIGEST}, f"source:{SOURCE}"), + ({"image_digest": DIGEST}, f"registry:{DIGEST}"), + ({"image_name": f"registry.example/img:v1@{DIGEST}"}, f"registry:{DIGEST}"), + ({"tar_gz_s3_url": "s3://bucket/img.tar.gz"}, None), +]) +def test_an_images_identity(fields, identity): + image = DockerImageArtifact(**{"id": "img", "description": "d", "image_name": "registry.example/img:v1", **fields}) + + assert image.image_identity == identity diff --git a/tst/unit/config/config_found_by_test.py b/tst/unit/config/config_found_by_test.py new file mode 100644 index 000000000..2910fb604 --- /dev/null +++ b/tst/unit/config/config_found_by_test.py @@ -0,0 +1,28 @@ +"""A Config says how the file it reads was found, never where: from AGENT_ENV_CONFIG, by walking up, or none.""" + +from agent_env.config.runtime import Config + + +def test_agent_env_config_is_the_environment(tmp_path, monkeypatch): + path = tmp_path / "config.toml" + path.write_text("") + monkeypatch.setenv("AGENT_ENV_CONFIG", str(path)) + + assert Config().config_found_by() == "environment" + + +def test_a_file_found_walking_up_is_discovered(tmp_path, monkeypatch): + monkeypatch.delenv("AGENT_ENV_CONFIG", raising=False) + (tmp_path / ".agentenv").mkdir() + (tmp_path / ".agentenv" / "config.toml").write_text("") + (tmp_path / "deeper").mkdir() + monkeypatch.chdir(tmp_path / "deeper") + + assert Config().config_found_by() == "discovered" + + +def test_no_file_is_none(tmp_path, monkeypatch): + monkeypatch.delenv("AGENT_ENV_CONFIG", raising=False) + monkeypatch.chdir(tmp_path) + + assert Config().config_found_by() == "none" diff --git a/tst/unit/eval/resolve_test.py b/tst/unit/eval/resolve_test.py index 6531e868e..7427a5f52 100644 --- a/tst/unit/eval/resolve_test.py +++ b/tst/unit/eval/resolve_test.py @@ -19,7 +19,8 @@ from agent_env.eval.instance import EvalInstance, EvalSettings, EvalSource, RunnerDeclarations, planned_slots from agent_env.eval.instance_store import create_eval_instance, get_eval_instance, get_slots from agent_env.eval.lock import IntentLock, LockedRead, TaskLock, Unread, UnreadRef -from agent_env.eval.resolve import _Resolver, content_hash, intent_lock, pinned_lines, resolve, task_refs +from agent_env.eval.intent import content_hash +from agent_env.eval.resolve import _Resolver, intent_lock, pinned_lines, resolve, task_refs from agent_env.plugins._bundles import ALIASES_FILE, InstalledBundle, installed_aliases from agent_env.store.query import Filter from agent_env.task import Task diff --git a/tst/unit/plugins/__init__.py b/tst/unit/plugins/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tst/unit/plugins/provenance_test.py b/tst/unit/plugins/provenance_test.py new file mode 100644 index 000000000..2a6bec35d --- /dev/null +++ b/tst/unit/plugins/provenance_test.py @@ -0,0 +1,52 @@ +"""Which installed distribution supplies a class, which agent-env plugins are installed and how a distribution was +installed, read from metadata alone and never naming a path.""" + +import json + +import pytest + +from agent_env.plugins import _provenance, distribution_of, distribution_version, install_origin +from agent_env.plugins._requirements import installed +from agent_env.task_step.task_steps.deploy_env import DeployEnvTaskStep + + +class _Unpackaged: + pass + + +class _Dist: + def __init__(self, direct_url): + self._text = None if direct_url is None else json.dumps(direct_url) + + def read_text(self, name): + return self._text if name == "direct_url.json" else None + + +def test_agent_envs_own_classes_are_its_own(): + assert distribution_of(DeployEnvTaskStep) == "agentenv-framework" + assert distribution_version(DeployEnvTaskStep) == installed("agentenv-framework") + assert distribution_of("agentenv_protocol.client:Client") == "agentenv-framework-protocol" + + +def test_a_class_an_entry_point_names_is_its_distributions_without_importing_it(monkeypatch): + monkeypatch.setattr(_provenance, "_entry_point_classes", lambda: {"acme_steps.grade:Grade": "acme-steps"}) + + assert distribution_of("acme_steps.grade:Grade") == "acme-steps" + assert distribution_of(_Unpackaged) is None # a module on the path, as a test's + + +@pytest.mark.parametrize("direct_url, origin", [ + (None, "index"), + ({"url": "https://github.com/acme/steps", "vcs_info": {"vcs": "git", "commit_id": "abc123"}}, "vcs@abc123"), + ({"url": "file:///home/someone/steps", "dir_info": {"editable": True}}, "editable"), + ({"url": "file:///home/someone/steps.whl", "archive_info": {}}, "local"), +]) +def test_an_install_is_named_by_its_kind_never_its_path(monkeypatch, direct_url, origin): + monkeypatch.setattr(_provenance, "distribution", lambda name: _Dist(direct_url)) + + assert install_origin("acme-steps") == origin + assert "/home/someone" not in origin + + +def test_a_distribution_that_isnt_installed_has_no_origin(): + assert install_origin("no-such-distribution-anywhere") is None diff --git a/tst/unit/task/run_lock_test.py b/tst/unit/task/run_lock_test.py new file mode 100644 index 000000000..c15499f9f --- /dev/null +++ b/tst/unit/task/run_lock_test.py @@ -0,0 +1,226 @@ +"""Each attempt of a run records, on its task instance and from the process that runs its steps, the code that ran it +(``runtime``) and what it was asked to do and read (``lock``): written at its start, completed when it ends however it +ends, an entry per attempt, never a path.""" + +import asyncio +import json + +import pytest + +from agent_env.a2a_agent import A2AAgent +from agent_env.artifact import Artifact +from agent_env.artifact.artifacts.docker_image import DockerImageArtifact +from agent_env.artifact.store import get_artifact_store +from agent_env.config import reset_config +from agent_env.config.runtime import Config +from agent_env.entity.refs import EntityRef +from agent_env.env.env import Env +from agent_env.env.envs.mcp_server import MCPServerEnv +from agent_env.env.envs.multi_env import MultiEnv +from agent_env.eval.intent import content_hash +from agent_env.plugins import _provenance +from agent_env.plugins._requirements import installed +from agent_env.task import Task +from agent_env.task import run_lock +from agent_env.task.result import RESULT_RULES_VERSION +from agent_env.task.store import TaskInstance, find_task_instance, 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 + +FRAMEWORK = installed("agentenv-framework") + + +class _Reads(TaskStep): + """Reads its env, agent and artifact at their latest, as a deploy does; fails when ``fail``, or waits when ``hang``.""" + + type = "run_lock_test_reads" + entity_refs = (EntityRef.env("env_id"), EntityRef.agent("a2a_agent_id"), EntityRef.artifact("artifact_id")) + started = None + + def __init__(self, *, env_id="office", a2a_agent_id="solver", artifact_id="data", fail=False, hang=False, + **kwargs): + super().__init__(**kwargs) + self.env_id, self.a2a_agent_id, self.artifact_id, self.fail, self.hang = ( + env_id, a2a_agent_id, artifact_id, fail, hang) + + @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(self.env_id), A2AAgent.get(self.a2a_agent_id), + Artifact.get(self.artifact_id))) + if self.hang: + _Reads.started.set() + await asyncio.Event().wait() + if self.fail: + raise RuntimeError("the step fails") + return context + + +class _Score(VerifierTaskStep): + type = "run_lock_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)) + + async def verify(self, context): + return Verification(score=1.0) + + +@pytest.fixture(autouse=True) +def registries(monkeypatch, local_stores): + steps = {**Config().task_step_registry(), _Reads.type: _Reads, _Score.type: _Score} + monkeypatch.setattr(Config, "task_step_registry", lambda self: steps) + image = lambda image_id, **fields: get_artifact_store().put_document(DockerImageArtifact( # noqa: E731 + id=image_id, description=image_id, image_name=f"registry.example/{image_id}:v1", **fields)) + servers = [MCPServerEnv.put(id=name, docker_image_artifact=image(f"{name}-image", source_digest="sha256:" + "a" * 64, + tar_gz_s3_url="s3://b/x"), environment_name=name) + for name in ("crm", "desk")] + MultiEnv.put(id="office", mcp_server_envs=servers) + A2AAgent.put(id="solver", docker_image_artifact=image("solver-image", image_digest="sha256:" + "b" * 64)) + image("data", tar_gz_s3_url="s3://b/data") + + +def _task(*steps): + return Task(id="t", version=1, steps=list(steps or [_Reads(id="reads", version=None), + _Score(id="score", version=None, verifier_id="score")])) + + +def _run(task, overrides=None, **kwargs): + context = TaskStepContext(metadata={"user_overrides": overrides or {}}) + return asyncio.run(task.run(context=context, **kwargs)), context + + +def test_a_run_records_what_ran_it_and_what_it_was_asked_and_read(): + task = _task() + _, context = _run(task, {"pins": {"env": {"office": 1}}, "judge_model": "j", "litellm_api_key": "sk-x", + "step_params": {"score": {"threshold": 0.9}}}, agent_model="solver-model") + instance = find_task_instance(context.instance_id) + + [runtime], [lock] = instance.runtime, instance.lock + assert (runtime["attempt_epoch"], runtime["agentenv_framework"], runtime["config"]) == ( + 0, FRAMEWORK, {"selected_by": "none"}) + 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"} + 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) + assert intent["pins"] == {"env": {"office": 1}} + assert intent["overrides"] == {"judge_model": "j", "step_params": {"score": {"threshold": 0.9}}, + "agent_model": "solver-model"} + assert (intent["roles"]["solver"]["model"], intent["roles"]["judge"]["model"]) == ("solver-model", "j") + verifier = lock["resolved"]["verifiers"]["score"] + assert (verifier["type"], verifier["distribution"], verifier["settings"]["scoring_rules"]) == ( + "run_lock_test_score", None, 1) + assert {(r["kind"], r["id"], r["version"], r["latest"]) for r in lock["resolved"]["reads"]} == { + ("env", "office", 1, True), ("env", "crm", 1, False), ("env", "desk", 1, False), + ("artifact", "crm-image", 1, False), ("artifact", "desk-image", 1, False), + ("agent", "solver", 1, True), ("artifact", "solver-image", 1, False), ("artifact", "data", 1, True)} + identities = {r["id"]: r.get("image_identity") for r in lock["resolved"]["reads"] if r["kind"] == "artifact"} + assert identities == {"crm-image": "source:sha256:" + "a" * 64, "desk-image": "source:sha256:" + "a" * 64, + "solver-image": "registry:sha256:" + "b" * 64, "data": None} + + +def test_the_grades_verifier_version_and_settings_are_the_locks(): + _, context = _run(_task()) + instance = find_task_instance(context.instance_id) + + grade, locked = context.metadata["grades"]["score"], instance.lock[0]["resolved"]["verifiers"]["score"] + assert grade["verifier_settings"] == locked["settings"] and grade["verifier_version"] == locked["version"] + + +def test_a_resume_in_another_process_adds_its_own_entries_and_keeps_the_first(): + task = _task() + _, first = _run(task) + _, second = _run(task, instance_id=first.instance_id, start_step=1) + instance = find_task_instance(first.instance_id) + + assert [e["attempt_epoch"] for e in instance.runtime] == [e["attempt_epoch"] for e in instance.lock] == [0, 1] + assert instance.lock[0]["resolved"]["reads"] and instance.lock[1]["resolved"]["reads"] == [] + + +def test_a_run_that_fails_records_what_it_read(): + context = TaskStepContext() + with pytest.raises(RuntimeError, match="the step fails"): + asyncio.run(_task(_Reads(id="reads", version=None, fail=True)).run(context=context)) + + [lock] = find_task_instance(context.instance_id).lock + assert {r["id"] for r in lock["resolved"]["reads"]} >= {"office", "solver", "data"} + + +def test_a_cancelled_run_records_what_it_read_before_the_cancel(): + async def cancelled(): + _Reads.started = asyncio.Event() + context = TaskStepContext() + running = asyncio.ensure_future(_task(_Reads(id="reads", version=None, hang=True)).run(context=context)) + await _Reads.started.wait() + running.cancel() + with pytest.raises(asyncio.CancelledError): + await running + await asyncio.sleep(0.2) # the record's write runs on past the cancel + return context + + context = asyncio.run(cancelled()) + [lock] = find_task_instance(context.instance_id).lock + assert {r["id"] for r in lock["resolved"]["reads"]} >= {"office", "solver", "data"} + + +def test_a_run_whose_record_cant_be_made_runs_unrecorded(monkeypatch): + def broken(*args, **kwargs): + raise RuntimeError("no record") + + monkeypatch.setattr(run_lock, "lock_entry", broken) + _, context = _run(_task()) + instance = find_task_instance(context.instance_id) + + assert (instance.status, instance.runtime, instance.lock) == ("completed", [], []) + + +def test_no_path_is_recorded_whatever_the_plugin_or_config(monkeypatch, tmp_path): + config = tmp_path / "private-config-dir" / "config.toml" + config.parent.mkdir() + config.write_text("") + monkeypatch.setenv("AGENT_ENV_CONFIG", str(config)) + monkeypatch.setattr(run_lock, "installed_plugins", lambda: {"acme-steps": "1.2.0"}) + monkeypatch.setattr(run_lock, "install_origin", lambda name: _provenance._origin(_Editable())) + reset_config() # the next get_config reads the file AGENT_ENV_CONFIG names + + _, context = _run(_task()) + [runtime] = find_task_instance(context.instance_id).runtime + + assert runtime["plugins"] == {"acme-steps": {"version": "1.2.0", "origin": "editable"}} + assert runtime["config"] == {"selected_by": "environment"} + assert str(tmp_path) not in json.dumps(runtime) and "/home/someone" not in json.dumps(runtime) + + +class _Editable: + def read_text(self, name): + return json.dumps({"url": "file:///home/someone/acme-steps", "dir_info": {"editable": True}}) + + +def test_an_attempts_record_written_again_replaces_its_own_and_keeps_the_others(): + _, context = _run(_task()) + store = get_task_instance_store() + store.record_run_lock_sync(context.instance_id, {"attempt_epoch": 3, "n": 1}, {"attempt_epoch": 3}) + store.record_run_lock_sync(context.instance_id, {"attempt_epoch": 3, "n": 2}, {"attempt_epoch": 3}) + + instance = find_task_instance(context.instance_id) + assert [(e["attempt_epoch"], e.get("n")) for e in instance.runtime] == [(0, None), (3, 2)] + + +def test_an_instance_stored_before_the_records_loads_without_them(): + instance = TaskInstance.from_dict({"instance_id": "i", "task_id": "t", "task_version": 1, "status": "running", + "current_step": 0, "total_steps": 1}) + assert (instance.runtime, instance.lock) == ([], []) From 69285b3f8564ff41647eb46586add6475b99a13a Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 30 Nov 2026 10:12:55 -0800 Subject: [PATCH 02/10] fix(task): a run's record adds no point where a cancel can land outside the run's own handling of one The start entries are written in step, as the run is registered, and the end entries on a thread the run doesn't wait for, so a cancel between registering and the first step, or after the result is recorded, is the run's own as before. The config tests that stand in for discovery patch discover_config, the function the snapshot now calls. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task/run_lock.py | 24 +++++++++++++++---- .../config/test_one_document_per_process.py | 6 ++--- .../test_registry_builders_take_a_config.py | 2 +- 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/src/agent_env/task/run_lock.py b/src/agent_env/task/run_lock.py index 0e8931d3b..5bfbb3cd1 100644 --- a/src/agent_env/task/run_lock.py +++ b/src/agent_env/task/run_lock.py @@ -15,7 +15,9 @@ (``entity.pins.recording``), each image with its identity, so a rebuild of an unchanged context reads as the same. Both are written when the run starts and again, with what it read, when it ends, however it ends, so a run that dies -midway keeps what it started with. A write that fails is logged, never failing the run. ``Task.run`` records them +midway keeps what it started with. A write that fails is logged, never failing the run, and neither adds a point where +a cancel can land outside the run's own handling of one: the start is written as the run is registered, in step, and +the end on a thread the run doesn't wait for, so it may land just after the run returns. ``Task.run`` records them through ``run_recorded``; a worker that runs a task's steps itself enters ``run_recorded`` around them the same way. Reads made on a thread that doesn't carry the run's context, as the computer composer's pool, aren't listed. """ @@ -144,8 +146,9 @@ def read_entries(reads: Sequence[Read]) -> list[dict[str, Any]]: 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.""" - started = await asyncio.to_thread(_started, instance_id, task, steps, context, attempt_epoch) if instance_id else None + 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 @@ -159,8 +162,19 @@ async def run_recorded(instance_id: Optional[str], task: "Task", steps: Sequence except Exception: logger.warning("The reads of attempt %s of %s couldn't be recorded", attempt_epoch, instance_id, exc_info=True) - else: # a cancel can't stop the record: the write runs on, as the run's other end writes do - await asyncio.shield(asyncio.to_thread(record_run_lock, instance_id, runtime, lock)) + else: + _write_unawaited(instance_id, runtime, lock) + + +_UNAWAITED: set[asyncio.Future] = set() + + +def _write_unawaited(instance_id: str, runtime: dict[str, Any], lock: dict[str, Any]) -> None: + """Write the attempt's entries on a thread the run doesn't wait for, held here until it ends; ``asyncio.run``'s + shutdown waits for it, and a write that fails is logged by ``record_run_lock``.""" + writing = asyncio.get_running_loop().run_in_executor(None, record_run_lock, instance_id, runtime, lock) + _UNAWAITED.add(writing) + writing.add_done_callback(_UNAWAITED.discard) def _started(instance_id: str, task: "Task", steps: Sequence[TaskStep], context: TaskStepContext, diff --git a/tst/unit/config/test_one_document_per_process.py b/tst/unit/config/test_one_document_per_process.py index e478fe799..fed947773 100644 --- a/tst/unit/config/test_one_document_per_process.py +++ b/tst/unit/config/test_one_document_per_process.py @@ -341,9 +341,9 @@ def test_a_file_that_vanishes_after_discovery_is_a_race_not_an_absent_config(tmp that was not there. The error rides on the snapshot, so the path stays reportable.""" path = _config_at(tmp_path, '[sandbox]\ndefault = "modal"\n') monkeypatch.setenv("AGENT_ENV_CONFIG", str(path)) - real = snapshot.loader.discover_config_path - monkeypatch.setattr(snapshot.loader, "discover_config_path", - lambda *a, **k: (lambda p: (p.unlink(), p)[1])(real(*a, **k))) + real = snapshot.loader.discover_config + monkeypatch.setattr(snapshot.loader, "discover_config", + lambda *a, **k: (lambda found: (found[0].unlink(), found)[1])(real(*a, **k))) resolved = get_config()._document() assert resolved.path == path # still nameable diff --git a/tst/unit/config/test_registry_builders_take_a_config.py b/tst/unit/config/test_registry_builders_take_a_config.py index 8196b1c1e..921f6af7b 100644 --- a/tst/unit/config/test_registry_builders_take_a_config.py +++ b/tst/unit/config/test_registry_builders_take_a_config.py @@ -57,7 +57,7 @@ def test_a_given_document_is_not_re_discovered(tmp_path, monkeypatch, section, b def no_discovery(*_a, **_k): raise AssertionError("discovery ran even though a document was supplied") - monkeypatch.setattr(config_snapshot.loader, "discover_config_path", no_discovery) + monkeypatch.setattr(config_snapshot.loader, "discover_config", no_discovery) build(source=config_with_document({})) From ba267d0945d9312ece2f937f61544ea155b3d2b9 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 30 Nov 2026 10:15:11 -0800 Subject: [PATCH 03/10] fix(task): the provenance scan works on Python 3.11, the lock keeps the settings each grade ran with, and a seed shows - The plugin scan reads each distribution's entry points: Python 3.11's entry_points() with no group yields group names, which left every run unrecorded there. - A verifier's lock entry gains graded_settings, the settings its grade records once a judge has called, beside those it started with. - The intent gains steps_hash, a hash of the steps as the run runs them, its seed applied, so runs of one task with different seeds tell apart without recording the seed. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/plugins/_provenance.py | 28 +++++++++++++++------- src/agent_env/task/run_lock.py | 33 +++++++++++++++++++------- tst/unit/plugins/provenance_test.py | 28 ++++++++++++++++++++++ tst/unit/task/run_lock_test.py | 35 ++++++++++++++++++++++++---- 4 files changed, 103 insertions(+), 21 deletions(-) diff --git a/src/agent_env/plugins/_provenance.py b/src/agent_env/plugins/_provenance.py index 62b5afa1f..8c39e9062 100644 --- a/src/agent_env/plugins/_provenance.py +++ b/src/agent_env/plugins/_provenance.py @@ -6,7 +6,8 @@ import functools import json -from importlib.metadata import Distribution, PackageNotFoundError, distribution, entry_points, packages_distributions +from collections.abc import Iterator +from importlib.metadata import Distribution, EntryPoint, PackageNotFoundError, distribution, distributions, packages_distributions from typing import Optional, Union from packaging.utils import canonicalize_name @@ -41,11 +42,9 @@ def distribution_version(target: Union[type, str]) -> Optional[str]: def installed_plugins() -> dict[str, Optional[str]]: """Every installed distribution declaring an agent-env entry point, by name, with its version.""" plugins = {} - for point in entry_points(): - if point.group.startswith(_GROUP_PREFIX) and point.dist is not None: - name = canonicalize_name(point.dist.name) - if name not in CORE: - plugins.setdefault(name, point.dist.version) + for name, version, _ in _agent_env_entry_points(): + if name not in CORE: + plugins.setdefault(name, version) return dict(sorted(plugins.items())) @@ -78,12 +77,23 @@ def _origin(found: Distribution) -> str: def _entry_point_classes() -> dict[str, str]: """Each class an agent-env entry point names (``module:Class``), by the distribution declaring it.""" classes: dict[str, str] = {} - for point in entry_points(): - if point.group.startswith(_GROUP_PREFIX) and point.dist is not None: - classes.setdefault(point.value.strip(), canonicalize_name(point.dist.name)) + for name, _, point in _agent_env_entry_points(): + classes.setdefault(point.value.strip(), name) return classes +def _agent_env_entry_points() -> Iterator[tuple[str, Optional[str], EntryPoint]]: + """Each installed distribution's agent-env entry points, with its name and version: Python 3.11's + ``entry_points()`` with no group gives group names, not entry points, so the scan goes through the distributions. + A distribution whose metadata names none is skipped.""" + for found in distributions(): + if not (name := found.metadata["Name"]): + continue + for point in found.entry_points: + if point.group.startswith(_GROUP_PREFIX): + yield canonicalize_name(name), found.version, point + + @functools.cache def _packages() -> dict: return packages_distributions() diff --git a/src/agent_env/task/run_lock.py b/src/agent_env/task/run_lock.py index 5bfbb3cd1..ecf7933b8 100644 --- a/src/agent_env/task/run_lock.py +++ b/src/agent_env/task/run_lock.py @@ -9,10 +9,12 @@ (``loader.discover_config``); and the distribution supplying each type the run used, its steps' from the start and the envs, artifacts and providers it used once it ends. Never a path. - ``lock``: ``intent``, what it was asked to do, as the eval engine's plan computes it (``agent_env.eval.intent``): the - task's id, version and content hash, its pins, each role's model and the host its calls go to as this process's config - resolves them, its overrides without secrets, and the result rules version. And ``resolved``, what this process found: - each verifier's settings and version at the run's start, and, once the run ends, every entity version it read - (``entity.pins.recording``), each image with its identity, so a rebuild of an unchanged context reads as the same. + task's id, version and content hash, a hash of its steps as this run runs them (its seed applied), its pins, each + role's model and the host its calls go to as this process's config resolves them, its overrides without secrets, and + the result rules version. And ``resolved``, what this process found: each verifier's settings and version at the + run's start, and, once the run ends, the settings each grade records (a judge completes them as it calls) and every + entity version it read (``entity.pins.recording``), each image with its identity, so a rebuild of an unchanged + context reads as the same. Both are written when the run starts and again, with what it read, when it ends, however it ends, so a run that dies midway keeps what it started with. A write that fails is logged, never failing the run, and neither adds a point where @@ -26,6 +28,7 @@ import asyncio import contextlib +import hashlib import logging import platform from typing import TYPE_CHECKING, Any, AsyncIterator, Optional, Sequence @@ -50,7 +53,8 @@ from agent_env.task.store import record_run_lock 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 VerifierTaskStep +from agent_env.task_step.task_steps.verifiers.verifier import GRADES_KEY, VerifierTaskStep +from agent_env.utils.canonical import canonical_json if TYPE_CHECKING: from agent_env.task import Task @@ -96,6 +100,7 @@ def lock_entry(task: "Task", steps: Sequence[TaskStep], context: TaskStepContext "task_id": task.id, "task_version": task.version, "content_hash": content_hash(task), + "steps_hash": steps_hash(steps), "pins": checked_pins(user_overrides.get(PINS_KEY)), "roles": {name: role.to_dict() for name, role in role_models(overrides).items()}, "overrides": recorded_overrides(overrides), @@ -111,10 +116,18 @@ def lock_entry(task: "Task", steps: Sequence[TaskStep], context: TaskStepContext } +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 + seed's values.""" + return "sha256:" + hashlib.sha256(canonical_json([step.to_dict() for step in steps])).hexdigest() + + def finished_entries(runtime: dict[str, Any], lock: dict[str, Any], reads: Sequence[Read], context: TaskStepContext) -> tuple[dict[str, Any], dict[str, Any]]: - """The attempt's entries once its run ends: ``reads``, every entity version it read, in its lock, and the types of - the envs, artifacts and providers it used in its runtime.""" + """The attempt's entries once its run ends: in its lock, ``reads``, every entity version it read, and each verifier + that graded with the settings its grade records (``graded_settings``), which a judge completes as it calls, beside + those it started with; in its runtime, the types of the envs, artifacts and providers it used.""" 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: @@ -123,8 +136,12 @@ def finished_entries(runtime: dict[str, Any], lock: dict[str, Any], reads: Seque (_group(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: ({**verifier, "graded_settings": grades[step_id].get("verifier_settings")} + if isinstance(grades.get(step_id), dict) else verifier) + for step_id, verifier in lock["resolved"]["verifiers"].items()} return ({**runtime, "types": types}, - {**lock, "resolved": {**lock["resolved"], "reads": read_entries(reads)}}) + {**lock, "resolved": {**lock["resolved"], "verifiers": verifiers, "reads": read_entries(reads)}}) def read_entries(reads: Sequence[Read]) -> list[dict[str, Any]]: diff --git a/tst/unit/plugins/provenance_test.py b/tst/unit/plugins/provenance_test.py index 2a6bec35d..e000aa65f 100644 --- a/tst/unit/plugins/provenance_test.py +++ b/tst/unit/plugins/provenance_test.py @@ -2,6 +2,7 @@ installed, read from metadata alone and never naming a path.""" import json +from importlib.metadata import EntryPoint import pytest @@ -50,3 +51,30 @@ def test_an_install_is_named_by_its_kind_never_its_path(monkeypatch, direct_url, def test_a_distribution_that_isnt_installed_has_no_origin(): assert install_origin("no-such-distribution-anywhere") is None + + +class _Metadata(dict): + def __getitem__(self, key): + return self.get(key) + + +class _Installed: + def __init__(self, name, version, points): + self.metadata, self.version = _Metadata(Name=name), version + self.entry_points = [EntryPoint(name=n, value=v, group=g) for g, n, v in points] + + +def test_plugins_and_their_classes_are_read_through_each_distribution_on_every_python(monkeypatch): + found = [_Installed("Acme_Steps", "1.2.0", [("agent_env.task_steps", "grade", "acme_steps.grade:Grade")]), + _Installed("agentenv-framework", "9.9", [("agent_env.bundles", "hello", "agent_env.examples")]), + _Installed("unrelated", "1.0", [("console_scripts", "x", "x:main")]), + _Installed(None, "0", [("agent_env.envs", "nameless", "nameless:Env")])] + monkeypatch.setattr(_provenance, "distributions", lambda: found) + _provenance.installed_plugins.cache_clear() + _provenance._entry_point_classes.cache_clear() + try: + assert _provenance.installed_plugins() == {"acme-steps": "1.2.0"} + assert distribution_of("acme_steps.grade:Grade") == "acme-steps" + finally: + _provenance.installed_plugins.cache_clear() + _provenance._entry_point_classes.cache_clear() diff --git a/tst/unit/task/run_lock_test.py b/tst/unit/task/run_lock_test.py index c15499f9f..e63a428cc 100644 --- a/tst/unit/task/run_lock_test.py +++ b/tst/unit/task/run_lock_test.py @@ -63,16 +63,16 @@ class _Score(VerifierTaskStep): type = "run_lock_test_score" entity_refs = () - def __init__(self, *, threshold=0.5, **kwargs): + def __init__(self, *, threshold=0.5, note="", **kwargs): super().__init__(**kwargs) - self.threshold = threshold + self.threshold, self.note = threshold, note def to_dict(self): - return {**super().to_dict(), "threshold": self.threshold} + return {**super().to_dict(), "threshold": self.threshold, "note": self.note} @classmethod def from_dict(cls, data): - return cls(**cls._base_from_dict(data), threshold=data.get("threshold", 0.5)) + return cls(**cls._base_from_dict(data), threshold=data.get("threshold", 0.5), note=data.get("note", "")) async def verify(self, context): return Verification(score=1.0) @@ -139,6 +139,33 @@ def test_the_grades_verifier_version_and_settings_are_the_locks(): grade, locked = context.metadata["grades"]["score"], instance.lock[0]["resolved"]["verifiers"]["score"] assert grade["verifier_settings"] == locked["settings"] and grade["verifier_version"] == locked["version"] + assert locked["graded_settings"] == grade["verifier_settings"] + + +def test_settings_a_verifier_completes_as_it_grades_are_in_the_lock_beside_those_it_started_with(monkeypatch): + def settings(self, context): + return {"threshold": self.threshold, **({"temperature": 0.3} if context.metadata.get("grading") else {})} + + async def verify(self, context): + context.metadata["grading"] = True + return Verification(score=1.0) + + monkeypatch.setattr(_Score, "verifier_settings", settings) + monkeypatch.setattr(_Score, "verify", verify) + _, context = _run(_task()) + + locked = find_task_instance(context.instance_id).lock[0]["resolved"]["verifiers"]["score"] + assert "temperature" not in locked["settings"] and locked["graded_settings"]["temperature"] == 0.3 + + +def test_two_runs_with_different_seeds_ask_different_things_and_say_so(): + task = _task(_Score(id="score", version=None, verifier_id="score", note="grade it as would")) + locks = [find_task_instance(context.instance_id).lock[0]["intent"] + for context in (asyncio.run(task.run(context=TaskStepContext(metadata={"seed": {"who": who}}))) + for who in ("a", "b"))] + + assert locks[0]["content_hash"] == locks[1]["content_hash"] + assert locks[0]["steps_hash"] != locks[1]["steps_hash"] and "grade it as a" not in json.dumps(locks) def test_a_resume_in_another_process_adds_its_own_entries_and_keeps_the_first(): From 939d43efae95ec28f1febdaaf75be29acbae2eed Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 30 Nov 2026 10:29:43 -0800 Subject: [PATCH 04/10] fix(task): a run's end record is written in the run's context, so an @local run's goes to the local stores run_in_executor doesn't carry context variables, so the unawaited end write ran outside the run's namespace scope and an @local run's record went for the configured store, which the write fence refused. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task/run_lock.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/agent_env/task/run_lock.py b/src/agent_env/task/run_lock.py index ecf7933b8..dd3fd6e0f 100644 --- a/src/agent_env/task/run_lock.py +++ b/src/agent_env/task/run_lock.py @@ -28,6 +28,8 @@ import asyncio import contextlib +import contextvars +import functools import hashlib import logging import platform @@ -187,9 +189,11 @@ async def run_recorded(instance_id: Optional[str], task: "Task", steps: Sequence def _write_unawaited(instance_id: str, runtime: dict[str, Any], lock: dict[str, Any]) -> None: - """Write the attempt's entries on a thread the run doesn't wait for, held here until it ends; ``asyncio.run``'s - shutdown waits for it, and a write that fails is logged by ``record_run_lock``.""" - writing = asyncio.get_running_loop().run_in_executor(None, record_run_lock, instance_id, runtime, lock) + """Write the attempt's entries on a thread the run doesn't wait for, held here until it ends, in the run's context, + so an ``@local`` run's record goes to the local stores as the run's own writes do; ``asyncio.run``'s shutdown waits + for it, and a write that fails is logged by ``record_run_lock``.""" + write = functools.partial(contextvars.copy_context().run, record_run_lock, instance_id, runtime, lock) + writing = asyncio.get_running_loop().run_in_executor(None, write) _UNAWAITED.add(writing) writing.add_done_callback(_UNAWAITED.discard) From 75b7e82c8602c23ef405f1e1a2c4122af6fc7075 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 30 Nov 2026 10:50:46 -0800 Subject: [PATCH 05/10] fix(task): a run's records are never awaited, the store keeps the end in whichever order they land, and a resume names only the grades it made - The start entries are made on the event loop, reading metadata and the context but no store, and written on a thread like the end ones, so a slow store holds up neither the run nor the loop; a finished entry never gives way to a started one, so the two writes may land in either order. - graded_settings names only the grades this attempt wrote, not those a resume's restored context carries. - The public names of agent_env.plugins include the provenance helpers. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task/run_lock.py | 35 +++++++++++++---------- src/agent_env/task/store.py | 17 ++++++++++-- tst/unit/plugins_test.py | 3 +- tst/unit/task/run_lock_test.py | 51 ++++++++++++++++++++++++++++++++++ 4 files changed, 87 insertions(+), 19 deletions(-) diff --git a/src/agent_env/task/run_lock.py b/src/agent_env/task/run_lock.py index dd3fd6e0f..2b4345415 100644 --- a/src/agent_env/task/run_lock.py +++ b/src/agent_env/task/run_lock.py @@ -17,9 +17,10 @@ context reads as the same. Both are written when the run starts and again, with what it read, when it ends, however it ends, so a run that dies -midway keeps what it started with. A write that fails is logged, never failing the run, and neither adds a point where -a cancel can land outside the run's own handling of one: the start is written as the run is registered, in step, and -the end on a thread the run doesn't wait for, so it may land just after the run returns. ``Task.run`` records them +midway keeps what it started with, unless it dies within moments of starting. A write that fails is logged, never failing +the run. Neither write is awaited: both go on threads the run doesn't wait for, so neither holds up the event loop when +the store is slow, nor adds a point where a cancel can land outside the run's own handling of one, and the end may land +just after the run returns. They may land in either order, and the store keeps the end (``record_run_lock_sync``). ``Task.run`` records them through ``run_recorded``; a worker that runs a task's steps itself enters ``run_recorded`` around them the same way. Reads made on a thread that doesn't carry the run's context, as the computer composer's pool, aren't listed. """ @@ -33,7 +34,7 @@ import hashlib import logging import platform -from typing import TYPE_CHECKING, Any, AsyncIterator, Optional, Sequence +from typing import TYPE_CHECKING, Any, AsyncIterator, Mapping, Optional, Sequence from agent_env.config import get_config from agent_env.entity.pins import PINS_KEY, Read, checked_pins, recording @@ -125,11 +126,13 @@ def steps_hash(steps: Sequence[TaskStep]) -> str: return "sha256:" + hashlib.sha256(canonical_json([step.to_dict() for step in steps])).hexdigest() -def finished_entries(runtime: dict[str, Any], lock: dict[str, Any], reads: Sequence[Read], - context: TaskStepContext) -> tuple[dict[str, Any], dict[str, Any]]: +def finished_entries(runtime: dict[str, Any], lock: dict[str, Any], reads: Sequence[Read], context: TaskStepContext, + graded_before: Optional[Mapping[str, Any]] = None) -> tuple[dict[str, Any], dict[str, Any]]: """The attempt's entries once its run ends: in its lock, ``reads``, every entity version it read, and each verifier - that graded with the settings its grade records (``graded_settings``), which a judge completes as it calls, beside - those it started with; in its runtime, the types of the envs, artifacts and providers it used.""" + it graded with the settings its grade records (``graded_settings``), which a judge completes as it calls, beside + those it started with; in its runtime, the types of the envs, artifacts and providers it used. ``graded_before`` are + the grades the context held as the attempt started, as a resume's restored context does: a grade still the one it + held is an earlier attempt's, whose settings this one didn't grade with.""" 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: @@ -138,9 +141,10 @@ def finished_entries(runtime: dict[str, Any], lock: dict[str, Any], reads: Seque (_group(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 {} + grades, before = context.metadata.get(GRADES_KEY) or {}, graded_before or {} verifiers = {step_id: ({**verifier, "graded_settings": grades[step_id].get("verifier_settings")} - if isinstance(grades.get(step_id), dict) else verifier) + if isinstance(grades.get(step_id), dict) and grades[step_id] is not before.get(step_id) + else verifier) for step_id, verifier in lock["resolved"]["verifiers"].items()} return ({**runtime, "types": types}, {**lock, "resolved": {**lock["resolved"], "verifiers": verifiers, "reads": read_entries(reads)}}) @@ -172,12 +176,14 @@ async def run_recorded(instance_id: Optional[str], task: "Task", steps: Sequence yield return runtime, lock = started + _write_unawaited(instance_id, runtime, lock) + graded_before = dict(context.metadata.get(GRADES_KEY) or {}) with recording() as reads: try: yield finally: try: - runtime, lock = finished_entries(runtime, lock, list(reads), context) + runtime, lock = finished_entries(runtime, lock, list(reads), context, graded_before) except Exception: logger.warning("The reads of attempt %s of %s couldn't be recorded", attempt_epoch, instance_id, exc_info=True) @@ -200,14 +206,13 @@ def _write_unawaited(instance_id: str, runtime: dict[str, Any], lock: dict[str, def _started(instance_id: str, task: "Task", steps: Sequence[TaskStep], context: TaskStepContext, attempt_epoch: int) -> Optional[tuple[dict[str, Any], dict[str, Any]]]: - """The attempt's entries, recorded; None, logged, when they can't be made, so the run goes on unrecorded.""" + """The attempt's entries, made on the event loop, which reads installed metadata and the context but no store; None, + logged, when they can't be made, so the run goes on unrecorded.""" try: - runtime, lock = runtime_entry(attempt_epoch, steps), lock_entry(task, steps, context, attempt_epoch) + return runtime_entry(attempt_epoch, steps), lock_entry(task, steps, context, attempt_epoch) except Exception: logger.warning("What attempt %s of %s runs couldn't be recorded", attempt_epoch, instance_id, exc_info=True) return None - record_run_lock(instance_id, runtime, lock) - return runtime, lock def _sandbox_types(context: TaskStepContext) -> dict[str, Any]: diff --git a/src/agent_env/task/store.py b/src/agent_env/task/store.py index a8c0a8cc5..66e1721e0 100644 --- a/src/agent_env/task/store.py +++ b/src/agent_env/task/store.py @@ -902,11 +902,17 @@ def _mutate(doc: dict) -> UpdateSpec | None: def record_run_lock_sync(self, instance_id: str, runtime: dict, lock: dict) -> bool: """Keep an attempt's ``runtime`` and ``lock`` entries, in place of any the attempt (their ``attempt_epoch``) - kept before, so the same write sent again, or a run's end replacing its start, keeps one of each; whether the - instance was found. Entries of other attempts stay, a later one's included, since each describes its own.""" + kept before, so the same write sent again, or a run's end replacing its start, keeps one of each; whether they + were kept. A finished entry, one listing what its run read, never gives way to a started one, so the start and + end writes keep the end in whichever order they land. Entries of other attempts stay, a later one's included, + since each describes its own.""" epoch = runtime["attempt_epoch"] - def _mutate(doc: dict) -> UpdateSpec: + def _mutate(doc: dict) -> UpdateSpec | None: + stored = next((e for e in doc.get(LOCK_KEY) or [] if e.get("attempt_epoch") == epoch), None) + if stored is not None and _finished(stored) and not _finished(lock): + return None + def replaced(entries: list | None, entry: dict) -> list[dict]: kept = [e for e in entries or [] if e.get("attempt_epoch") != epoch] return sorted([*kept, entry], key=lambda e: e.get("attempt_epoch", 0)) @@ -1211,6 +1217,11 @@ def _retried(write: Callable[[], _T], failed: _T, what: str) -> _T: logger.warning("Failed to %s after %d attempts", what, _FAILURE_WRITE_MAX_ATTEMPTS, exc_info=last_exc) return failed +def _finished(lock: dict) -> bool: + """Whether a run lock entry is its run's end one: it lists what the run read.""" + return isinstance((lock.get("resolved") or {}).get("reads"), list) + + def record_run_lock(instance_id: str, runtime: dict, lock: dict) -> bool: """``TaskInstanceStore.record_run_lock_sync``, retried like the run's other records; whether it was kept. A write that keeps failing is logged rather than raised: a run isn't failed for its record of what ran.""" diff --git a/tst/unit/plugins_test.py b/tst/unit/plugins_test.py index b6260a4cf..3bcf5ae7c 100644 --- a/tst/unit/plugins_test.py +++ b/tst/unit/plugins_test.py @@ -349,7 +349,8 @@ def test_the_public_module_is_only_the_contract(): assert sorted(plugins.__all__) == [ "ARTIFACTS", "Claimant", "Contribution", "Diagnostic", "Distribution", "ENVS", "ENV_PROVIDERS", "EXPLORER_PLUGINS", "Inventory", "Replacement", "SANDBOX_PROVIDERS", "STATE_PROVIDERS", "Status", - "TASK_STEPS", "inventory", "load_failures", "settings", + "TASK_STEPS", "distribution_of", "distribution_version", "install_origin", "installed_plugins", "inventory", + "load_failures", "settings", ] assert sorted(n for n in vars(plugins) if not n.startswith("_")) == sorted(plugins.__all__) diff --git a/tst/unit/task/run_lock_test.py b/tst/unit/task/run_lock_test.py index e63a428cc..5243d33b1 100644 --- a/tst/unit/task/run_lock_test.py +++ b/tst/unit/task/run_lock_test.py @@ -3,6 +3,7 @@ ends, an entry per attempt, never a path.""" import asyncio +import threading import json import pytest @@ -251,3 +252,53 @@ def test_an_instance_stored_before_the_records_loads_without_them(): instance = TaskInstance.from_dict({"instance_id": "i", "task_id": "t", "task_version": 1, "status": "running", "current_step": 0, "total_steps": 1}) assert (instance.runtime, instance.lock) == ([], []) + + +def test_a_start_landing_after_its_attempts_end_keeps_the_end(): + _, context = _run(_task()) + store = get_task_instance_store() + finished = find_task_instance(context.instance_id) + started = {**finished.lock[0], "resolved": {**finished.lock[0]["resolved"], "reads": None}} + + assert not store.record_run_lock_sync(context.instance_id, finished.runtime[0], started) + assert find_task_instance(context.instance_id).lock == finished.lock + + +def test_a_resume_names_the_settings_only_of_the_verifiers_it_graded(): + task = _task(_Score(id="early", version=None, verifier_id="early"), _Reads(id="reads", version=None), + _Score(id="late", version=None, verifier_id="late")) + _, first = _run(task) + asyncio.run(task.run(context=first, instance_id=first.instance_id, start_step=2)) + + resumed = find_task_instance(first.instance_id).lock[1]["resolved"]["verifiers"] + assert "graded_settings" not in resumed["early"] and "graded_settings" in resumed["late"] + + +def test_a_store_that_hangs_holds_up_neither_the_run_nor_its_loop(monkeypatch): + release, written = threading.Event(), [] + + def hanging(instance_id, runtime, lock): + release.wait(10) + written.append(lock["resolved"]["reads"] is not None) + return True + + monkeypatch.setattr(run_lock, "record_run_lock", hanging) + + async def main(): + ticks = 0 + + async def tick(): + nonlocal ticks + while True: + ticks += 1 + await asyncio.sleep(0.001) + + ticker = asyncio.ensure_future(tick()) + await _task().run(context=TaskStepContext()) + ticker.cancel() + done = (written[:], ticks) + release.set() + return done + + (before_release, ticks) = asyncio.run(main()) + assert before_release == [] and ticks > 0 and sorted(written) == [False, True] From 1f00ca06834bd040f115f4c81368e4860f9a1595 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 30 Nov 2026 13:00:43 -0800 Subject: [PATCH 06/10] fix(task): run records go to writer threads of their own, an exit waits for them only so long, and a run keeps each read once - The start and end records are written by a few daemon threads of their own, not the event loop's default pool, which the run's result write and its steps' blocking work share, so a store that hangs ties up only them. flush_run_records waits for those pending; at exit the process waits EXIT_WAIT_SECONDS at most, then logs how many it drops. - recording() keeps each entity version once (entity.pins.Reads), a repeated read adding only that it was read at its latest or through an alias, so a long run that reads one env over and over holds one entry. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/entity/pins.py | 46 +++++++++++++++---- src/agent_env/eval/resolve.py | 2 +- src/agent_env/task/run_lock.py | 80 ++++++++++++++++++++++++++++------ tst/unit/task/run_lock_test.py | 59 ++++++++++++++++++++++--- 4 files changed, 159 insertions(+), 28 deletions(-) diff --git a/src/agent_env/entity/pins.py b/src/agent_env/entity/pins.py index 045f87a77..2603d596d 100644 --- a/src/agent_env/entity/pins.py +++ b/src/agent_env/entity/pins.py @@ -16,7 +16,8 @@ from collections.abc import Iterator, Mapping from contextlib import contextmanager from contextvars import ContextVar -from dataclasses import dataclass, field +import threading +from dataclasses import dataclass, field, replace from typing import Any, Optional from agent_env.entity.refs import EntityKind @@ -89,18 +90,45 @@ def pinned_version(kind: EntityKind, entity_id: str, version: Optional[int]) -> return _PINS.get().get(str(kind), {}).get(entity_id) +class Reads: + """The distinct reads a ``recording`` block made, each entity version once, in the order first read: a read of one + already listed adds only what it says, that it was read at its latest or through an alias, so a long run that reads + one env over and over keeps one entry. Reads made on several threads at once are kept whole.""" + + def __init__(self) -> None: + self._by_version: dict[tuple[str, str, int], Read] = {} + self._lock = threading.Lock() + + def add(self, read: Read) -> None: + key = (str(read.kind), read.id, read.version) + with self._lock: + held = self._by_version.get(key) + if held is None: + self._by_version[key] = read + elif (read.asked is None and held.asked is not None) or (read.alias and not held.alias): + self._by_version[key] = replace(held, asked=None if read.asked is None else held.asked, + alias=held.alias or read.alias) + + def __iter__(self) -> Iterator[Read]: + with self._lock: + return iter(list(self._by_version.values())) + + def __len__(self) -> int: + return len(self._by_version) + + @dataclass class _Recording: - reads: list[Read] + reads: Reads pins: Optional[dict[str, dict[str, int]]] @contextmanager -def recording(pins: Optional[dict[str, dict[str, int]]] = None) -> Iterator[list[Read]]: - """The reads the getters make in the block, in order, each loaded child's before its parent's. With ``pins``, the - block reads through them, and each read at its latest, not through an alias, adds its version to them as it lands, - so every later read of that id, a sibling child's in the same load included, reads the same version.""" - record = _Recording([], pins) +def recording(pins: Optional[dict[str, dict[str, int]]] = None) -> Iterator[Reads]: + """The distinct reads the getters make in the block (``Reads``), each loaded child's before its parent's. With + ``pins``, the block reads through them, and each read at its latest, not through an alias, adds its version to them + as it lands, so every later read of that id, a sibling child's in the same load included, reads the same version.""" + record = _Recording(Reads(), pins) token = _RECORDING.set(record) try: if pins is None: @@ -117,7 +145,7 @@ def note_read(kind: EntityKind, entity_id: str, asked: Optional[int], entity: An its latest.""" if (record := _RECORDING.get()) is None: return - record.reads.append(Read(kind, entity_id, asked, entity.version, alias, getattr(entity, "type", None), - type(entity), getattr(entity, "image_identity", None))) + record.reads.add(Read(kind, entity_id, asked, entity.version, alias, getattr(entity, "type", None), + type(entity), getattr(entity, "image_identity", None))) if record.pins is not None and asked is None and not alias: record.pins.setdefault(str(kind), {}).setdefault(entity_id, entity.version) diff --git a/src/agent_env/eval/resolve.py b/src/agent_env/eval/resolve.py index c0a6aa4ee..f2fd2da17 100644 --- a/src/agent_env/eval/resolve.py +++ b/src/agent_env/eval/resolve.py @@ -114,7 +114,7 @@ def _read(self, namespace: Optional[str], kind: EntityKind, entity_id: str, _GETTERS[kind](entity_id, asked) except NotFoundError: reads = None - self._resolved[key] = reads + self._resolved[key] = None if reads is None else list(reads) return self._resolved[key] diff --git a/src/agent_env/task/run_lock.py b/src/agent_env/task/run_lock.py index 2b4345415..10a37cdf2 100644 --- a/src/agent_env/task/run_lock.py +++ b/src/agent_env/task/run_lock.py @@ -18,23 +18,27 @@ Both are written when the run starts and again, with what it read, when it ends, however it ends, so a run that dies midway keeps what it started with, unless it dies within moments of starting. A write that fails is logged, never failing -the run. Neither write is awaited: both go on threads the run doesn't wait for, so neither holds up the event loop when -the store is slow, nor adds a point where a cancel can land outside the run's own handling of one, and the end may land -just after the run returns. They may land in either order, and the store keeps the end (``record_run_lock_sync``). ``Task.run`` records them +the run. Neither write is awaited: both go to a few writer threads of their own, in the run's context, so neither holds +up the event loop or the threads its other work shares when the store is slow, nor adds a point where a cancel can land +outside the run's own handling of one. The end may land just after the run returns (``flush_run_records`` waits for +it), and a process exiting waits ``EXIT_WAIT_SECONDS`` at most for records still pending, then logs those it drops. +The writes may land in either order, and the store keeps the end (``record_run_lock_sync``). ``Task.run`` records them through ``run_recorded``; a worker that runs a task's steps itself enters ``run_recorded`` around them the same way. Reads made on a thread that doesn't carry the run's context, as the computer composer's pool, aren't listed. """ from __future__ import annotations -import asyncio +import atexit import contextlib import contextvars import functools import hashlib import logging import platform -from typing import TYPE_CHECKING, Any, AsyncIterator, Mapping, Optional, Sequence +import queue +import threading +from typing import TYPE_CHECKING, Any, AsyncIterator, Callable, Mapping, Optional, Sequence from agent_env.config import get_config from agent_env.entity.pins import PINS_KEY, Read, checked_pins, recording @@ -191,17 +195,67 @@ async def run_recorded(instance_id: Optional[str], task: "Task", steps: Sequence _write_unawaited(instance_id, runtime, lock) -_UNAWAITED: set[asyncio.Future] = set() +WRITER_THREADS = 4 +EXIT_WAIT_SECONDS = 10.0 + + +class _Writer: + """Daemon threads that write run records, apart from the event loop's default pool, which the run's result write + and its steps' blocking work share, so a store that hangs ties up only these; ``flush`` waits for what's pending.""" + + def __init__(self, threads: int) -> None: + self._threads, self._queue = threads, queue.SimpleQueue() + self._pending, self._started = 0, False + self._done = threading.Condition() + + def submit(self, write: Callable[[], Any]) -> None: + with self._done: + self._pending += 1 + if not self._started: + self._started = True + for n in range(self._threads): + threading.Thread(target=self._work, name=f"agentenv-run-record-{n}", daemon=True).start() + self._queue.put(write) + + def flush(self, timeout: Optional[float] = None) -> bool: + with self._done: + return self._done.wait_for(lambda: self._pending == 0, timeout) + + def pending(self) -> int: + return self._pending + + def _work(self) -> None: + while True: + write = self._queue.get() + try: + write() + except Exception: + logger.warning("A run record couldn't be written", exc_info=True) + finally: + with self._done: + self._pending -= 1 + self._done.notify_all() + + +_WRITER = _Writer(WRITER_THREADS) + + +def flush_run_records(timeout: Optional[float] = None) -> bool: + """Wait for the run records still being written, ``timeout`` seconds at most; whether none is left.""" + return _WRITER.flush(timeout) + + +@atexit.register +def _flush_at_exit() -> None: + if not _WRITER.flush(EXIT_WAIT_SECONDS): + logger.warning("%s run record(s) not written before exit, %ss after it began", _WRITER.pending(), + EXIT_WAIT_SECONDS) def _write_unawaited(instance_id: str, runtime: dict[str, Any], lock: dict[str, Any]) -> None: - """Write the attempt's entries on a thread the run doesn't wait for, held here until it ends, in the run's context, - so an ``@local`` run's record goes to the local stores as the run's own writes do; ``asyncio.run``'s shutdown waits - for it, and a write that fails is logged by ``record_run_lock``.""" - write = functools.partial(contextvars.copy_context().run, record_run_lock, instance_id, runtime, lock) - writing = asyncio.get_running_loop().run_in_executor(None, write) - _UNAWAITED.add(writing) - writing.add_done_callback(_UNAWAITED.discard) + """Write the attempt's entries on the record writers, in the run's context, so an ``@local`` run's record goes to + the local stores as the run's own writes do; a write that fails is logged by ``record_run_lock``.""" + _WRITER.submit(functools.partial(contextvars.copy_context().run, record_run_lock, instance_id, runtime, lock)) def _started(instance_id: str, task: "Task", steps: Sequence[TaskStep], context: TaskStepContext, diff --git a/tst/unit/task/run_lock_test.py b/tst/unit/task/run_lock_test.py index 5243d33b1..ab68dae4c 100644 --- a/tst/unit/task/run_lock_test.py +++ b/tst/unit/task/run_lock_test.py @@ -4,6 +4,7 @@ import asyncio import threading +from concurrent.futures import ThreadPoolExecutor import json import pytest @@ -14,6 +15,7 @@ from agent_env.artifact.store import get_artifact_store from agent_env.config import reset_config from agent_env.config.runtime import Config +from agent_env.entity.pins import recording from agent_env.entity.refs import EntityRef from agent_env.env.env import Env from agent_env.env.envs.mcp_server import MCPServerEnv @@ -100,7 +102,9 @@ def _task(*steps): def _run(task, overrides=None, **kwargs): context = TaskStepContext(metadata={"user_overrides": overrides or {}}) - return asyncio.run(task.run(context=context, **kwargs)), context + result = asyncio.run(task.run(context=context, **kwargs)) + assert run_lock.flush_run_records(10) + return result, context def test_a_run_records_what_ran_it_and_what_it_was_asked_and_read(): @@ -161,9 +165,9 @@ async def verify(self, context): def test_two_runs_with_different_seeds_ask_different_things_and_say_so(): task = _task(_Score(id="score", version=None, verifier_id="score", note="grade it as would")) - locks = [find_task_instance(context.instance_id).lock[0]["intent"] - for context in (asyncio.run(task.run(context=TaskStepContext(metadata={"seed": {"who": who}}))) - for who in ("a", "b"))] + contexts = [asyncio.run(task.run(context=TaskStepContext(metadata={"seed": {"who": who}}))) for who in ("a", "b")] + assert run_lock.flush_run_records(10) + locks = [find_task_instance(context.instance_id).lock[0]["intent"] for context in contexts] assert locks[0]["content_hash"] == locks[1]["content_hash"] assert locks[0]["steps_hash"] != locks[1]["steps_hash"] and "grade it as a" not in json.dumps(locks) @@ -183,6 +187,7 @@ def test_a_run_that_fails_records_what_it_read(): context = TaskStepContext() with pytest.raises(RuntimeError, match="the step fails"): asyncio.run(_task(_Reads(id="reads", version=None, fail=True)).run(context=context)) + assert run_lock.flush_run_records(10) [lock] = find_task_instance(context.instance_id).lock assert {r["id"] for r in lock["resolved"]["reads"]} >= {"office", "solver", "data"} @@ -197,10 +202,10 @@ async def cancelled(): running.cancel() with pytest.raises(asyncio.CancelledError): await running - await asyncio.sleep(0.2) # the record's write runs on past the cancel return context context = asyncio.run(cancelled()) + assert run_lock.flush_run_records(10) # the record's write runs on past the cancel [lock] = find_task_instance(context.instance_id).lock assert {r["id"] for r in lock["resolved"]["reads"]} >= {"office", "solver", "data"} @@ -269,6 +274,7 @@ def test_a_resume_names_the_settings_only_of_the_verifiers_it_graded(): _Score(id="late", version=None, verifier_id="late")) _, first = _run(task) asyncio.run(task.run(context=first, instance_id=first.instance_id, start_step=2)) + assert run_lock.flush_run_records(10) resumed = find_task_instance(first.instance_id).lock[1]["resolved"]["verifiers"] assert "graded_settings" not in resumed["early"] and "graded_settings" in resumed["late"] @@ -301,4 +307,47 @@ async def tick(): return done (before_release, ticks) = asyncio.run(main()) + assert run_lock.flush_run_records(10) assert before_release == [] and ticks > 0 and sorted(written) == [False, True] + + +def test_a_hanging_record_write_ties_up_none_of_the_threads_a_runs_other_work_shares(monkeypatch): + release = threading.Event() + monkeypatch.setattr(run_lock, "record_run_lock", lambda *args: release.wait(10)) + + async def main(): + asyncio.get_running_loop().set_default_executor(ThreadPoolExecutor(max_workers=1)) + try: # _Reads reads on asyncio.to_thread, the run's one default worker + return await asyncio.wait_for(_task().run(context=TaskStepContext()), 20) + finally: + release.set() + + context = asyncio.run(main()) + assert run_lock.flush_run_records(10) + assert context.metadata["grades"]["score"]["passed"] + + +def test_exiting_waits_for_pending_records_only_so_long_and_says_how_many_it_dropped(monkeypatch, caplog): + release, writer = threading.Event(), run_lock._Writer(1) + monkeypatch.setattr(run_lock, "_WRITER", writer) + monkeypatch.setattr(run_lock, "EXIT_WAIT_SECONDS", 0.2) + writer.submit(lambda: release.wait(10)) + writer.submit(lambda: None) + try: + run_lock._flush_at_exit() + assert "2 run record(s) not written before exit" in caplog.text + finally: + release.set() + assert writer.flush(5) + + +def test_a_run_that_reads_one_env_over_and_over_keeps_one_entry_per_entity_version(): + with recording() as reads: + for _ in range(500): + Env.get("office") + A2AAgent.get("solver", 1) + A2AAgent.get("solver") + + assert len(reads) == 7 # office, crm, desk, their two images, solver and its image + [solver] = [read for read in reads if read.id == "solver"] + assert solver.asked is None # read at its latest once, which the entry keeps From 0f47ba589990d62b172f3cb48b8f8828f4ffae83 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 30 Nov 2026 13:24:59 -0800 Subject: [PATCH 07/10] refactor(task): typed run records with a stage, written under a counter of their own, and one place that dedupes reads - task/run_records.py declares RunRuntime and RunLock (with RunIntent, VerifierRecord, ReadRecord, InstalledPlugin): every field in one place, read leniently, one record_version, and an explicit started/finished stage, which the store checks rather than the shape of the reads. - The record writes compare-and-swap on run_records_rev, as only they touch runtime and lock, so they never make the instance's other writes retry, nor those them. - read_records maps the recorder's distinct reads (entity.pins.Reads) without merging them again. - task/record_writer.py holds the writer threads, saying why they aren't a ThreadPoolExecutor (an exit would wait on a hung store without bound). - tst/util/entities.py is the stored world the resolver's and the run records' tests share. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 20 ++- src/agent_env/task/record_writer.py | 80 +++++++++ src/agent_env/task/run_lock.py | 251 ++++++++++------------------ src/agent_env/task/run_records.py | 225 +++++++++++++++++++++++++ src/agent_env/task/store.py | 44 +++-- tst/unit/eval/resolve_test.py | 20 +-- tst/unit/task/run_lock_test.py | 241 +++++++++++++++----------- tst/util/entities.py | 36 ++++ 8 files changed, 615 insertions(+), 302 deletions(-) create mode 100644 src/agent_env/task/record_writer.py create mode 100644 src/agent_env/task/run_records.py create mode 100644 tst/util/entities.py diff --git a/AGENTS.md b/AGENTS.md index 8a64a850d..fe098dbb5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -475,14 +475,18 @@ orchestrators call it the same way. What callers rely on: - A run is resumable: pass a previously persisted `context`, a `start_step` and the existing `instance_id`; completed steps are seeded as SUCCESS. - Each attempt a process starts records, on the instance and by its `attempt_epoch`, the code that ran it and what - it was asked to do and read (`task/run_lock.py`, `run_recorded`): `runtime` (the core, protocol and Python versions, - 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`; never a path) and `lock` (`intent`: the task's content - hash, pins, each role's model and endpoint host as this process resolves them, the overrides without secrets, the - result rules version, computed as the eval plan computes its own, `eval/intent.py`; `resolved`: each verifier's - settings and version at the start and every entity version the run read, each image with its `image_identity`). - Both are written at the start and again when the run ends, however it ends; a resume adds its own entries. A - worker that runs a task's steps itself enters `run_recorded` around them, as it sets `run_pins`. + it was asked to do and read (`task/run_lock.py`, `run_recorded`), as the typed records `task/run_records.py` + declares: `RunRuntime` (the core, protocol and Python versions, 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`; 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; 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`) so they never make the instance's other writes retry; the store keeps the + finished record whichever lands last, and a resume adds its own. A worker that runs a task's steps itself enters + `run_recorded` around them, as it sets `run_pins`. - A runner that must hear from a long step puts a zero-argument callable at `context.metadata[HEARTBEAT_KEY]` (`task_step/context.py`); a step that blocks for long calls `context.heartbeat()`, a no-op without one. The key is in `_REDACTED_KEYS`, so it is never persisted. diff --git a/src/agent_env/task/record_writer.py b/src/agent_env/task/record_writer.py new file mode 100644 index 000000000..e3f1cfa0d --- /dev/null +++ b/src/agent_env/task/record_writer.py @@ -0,0 +1,80 @@ +"""The threads that write a run's records (``agent_env.task.run_lock``), so no run waits for them. + +They are a few daemon threads of their own, apart from the event loop's default pool, which a run's result write and +its steps' blocking work share, so a store that hangs ties up only these. They aren't a ``ThreadPoolExecutor``: its +workers are joined when the process exits, with no timeout, so a store that hangs would hang the exit. Instead the exit +waits ``EXIT_WAIT_SECONDS`` at most for what's pending, then logs how many records it drops; ``flush_run_records`` +waits for them sooner, as a caller that reads a record right after its run does. +""" + +from __future__ import annotations + +import atexit +import logging +import queue +import threading +from typing import Any, Callable, Optional + +logger = logging.getLogger(__name__) + +WRITER_THREADS = 4 +EXIT_WAIT_SECONDS = 10.0 + + +class _Writer: + """Runs each write it's given on one of ``threads`` daemon threads, started on the first, and counts those + pending.""" + + def __init__(self, threads: int) -> None: + self._threads, self._queue = threads, queue.SimpleQueue() + self._pending, self._started = 0, False + self._done = threading.Condition() + + def submit(self, write: Callable[[], Any]) -> None: + with self._done: + self._pending += 1 + if not self._started: + self._started = True + for n in range(self._threads): + threading.Thread(target=self._work, name=f"agentenv-run-record-{n}", daemon=True).start() + self._queue.put(write) + + def flush(self, timeout: Optional[float] = None) -> bool: + with self._done: + return self._done.wait_for(lambda: self._pending == 0, timeout) + + def pending(self) -> int: + with self._done: + return self._pending + + def _work(self) -> None: + while True: + write = self._queue.get() + try: + write() + except Exception: + logger.warning("A run record couldn't be written", exc_info=True) + finally: + with self._done: + self._pending -= 1 + self._done.notify_all() + + +_WRITER = _Writer(WRITER_THREADS) + + +def write_record(write: Callable[[], Any]) -> None: + """Run ``write`` on the record writers; one that raises is logged.""" + _WRITER.submit(write) + + +def flush_run_records(timeout: Optional[float] = None) -> bool: + """Wait for the run records still being written, ``timeout`` seconds at most; whether none is left.""" + return _WRITER.flush(timeout) + + +@atexit.register +def _flush_at_exit() -> None: + if not _WRITER.flush(EXIT_WAIT_SECONDS): + logger.warning("%s run record(s) not written before exit, %ss after it began", _WRITER.pending(), + EXIT_WAIT_SECONDS) diff --git a/src/agent_env/task/run_lock.py b/src/agent_env/task/run_lock.py index 10a37cdf2..0665ea6dd 100644 --- a/src/agent_env/task/run_lock.py +++ b/src/agent_env/task/run_lock.py @@ -1,44 +1,32 @@ """What each attempt of a run ran and was asked to do, recorded on its task instance by the process that runs its -steps, so two runs of a task, or a run and its resume, can be told apart and compared. - -Each attempt a process starts keeps an entry in each of two lists, by the ``attempt_epoch`` it started under; an attempt -a retry starts within the run belongs to the entry before it, since the same process runs it with the same code. - -- ``runtime``: the code that ran it. The core, protocol and Python versions; each installed agent-env plugin's version - and how it was installed (``index``, ``vcs@``, ``editable`` or ``local``); how the config file was found - (``loader.discover_config``); and the distribution supplying each type the run used, its steps' from the start and - the envs, artifacts and providers it used once it ends. Never a path. -- ``lock``: ``intent``, what it was asked to do, as the eval engine's plan computes it (``agent_env.eval.intent``): the - task's id, version and content hash, a hash of its steps as this run runs them (its seed applied), its pins, each - role's model and the host its calls go to as this process's config resolves them, its overrides without secrets, and - the result rules version. And ``resolved``, what this process found: each verifier's settings and version at the - run's start, and, once the run ends, the settings each grade records (a judge completes them as it calls) and every - entity version it read (``entity.pins.recording``), each image with its identity, so a rebuild of an unchanged - context reads as the same. - -Both are written when the run starts and again, with what it read, when it ends, however it ends, so a run that dies -midway keeps what it started with, unless it dies within moments of starting. A write that fails is logged, never failing -the run. Neither write is awaited: both go to a few writer threads of their own, in the run's context, so neither holds -up the event loop or the threads its other work shares when the store is slow, nor adds a point where a cancel can land -outside the run's own handling of one. The end may land just after the run returns (``flush_run_records`` waits for -it), and a process exiting waits ``EXIT_WAIT_SECONDS`` at most for records still pending, then logs those it drops. -The writes may land in either order, and the store keeps the end (``record_run_lock_sync``). ``Task.run`` records them -through ``run_recorded``; a worker that runs a task's steps itself enters ``run_recorded`` around them the same way. -Reads made on a thread that doesn't carry the run's context, as the computer composer's pool, aren't listed. +steps, so two runs of a task, or a run and its resume, can be told apart and compared. The records' fields are +declared in ``agent_env.task.run_records``: ``RunRuntime``, the code that ran it, and ``RunLock``, what it was asked to +do (its intent, computed as the eval engine's plan computes its own, ``agent_env.eval.intent``) and what it resolved. + +Each attempt a process starts keeps one of each, by the ``attempt_epoch`` it started under; an attempt a retry starts +within the run belongs to the records before it, since the same process runs it with the same code. They are written +``started`` when the run starts and ``finished``, with what it read, when it ends, however it ends, so a run that dies +midway keeps what it started with, unless it dies within moments of starting. A write that fails is logged, never +failing the run. Neither is awaited: both go to the record writers (``agent_env.task.record_writer``), in the run's +context, so neither holds up the run or the threads its other work shares when the store is slow, nor adds a point +where a cancel can land outside the run's own handling of one. The finished record may land just after the run returns, +and the two may land in either order: the store keeps the finished one (``record_run_lock_sync``). + +``Task.run`` records them through ``run_recorded``; a worker that runs a task's steps itself enters ``run_recorded`` +around them the same way. Reads made on a thread that doesn't carry the run's context, as the computer composer's +pool, aren't listed. """ from __future__ import annotations -import atexit import contextlib import contextvars +import dataclasses import functools import hashlib import logging import platform -import queue -import threading -from typing import TYPE_CHECKING, Any, AsyncIterator, Callable, Mapping, Optional, Sequence +from typing import TYPE_CHECKING, Any, AsyncIterator, Iterable, Mapping, Optional, Sequence from agent_env.config import get_config from agent_env.entity.pins import PINS_KEY, Read, checked_pins, recording @@ -56,7 +44,17 @@ ) from agent_env.plugins._provenance import FRAMEWORK, PROTOCOL from agent_env.plugins._requirements import installed +from agent_env.task.record_writer import write_record from agent_env.task.result import RESULT_RULES_VERSION +from agent_env.task.run_records import ( + InstalledPlugin, + ReadRecord, + RunIntent, + RunLock, + RunRuntime, + Stage, + VerifierRecord, +) from agent_env.task.store import record_run_lock from agent_env.task_step.context import TaskStepContext from agent_env.task_step.task_step import TaskStep @@ -68,8 +66,6 @@ logger = logging.getLogger(__name__) -RUN_LOCK_VERSION = 1 - 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``).""" @@ -79,48 +75,42 @@ def _group(entry_point_group: str) -> str: _READ_KINDS = {"env": _group(ENVS), "artifact": _group(ARTIFACTS)} -def runtime_entry(attempt_epoch: int, steps: Sequence[TaskStep]) -> dict[str, Any]: - """The ``runtime`` entry of an attempt this process starts, with its steps' types; ``finished_entries`` adds the - other types the run used.""" - return { - "attempt_epoch": attempt_epoch, - "agentenv_framework": installed(FRAMEWORK), - "agentenv_protocol": installed(PROTOCOL), - "python": platform.python_version(), - "plugins": {name: {"version": version, "origin": 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}}, - } +def started_runtime(attempt_epoch: int, steps: Sequence[TaskStep]) -> RunRuntime: + """The runtime of an attempt this process starts, with its steps' types; ``finished_records`` adds the other types + the run used.""" + return RunRuntime( + attempt_epoch=attempt_epoch, + agentenv_framework=installed(FRAMEWORK), + agentenv_protocol=installed(PROTOCOL), + 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}}, + ) -def lock_entry(task: "Task", steps: Sequence[TaskStep], context: TaskStepContext, attempt_epoch: int) -> dict[str, Any]: - """The ``lock`` entry of an attempt this process starts: its intent and what it resolved at the start. ``steps`` are - the steps it runs, its seed applied; ``task`` the task as stored, whose content its hash names.""" +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.""" 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) - return { - "attempt_epoch": attempt_epoch, - "lock_version": RUN_LOCK_VERSION, - "intent": { - "task_id": task.id, - "task_version": task.version, - "content_hash": content_hash(task), - "steps_hash": steps_hash(steps), - "pins": checked_pins(user_overrides.get(PINS_KEY)), - "roles": {name: role.to_dict() for name, role in role_models(overrides).items()}, - "overrides": recorded_overrides(overrides), - "result_rules_version": RESULT_RULES_VERSION, - }, - "resolved": { - "verifiers": {step.id: {"type": step.type, "distribution": distribution_of(type(step)), - "version": distribution_version(type(step)), - "settings": step.recorded_settings(context)} - for step in steps if isinstance(step, VerifierTaskStep)}, - "reads": None, - }, - } + return RunLock( + attempt_epoch=attempt_epoch, + intent=RunIntent( + task_id=task.id, + task_version=task.version, + content_hash=content_hash(task), + steps_hash=steps_hash(steps), + pins=checked_pins(user_overrides.get(PINS_KEY)), + roles=role_models(overrides), + overrides=recorded_overrides(overrides), + result_rules_version=RESULT_RULES_VERSION, + ), + verifiers={step.id: VerifierRecord(step.type, distribution_of(type(step)), distribution_version(type(step)), + step.recorded_settings(context)) + for step in steps if isinstance(step, VerifierTaskStep)}, + ) def steps_hash(steps: Sequence[TaskStep]) -> str: @@ -130,14 +120,15 @@ def steps_hash(steps: Sequence[TaskStep]) -> str: return "sha256:" + hashlib.sha256(canonical_json([step.to_dict() for step in steps])).hexdigest() -def finished_entries(runtime: dict[str, Any], lock: dict[str, Any], reads: Sequence[Read], context: TaskStepContext, - graded_before: Optional[Mapping[str, Any]] = None) -> tuple[dict[str, Any], dict[str, Any]]: - """The attempt's entries 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, beside - those it started with; in its runtime, the types of the envs, artifacts and providers it used. ``graded_before`` are - the grades the context held as the attempt started, as a resume's restored context does: a grade still the one it - held is an earlier attempt's, whose settings this one didn't grade with.""" - types = {group: dict(found) for group, found in runtime["types"].items()} +def finished_records(runtime: RunRuntime, lock: RunLock, reads: Iterable[Read], context: TaskStepContext, + graded_before: Optional[Mapping[str, Any]] = None) -> tuple[RunRuntime, RunLock]: + """The attempt's records once its run ends: in its lock, ``reads``, every entity version it read, and each verifier + it graded with the settings its grade records (``graded_settings``), which a judge completes as it calls; in its + runtime, the types of the envs, artifacts and providers it used. ``graded_before`` are the grades the context held + as the attempt started, as a resume's restored context does: a grade still the one it held is an earlier + attempt's, whose settings this one didn't grade with.""" + 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) @@ -146,27 +137,20 @@ def finished_entries(runtime: dict[str, Any], lock: dict[str, Any], reads: Seque for name, impl in used.items(): types.setdefault(group, {})[name] = distribution_of(impl) if impl is not None else None grades, before = context.metadata.get(GRADES_KEY) or {}, graded_before or {} - verifiers = {step_id: ({**verifier, "graded_settings": grades[step_id].get("verifier_settings")} + verifiers = {step_id: (dataclasses.replace(verifier, graded_settings=grades[step_id].get("verifier_settings")) if isinstance(grades.get(step_id), dict) and grades[step_id] is not before.get(step_id) else verifier) - for step_id, verifier in lock["resolved"]["verifiers"].items()} - return ({**runtime, "types": types}, - {**lock, "resolved": {**lock["resolved"], "verifiers": verifiers, "reads": read_entries(reads)}}) + for step_id, verifier in lock.verifiers.items()} + return (dataclasses.replace(runtime, types=types, stage=Stage.FINISHED), + dataclasses.replace(lock, verifiers=verifiers, reads=read_records(reads), stage=Stage.FINISHED)) -def read_entries(reads: Sequence[Read]) -> list[dict[str, Any]]: - """Each entity version ``reads`` name, once, in order: ``latest`` when any read asked for its latest, which the run's - pins answer when they name it; ``alias`` when it came through an installed bundle's alias.""" - entries: dict[tuple[str, str, int], dict[str, Any]] = {} - for read in reads: - key = (str(read.kind), read.id, read.version) - entry = entries.setdefault(key, {"kind": key[0], "id": read.id, "version": read.version, "type": read.type, - "latest": False, "alias": False}) - entry["latest"] = entry["latest"] or read.asked is None - entry["alias"] = entry["alias"] or read.alias - if read.image_identity: - entry["image_identity"] = read.image_identity - return [entries[key] for key in sorted(entries)] +def read_records(reads: Iterable[Read]) -> list[ReadRecord]: + """Each read as its lock lists it, by kind, id and version. ``reads`` are distinct already + (``entity.pins.Reads``), each carrying whether it was read at its latest or through an alias.""" + records = [ReadRecord(str(read.kind), read.id, read.version, read.type, read.asked is None, read.alias, + read.image_identity) for read in reads] + return sorted(records, key=lambda record: (record.kind, record.id, record.version)) @contextlib.asynccontextmanager @@ -180,90 +164,33 @@ async def run_recorded(instance_id: Optional[str], task: "Task", steps: Sequence yield return runtime, lock = started - _write_unawaited(instance_id, runtime, lock) + _write(instance_id, runtime, lock) graded_before = dict(context.metadata.get(GRADES_KEY) or {}) with recording() as reads: try: yield finally: try: - runtime, lock = finished_entries(runtime, lock, list(reads), context, graded_before) + runtime, lock = finished_records(runtime, lock, reads, context, graded_before) except Exception: logger.warning("The reads of attempt %s of %s couldn't be recorded", attempt_epoch, instance_id, exc_info=True) else: - _write_unawaited(instance_id, runtime, lock) - - -WRITER_THREADS = 4 -EXIT_WAIT_SECONDS = 10.0 - - -class _Writer: - """Daemon threads that write run records, apart from the event loop's default pool, which the run's result write - and its steps' blocking work share, so a store that hangs ties up only these; ``flush`` waits for what's pending.""" - - def __init__(self, threads: int) -> None: - self._threads, self._queue = threads, queue.SimpleQueue() - self._pending, self._started = 0, False - self._done = threading.Condition() - - def submit(self, write: Callable[[], Any]) -> None: - with self._done: - self._pending += 1 - if not self._started: - self._started = True - for n in range(self._threads): - threading.Thread(target=self._work, name=f"agentenv-run-record-{n}", daemon=True).start() - self._queue.put(write) - - def flush(self, timeout: Optional[float] = None) -> bool: - with self._done: - return self._done.wait_for(lambda: self._pending == 0, timeout) - - def pending(self) -> int: - return self._pending - - def _work(self) -> None: - while True: - write = self._queue.get() - try: - write() - except Exception: - logger.warning("A run record couldn't be written", exc_info=True) - finally: - with self._done: - self._pending -= 1 - self._done.notify_all() - - -_WRITER = _Writer(WRITER_THREADS) - - -def flush_run_records(timeout: Optional[float] = None) -> bool: - """Wait for the run records still being written, ``timeout`` seconds at most; whether none is left.""" - return _WRITER.flush(timeout) - - -@atexit.register -def _flush_at_exit() -> None: - if not _WRITER.flush(EXIT_WAIT_SECONDS): - logger.warning("%s run record(s) not written before exit, %ss after it began", _WRITER.pending(), - EXIT_WAIT_SECONDS) + _write(instance_id, runtime, lock) -def _write_unawaited(instance_id: str, runtime: dict[str, Any], lock: dict[str, Any]) -> None: - """Write the attempt's entries on the record writers, in the run's context, so an ``@local`` run's record goes to - the local stores as the run's own writes do; a write that fails is logged by ``record_run_lock``.""" - _WRITER.submit(functools.partial(contextvars.copy_context().run, record_run_lock, instance_id, runtime, lock)) +def _write(instance_id: str, runtime: RunRuntime, lock: RunLock) -> None: + """Write the attempt's records on the record writers, in the run's context, so an ``@local`` run's records go to the + local stores as the run's own writes do; a write that fails is logged by ``record_run_lock``.""" + write_record(functools.partial(contextvars.copy_context().run, record_run_lock, instance_id, runtime, lock)) def _started(instance_id: str, task: "Task", steps: Sequence[TaskStep], context: TaskStepContext, - attempt_epoch: int) -> Optional[tuple[dict[str, Any], dict[str, Any]]]: - """The attempt's entries, made on the event loop, which reads installed metadata and the context but no store; None, - logged, when they can't be made, so the run goes on unrecorded.""" + attempt_epoch: int) -> Optional[tuple[RunRuntime, RunLock]]: + """The attempt's started records, made on the event loop, which reads installed metadata and the context but no + store; None, logged, when they can't be made, so the run goes on unrecorded.""" try: - return runtime_entry(attempt_epoch, steps), lock_entry(task, steps, context, attempt_epoch) + return started_runtime(attempt_epoch, steps), started_lock(task, steps, context, attempt_epoch) except Exception: logger.warning("What attempt %s of %s runs couldn't be recorded", attempt_epoch, instance_id, exc_info=True) return None diff --git a/src/agent_env/task/run_records.py b/src/agent_env/task/run_records.py new file mode 100644 index 000000000..e1b2635a6 --- /dev/null +++ b/src/agent_env/task/run_records.py @@ -0,0 +1,225 @@ +"""The records each attempt of a run keeps on its task instance (``agent_env.task.run_lock`` makes them): ``RunRuntime``, +the code that ran it, and ``RunLock``, what it was asked to do and what it read. Every field is declared here, so a +comparison of two runs can name each one it reads. + +Each record is written twice by the process that runs the attempt, ``started`` and then ``finished`` (``Stage``), and +names the ``attempt_epoch`` it started under. Reading is lenient: a key this version doesn't know is ignored, one it +lacks takes its default, and a stage it doesn't know is kept as stored, since a newer version may have written the +record to a store several versions share. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from enum import StrEnum +from typing import Any, Optional + +from agent_env.eval.lock import RoleModel + +RUN_RECORD_VERSION = 1 + + +class Stage(StrEnum): + """``started`` when the attempt began; ``finished`` once it ended, however it ended, with what it read.""" + + STARTED = "started" + FINISHED = "finished" + + +def _stage(value: Any) -> Stage | str: + try: + return Stage(value) + except ValueError: + return value + + +@dataclass +class InstalledPlugin: + """An installed agent-env plugin's version, and how it was installed: ``index``, ``vcs@``, ``editable`` or + ``local``; never a path.""" + + version: Optional[str] + origin: Optional[str] + + def to_dict(self) -> dict: + return {"version": self.version, "origin": self.origin} + + @classmethod + def from_dict(cls, data: dict) -> InstalledPlugin: + return cls(version=data.get("version"), origin=data.get("origin")) + + +@dataclass +class RunRuntime: + """The code that ran an attempt: the core, protocol and Python versions, each installed agent-env plugin, how the + config file was found (``environment``, ``discovered`` or ``none``), and, by registry (``task_steps``, ``envs``, + ``artifacts``, ``sandbox_providers``, ``env_providers``), the distribution that supplied each type the run used: + its steps' from the start, the rest once it finished.""" + + attempt_epoch: int + agentenv_framework: Optional[str] + agentenv_protocol: Optional[str] + python: str + plugins: dict[str, InstalledPlugin] = field(default_factory=dict) + config_selected_by: Optional[str] = None + types: dict[str, dict[str, Optional[str]]] = field(default_factory=dict) + stage: Stage | str = Stage.STARTED + record_version: int = RUN_RECORD_VERSION + + def to_dict(self) -> dict: + return { + "attempt_epoch": self.attempt_epoch, + "record_version": self.record_version, + "stage": str(self.stage), + "agentenv_framework": self.agentenv_framework, + "agentenv_protocol": self.agentenv_protocol, + "python": self.python, + "plugins": {name: plugin.to_dict() for name, plugin in self.plugins.items()}, + "config": {"selected_by": self.config_selected_by}, + "types": {group: dict(found) for group, found in self.types.items()}, + } + + @classmethod + def from_dict(cls, data: dict) -> RunRuntime: + return cls( + attempt_epoch=data["attempt_epoch"], + agentenv_framework=data.get("agentenv_framework"), + agentenv_protocol=data.get("agentenv_protocol"), + python=data.get("python", ""), + plugins={name: InstalledPlugin.from_dict(plugin) for name, plugin in (data.get("plugins") or {}).items()}, + config_selected_by=(data.get("config") or {}).get("selected_by"), + types={group: dict(found) for group, found in (data.get("types") or {}).items()}, + stage=_stage(data.get("stage", Stage.STARTED)), + record_version=data.get("record_version", RUN_RECORD_VERSION), + ) + + +@dataclass +class RunIntent: + """What an attempt was asked to do, computed as an eval plan computes its own (``agent_env.eval.intent``): the task's + id, version and content hash; ``steps_hash``, of its steps as this run runs them, its seed applied; its pins; each + role's model and endpoint host as this process's config resolves them; its overrides without secrets; and the + result rules version.""" + + task_id: str + task_version: int + content_hash: str + steps_hash: str + pins: dict[str, dict[str, int]] = field(default_factory=dict) + roles: dict[str, RoleModel] = field(default_factory=dict) + overrides: dict[str, Any] = field(default_factory=dict) + result_rules_version: int = 0 + + def to_dict(self) -> dict: + return { + "task_id": self.task_id, + "task_version": self.task_version, + "content_hash": self.content_hash, + "steps_hash": self.steps_hash, + "pins": self.pins, + "roles": {name: role.to_dict() for name, role in self.roles.items()}, + "overrides": self.overrides, + "result_rules_version": self.result_rules_version, + } + + @classmethod + def from_dict(cls, data: dict) -> RunIntent: + return cls( + task_id=data["task_id"], + task_version=data["task_version"], + content_hash=data["content_hash"], + steps_hash=data.get("steps_hash", ""), + 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 {}, + result_rules_version=data.get("result_rules_version", 0), + ) + + +@dataclass +class VerifierRecord: + """A verifier step's type, the distribution and version that supplied it, its settings at the attempt's start, and + ``graded_settings``, those its grade records, which a judge completes as it calls; None until this attempt grades.""" + + type: str + distribution: Optional[str] + version: Optional[str] + settings: dict[str, Any] = field(default_factory=dict) + graded_settings: Optional[dict[str, Any]] = None + + def to_dict(self) -> dict: + return {"type": self.type, "distribution": self.distribution, "version": self.version, + "settings": self.settings, "graded_settings": self.graded_settings} + + @classmethod + def from_dict(cls, data: dict) -> VerifierRecord: + return cls(type=data["type"], distribution=data.get("distribution"), version=data.get("version"), + settings=data.get("settings") or {}, graded_settings=data.get("graded_settings")) + + +@dataclass(frozen=True) +class ReadRecord: + """One entity version an attempt read: its kind, id, version and type; ``latest`` when the run asked for its + latest, which its pins answer when they name it; ``alias`` when it came through an installed bundle's alias; and an + image's identity (``DockerImageArtifact.image_identity``).""" + + kind: str + id: str + version: int + type: Optional[str] = None + latest: bool = False + alias: bool = False + image_identity: Optional[str] = None + + def to_dict(self) -> dict: + return {"kind": self.kind, "id": self.id, "version": self.version, "type": self.type, "latest": self.latest, + "alias": self.alias, "image_identity": self.image_identity} + + @classmethod + def from_dict(cls, data: dict) -> ReadRecord: + return cls(kind=data["kind"], id=data["id"], version=data["version"], type=data.get("type"), + latest=bool(data.get("latest")), alias=bool(data.get("alias")), + image_identity=data.get("image_identity")) + + +@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``.""" + + attempt_epoch: int + intent: RunIntent + verifiers: dict[str, VerifierRecord] = field(default_factory=dict) + reads: Optional[list[ReadRecord]] = None + stage: Stage | str = Stage.STARTED + record_version: int = RUN_RECORD_VERSION + + @property + def finished(self) -> bool: + return self.stage == Stage.FINISHED + + def to_dict(self) -> dict: + return { + "attempt_epoch": self.attempt_epoch, + "record_version": self.record_version, + "stage": str(self.stage), + "intent": self.intent.to_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], + }, + } + + @classmethod + def from_dict(cls, data: dict) -> RunLock: + resolved = data.get("resolved") or {} + reads = resolved.get("reads") + return cls( + attempt_epoch=data["attempt_epoch"], + intent=RunIntent.from_dict(data["intent"]), + 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], + stage=_stage(data.get("stage", Stage.STARTED)), + record_version=data.get("record_version", RUN_RECORD_VERSION), + ) diff --git a/src/agent_env/task/store.py b/src/agent_env/task/store.py index 66e1721e0..f18dbf7fb 100644 --- a/src/agent_env/task/store.py +++ b/src/agent_env/task/store.py @@ -28,6 +28,7 @@ commit_ordered, replay_context, ) +from agent_env.task.run_records import RunLock, RunRuntime from agent_env.task.usage.ledger import LEDGER_KEY, TOTAL_KEY, ahead, entries_of, ledger_fields, total from agent_env.task_step.context import TaskStepContext from agent_env.task_step.context_ops import ContextUpdateOps @@ -49,10 +50,12 @@ _GENERATION = "run_generation" # The run's result, outside its context (``agent_env.task.result``): a grade version per grading, oldest first. RESULT_KEY = "result" -# What ran each attempt and what it read (``agent_env.task.run_lock``): an entry per attempt a process started, by its -# ``attempt_epoch``, kept across re-registers so a resume's entries sit beside the first run's. +# What ran each attempt and what it read (``agent_env.task.run_records``): an entry per attempt a process started, by its +# ``attempt_epoch``, kept across re-registers so a resume's entries sit beside the first run's. Only the record writes +# touch them, under a counter of their own, so they never make the instance's other writers retry, nor those them. RUNTIME_KEY = "runtime" LOCK_KEY = "lock" +_RUN_RECORDS_REV = "run_records_rev" # Where a submitter names the eval slot a run fills, in ``context.metadata``: ``{eval_instance_id, slot, attempt}``, # which registering the run keeps as the instance's own fields. EVAL_SLOT_KEY = "eval_slot" @@ -209,8 +212,8 @@ class TaskInstance: # A grade version per grading of the run, oldest first; empty until the run ends. result: list[dict] = field(default_factory=list) # An entry per attempt a process started, by attempt_epoch: the code that ran it and what it was asked and read. - runtime: list[dict] = field(default_factory=list) - lock: list[dict] = field(default_factory=list) + runtime: list[RunRuntime] = field(default_factory=list) + lock: list[RunLock] = field(default_factory=list) @classmethod def from_dict(cls, data: dict) -> TaskInstance: @@ -235,8 +238,8 @@ def from_dict(cls, data: dict) -> TaskInstance: slot=data.get("slot"), attempt=data.get("attempt"), result=data.get(RESULT_KEY) or [], - runtime=data.get(RUNTIME_KEY) or [], - lock=data.get(LOCK_KEY) or [], + runtime=[RunRuntime.from_dict(entry) for entry in data.get(RUNTIME_KEY) or []], + lock=[RunLock.from_dict(entry) for entry in data.get(LOCK_KEY) or []], ) @@ -900,27 +903,27 @@ def _mutate(doc: dict) -> UpdateSpec | None: return compare_and_swap(self._doc_store, TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id), _mutate, counter_field=_REV) is not None - def record_run_lock_sync(self, instance_id: str, runtime: dict, lock: dict) -> bool: - """Keep an attempt's ``runtime`` and ``lock`` entries, in place of any the attempt (their ``attempt_epoch``) + def record_run_lock_sync(self, instance_id: str, runtime: RunRuntime, lock: RunLock) -> bool: + """Keep an attempt's ``runtime`` and ``lock`` records, in place of any the attempt (their ``attempt_epoch``) kept before, so the same write sent again, or a run's end replacing its start, keeps one of each; whether they - were kept. A finished entry, one listing what its run read, never gives way to a started one, so the start and - end writes keep the end in whichever order they land. Entries of other attempts stay, a later one's included, - since each describes its own.""" - epoch = runtime["attempt_epoch"] + were kept. A ``finished`` record never gives way to a ``started`` one, so the start and end writes keep the end + in whichever order they land. Records of other attempts stay, a later one's included, since each describes its + own. The write is fenced by the records' own counter, as only it touches them.""" + epoch = lock.attempt_epoch def _mutate(doc: dict) -> UpdateSpec | None: stored = next((e for e in doc.get(LOCK_KEY) or [] if e.get("attempt_epoch") == epoch), None) - if stored is not None and _finished(stored) and not _finished(lock): + if stored is not None and RunLock.from_dict(stored).finished and not lock.finished: return None def replaced(entries: list | None, entry: dict) -> list[dict]: kept = [e for e in entries or [] if e.get("attempt_epoch") != epoch] return sorted([*kept, entry], key=lambda e: e.get("attempt_epoch", 0)) - return UpdateSpec(set={RUNTIME_KEY: replaced(doc.get(RUNTIME_KEY), runtime), - LOCK_KEY: replaced(doc.get(LOCK_KEY), lock)}) + return UpdateSpec(set={RUNTIME_KEY: replaced(doc.get(RUNTIME_KEY), runtime.to_dict()), + LOCK_KEY: replaced(doc.get(LOCK_KEY), lock.to_dict())}) return compare_and_swap(self._doc_store, TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id), - _mutate, counter_field=_REV) is not None + _mutate, counter_field=_RUN_RECORDS_REV) is not None def record_teardown_sync(self, instance_id: str, context: "TaskStepContext", attempt_epoch: int) -> None: """Keep the context a run's teardown ended with: what the run deployed, writes of a step a signal cut short @@ -1217,17 +1220,12 @@ def _retried(write: Callable[[], _T], failed: _T, what: str) -> _T: logger.warning("Failed to %s after %d attempts", what, _FAILURE_WRITE_MAX_ATTEMPTS, exc_info=last_exc) return failed -def _finished(lock: dict) -> bool: - """Whether a run lock entry is its run's end one: it lists what the run read.""" - return isinstance((lock.get("resolved") or {}).get("reads"), list) - - -def record_run_lock(instance_id: str, runtime: dict, lock: dict) -> bool: +def record_run_lock(instance_id: str, runtime: RunRuntime, lock: RunLock) -> bool: """``TaskInstanceStore.record_run_lock_sync``, retried like the run's other records; whether it was kept. A write that keeps failing is logged rather than raised: a run isn't failed for its record of what ran.""" store = get_task_instance_store() return _retried(lambda: store.record_run_lock_sync(instance_id, runtime, lock), False, - f"record what attempt {runtime['attempt_epoch']} of instance_id={instance_id} ran") + f"record what attempt {lock.attempt_epoch} of instance_id={instance_id} ran") def record_result(instance_id: str, result: list[dict], attempt_epoch: int | None = None) -> bool: diff --git a/tst/unit/eval/resolve_test.py b/tst/unit/eval/resolve_test.py index 7427a5f52..d0801870a 100644 --- a/tst/unit/eval/resolve_test.py +++ b/tst/unit/eval/resolve_test.py @@ -7,13 +7,12 @@ from agent_env.a2a_agent import a2a_agent as a2a_agent_module from agent_env.artifact import Artifact from agent_env.artifact.artifacts.docker_image import DockerImageArtifact -from agent_env.artifact.store import ArtifactStore, get_artifact_store +from agent_env.artifact.store import ArtifactStore from agent_env.config import configure, get_config from agent_env.config.runtime import Config from agent_env.entity.pins import PINS_KEY, checked_pins, pinned_version, run_pins from agent_env.entity.refs import EntityKind, EntityRef from agent_env.env.env import Env -from agent_env.env.envs.mcp_server import MCPServerEnv from agent_env.env.envs.multi_env import MultiEnv from agent_env.env.store import ENVS_COLLECTION, get_env_store from agent_env.eval.instance import EvalInstance, EvalSettings, EvalSource, RunnerDeclarations, planned_slots @@ -32,6 +31,7 @@ from agent_env.task_step.task_steps.install_agent import InstallAgentTaskStep from agent_env.task_step.task_steps.load_artifact import LoadArtifactTaskStep from agent_env.task_step.task_steps.snapshot_env import SnapshotEnvTaskStep +from tst.util import entities INFRA = ("default", "default-db", "playwright-mcp") @@ -69,24 +69,12 @@ def registries(monkeypatch): monkeypatch.setattr(_Reads, "seen", []) -def _image(image_id): - return get_artifact_store().put_document(DockerImageArtifact( - id=image_id, description=image_id, image_name=f"registry.example/{image_id}:v1", - tar_gz_s3_url=f"s3://bucket/{image_id}.tar.gz")) - - -def _server(env_id): - return MCPServerEnv.put(id=env_id, docker_image_artifact=_image(f"{env_id}-image"), environment_name=env_id) - - -def _agent(agent_id): - return A2AAgent.put(id=agent_id, docker_image_artifact=_image(f"{agent_id}-image")) +_image, _server, _agent = entities.image, entities.server, entities.agent def _office(): """``office``, a multi env holding ``crm`` and ``inbox``, and the agent ``solver``.""" - MultiEnv.put(id="office", mcp_server_envs=[_server("crm"), _server("inbox")]) - _agent("solver") + entities.office(children=("crm", "inbox")) def _task(task_id="t", *steps): diff --git a/tst/unit/task/run_lock_test.py b/tst/unit/task/run_lock_test.py index ab68dae4c..9bcc767a1 100644 --- a/tst/unit/task/run_lock_test.py +++ b/tst/unit/task/run_lock_test.py @@ -1,37 +1,51 @@ """Each attempt of a run records, on its task instance and from the process that runs its steps, the code that ran it -(``runtime``) and what it was asked to do and read (``lock``): written at its start, completed when it ends however it -ends, an entry per attempt, never a path.""" +(``runtime``) and what it was asked to do and read (``lock``): written started, then finished however it ends, a +record per attempt, never a path, and never in the way of the run or the instance's other writes.""" import asyncio +import dataclasses +import json import threading from concurrent.futures import ThreadPoolExecutor -import json import pytest from agent_env.a2a_agent import A2AAgent from agent_env.artifact import Artifact -from agent_env.artifact.artifacts.docker_image import DockerImageArtifact -from agent_env.artifact.store import get_artifact_store -from agent_env.config import reset_config +from agent_env.config import get_config, reset_config from agent_env.config.runtime import Config from agent_env.entity.pins import recording from agent_env.entity.refs import EntityRef from agent_env.env.env import Env -from agent_env.env.envs.mcp_server import MCPServerEnv -from agent_env.env.envs.multi_env import MultiEnv from agent_env.eval.intent import content_hash +from agent_env.eval.lock import RoleModel from agent_env.plugins import _provenance from agent_env.plugins._requirements import installed -from agent_env.task import Task -from agent_env.task import run_lock +from agent_env.store.query import Filter +from agent_env.task import Task, record_writer, run_lock from agent_env.task.result import RESULT_RULES_VERSION -from agent_env.task.store import TaskInstance, find_task_instance, get_task_instance_store +from agent_env.task.run_records import ( + InstalledPlugin, + ReadRecord, + RunIntent, + RunLock, + RunRuntime, + Stage, + VerifierRecord, +) +from agent_env.task.store import ( + TASK_INSTANCES_COLLECTION, + TaskInstance, + find_task_instance, + 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 FRAMEWORK = installed("agentenv-framework") +SOURCE, DIGEST = "sha256:" + "a" * 64, "sha256:" + "b" * 64 class _Reads(TaskStep): @@ -85,14 +99,9 @@ async def verify(self, context): def registries(monkeypatch, local_stores): steps = {**Config().task_step_registry(), _Reads.type: _Reads, _Score.type: _Score} monkeypatch.setattr(Config, "task_step_registry", lambda self: steps) - image = lambda image_id, **fields: get_artifact_store().put_document(DockerImageArtifact( # noqa: E731 - id=image_id, description=image_id, image_name=f"registry.example/{image_id}:v1", **fields)) - servers = [MCPServerEnv.put(id=name, docker_image_artifact=image(f"{name}-image", source_digest="sha256:" + "a" * 64, - tar_gz_s3_url="s3://b/x"), environment_name=name) - for name in ("crm", "desk")] - MultiEnv.put(id="office", mcp_server_envs=servers) - A2AAgent.put(id="solver", docker_image_artifact=image("solver-image", image_digest="sha256:" + "b" * 64)) - image("data", tar_gz_s3_url="s3://b/data") + entities.office(source_digest=SOURCE, agent_id=None) + entities.agent("solver", image_digest=DIGEST) + entities.image("data") def _task(*steps): @@ -103,7 +112,7 @@ def _task(*steps): def _run(task, overrides=None, **kwargs): context = TaskStepContext(metadata={"user_overrides": overrides or {}}) result = asyncio.run(task.run(context=context, **kwargs)) - assert run_lock.flush_run_records(10) + assert record_writer.flush_run_records(10) return result, context @@ -114,37 +123,37 @@ def test_a_run_records_what_ran_it_and_what_it_was_asked_and_read(): instance = find_task_instance(context.instance_id) [runtime], [lock] = instance.runtime, instance.lock - assert (runtime["attempt_epoch"], runtime["agentenv_framework"], runtime["config"]) == ( - 0, FRAMEWORK, {"selected_by": "none"}) - 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"} - intent = lock["intent"] - assert (intent["task_id"], intent["task_version"], intent["content_hash"], intent["result_rules_version"]) == ( + assert (runtime.attempt_epoch, runtime.agentenv_framework, runtime.config_selected_by, runtime.stage) == ( + 0, FRAMEWORK, "none", Stage.FINISHED) + 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 + 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) - assert intent["pins"] == {"env": {"office": 1}} - assert intent["overrides"] == {"judge_model": "j", "step_params": {"score": {"threshold": 0.9}}, - "agent_model": "solver-model"} - assert (intent["roles"]["solver"]["model"], intent["roles"]["judge"]["model"]) == ("solver-model", "j") - verifier = lock["resolved"]["verifiers"]["score"] - assert (verifier["type"], verifier["distribution"], verifier["settings"]["scoring_rules"]) == ( - "run_lock_test_score", None, 1) - assert {(r["kind"], r["id"], r["version"], r["latest"]) for r in lock["resolved"]["reads"]} == { + assert intent.pins == {"env": {"office": 1}} + assert intent.overrides == {"judge_model": "j", "step_params": {"score": {"threshold": 0.9}}, + "agent_model": "solver-model"} + assert (intent.roles["solver"].model, intent.roles["judge"].model) == ("solver-model", "j") + verifier = lock.verifiers["score"] + assert (verifier.type, verifier.distribution, verifier.settings["scoring_rules"]) == ("run_lock_test_score", None, 1) + assert {(r.kind, r.id, r.version, r.latest) for r in lock.reads} == { ("env", "office", 1, True), ("env", "crm", 1, False), ("env", "desk", 1, False), ("artifact", "crm-image", 1, False), ("artifact", "desk-image", 1, False), ("agent", "solver", 1, True), ("artifact", "solver-image", 1, False), ("artifact", "data", 1, True)} - identities = {r["id"]: r.get("image_identity") for r in lock["resolved"]["reads"] if r["kind"] == "artifact"} - assert identities == {"crm-image": "source:sha256:" + "a" * 64, "desk-image": "source:sha256:" + "a" * 64, - "solver-image": "registry:sha256:" + "b" * 64, "data": None} + assert {r.id: r.image_identity for r in lock.reads if r.kind == "artifact"} == { + "crm-image": f"source:{SOURCE}", "desk-image": f"source:{SOURCE}", "solver-image": f"registry:{DIGEST}", + "data": None} def test_the_grades_verifier_version_and_settings_are_the_locks(): _, context = _run(_task()) - instance = find_task_instance(context.instance_id) + locked = find_task_instance(context.instance_id).lock[0].verifiers["score"] - grade, locked = context.metadata["grades"]["score"], instance.lock[0]["resolved"]["verifiers"]["score"] - assert grade["verifier_settings"] == locked["settings"] and grade["verifier_version"] == locked["version"] - assert locked["graded_settings"] == grade["verifier_settings"] + grade = context.metadata["grades"]["score"] + assert grade["verifier_settings"] == locked.settings == locked.graded_settings + assert grade["verifier_version"] == locked.version def test_settings_a_verifier_completes_as_it_grades_are_in_the_lock_beside_those_it_started_with(monkeypatch): @@ -159,38 +168,50 @@ async def verify(self, context): monkeypatch.setattr(_Score, "verify", verify) _, context = _run(_task()) - locked = find_task_instance(context.instance_id).lock[0]["resolved"]["verifiers"]["score"] - assert "temperature" not in locked["settings"] and locked["graded_settings"]["temperature"] == 0.3 + locked = find_task_instance(context.instance_id).lock[0].verifiers["score"] + assert "temperature" not in locked.settings and locked.graded_settings["temperature"] == 0.3 def test_two_runs_with_different_seeds_ask_different_things_and_say_so(): task = _task(_Score(id="score", version=None, verifier_id="score", note="grade it as would")) contexts = [asyncio.run(task.run(context=TaskStepContext(metadata={"seed": {"who": who}}))) for who in ("a", "b")] - assert run_lock.flush_run_records(10) - locks = [find_task_instance(context.instance_id).lock[0]["intent"] for context in contexts] + assert record_writer.flush_run_records(10) + intents = [find_task_instance(context.instance_id).lock[0].intent for context in contexts] - assert locks[0]["content_hash"] == locks[1]["content_hash"] - assert locks[0]["steps_hash"] != locks[1]["steps_hash"] and "grade it as a" not in json.dumps(locks) + assert intents[0].content_hash == intents[1].content_hash + assert intents[0].steps_hash != intents[1].steps_hash + assert "grade it as a" not in json.dumps([intent.to_dict() for intent in intents]) -def test_a_resume_in_another_process_adds_its_own_entries_and_keeps_the_first(): +def test_a_resume_in_another_process_adds_its_own_records_and_keeps_the_first(): task = _task() _, first = _run(task) - _, second = _run(task, instance_id=first.instance_id, start_step=1) + _run(task, instance_id=first.instance_id, start_step=1) instance = find_task_instance(first.instance_id) - assert [e["attempt_epoch"] for e in instance.runtime] == [e["attempt_epoch"] for e in instance.lock] == [0, 1] - assert instance.lock[0]["resolved"]["reads"] and instance.lock[1]["resolved"]["reads"] == [] + assert [r.attempt_epoch for r in instance.runtime] == [r.attempt_epoch for r in instance.lock] == [0, 1] + assert instance.lock[0].reads and instance.lock[1].reads == [] + + +def test_a_resume_names_the_settings_only_of_the_verifiers_it_graded(): + task = _task(_Score(id="early", version=None, verifier_id="early"), _Reads(id="reads", version=None), + _Score(id="late", version=None, verifier_id="late")) + _, first = _run(task) + asyncio.run(task.run(context=first, instance_id=first.instance_id, start_step=2)) + assert record_writer.flush_run_records(10) + + resumed = find_task_instance(first.instance_id).lock[1].verifiers + assert resumed["early"].graded_settings is None and resumed["late"].graded_settings is not None def test_a_run_that_fails_records_what_it_read(): context = TaskStepContext() with pytest.raises(RuntimeError, match="the step fails"): asyncio.run(_task(_Reads(id="reads", version=None, fail=True)).run(context=context)) - assert run_lock.flush_run_records(10) + assert record_writer.flush_run_records(10) [lock] = find_task_instance(context.instance_id).lock - assert {r["id"] for r in lock["resolved"]["reads"]} >= {"office", "solver", "data"} + assert lock.finished and {r.id for r in lock.reads} >= {"office", "solver", "data"} def test_a_cancelled_run_records_what_it_read_before_the_cancel(): @@ -205,16 +226,16 @@ async def cancelled(): return context context = asyncio.run(cancelled()) - assert run_lock.flush_run_records(10) # the record's write runs on past the cancel + assert record_writer.flush_run_records(10) # the record's write runs on past the cancel [lock] = find_task_instance(context.instance_id).lock - assert {r["id"] for r in lock["resolved"]["reads"]} >= {"office", "solver", "data"} + assert {r.id for r in lock.reads} >= {"office", "solver", "data"} -def test_a_run_whose_record_cant_be_made_runs_unrecorded(monkeypatch): +def test_a_run_whose_records_cant_be_made_runs_unrecorded(monkeypatch): def broken(*args, **kwargs): raise RuntimeError("no record") - monkeypatch.setattr(run_lock, "lock_entry", broken) + monkeypatch.setattr(run_lock, "started_lock", broken) _, context = _run(_task()) instance = find_task_instance(context.instance_id) @@ -233,9 +254,10 @@ def test_no_path_is_recorded_whatever_the_plugin_or_config(monkeypatch, tmp_path _, context = _run(_task()) [runtime] = find_task_instance(context.instance_id).runtime - assert runtime["plugins"] == {"acme-steps": {"version": "1.2.0", "origin": "editable"}} - assert runtime["config"] == {"selected_by": "environment"} - assert str(tmp_path) not in json.dumps(runtime) and "/home/someone" not in json.dumps(runtime) + assert runtime.plugins == {"acme-steps": InstalledPlugin("1.2.0", "editable")} + assert runtime.config_selected_by == "environment" + stored = json.dumps(runtime.to_dict()) + assert str(tmp_path) not in stored and "/home/someone" not in stored class _Editable: @@ -243,41 +265,73 @@ def read_text(self, name): return json.dumps({"url": "file:///home/someone/acme-steps", "dir_info": {"editable": True}}) -def test_an_attempts_record_written_again_replaces_its_own_and_keeps_the_others(): +def _records(epoch, stage=Stage.STARTED, python="3"): + intent = RunIntent(task_id="t", task_version=1, content_hash="sha256:c", steps_hash="sha256:s") + return (RunRuntime(attempt_epoch=epoch, agentenv_framework="1", agentenv_protocol="1", python=python, stage=stage), + RunLock(attempt_epoch=epoch, intent=intent, stage=stage, + reads=[] if stage == Stage.FINISHED else None)) + + +def test_an_attempts_records_written_again_replace_its_own_and_keep_the_others(): _, context = _run(_task()) store = get_task_instance_store() - store.record_run_lock_sync(context.instance_id, {"attempt_epoch": 3, "n": 1}, {"attempt_epoch": 3}) - store.record_run_lock_sync(context.instance_id, {"attempt_epoch": 3, "n": 2}, {"attempt_epoch": 3}) + store.record_run_lock_sync(context.instance_id, *_records(3, python="first")) + store.record_run_lock_sync(context.instance_id, *_records(3, python="second")) instance = find_task_instance(context.instance_id) - assert [(e["attempt_epoch"], e.get("n")) for e in instance.runtime] == [(0, None), (3, 2)] - + assert [(r.attempt_epoch, r.python) for r in instance.runtime][1:] == [(3, "second")] + assert [r.attempt_epoch for r in instance.lock] == [0, 3] -def test_an_instance_stored_before_the_records_loads_without_them(): - instance = TaskInstance.from_dict({"instance_id": "i", "task_id": "t", "task_version": 1, "status": "running", - "current_step": 0, "total_steps": 1}) - assert (instance.runtime, instance.lock) == ([], []) - -def test_a_start_landing_after_its_attempts_end_keeps_the_end(): +def test_a_started_record_landing_after_its_attempts_finished_one_keeps_the_finished(): _, context = _run(_task()) - store = get_task_instance_store() finished = find_task_instance(context.instance_id) - started = {**finished.lock[0], "resolved": {**finished.lock[0]["resolved"], "reads": None}} + started = dataclasses.replace(finished.lock[0], reads=None, stage=Stage.STARTED) - assert not store.record_run_lock_sync(context.instance_id, finished.runtime[0], started) + assert not get_task_instance_store().record_run_lock_sync(context.instance_id, finished.runtime[0], started) assert find_task_instance(context.instance_id).lock == finished.lock -def test_a_resume_names_the_settings_only_of_the_verifiers_it_graded(): - task = _task(_Score(id="early", version=None, verifier_id="early"), _Reads(id="reads", version=None), - _Score(id="late", version=None, verifier_id="late")) - _, first = _run(task) - asyncio.run(task.run(context=first, instance_id=first.instance_id, start_step=2)) - assert run_lock.flush_run_records(10) +def test_a_record_write_leaves_the_instances_own_counter_to_its_other_writers(): + _, context = _run(_task()) + docs, key = get_config().get_document_store(), Filter.of(instance_id=context.instance_id) + before = docs.find_one(TASK_INSTANCES_COLLECTION, key) + + get_task_instance_store().record_run_lock_sync(context.instance_id, *_records(5, Stage.FINISHED)) + after = docs.find_one(TASK_INSTANCES_COLLECTION, key) + + assert after["rev"] == before["rev"] # a writer that read before the record write still lands + assert after.get("run_records_rev", 0) > before.get("run_records_rev", 0) + + +def test_an_instance_stored_before_the_records_loads_without_them(): + instance = TaskInstance.from_dict({"instance_id": "i", "task_id": "t", "task_version": 1, "status": "running", + "current_step": 0, "total_steps": 1}) + assert (instance.runtime, instance.lock) == ([], []) + - resumed = find_task_instance(first.instance_id).lock[1]["resolved"]["verifiers"] - assert "graded_settings" not in resumed["early"] and "graded_settings" in resumed["late"] +def test_every_field_of_the_records_survives_a_round_trip(): + """The records' to_dict and from_dict are written by hand, so each sample sets every field away from its default + and must come back equal: a field either one leaves out fails here.""" + plugin = InstalledPlugin(version="1.2.0", origin="editable") + runtime = RunRuntime(attempt_epoch=2, agentenv_framework="9.9", agentenv_protocol="9.8", python="3.12.4", + 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")}, + 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) + 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 + assert default is dataclasses.MISSING or getattr(sample, f.name) != default, (type(sample), f.name) + assert type(sample).from_dict(json.loads(json.dumps(sample.to_dict()))) == sample + assert RunLock.from_dict({**lock.to_dict(), "stage": "from-a-newer-version"}).stage == "from-a-newer-version" def test_a_store_that_hangs_holds_up_neither_the_run_nor_its_loop(monkeypatch): @@ -285,7 +339,7 @@ def test_a_store_that_hangs_holds_up_neither_the_run_nor_its_loop(monkeypatch): def hanging(instance_id, runtime, lock): release.wait(10) - written.append(lock["resolved"]["reads"] is not None) + written.append(lock.finished) return True monkeypatch.setattr(run_lock, "record_run_lock", hanging) @@ -306,8 +360,8 @@ async def tick(): release.set() return done - (before_release, ticks) = asyncio.run(main()) - assert run_lock.flush_run_records(10) + before_release, ticks = asyncio.run(main()) + assert record_writer.flush_run_records(10) assert before_release == [] and ticks > 0 and sorted(written) == [False, True] @@ -323,25 +377,25 @@ async def main(): release.set() context = asyncio.run(main()) - assert run_lock.flush_run_records(10) + assert record_writer.flush_run_records(10) assert context.metadata["grades"]["score"]["passed"] def test_exiting_waits_for_pending_records_only_so_long_and_says_how_many_it_dropped(monkeypatch, caplog): - release, writer = threading.Event(), run_lock._Writer(1) - monkeypatch.setattr(run_lock, "_WRITER", writer) - monkeypatch.setattr(run_lock, "EXIT_WAIT_SECONDS", 0.2) + release, writer = threading.Event(), record_writer._Writer(1) + monkeypatch.setattr(record_writer, "_WRITER", writer) + monkeypatch.setattr(record_writer, "EXIT_WAIT_SECONDS", 0.2) writer.submit(lambda: release.wait(10)) writer.submit(lambda: None) try: - run_lock._flush_at_exit() + record_writer._flush_at_exit() assert "2 run record(s) not written before exit" in caplog.text finally: release.set() assert writer.flush(5) -def test_a_run_that_reads_one_env_over_and_over_keeps_one_entry_per_entity_version(): +def test_a_run_that_reads_one_env_over_and_over_keeps_one_record_per_entity_version(): with recording() as reads: for _ in range(500): Env.get("office") @@ -350,4 +404,5 @@ def test_a_run_that_reads_one_env_over_and_over_keeps_one_entry_per_entity_versi assert len(reads) == 7 # office, crm, desk, their two images, solver and its image [solver] = [read for read in reads if read.id == "solver"] - assert solver.asked is None # read at its latest once, which the entry keeps + assert solver.asked is None # read at its latest once, which the record keeps + assert [(r.id, r.latest) for r in run_lock.read_records(reads) if r.id == "solver"] == [("solver", True)] diff --git a/tst/util/entities.py b/tst/util/entities.py new file mode 100644 index 000000000..39de1c74c --- /dev/null +++ b/tst/util/entities.py @@ -0,0 +1,36 @@ +"""A small stored world for tests of what runs read: images, MCP servers, an office (a multi env of servers) and an +agent, each put in the configured stores. Every call puts a new version, so a test publishes one by calling again.""" + +from agent_env.a2a_agent import A2AAgent +from agent_env.artifact.artifacts.docker_image import DockerImageArtifact +from agent_env.artifact.store import get_artifact_store +from agent_env.env.envs.mcp_server import MCPServerEnv +from agent_env.env.envs.multi_env import MultiEnv + + +def image(image_id: str, **fields) -> DockerImageArtifact: + """An image held as a tarball unless ``fields`` say otherwise (``source_digest``, ``image_digest``).""" + return get_artifact_store().put_document(DockerImageArtifact(**{ + "id": image_id, "description": image_id, "image_name": f"registry.example/{image_id}:v1", + "tar_gz_s3_url": f"s3://bucket/{image_id}.tar.gz", **fields})) + + +def server(env_id: str, **image_fields) -> MCPServerEnv: + """An MCP server env on a new version of its image ``-image``.""" + return MCPServerEnv.put(id=env_id, docker_image_artifact=image(f"{env_id}-image", **image_fields), + environment_name=env_id) + + +def agent(agent_id: str, **image_fields) -> A2AAgent: + """An agent on a new version of its image ``-image``.""" + return A2AAgent.put(id=agent_id, docker_image_artifact=image(f"{agent_id}-image", **image_fields)) + + +def office(children=("crm", "desk"), *, env_id: str = "office", agent_id: str | None = "solver", + **image_fields) -> MultiEnv: + """``office``, a multi env holding a new version of each server in ``children``, their images taking + ``image_fields``, and a new version of the agent ``agent_id`` unless it's None.""" + env = MultiEnv.put(id=env_id, mcp_server_envs=[server(child, **image_fields) for child in children]) + if agent_id: + agent(agent_id) + return env From c2c68436dd80f3bd810c7ad4ee3bfd656a1daa03 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 30 Nov 2026 13:35:25 -0800 Subject: [PATCH 08/10] fix(task): a run's record write goes to the store the run wrote to, resolved when it's queued Namespace routing is on while a scope count is, which copying the run's context doesn't carry, so a record write that landed after its caller left its namespace_routing() block went to the configured store and missed an @local instance. The document store is now resolved as the write is queued, in the run, and handed to it. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task/run_lock.py | 8 +++++--- src/agent_env/task/store.py | 13 ++++++++----- tst/unit/task/run_lock_test.py | 18 +++++++++++++++++- 3 files changed, 30 insertions(+), 9 deletions(-) diff --git a/src/agent_env/task/run_lock.py b/src/agent_env/task/run_lock.py index 0665ea6dd..03bfff1c4 100644 --- a/src/agent_env/task/run_lock.py +++ b/src/agent_env/task/run_lock.py @@ -180,9 +180,11 @@ async def run_recorded(instance_id: Optional[str], task: "Task", steps: Sequence def _write(instance_id: str, runtime: RunRuntime, lock: RunLock) -> None: - """Write the attempt's records on the record writers, in the run's context, so an ``@local`` run's records go to the - local stores as the run's own writes do; a write that fails is logged by ``record_run_lock``.""" - write_record(functools.partial(contextvars.copy_context().run, record_run_lock, instance_id, runtime, lock)) + """Write the attempt's records on the record writers, to the document store the run writes to, resolved now, in the + run's context: a write may land after the run returns and its caller leaves its ``namespace_routing`` block, and an + ``@local`` run's records must still go to the local stores. A write that fails is logged by ``record_run_lock``.""" + docs = get_config().get_document_store() + write_record(functools.partial(contextvars.copy_context().run, record_run_lock, instance_id, runtime, lock, docs)) def _started(instance_id: str, task: "Task", steps: Sequence[TaskStep], context: TaskStepContext, diff --git a/src/agent_env/task/store.py b/src/agent_env/task/store.py index f18dbf7fb..8802597a8 100644 --- a/src/agent_env/task/store.py +++ b/src/agent_env/task/store.py @@ -903,12 +903,15 @@ def _mutate(doc: dict) -> UpdateSpec | None: return compare_and_swap(self._doc_store, TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id), _mutate, counter_field=_REV) is not None - def record_run_lock_sync(self, instance_id: str, runtime: RunRuntime, lock: RunLock) -> bool: + def record_run_lock_sync(self, instance_id: str, runtime: RunRuntime, lock: RunLock, + docs: Optional[DocumentStore] = None) -> bool: """Keep an attempt's ``runtime`` and ``lock`` records, in place of any the attempt (their ``attempt_epoch``) kept before, so the same write sent again, or a run's end replacing its start, keeps one of each; whether they were kept. A ``finished`` record never gives way to a ``started`` one, so the start and end writes keep the end in whichever order they land. Records of other attempts stay, a later one's included, since each describes its - own. The write is fenced by the records' own counter, as only it touches them.""" + own. The write is fenced by the records' own counter, as only it touches them. ``docs`` is the document store + to write to, resolved when the write was queued, as a write that lands after its run returns must still reach + the store the run wrote to; this process's own by default.""" epoch = lock.attempt_epoch def _mutate(doc: dict) -> UpdateSpec | None: @@ -922,7 +925,7 @@ def replaced(entries: list | None, entry: dict) -> list[dict]: return UpdateSpec(set={RUNTIME_KEY: replaced(doc.get(RUNTIME_KEY), runtime.to_dict()), LOCK_KEY: replaced(doc.get(LOCK_KEY), lock.to_dict())}) - return compare_and_swap(self._doc_store, TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id), + return compare_and_swap(docs or self._doc_store, TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id), _mutate, counter_field=_RUN_RECORDS_REV) is not None def record_teardown_sync(self, instance_id: str, context: "TaskStepContext", attempt_epoch: int) -> None: @@ -1220,11 +1223,11 @@ def _retried(write: Callable[[], _T], failed: _T, what: str) -> _T: logger.warning("Failed to %s after %d attempts", what, _FAILURE_WRITE_MAX_ATTEMPTS, exc_info=last_exc) return failed -def record_run_lock(instance_id: str, runtime: RunRuntime, lock: RunLock) -> bool: +def record_run_lock(instance_id: str, runtime: RunRuntime, lock: RunLock, docs: Optional[DocumentStore] = None) -> bool: """``TaskInstanceStore.record_run_lock_sync``, retried like the run's other records; whether it was kept. A write that keeps failing is logged rather than raised: a run isn't failed for its record of what ran.""" store = get_task_instance_store() - return _retried(lambda: store.record_run_lock_sync(instance_id, runtime, lock), False, + return _retried(lambda: store.record_run_lock_sync(instance_id, runtime, lock, docs), False, f"record what attempt {lock.attempt_epoch} of instance_id={instance_id} ran") diff --git a/tst/unit/task/run_lock_test.py b/tst/unit/task/run_lock_test.py index 9bcc767a1..b97f9a147 100644 --- a/tst/unit/task/run_lock_test.py +++ b/tst/unit/task/run_lock_test.py @@ -22,6 +22,7 @@ from agent_env.plugins import _provenance from agent_env.plugins._requirements import installed from agent_env.store.query import Filter +from agent_env.store.routing import namespace_routing from agent_env.task import Task, record_writer, run_lock from agent_env.task.result import RESULT_RULES_VERSION from agent_env.task.run_records import ( @@ -337,7 +338,7 @@ def test_every_field_of_the_records_survives_a_round_trip(): def test_a_store_that_hangs_holds_up_neither_the_run_nor_its_loop(monkeypatch): release, written = threading.Event(), [] - def hanging(instance_id, runtime, lock): + def hanging(instance_id, runtime, lock, docs=None): release.wait(10) written.append(lock.finished) return True @@ -406,3 +407,18 @@ def test_a_run_that_reads_one_env_over_and_over_keeps_one_record_per_entity_vers [solver] = [read for read in reads if read.id == "solver"] assert solver.asked is None # read at its latest once, which the record keeps assert [(r.id, r.latest) for r in run_lock.read_records(reads) if r.id == "solver"] == [("solver", True)] + + +def test_a_local_runs_records_reach_the_local_stores_when_they_land_after_routing_ends(monkeypatch): + held = [] + monkeypatch.setattr(run_lock, "write_record", held.append) # the writes land only once the routing block is left + task = Task(id="@local/t", version=1, steps=[_Score(id="score", version=None, verifier_id="score")]) + with namespace_routing(): + context = asyncio.run(task.run(context=TaskStepContext())) + for write in held: + write() + + assert find_task_instance(context.instance_id) is None # nothing reached the configured store + with namespace_routing(): + [lock] = find_task_instance(context.instance_id).lock + assert lock.finished and lock.intent.task_id == "@local/t" From 368dd73079bc8fc2347066d1bf3e03d67283f195 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 30 Nov 2026 14:29:45 -0800 Subject: [PATCH 09/10] fix(task): a run record this version can't read leaves its instance readable, and grades name their attempt - An instance leaves out, with a warning, a run record this version can't read, as a newer version may write, rather than fail to load; a resume's re-register reads the instance back, so such a record had stopped the resume after its write reset the run. The store decides a write on the stored stage alone and keeps other entries as stored. - Each grade records the attempt epoch it was written under (`attempt_epoch`), and a lock's `graded_settings` are those of the grades its own attempt, or a retry within it, wrote. The lock had told them apart by object identity, which a retry's rebuilt context breaks, crediting a resume with grades it restored. - A record write that can't be queued, as when no writer thread can start, is logged instead of failing the run or replacing its exception; the writers count each thread as it starts, so the next write starts the rest. - The explorer gives an instance's run records as they're stored, and its listing leaves them out. - Names settled before any record is stored: `runtimes` and `run_locks` on the instance, `packages` for the core's and protocol's versions as the eval plan's `IntentLock` holds them, and `record_run_records`. - The counter's docs say what DynamoDB, which conditions a write on the whole item, still retries; one `run_recorded` block per attempt is the contract. - Tests: the resume rolls a step back, the version check uses a built-in verifier, and tst/conftest.py waits for each test's run records before the next. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 31 ++-- src/agent_env/explorer/routers/runs.py | 27 +++- src/agent_env/task/record_writer.py | 13 +- src/agent_env/task/run_lock.py | 60 ++++---- src/agent_env/task/run_records.py | 26 ++-- src/agent_env/task/store.py | 63 +++++--- .../task_steps/verifiers/verifier.py | 11 +- tst/conftest.py | 11 ++ tst/unit/explorer/explorer_app_test.py | 19 +++ tst/unit/task/run_lock_test.py | 138 +++++++++++++----- .../task_step/verifiers/test_verifier_base.py | 1 + 11 files changed, 274 insertions(+), 126 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index fe098dbb5..c0e176181 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -182,7 +182,7 @@ and deserialized through a registry. |---|---| | `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on, its `placement` (`inside` its computer, the default, or `beside` a device it reaches, as an Android phone's driver does over adb; its class says it too, a put refusing the two when they differ, and `provider` is reserved and refused) and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | | `artifact/` | Immutable versioned artifacts; every `put()` creates a new version. The document goes to the document store, binary payloads to the object store. Every artifact but an environment universe, whose `metadata` key holds its legacy metadata file ids, carries a `metadata` dict outside its versioned fields, changed by compare-and-swap (`merge_metadata`). Built-ins: `CliArtifact` (`cli`), `ComputerArtifact` (`computer`, a base computer: its architectures, OS, session user, settings and container form, whose image `put` reads from its registry into `metadata.validated_images`), `FileArtifact` (`file`), `FileArtifactUniverse` (`file_artifact_universe`), `DockerImageArtifact` (`docker_image`), `EnvironmentArtifact` (`environment`: its environment's files by path, stored as the one wrapped `file_artifact_ref` every environment artifact had when it has one file at its filename, else as `file_artifact_refs`; `get_file_artifacts()` reads either, and a load hands each file to the env's `data/add` with its path, which a pre-v1 load, taking one file, refuses), `EnvironmentUniverseArtifact` (`environment_universe`), `SkillArtifact` (`skill`); `[artifacts] type_aliases` maps another stored spelling of a type onto one of them. A `DockerImageArtifact` holds a tar.gz of its image, or, written by `put_ref` (`--image-ref` on `env mcp-server put` and `a2a-agent put`), only a registry reference with its tag pinned to a digest, which sandboxes pull, or a published image's tag with its `image_digest` and its build context, which sandboxes pull by the digest and build from the context when they can't (the infra images, and a bundle agent built from a shipped agent's sources, `Plan.published`), or, written by `put_context`, only its build context, which a VM sandbox builds before running it (`VmSandbox.load_docker_images`) and Modal builds before creating its container (`ModalSandboxProvider.prepare_image`, outside a fallback chain's deadline); anything else that runs images by name (a container on the local provider, a lone server on any provider but Modal) refuses such an image. A build context (`utils/docker/context.py`) is what `docker build` would send, `.dockerignore` applied, written so equal files give equal bytes and an equal `source_digest`. | -| `task/`, `task_step/` | A `Task` holds its `TaskStep`s inline; `Task.run()` executes them as a DAG. Its `headline_verifiers`, step ids saved only when set, name the grades that are its reward: one is the reward, several a multi-reward over them, none a multi-reward over every grade; it refuses one that names no step of the task, or one named twice. `depends_on` (None means all prior steps) gates a step, independent steps run concurrently, `fail_task_on_error` makes a failure fatal or tolerated, `retry_config` rolls a failed span back through the step journal and re-dispatches it. `task/lint.py` is `agent-env task lint` (a bundle folder, a task file or a stored task): an error is what a task gets wrong before it runs (a field its step doesn't read, a step's own `config_problems`, a headline that grades nothing, an aggregate source no verifier writes) and refuses `agent-env run`, `bundle register`, `task create`, `task validate` and `eval run`, and the bundle plans `openenv`'s `build_app` and the trainers make (`run`, `register`, `build_app`, `prepare_bundle` and the trainers take `--skip-lint`/`skip_lint`, which lifts lint's own rules but not a step's `config_problems`, which refused a bundle before lint; `eval run`'s lifts every error, since it checked none before); a warning is what may be wrong (a step's `config_warnings`, a store entity read with no version, no verifier, several and no headline, a judge that runs in the solver's own agent, which training refuses) and is only printed, each kind once by a run (`task.lint.said`), an eval run's unpinned references as one count (`unpinned_summary`), every one by `task lint`. `aggregate_verifiers` names its sources by step id (`sources`, `gates`) and reads their named grades: `combine` `pooled` (the default) pools their rows, `weighted_mean` weighs their scores, equally unless `weights` gives every source one, and a failing gate scores it 0; a failed or missing source fails it, and its older `verifier_ids` pools legacy entries as it always has. Built-in steps live in `task_step/task_steps/` (`deploy_env`, `deploy_agent`, `prompt_agent`, the verifiers under `verifiers/`, among them `start_computer_recording` (its driver draws each input over the frames in its caller's colour, and a pointer per role where the frames lack one, unless `annotation_settings` says `is_enabled: false`; a driver whose card lists no `annotate` records it plain, with a warning, and the run's recording entry says `annotated`) and `end_computer_recording`, `start_browser_recording` and `end_browser_recording` (`browser-recording/v1`: one recording per context, a lease's or the default one's, with a video of the tab its agent is on, its context's log, the browser's network log as HAR and opt-in frames keyed to the action log, the contexts its agents make recorded with it, one universe per recording, anything missing failing the run), and more). Every built-in verifier is on the `VerifierTaskStep` base (`verifiers/verifier.py`): it implements `verify` and returns a `Verification`, and the base writes the step's named grade to `context.metadata["grades"][]` (score, `min_passing_score`, `passed`, `verifier_status` graded, skipped or failed, criteria rows, type, version, and `verifier_settings`, the values the run graded with, its overrides applied and named in `overridden`, with `scoring_rules`) beside the legacy `verifications` entries every reader still takes; a judge's grade also has `judge_calls`, a record of each model call it made (`JudgeUsage`), each naming exactly what it was sent (`input`: a direct call's messages, response format and settings, an agent call's message, every file its step staged in the judge's sandbox and, for a judge the task deployed, what the task's own `load_artifact` steps put there as the run recorded it, stored by sha256 under `judge-inputs/` in the background, `judge_utils/judge_inputs.py`; the step waits for those uploads, at most 120 s, before it writes its grade, `VerifierTaskStep.settle`, and one that failed or hadn't finished is the call's `input_error`, never a failed grade), and its `verifier_settings` hold the trajectory source of each turn it read (`trajectory_sources`); with `judge_samples` (a count, as a step field, a run override or `--judge-samples` on `run`, `task run` and `eval run`), a rubric_binary or rubric_partial judge grades each criterion that many times, each a call of its own under `judge_batch_concurrency` (an agent judge the verifier deploys gets a deployment of its own per sample, its trajectory staged in each; the task's own judge takes every sample), and keeps its median, the lower middle score on a tie, which fails it, the row the first sample that scored it gave with every sample's score, verdict and justification in its `samples` and its `agreement`, the share of samples giving its verdict; a row under `min_judge_agreement` (0.5 by default, which never fails, so the median decides; 1.0 fails any split; set where `judge_samples` is, `--min-judge-agreement`) fails the grade, its rows kept, and then the step (`JudgeDisagreementError`), and `agent-env run` names the criteria a grade that stood split on (`samples split:`), and one failed sample fails the grade (a run's count or agreement a judge of another format can't take is recorded in `not_sent`) and the effort and thinking budget its calls carried, with `not_sent` for those its route or agent card doesn't take (a value the model refuses fails the grade); an exception from `verify` or a `Verification` with an `error`, as a timed-out `run_container_unit_tests_verifier`, is a failed grade, and `rubrics_verifier` still writes its `-trajectory-mistakes` entry itself. On an env whose card serves computer-exec/v1 (a computer), `run_code` with `env_id` and `run_container_unit_tests_verifier` with `env_id` run inside it as its session user through the driver: files staged with `data/add` and read with `data/get`, commands run with `run`; `computer_exec` runs one command there through `run` (a program and its arguments, or a string through `sh -c`; in a multi env, the computer it names), recorded under `computer_exec` in the run's metadata, a non-zero exit or a timeout failing it unless `check` is off, or with `background` starts it and leaves it running, as an app launched for the agent, a program that isn't there exiting 127; with `scope: "system"` it runs as root instead, through the computer's sandbox (`RootChannel`, `docker exec -u 0`), in the session user's folder and `HOME`, its output capped in the computer, never with `background` and not on a computer booted from a disk; on a Windows computer, which has no `sh`, a string or `background` command is refused; on a multi env, `load_artifact` with `env_id` puts an environment artifact named after one of its computers, or after an app of one, into that computer, the computer's own as files at their paths under the session user's home; `env_outcome_verifier` hands a `verify` that takes an `env_url` keyword the env's address. A computer's framework-only routes (everything but MCP and the card) take the per-deploy control token its provider boots it with (`DeployedEnv.control_token`), each computer its own, a multi env's included, never the gateway's: its boot environment holds only the token's sha256 (`AGENTENV_CONTROL_TOKEN_SHA256`) when its probed card's computer/v1 says `control_token = "sha256"`, else, for a driver an older protocol built, the token itself (`AGENTENV_CONTROL_TOKEN`); the gateway learns each computer's (`CHILD_CONTROL_TOKENS`), puts it in place of its own on that computer's `/svc` routes, and lets a computer's token through only to that computer and its clock watch; a multi env's record grants each computer's `/svc` route its own token (`DeployedGatewayEnv.control_grants`, the longest granted address winning), and `CONTROL_TOKEN_CHILDREN`, the computers an older agent-env booted with the gateway's token, is kept for them; framework calls send `deployed.control_headers`, `Task.run` runs every step under `protocol_v1.authorized` with each deployed env's (a `verify` included), and a `run_code` script inside the computer gets `input["env"]["headers"]`. `teardown_run` and the `teardown_sandboxes` step share one core (`task/teardown.py` `tear_down`): the recordings the run left open end with fresh grants, each env still up closes (`Env.close`; a computer env ends any recording still open), what stayed open is registered from its namespace, then every sandbox is terminated by id. A run whose teardown leaves sandboxes up, stopped by a second signal or failing, keeps on its instance the context it ended with (`record_teardown`), and `agent-env run` and `task run --keep` name `agent-env task teardown --instance `, which tears down what that context still records up, a running one only with `--force`. `task/episode/` runs a task with some of its agents played from outside, as a training loop does (`EpisodeSpec`). | +| `task/`, `task_step/` | A `Task` holds its `TaskStep`s inline; `Task.run()` executes them as a DAG. Its `headline_verifiers`, step ids saved only when set, name the grades that are its reward: one is the reward, several a multi-reward over them, none a multi-reward over every grade; it refuses one that names no step of the task, or one named twice. `depends_on` (None means all prior steps) gates a step, independent steps run concurrently, `fail_task_on_error` makes a failure fatal or tolerated, `retry_config` rolls a failed span back through the step journal and re-dispatches it. `task/lint.py` is `agent-env task lint` (a bundle folder, a task file or a stored task): an error is what a task gets wrong before it runs (a field its step doesn't read, a step's own `config_problems`, a headline that grades nothing, an aggregate source no verifier writes) and refuses `agent-env run`, `bundle register`, `task create`, `task validate` and `eval run`, and the bundle plans `openenv`'s `build_app` and the trainers make (`run`, `register`, `build_app`, `prepare_bundle` and the trainers take `--skip-lint`/`skip_lint`, which lifts lint's own rules but not a step's `config_problems`, which refused a bundle before lint; `eval run`'s lifts every error, since it checked none before); a warning is what may be wrong (a step's `config_warnings`, a store entity read with no version, no verifier, several and no headline, a judge that runs in the solver's own agent, which training refuses) and is only printed, each kind once by a run (`task.lint.said`), an eval run's unpinned references as one count (`unpinned_summary`), every one by `task lint`. `aggregate_verifiers` names its sources by step id (`sources`, `gates`) and reads their named grades: `combine` `pooled` (the default) pools their rows, `weighted_mean` weighs their scores, equally unless `weights` gives every source one, and a failing gate scores it 0; a failed or missing source fails it, and its older `verifier_ids` pools legacy entries as it always has. Built-in steps live in `task_step/task_steps/` (`deploy_env`, `deploy_agent`, `prompt_agent`, the verifiers under `verifiers/`, among them `start_computer_recording` (its driver draws each input over the frames in its caller's colour, and a pointer per role where the frames lack one, unless `annotation_settings` says `is_enabled: false`; a driver whose card lists no `annotate` records it plain, with a warning, and the run's recording entry says `annotated`) and `end_computer_recording`, `start_browser_recording` and `end_browser_recording` (`browser-recording/v1`: one recording per context, a lease's or the default one's, with a video of the tab its agent is on, its context's log, the browser's network log as HAR and opt-in frames keyed to the action log, the contexts its agents make recorded with it, one universe per recording, anything missing failing the run), and more). Every built-in verifier is on the `VerifierTaskStep` base (`verifiers/verifier.py`): it implements `verify` and returns a `Verification`, and the base writes the step's named grade to `context.metadata["grades"][]` (score, `min_passing_score`, `passed`, `verifier_status` graded, skipped or failed, criteria rows, type, version, the `attempt_epoch` it was written under, and `verifier_settings`, the values the run graded with, its overrides applied and named in `overridden`, with `scoring_rules`) beside the legacy `verifications` entries every reader still takes; a judge's grade also has `judge_calls`, a record of each model call it made (`JudgeUsage`), each naming exactly what it was sent (`input`: a direct call's messages, response format and settings, an agent call's message, every file its step staged in the judge's sandbox and, for a judge the task deployed, what the task's own `load_artifact` steps put there as the run recorded it, stored by sha256 under `judge-inputs/` in the background, `judge_utils/judge_inputs.py`; the step waits for those uploads, at most 120 s, before it writes its grade, `VerifierTaskStep.settle`, and one that failed or hadn't finished is the call's `input_error`, never a failed grade), and its `verifier_settings` hold the trajectory source of each turn it read (`trajectory_sources`); with `judge_samples` (a count, as a step field, a run override or `--judge-samples` on `run`, `task run` and `eval run`), a rubric_binary or rubric_partial judge grades each criterion that many times, each a call of its own under `judge_batch_concurrency` (an agent judge the verifier deploys gets a deployment of its own per sample, its trajectory staged in each; the task's own judge takes every sample), and keeps its median, the lower middle score on a tie, which fails it, the row the first sample that scored it gave with every sample's score, verdict and justification in its `samples` and its `agreement`, the share of samples giving its verdict; a row under `min_judge_agreement` (0.5 by default, which never fails, so the median decides; 1.0 fails any split; set where `judge_samples` is, `--min-judge-agreement`) fails the grade, its rows kept, and then the step (`JudgeDisagreementError`), and `agent-env run` names the criteria a grade that stood split on (`samples split:`), and one failed sample fails the grade (a run's count or agreement a judge of another format can't take is recorded in `not_sent`) and the effort and thinking budget its calls carried, with `not_sent` for those its route or agent card doesn't take (a value the model refuses fails the grade); an exception from `verify` or a `Verification` with an `error`, as a timed-out `run_container_unit_tests_verifier`, is a failed grade, and `rubrics_verifier` still writes its `-trajectory-mistakes` entry itself. On an env whose card serves computer-exec/v1 (a computer), `run_code` with `env_id` and `run_container_unit_tests_verifier` with `env_id` run inside it as its session user through the driver: files staged with `data/add` and read with `data/get`, commands run with `run`; `computer_exec` runs one command there through `run` (a program and its arguments, or a string through `sh -c`; in a multi env, the computer it names), recorded under `computer_exec` in the run's metadata, a non-zero exit or a timeout failing it unless `check` is off, or with `background` starts it and leaves it running, as an app launched for the agent, a program that isn't there exiting 127; with `scope: "system"` it runs as root instead, through the computer's sandbox (`RootChannel`, `docker exec -u 0`), in the session user's folder and `HOME`, its output capped in the computer, never with `background` and not on a computer booted from a disk; on a Windows computer, which has no `sh`, a string or `background` command is refused; on a multi env, `load_artifact` with `env_id` puts an environment artifact named after one of its computers, or after an app of one, into that computer, the computer's own as files at their paths under the session user's home; `env_outcome_verifier` hands a `verify` that takes an `env_url` keyword the env's address. A computer's framework-only routes (everything but MCP and the card) take the per-deploy control token its provider boots it with (`DeployedEnv.control_token`), each computer its own, a multi env's included, never the gateway's: its boot environment holds only the token's sha256 (`AGENTENV_CONTROL_TOKEN_SHA256`) when its probed card's computer/v1 says `control_token = "sha256"`, else, for a driver an older protocol built, the token itself (`AGENTENV_CONTROL_TOKEN`); the gateway learns each computer's (`CHILD_CONTROL_TOKENS`), puts it in place of its own on that computer's `/svc` routes, and lets a computer's token through only to that computer and its clock watch; a multi env's record grants each computer's `/svc` route its own token (`DeployedGatewayEnv.control_grants`, the longest granted address winning), and `CONTROL_TOKEN_CHILDREN`, the computers an older agent-env booted with the gateway's token, is kept for them; framework calls send `deployed.control_headers`, `Task.run` runs every step under `protocol_v1.authorized` with each deployed env's (a `verify` included), and a `run_code` script inside the computer gets `input["env"]["headers"]`. `teardown_run` and the `teardown_sandboxes` step share one core (`task/teardown.py` `tear_down`): the recordings the run left open end with fresh grants, each env still up closes (`Env.close`; a computer env ends any recording still open), what stayed open is registered from its namespace, then every sandbox is terminated by id. A run whose teardown leaves sandboxes up, stopped by a second signal or failing, keeps on its instance the context it ended with (`record_teardown`), and `agent-env run` and `task run --keep` name `agent-env task teardown --instance `, which tears down what that context still records up, a running one only with `--force`. `task/episode/` runs a task with some of its agents played from outside, as a training loop does (`EpisodeSpec`). | | `store/` | Four store ABCs with local and cloud implementations: `DocumentStore` (SQLite, MongoDB, DynamoDB, Firestore with MongoDB compatibility), `ObjectStore` (filesystem, S3, Cloud Storage), `ImageStore` (local OCI registry, ECR), `SecretStore` (env vars or file, AWS Secrets Manager, Google Cloud Secret Manager). `VersionedEntityStore` implements the shared versioned get/put logic, `QueryBuilder` is the immutable chained query API, `store/base.py` holds the error types. `store/routing.py` is the local namespaces, `@local` and `@hf` (`is_local_id`), each with a documents file of its own: while the CLI or a `build_app` server runs, a local id and what a local task's run records go to local stores beside the configured ones, and that run's writes to the configured stores are refused. A new backend must pass the conformance kits in `tst/store/`. | | `config/` | The `Config` singleton (`get_config`, `configure`, `reset_config`) in `config/runtime.py`, file discovery in `config/loader.py`, and `load_impl`, which resolves `module:Class` pointers. `agent_env.store` re-exports the config names for compatibility. | | `providers/` | `providers/sandbox_providers/` holds the sandbox providers `local`, `modal`, `modal_vm`, `e2b`, `sail_vm` (the `sail` extra), `smol_vm` (the `smol` extra), `tensorlake` (the `tensorlake` extra), `tenki` (the `tenki` extra), `vercel` (the `vercel` extra), `boxd` (the `boxd` extra), `coreweave` (the `coreweave` extra), `daytona` (the `daytona` extra), `boat` (the `boat` extra), `agent37` (no extra), `kosa8` (no extra); `[sandbox] default` and `agent_default` accept a comma-separated fallback chain, whose deploys skip a provider that can't run them. A sandbox provider declares what it runs (`ON_THIS_MACHINE`, and for VMs on this machine the address their requests to it arrive at, `REACHES_HOST_AT`; `CONTAINER_ACCEPTS`, `PRIVATE_NETWORK`, `WEBSOCKETS`; `SUPPORTED_SANDBOX_MODES`, derived from whether it implements `create_sandbox` and `create_vm`; and `SANDBOX_ACCEPTS`, the images an agent's sandbox runs, which defaults to those a VM loads when it implements `create_vm` and to `CONTAINER_ACCEPTS` otherwise, so only a provider that implements `create_vm` yet gives an agent a container, like the local one, declares it), each sandbox carries the `platform` of the images it runs (linux/amd64 unless its provider sets another when it creates it; None, any, unchecked, for a local sandbox), and code outside `providers/sandbox_providers/` reads those, never which provider it has. `providers/env_providers/` holds the environment providers: `EnvironmentProvider` (an env's containers and state store), `EnvironmentGatewayProvider` (`gateway`, an env's default), which renders a docker-compose for the gateway and its MCP servers inside the sandbox, and `EnvironmentServerProvider` (`server`), one MCP server in its own container with no gateway in front and no state store; `providers/env_state/` holds env-state providers (`local_postgres` built in). | @@ -474,19 +474,22 @@ orchestrators call it the same way. What callers rely on: references it did not create. - A run is resumable: pass a previously persisted `context`, a `start_step` and the existing `instance_id`; completed steps are seeded as SUCCESS. -- Each attempt a process starts records, on the instance and by its `attempt_epoch`, the code that ran it and what - it was asked to do and read (`task/run_lock.py`, `run_recorded`), as the typed records `task/run_records.py` - declares: `RunRuntime` (the core, protocol and Python versions, 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`; 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; 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`) so they never make the instance's other writes retry; the store keeps the - finished record whichever lands last, and a resume adds its own. A worker that runs a task's steps itself enters - `run_recorded` around them, as it sets `run_pins`. +- Each attempt a process starts records, on the instance (`runtimes` and `run_locks`) and by its `attempt_epoch`, the + code that ran it and what it was asked to do and read (`task/run_lock.py`, `run_recorded`), as the typed records + `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`; 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`. - 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/explorer/routers/runs.py b/src/agent_env/explorer/routers/runs.py index 1113dd74d..b5327545c 100644 --- a/src/agent_env/explorer/routers/runs.py +++ b/src/agent_env/explorer/routers/runs.py @@ -22,7 +22,15 @@ from agent_env.explorer.routers.common import PaginatedResponse, docs from agent_env.runner.runner import RunStatus from agent_env.store import Filter -from agent_env.task.store import TaskStepStatus, count_task_instances, find_task_instance, task_instances +from agent_env.task.store import ( + RUN_LOCKS_KEY, + RUNTIMES_KEY, + TaskInstance, + TaskStepStatus, + count_task_instances, + find_task_instance, + task_instances, +) logger = logging.getLogger(__name__) @@ -261,8 +269,8 @@ def list_instances( ) -> PaginatedResponse: items = task_instances(task_id, task_version=task_version, limit=limit, offset=offset) total = count_task_instances(task_id, task_version=task_version) - return PaginatedResponse(items=[dataclasses.asdict(i) for i in items], total=total, limit=limit, offset=offset, - has_more=offset + len(items) < total) + return PaginatedResponse(items=[_instance_view(i, records=False) for i in items], total=total, limit=limit, + offset=offset, has_more=offset + len(items) < total) @router.get("/{task_id}/instances/{instance_id}") @@ -270,7 +278,18 @@ def get_instance(task_id: EntityId, instance_id: EntityId) -> dict: instance = find_task_instance(instance_id) if instance is None: raise HTTPException(status_code=404, detail=f"instance {instance_id} not found") - return dataclasses.asdict(instance) + return _instance_view(instance, records=True) + + +def _instance_view(instance: TaskInstance, *, records: bool) -> dict: + """An instance as the API gives it, its run records as they're stored (``to_dict``); a listing leaves them out, + since each attempt's reads would come with every row.""" + view = dataclasses.asdict(dataclasses.replace(instance, runtimes=[], run_locks=[])) + del view[RUNTIMES_KEY], view[RUN_LOCKS_KEY] + if records: + view[RUNTIMES_KEY] = [runtime.to_dict() for runtime in instance.runtimes] + view[RUN_LOCKS_KEY] = [lock.to_dict() for lock in instance.run_locks] + return view # --- run groups ------------------------------------------------------------- diff --git a/src/agent_env/task/record_writer.py b/src/agent_env/task/record_writer.py index e3f1cfa0d..e049cc061 100644 --- a/src/agent_env/task/record_writer.py +++ b/src/agent_env/task/record_writer.py @@ -22,21 +22,20 @@ class _Writer: - """Runs each write it's given on one of ``threads`` daemon threads, started on the first, and counts those - pending.""" + """Runs each write it's given on one of ``threads`` daemon threads, started as writes come, and counts those + pending. A thread that can't start raises from ``submit``, which queues nothing, and the next submit starts it.""" def __init__(self, threads: int) -> None: self._threads, self._queue = threads, queue.SimpleQueue() - self._pending, self._started = 0, False + self._pending, self._running = 0, 0 self._done = threading.Condition() def submit(self, write: Callable[[], Any]) -> None: with self._done: + while self._running < self._threads: + threading.Thread(target=self._work, name=f"agentenv-run-record-{self._running}", daemon=True).start() + self._running += 1 self._pending += 1 - if not self._started: - self._started = True - for n in range(self._threads): - threading.Thread(target=self._work, name=f"agentenv-run-record-{n}", daemon=True).start() self._queue.put(write) def flush(self, timeout: Optional[float] = None) -> bool: diff --git a/src/agent_env/task/run_lock.py b/src/agent_env/task/run_lock.py index 03bfff1c4..e739007ff 100644 --- a/src/agent_env/task/run_lock.py +++ b/src/agent_env/task/run_lock.py @@ -6,15 +6,16 @@ Each attempt a process starts keeps one of each, by the ``attempt_epoch`` it started under; an attempt a retry starts within the run belongs to the records before it, since the same process runs it with the same code. They are written ``started`` when the run starts and ``finished``, with what it read, when it ends, however it ends, so a run that dies -midway keeps what it started with, unless it dies within moments of starting. A write that fails is logged, never -failing the run. Neither is awaited: both go to the record writers (``agent_env.task.record_writer``), in the run's -context, so neither holds up the run or the threads its other work shares when the store is slow, nor adds a point -where a cancel can land outside the run's own handling of one. The finished record may land just after the run returns, -and the two may land in either order: the store keeps the finished one (``record_run_lock_sync``). +midway keeps what it started with, unless it dies within moments of starting. A write that fails, or can't be queued, +is logged, never failing the run. Neither is awaited: both go to the record writers (``agent_env.task.record_writer``), +in the run's context, so neither holds up the run or the threads its other work shares when the store is slow, nor adds +a point where a cancel can land outside the run's own handling of one. The finished record may land just after the run +returns, and the two may land in either order: the store keeps the finished one (``record_run_records_sync``). ``Task.run`` records them through ``run_recorded``; a worker that runs a task's steps itself enters ``run_recorded`` -around them the same way. Reads made on a thread that doesn't carry the run's context, as the computer composer's -pool, aren't listed. +around them the same way, once per attempt, in the process that runs all of the attempt's steps: a second block on the +same attempt replaces the first's finished records. Reads made on a thread that doesn't carry the run's context, as the +computer composer's pool, aren't listed. """ from __future__ import annotations @@ -26,7 +27,7 @@ import hashlib import logging import platform -from typing import TYPE_CHECKING, Any, AsyncIterator, Iterable, Mapping, Optional, Sequence +from typing import TYPE_CHECKING, Any, AsyncIterator, Iterable, Optional, Sequence from agent_env.config import get_config from agent_env.entity.pins import PINS_KEY, Read, checked_pins, recording @@ -42,8 +43,7 @@ install_origin, installed_plugins, ) -from agent_env.plugins._provenance import FRAMEWORK, PROTOCOL -from agent_env.plugins._requirements import installed +from agent_env.plugins._requirements import CORE, installed from agent_env.task.record_writer import write_record from agent_env.task.result import RESULT_RULES_VERSION from agent_env.task.run_records import ( @@ -55,7 +55,7 @@ Stage, VerifierRecord, ) -from agent_env.task.store import record_run_lock +from agent_env.task.store import record_run_records from agent_env.task_step.context import TaskStepContext from agent_env.task_step.task_step import TaskStep from agent_env.task_step.task_steps.verifiers.verifier import GRADES_KEY, VerifierTaskStep @@ -80,8 +80,7 @@ def started_runtime(attempt_epoch: int, steps: Sequence[TaskStep]) -> RunRuntime the run used.""" return RunRuntime( attempt_epoch=attempt_epoch, - agentenv_framework=installed(FRAMEWORK), - agentenv_protocol=installed(PROTOCOL), + packages={name: installed(name) for name in CORE}, 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(), @@ -120,13 +119,11 @@ 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, - graded_before: Optional[Mapping[str, Any]] = None) -> tuple[RunRuntime, RunLock]: +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 - runtime, the types of the envs, artifacts and providers it used. ``graded_before`` are the grades the context held - as the attempt started, as a resume's restored context does: a grade still the one it held is an earlier - attempt's, whose settings this one didn't grade with.""" + 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: @@ -136,15 +133,21 @@ def finished_records(runtime: RunRuntime, lock: RunLock, reads: Iterable[Read], (_group(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, before = context.metadata.get(GRADES_KEY) or {}, graded_before or {} + grades = context.metadata.get(GRADES_KEY) or {} verifiers = {step_id: (dataclasses.replace(verifier, graded_settings=grades[step_id].get("verifier_settings")) - if isinstance(grades.get(step_id), dict) and grades[step_id] is not before.get(step_id) - else verifier) + if _graded_in(grades.get(step_id), lock.attempt_epoch) else verifier) for step_id, verifier in lock.verifiers.items()} return (dataclasses.replace(runtime, types=types, stage=Stage.FINISHED), dataclasses.replace(lock, verifiers=verifiers, reads=read_records(reads), stage=Stage.FINISHED)) +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 + return isinstance(epoch, int) and epoch >= attempt_epoch + + def read_records(reads: Iterable[Read]) -> list[ReadRecord]: """Each read as its lock lists it, by kind, id and version. ``reads`` are distinct already (``entity.pins.Reads``), each carrying whether it was read at its latest or through an alias.""" @@ -165,13 +168,12 @@ async def run_recorded(instance_id: Optional[str], task: "Task", steps: Sequence return runtime, lock = started _write(instance_id, runtime, lock) - graded_before = dict(context.metadata.get(GRADES_KEY) or {}) with recording() as reads: try: yield finally: try: - runtime, lock = finished_records(runtime, lock, reads, context, graded_before) + runtime, lock = finished_records(runtime, lock, reads, context) except Exception: logger.warning("The reads of attempt %s of %s couldn't be recorded", attempt_epoch, instance_id, exc_info=True) @@ -182,9 +184,15 @@ async def run_recorded(instance_id: Optional[str], task: "Task", steps: Sequence def _write(instance_id: str, runtime: RunRuntime, lock: RunLock) -> None: """Write the attempt's records on the record writers, to the document store the run writes to, resolved now, in the run's context: a write may land after the run returns and its caller leaves its ``namespace_routing`` block, and an - ``@local`` run's records must still go to the local stores. A write that fails is logged by ``record_run_lock``.""" - docs = get_config().get_document_store() - write_record(functools.partial(contextvars.copy_context().run, record_run_lock, instance_id, runtime, lock, docs)) + ``@local`` run's records must still go to the local stores. A write that fails is logged by + ``record_run_records``, and one that can't be queued, as when no writer thread can start, here.""" + try: + docs = get_config().get_document_store() + write_record(functools.partial(contextvars.copy_context().run, record_run_records, instance_id, runtime, lock, + docs)) + except Exception: + logger.warning("The %s records of attempt %s of %s couldn't be queued", lock.stage, lock.attempt_epoch, + instance_id, exc_info=True) def _started(instance_id: str, task: "Task", steps: Sequence[TaskStep], context: TaskStepContext, diff --git a/src/agent_env/task/run_records.py b/src/agent_env/task/run_records.py index e1b2635a6..f50820709 100644 --- a/src/agent_env/task/run_records.py +++ b/src/agent_env/task/run_records.py @@ -3,9 +3,11 @@ comparison of two runs can name each one it reads. Each record is written twice by the process that runs the attempt, ``started`` and then ``finished`` (``Stage``), and -names the ``attempt_epoch`` it started under. Reading is lenient: a key this version doesn't know is ignored, one it -lacks takes its default, and a stage it doesn't know is kept as stored, since a newer version may have written the -record to a store several versions share. +names the ``attempt_epoch`` it started under. Reading is lenient, since a newer version may have written the record to a +store several versions share: a key this version doesn't know is ignored, an optional one it lacks takes its default, +and a stage it doesn't know is kept as stored. A record that lacks a key every version writes, as its +``attempt_epoch`` or a lock's ``intent``, can't be read: its instance leaves it out (``TaskInstance``) and the store +keeps it as stored. """ from __future__ import annotations @@ -51,14 +53,14 @@ def from_dict(cls, data: dict) -> InstalledPlugin: @dataclass class RunRuntime: - """The code that ran an attempt: the core, protocol and Python versions, each installed agent-env plugin, how the - config file was found (``environment``, ``discovered`` or ``none``), and, by registry (``task_steps``, ``envs``, - ``artifacts``, ``sandbox_providers``, ``env_providers``), the distribution that supplied each type the run used: - its steps' from the start, the rest once it finished.""" + """The code that ran an attempt: the core's and protocol's versions by distribution name (``packages``, as an eval + plan's ``IntentLock`` holds them), the Python version, each installed agent-env plugin, how the config file was + found (``environment``, ``discovered`` or ``none``), and, by registry (``task_steps``, ``envs``, ``artifacts``, + ``sandbox_providers``, ``env_providers``), the distribution that supplied each type the run used: its steps' from + the start, the rest once it finished.""" attempt_epoch: int - agentenv_framework: Optional[str] - agentenv_protocol: Optional[str] + packages: dict[str, Optional[str]] python: str plugins: dict[str, InstalledPlugin] = field(default_factory=dict) config_selected_by: Optional[str] = None @@ -71,8 +73,7 @@ def to_dict(self) -> dict: "attempt_epoch": self.attempt_epoch, "record_version": self.record_version, "stage": str(self.stage), - "agentenv_framework": self.agentenv_framework, - "agentenv_protocol": self.agentenv_protocol, + "packages": dict(self.packages), "python": self.python, "plugins": {name: plugin.to_dict() for name, plugin in self.plugins.items()}, "config": {"selected_by": self.config_selected_by}, @@ -83,8 +84,7 @@ def to_dict(self) -> dict: def from_dict(cls, data: dict) -> RunRuntime: return cls( attempt_epoch=data["attempt_epoch"], - agentenv_framework=data.get("agentenv_framework"), - agentenv_protocol=data.get("agentenv_protocol"), + packages=dict(data.get("packages") or {}), python=data.get("python", ""), plugins={name: InstalledPlugin.from_dict(plugin) for name, plugin in (data.get("plugins") or {}).items()}, config_selected_by=(data.get("config") or {}).get("selected_by"), diff --git a/src/agent_env/task/store.py b/src/agent_env/task/store.py index 8802597a8..4b7d400a2 100644 --- a/src/agent_env/task/store.py +++ b/src/agent_env/task/store.py @@ -28,7 +28,7 @@ commit_ordered, replay_context, ) -from agent_env.task.run_records import RunLock, RunRuntime +from agent_env.task.run_records import RunLock, RunRuntime, Stage from agent_env.task.usage.ledger import LEDGER_KEY, TOTAL_KEY, ahead, entries_of, ledger_fields, total from agent_env.task_step.context import TaskStepContext from agent_env.task_step.context_ops import ContextUpdateOps @@ -52,10 +52,13 @@ RESULT_KEY = "result" # What ran each attempt and what it read (``agent_env.task.run_records``): an entry per attempt a process started, by its # ``attempt_epoch``, kept across re-registers so a resume's entries sit beside the first run's. Only the record writes -# touch them, under a counter of their own, so they never make the instance's other writers retry, nor those them. -RUNTIME_KEY = "runtime" -LOCK_KEY = "lock" +# touch them, under a counter of their own, which the instance's other writers never check, nor these theirs; a store +# that conditions a write on the whole document, as DynamoDB's does, still has a write that lands between another's +# read and write retry it, without losing either. +RUNTIMES_KEY = "runtimes" +RUN_LOCKS_KEY = "run_locks" _RUN_RECORDS_REV = "run_records_rev" +_R = TypeVar("_R", RunRuntime, RunLock) # Where a submitter names the eval slot a run fills, in ``context.metadata``: ``{eval_instance_id, slot, attempt}``, # which registering the run keeps as the instance's own fields. EVAL_SLOT_KEY = "eval_slot" @@ -212,8 +215,8 @@ class TaskInstance: # A grade version per grading of the run, oldest first; empty until the run ends. result: list[dict] = field(default_factory=list) # An entry per attempt a process started, by attempt_epoch: the code that ran it and what it was asked and read. - runtime: list[RunRuntime] = field(default_factory=list) - lock: list[RunLock] = field(default_factory=list) + runtimes: list[RunRuntime] = field(default_factory=list) + run_locks: list[RunLock] = field(default_factory=list) @classmethod def from_dict(cls, data: dict) -> TaskInstance: @@ -238,11 +241,24 @@ def from_dict(cls, data: dict) -> TaskInstance: slot=data.get("slot"), attempt=data.get("attempt"), result=data.get(RESULT_KEY) or [], - runtime=[RunRuntime.from_dict(entry) for entry in data.get(RUNTIME_KEY) or []], - lock=[RunLock.from_dict(entry) for entry in data.get(LOCK_KEY) or []], + runtimes=_readable(data, RUNTIMES_KEY, RunRuntime), + run_locks=_readable(data, RUN_LOCKS_KEY, RunLock), ) +def _readable(data: dict, key: str, record: type[_R]) -> list[_R]: + """The entries under ``key`` this version can read; one it can't, as a newer version may write, is left out with a + warning rather than make its instance unreadable, which would fail a run that resumes it.""" + readable = [] + for entry in data.get(key) or []: + try: + readable.append(record.from_dict(entry)) + except Exception as exc: # noqa: BLE001 + logger.warning("instance %s: left out a %s entry this version can't read: %s: %s", data.get("instance_id"), + key, type(exc).__name__, exc) + return readable + + @dataclass class StepAttemptFailure: """Recorded once per failed step attempt, so a later retry can't clobber the earlier, @@ -307,8 +323,8 @@ def _new_instance_doc( _GENERATION: 0, LEDGER_KEY: [], TOTAL_KEY: total([]), - RUNTIME_KEY: [], - LOCK_KEY: [], + RUNTIMES_KEY: [], + RUN_LOCKS_KEY: [], **run_state, } @@ -903,27 +919,28 @@ def _mutate(doc: dict) -> UpdateSpec | None: return compare_and_swap(self._doc_store, TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id), _mutate, counter_field=_REV) is not None - def record_run_lock_sync(self, instance_id: str, runtime: RunRuntime, lock: RunLock, - docs: Optional[DocumentStore] = None) -> bool: + def record_run_records_sync(self, instance_id: str, runtime: RunRuntime, lock: RunLock, + docs: Optional[DocumentStore] = None) -> bool: """Keep an attempt's ``runtime`` and ``lock`` records, in place of any the attempt (their ``attempt_epoch``) kept before, so the same write sent again, or a run's end replacing its start, keeps one of each; whether they were kept. A ``finished`` record never gives way to a ``started`` one, so the start and end writes keep the end - in whichever order they land. Records of other attempts stay, a later one's included, since each describes its - own. The write is fenced by the records' own counter, as only it touches them. ``docs`` is the document store + in whichever order they land; only the stored stage is read to tell, so a record this version can't read is + still replaced. Records of other attempts stay as stored, a later one's included, since each describes its own. + The write is fenced by the records' own counter, as only it touches them. ``docs`` is the document store to write to, resolved when the write was queued, as a write that lands after its run returns must still reach the store the run wrote to; this process's own by default.""" epoch = lock.attempt_epoch def _mutate(doc: dict) -> UpdateSpec | None: - stored = next((e for e in doc.get(LOCK_KEY) or [] if e.get("attempt_epoch") == epoch), None) - if stored is not None and RunLock.from_dict(stored).finished and not lock.finished: + stored = next((e for e in doc.get(RUN_LOCKS_KEY) or [] if e.get("attempt_epoch") == epoch), None) + if stored is not None and stored.get("stage") == Stage.FINISHED and not lock.finished: return None def replaced(entries: list | None, entry: dict) -> list[dict]: kept = [e for e in entries or [] if e.get("attempt_epoch") != epoch] return sorted([*kept, entry], key=lambda e: e.get("attempt_epoch", 0)) - return UpdateSpec(set={RUNTIME_KEY: replaced(doc.get(RUNTIME_KEY), runtime.to_dict()), - LOCK_KEY: replaced(doc.get(LOCK_KEY), lock.to_dict())}) + return UpdateSpec(set={RUNTIMES_KEY: replaced(doc.get(RUNTIMES_KEY), runtime.to_dict()), + RUN_LOCKS_KEY: replaced(doc.get(RUN_LOCKS_KEY), lock.to_dict())}) return compare_and_swap(docs or self._doc_store, TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id), _mutate, counter_field=_RUN_RECORDS_REV) is not None @@ -1223,11 +1240,13 @@ def _retried(write: Callable[[], _T], failed: _T, what: str) -> _T: logger.warning("Failed to %s after %d attempts", what, _FAILURE_WRITE_MAX_ATTEMPTS, exc_info=last_exc) return failed -def record_run_lock(instance_id: str, runtime: RunRuntime, lock: RunLock, docs: Optional[DocumentStore] = None) -> bool: - """``TaskInstanceStore.record_run_lock_sync``, retried like the run's other records; whether it was kept. A write - that keeps failing is logged rather than raised: a run isn't failed for its record of what ran.""" + +def record_run_records(instance_id: str, runtime: RunRuntime, lock: RunLock, + docs: Optional[DocumentStore] = None) -> bool: + """``TaskInstanceStore.record_run_records_sync``, retried like the run's other records; whether they were kept. A + write that keeps failing is logged rather than raised: a run isn't failed for its record of what ran.""" store = get_task_instance_store() - return _retried(lambda: store.record_run_lock_sync(instance_id, runtime, lock, docs), False, + return _retried(lambda: store.record_run_records_sync(instance_id, runtime, lock, docs), False, f"record what attempt {lock.attempt_epoch} of instance_id={instance_id} ran") 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 af568a77f..0759e739e 100644 --- a/src/agent_env/task_step/task_steps/verifiers/verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/verifier.py @@ -16,7 +16,7 @@ from agent_env.config import get_config from agent_env.plugins import distribution_version -from agent_env.task_step.context import TaskStepContext +from agent_env.task_step.context import ATTEMPT_EPOCH, TaskStepContext from agent_env.task_step.task_step import RetryConfig, StepRole, TaskStep, TaskStepDependency from agent_env.task_step.task_steps.verifiers.scoring import ScoreAggregator, aggregate_score from agent_env.task_step.thread_work import finish_on_thread @@ -59,14 +59,16 @@ class _GradeFields(TypedDict): verifier_type: str verifier_version: Optional[str] verifier_settings: dict[str, Any] + attempt_epoch: Optional[int] class Grade(_GradeFields, total=False): """A verifier step's named grade, as ``context.metadata["grades"][]`` holds it. ``verifier_status`` is a ``VerifierStatus`` value, and ``score`` is None unless it is ``graded``; each ``verifier_criteria`` row has ``id``, - ``score``, ``passed``, ``weight`` and ``skipped``, besides any other keys the verifier gave it. The two - ``verifier_output`` fields here are written only for a large output; ``judge_calls``, a judge's record of each model - call it made, only by a judge (``grade_fields``).""" + ``score``, ``passed``, ``weight`` and ``skipped``, besides any other keys the verifier gave it. ``attempt_epoch`` + is the attempt epoch the step ran under (``ATTEMPT_EPOCH``), None outside ``Task.run``, so a reader can tell a grade + an attempt wrote from one its resume restored. The two ``verifier_output`` fields here are written only for a large + output; ``judge_calls``, a judge's record of each model call it made, only by a judge (``grade_fields``).""" verifier_output_ref: dict[str, Any] verifier_output_offload_error: str @@ -219,6 +221,7 @@ def _grade(self, context: TaskStepContext, status: VerifierStatus, score: Option verifier_type=self.type, verifier_version=distribution_version(type(self)), verifier_settings=self.recorded_settings(context), + attempt_epoch=ATTEMPT_EPOCH.get(), **self.grade_fields(context), ) diff --git a/tst/conftest.py b/tst/conftest.py index 881c1ea77..0461c58e8 100644 --- a/tst/conftest.py +++ b/tst/conftest.py @@ -26,6 +26,7 @@ def _reset_store_singletons() -> None: value() +RUN_RECORDS_WAIT_SECONDS = 10 _STATE_DIR = pytest.StashKey[str]() _PACKAGES_DIR = pytest.StashKey[str]() _state_home = pytest.MonkeyPatch() @@ -115,6 +116,16 @@ def fresh_config_document(): reset_config() +@pytest.fixture(autouse=True) +def run_records_written(fresh_config_document): + """The run records a test's runs left on the record writers' threads written before the next test, so none lands in + a store or a log the next test reads; before the config is reset, which this asks for so that it's torn down after. + A process that never imported the writers has none.""" + yield + if writers := sys.modules.get("agent_env.task.record_writer"): + writers.flush_run_records(RUN_RECORDS_WAIT_SECONDS) + + @pytest.fixture(scope="module", autouse=True) def setup_config(): """Per-module store-singleton sweep; the config itself is reset per test above. The grant servers close too: diff --git a/tst/unit/explorer/explorer_app_test.py b/tst/unit/explorer/explorer_app_test.py index e41644e32..aae8935c2 100644 --- a/tst/unit/explorer/explorer_app_test.py +++ b/tst/unit/explorer/explorer_app_test.py @@ -25,6 +25,7 @@ from agent_env.store.document_store.sqlite_document_store import LocalSqliteDocumentStore from agent_env.store.routing import LocalNamespaceDocumentStore, RoutingDocumentStore from agent_env.task import Task +from agent_env.task.run_records import ReadRecord, RunIntent, RunLock, RunRuntime, Stage from agent_env.explorer.routers import objects as objects_router from agent_env.explorer.routers import triggers as triggers_router from tst.unit.store.fakes import FakeObjectStore @@ -356,6 +357,24 @@ def test_a_bundle_runs_namespaced_instance_id_is_one_encoded_segment(client): assert len(client.get(f"/api/v1/task-instances/{instance}/conversations").json()["conversations"]) == 1 +def test_an_instance_gives_its_run_records_as_stored_and_a_listing_leaves_them_out(client): + task_id, instance_id = "@local/~/triage/recorded", "@local/~/triage/recorded-1" + runtime = RunRuntime(attempt_epoch=0, packages={"agentenv-framework": "1.0"}, python="3.12", + config_selected_by="none", stage=Stage.FINISHED) + intent = RunIntent(task_id=task_id, task_version=1, content_hash="sha256:c", steps_hash="sha256:s") + lock = RunLock(attempt_epoch=0, intent=intent, reads=[ReadRecord("env", "office", 1)], stage=Stage.FINISHED) + get_config().get_document_store().insert("task_instances", { + "instance_id": instance_id, "task_id": task_id, "task_version": 1, "status": "completed", "total_steps": 1, + "current_step": 1, "completed_steps": [], "runtimes": [runtime.to_dict()], "run_locks": [lock.to_dict()]}) + base = f"/api/v1/tasks/{quote(task_id, safe='')}/instances" + + single = client.get(f"{base}/{quote(instance_id, safe='')}").json() + [listed] = client.get(base).json()["items"] + + assert (single["runtimes"], single["run_locks"]) == ([runtime.to_dict()], [lock.to_dict()]) + assert listed["instance_id"] == instance_id and not {"runtimes", "run_locks"} & listed.keys() + + def test_the_instance_routes_page_newest_first_and_answer_404_for_an_unknown_run(client): task_id = "@local/~/triage/route-ticket" store = get_config().get_document_store() diff --git a/tst/unit/task/run_lock_test.py b/tst/unit/task/run_lock_test.py index b97f9a147..c8b832f5c 100644 --- a/tst/unit/task/run_lock_test.py +++ b/tst/unit/task/run_lock_test.py @@ -1,12 +1,13 @@ """Each attempt of a run records, on its task instance and from the process that runs its steps, the code that ran it -(``runtime``) and what it was asked to do and read (``lock``): written started, then finished however it ends, a -record per attempt, never a path, and never in the way of the run or the instance's other writes.""" +(``runtimes``) and what it was asked to do and read (``run_locks``): written started, then finished however it ends, a +record per attempt, never a path, and never in the way of the run, the instance's other writes or its reads.""" import asyncio import dataclasses import json import threading from concurrent.futures import ThreadPoolExecutor +from types import SimpleNamespace import pytest @@ -21,6 +22,7 @@ from agent_env.eval.lock import RoleModel from agent_env.plugins import _provenance from agent_env.plugins._requirements import installed +from agent_env.store.document_store import UpdateSpec, compare_and_swap from agent_env.store.query import Filter from agent_env.store.routing import namespace_routing from agent_env.task import Task, record_writer, run_lock @@ -41,7 +43,8 @@ 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_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 from tst.util import entities @@ -77,6 +80,27 @@ async def execute(self, context): return context +class _Flaky(TaskStep): + """Fails ``fails`` times, then passes; it retries itself, as a step whose ``retry_config`` names it does.""" + + 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"])) + self.fails = fails + + @classmethod + def from_dict(cls, data): + return cls(**{k: v for k, v in cls._base_from_dict(data).items() if k != "retry_config"}) + + async def execute(self, context): + if self.fails: + self.fails -= 1 + raise RuntimeError("the step fails this time") + return context + + class _Score(VerifierTaskStep): type = "run_lock_test_score" entity_refs = () @@ -98,7 +122,7 @@ async def verify(self, context): @pytest.fixture(autouse=True) def registries(monkeypatch, local_stores): - steps = {**Config().task_step_registry(), _Reads.type: _Reads, _Score.type: _Score} + steps = {**Config().task_step_registry(), _Reads.type: _Reads, _Score.type: _Score, _Flaky.type: _Flaky} monkeypatch.setattr(Config, "task_step_registry", lambda self: steps) entities.office(source_digest=SOURCE, agent_id=None) entities.agent("solver", image_digest=DIGEST) @@ -123,8 +147,8 @@ def test_a_run_records_what_ran_it_and_what_it_was_asked_and_read(): "step_params": {"score": {"threshold": 0.9}}}, agent_model="solver-model") instance = find_task_instance(context.instance_id) - [runtime], [lock] = instance.runtime, instance.lock - assert (runtime.attempt_epoch, runtime.agentenv_framework, runtime.config_selected_by, runtime.stage) == ( + [runtime], [lock] = instance.runtimes, instance.run_locks + assert (runtime.attempt_epoch, runtime.packages["agentenv-framework"], runtime.config_selected_by, runtime.stage) == ( 0, FRAMEWORK, "none", Stage.FINISHED) 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"} @@ -149,12 +173,14 @@ def test_a_run_records_what_ran_it_and_what_it_was_asked_and_read(): def test_the_grades_verifier_version_and_settings_are_the_locks(): - _, context = _run(_task()) - locked = find_task_instance(context.instance_id).lock[0].verifiers["score"] + task = _task(_Score(id="score", version=None, verifier_id="score"), + AggregateVerifiersTaskStep(id="total", version=None, sources=["score"])) + _, context = _run(task) + locked = find_task_instance(context.instance_id).run_locks[0].verifiers["total"] - grade = context.metadata["grades"]["score"] + grade = context.metadata["grades"]["total"] assert grade["verifier_settings"] == locked.settings == locked.graded_settings - assert grade["verifier_version"] == locked.version + assert grade["verifier_version"] == locked.version == FRAMEWORK is not None def test_settings_a_verifier_completes_as_it_grades_are_in_the_lock_beside_those_it_started_with(monkeypatch): @@ -169,7 +195,7 @@ async def verify(self, context): monkeypatch.setattr(_Score, "verify", verify) _, context = _run(_task()) - locked = find_task_instance(context.instance_id).lock[0].verifiers["score"] + locked = find_task_instance(context.instance_id).run_locks[0].verifiers["score"] assert "temperature" not in locked.settings and locked.graded_settings["temperature"] == 0.3 @@ -177,7 +203,7 @@ def test_two_runs_with_different_seeds_ask_different_things_and_say_so(): task = _task(_Score(id="score", version=None, verifier_id="score", note="grade it as would")) contexts = [asyncio.run(task.run(context=TaskStepContext(metadata={"seed": {"who": who}}))) for who in ("a", "b")] assert record_writer.flush_run_records(10) - intents = [find_task_instance(context.instance_id).lock[0].intent for context in contexts] + intents = [find_task_instance(context.instance_id).run_locks[0].intent for context in contexts] assert intents[0].content_hash == intents[1].content_hash assert intents[0].steps_hash != intents[1].steps_hash @@ -190,18 +216,22 @@ def test_a_resume_in_another_process_adds_its_own_records_and_keeps_the_first(): _run(task, instance_id=first.instance_id, start_step=1) instance = find_task_instance(first.instance_id) - assert [r.attempt_epoch for r in instance.runtime] == [r.attempt_epoch for r in instance.lock] == [0, 1] - assert instance.lock[0].reads and instance.lock[1].reads == [] + 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 == [] -def test_a_resume_names_the_settings_only_of_the_verifiers_it_graded(): - task = _task(_Score(id="early", version=None, verifier_id="early"), _Reads(id="reads", version=None), +def test_a_resume_names_the_settings_only_of_the_verifiers_it_graded_though_a_retry_rebuilds_its_context(): + flaky = _Flaky(id="flaky", version=None) + task = _task(_Score(id="early", version=None, verifier_id="early"), flaky, _Score(id="late", version=None, verifier_id="late")) _, first = _run(task) - asyncio.run(task.run(context=first, instance_id=first.instance_id, start_step=2)) + flaky.fails = 1 # the resume rolls the step back once, rebuilding its context from the store + 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).lock[1].verifiers + first_run, resumed = (lock.verifiers for lock in find_task_instance(first.instance_id).run_locks) + assert first_run["early"].graded_settings is not None and first_run["late"].graded_settings is not None assert resumed["early"].graded_settings is None and resumed["late"].graded_settings is not None @@ -211,7 +241,7 @@ def test_a_run_that_fails_records_what_it_read(): asyncio.run(_task(_Reads(id="reads", version=None, fail=True)).run(context=context)) assert record_writer.flush_run_records(10) - [lock] = find_task_instance(context.instance_id).lock + [lock] = find_task_instance(context.instance_id).run_locks assert lock.finished and {r.id for r in lock.reads} >= {"office", "solver", "data"} @@ -228,7 +258,7 @@ async def cancelled(): context = asyncio.run(cancelled()) assert record_writer.flush_run_records(10) # the record's write runs on past the cancel - [lock] = find_task_instance(context.instance_id).lock + [lock] = find_task_instance(context.instance_id).run_locks assert {r.id for r in lock.reads} >= {"office", "solver", "data"} @@ -240,7 +270,7 @@ def broken(*args, **kwargs): _, context = _run(_task()) instance = find_task_instance(context.instance_id) - assert (instance.status, instance.runtime, instance.lock) == ("completed", [], []) + assert (instance.status, instance.runtimes, instance.run_locks) == ("completed", [], []) def test_no_path_is_recorded_whatever_the_plugin_or_config(monkeypatch, tmp_path): @@ -253,7 +283,7 @@ def test_no_path_is_recorded_whatever_the_plugin_or_config(monkeypatch, tmp_path reset_config() # the next get_config reads the file AGENT_ENV_CONFIG names _, context = _run(_task()) - [runtime] = find_task_instance(context.instance_id).runtime + [runtime] = find_task_instance(context.instance_id).runtimes assert runtime.plugins == {"acme-steps": InstalledPlugin("1.2.0", "editable")} assert runtime.config_selected_by == "environment" @@ -268,7 +298,7 @@ def read_text(self, name): def _records(epoch, stage=Stage.STARTED, python="3"): intent = RunIntent(task_id="t", task_version=1, content_hash="sha256:c", steps_hash="sha256:s") - return (RunRuntime(attempt_epoch=epoch, agentenv_framework="1", agentenv_protocol="1", python=python, stage=stage), + return (RunRuntime(attempt_epoch=epoch, packages={"agentenv-framework": "1"}, python=python, stage=stage), RunLock(attempt_epoch=epoch, intent=intent, stage=stage, reads=[] if stage == Stage.FINISHED else None)) @@ -276,21 +306,21 @@ def _records(epoch, stage=Stage.STARTED, python="3"): def test_an_attempts_records_written_again_replace_its_own_and_keep_the_others(): _, context = _run(_task()) store = get_task_instance_store() - store.record_run_lock_sync(context.instance_id, *_records(3, python="first")) - store.record_run_lock_sync(context.instance_id, *_records(3, python="second")) + store.record_run_records_sync(context.instance_id, *_records(3, python="first")) + store.record_run_records_sync(context.instance_id, *_records(3, python="second")) instance = find_task_instance(context.instance_id) - assert [(r.attempt_epoch, r.python) for r in instance.runtime][1:] == [(3, "second")] - assert [r.attempt_epoch for r in instance.lock] == [0, 3] + assert [(r.attempt_epoch, r.python) for r in instance.runtimes][1:] == [(3, "second")] + assert [r.attempt_epoch for r in instance.run_locks] == [0, 3] def test_a_started_record_landing_after_its_attempts_finished_one_keeps_the_finished(): _, context = _run(_task()) finished = find_task_instance(context.instance_id) - started = dataclasses.replace(finished.lock[0], reads=None, stage=Stage.STARTED) + started = dataclasses.replace(finished.run_locks[0], reads=None, stage=Stage.STARTED) - assert not get_task_instance_store().record_run_lock_sync(context.instance_id, finished.runtime[0], started) - assert find_task_instance(context.instance_id).lock == finished.lock + assert not get_task_instance_store().record_run_records_sync(context.instance_id, finished.runtimes[0], started) + assert find_task_instance(context.instance_id).run_locks == finished.run_locks def test_a_record_write_leaves_the_instances_own_counter_to_its_other_writers(): @@ -298,7 +328,7 @@ def test_a_record_write_leaves_the_instances_own_counter_to_its_other_writers(): docs, key = get_config().get_document_store(), Filter.of(instance_id=context.instance_id) before = docs.find_one(TASK_INSTANCES_COLLECTION, key) - get_task_instance_store().record_run_lock_sync(context.instance_id, *_records(5, Stage.FINISHED)) + get_task_instance_store().record_run_records_sync(context.instance_id, *_records(5, Stage.FINISHED)) after = docs.find_one(TASK_INSTANCES_COLLECTION, key) assert after["rev"] == before["rev"] # a writer that read before the record write still lands @@ -308,14 +338,50 @@ def test_a_record_write_leaves_the_instances_own_counter_to_its_other_writers(): def test_an_instance_stored_before_the_records_loads_without_them(): instance = TaskInstance.from_dict({"instance_id": "i", "task_id": "t", "task_version": 1, "status": "running", "current_step": 0, "total_steps": 1}) - assert (instance.runtime, instance.lock) == ([], []) + assert (instance.runtimes, instance.run_locks) == ([], []) + + +def test_a_record_this_version_cant_read_leaves_its_instance_readable_and_resumable(caplog): + task = _task() + _, first = _run(task) + docs, key = get_config().get_document_store(), Filter.of(instance_id=first.instance_id) + newer = {"attempt_epoch": 7, "record_version": 2, "stage": "finished", "plan": {}} + compare_and_swap(docs, TASK_INSTANCES_COLLECTION, key, lambda doc: UpdateSpec(set={ + "run_locks": [*doc["run_locks"], newer], "runtimes": [*doc["runtimes"], {"record_version": 2}]}), + counter_field="run_records_rev") + + assert [lock.attempt_epoch for lock in find_task_instance(first.instance_id).run_locks] == [0] + assert "run_locks entry this version can't read" in caplog.text + _run(task, instance_id=first.instance_id, start_step=1) # its re-register reads the instance back + + assert [lock.attempt_epoch for lock in find_task_instance(first.instance_id).run_locks] == [0, 1] + assert newer in docs.find_one(TASK_INSTANCES_COLLECTION, key)["run_locks"] + + +def test_a_run_whose_record_writers_cant_start_completes_and_later_records_are_written(monkeypatch, caplog): + class _Refused: + def __init__(self, **kwargs): + pass + + def start(self): + raise RuntimeError("can't start new thread") + + monkeypatch.setattr(record_writer, "_WRITER", record_writer._Writer(1)) + with monkeypatch.context() as patched: + patched.setattr(record_writer, "threading", SimpleNamespace(Thread=_Refused)) + _, refused = _run(_task()) + _, later = _run(_task()) + + assert refused.metadata["grades"]["score"]["passed"] and "couldn't be queued" in caplog.text + assert find_task_instance(refused.instance_id).run_locks == [] + assert find_task_instance(later.instance_id).run_locks[0].finished def test_every_field_of_the_records_survives_a_round_trip(): """The records' to_dict and from_dict are written by hand, so each sample sets every field away from its default and must come back equal: a field either one leaves out fails here.""" plugin = InstalledPlugin(version="1.2.0", origin="editable") - runtime = RunRuntime(attempt_epoch=2, agentenv_framework="9.9", agentenv_protocol="9.8", python="3.12.4", + runtime = RunRuntime(attempt_epoch=2, packages={"agentenv-framework": "9.9"}, python="3.12.4", 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", @@ -343,7 +409,7 @@ def hanging(instance_id, runtime, lock, docs=None): written.append(lock.finished) return True - monkeypatch.setattr(run_lock, "record_run_lock", hanging) + monkeypatch.setattr(run_lock, "record_run_records", hanging) async def main(): ticks = 0 @@ -368,7 +434,7 @@ async def tick(): def test_a_hanging_record_write_ties_up_none_of_the_threads_a_runs_other_work_shares(monkeypatch): release = threading.Event() - monkeypatch.setattr(run_lock, "record_run_lock", lambda *args: release.wait(10)) + monkeypatch.setattr(run_lock, "record_run_records", lambda *args: release.wait(10)) async def main(): asyncio.get_running_loop().set_default_executor(ThreadPoolExecutor(max_workers=1)) @@ -420,5 +486,5 @@ def test_a_local_runs_records_reach_the_local_stores_when_they_land_after_routin assert find_task_instance(context.instance_id) is None # nothing reached the configured store with namespace_routing(): - [lock] = find_task_instance(context.instance_id).lock + [lock] = find_task_instance(context.instance_id).run_locks assert lock.finished and lock.intent.task_id == "@local/t" diff --git a/tst/unit/task_step/verifiers/test_verifier_base.py b/tst/unit/task_step/verifiers/test_verifier_base.py index e76cff4bb..bbd87ac00 100644 --- a/tst/unit/task_step/verifiers/test_verifier_base.py +++ b/tst/unit/task_step/verifiers/test_verifier_base.py @@ -63,6 +63,7 @@ def test_a_graded_verification_writes_its_named_grade_and_the_legacy_entry(): ], "verifier_type": "toy_verifier", "verifier_version": None, "verifier_settings": {"scoring_rules": 1, "note": "n", "score_aggregator": "all_pass"}, + "attempt_epoch": None, } From a6e89b9b51364991a1560bb0a5d5acb1ad8a4f52 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 30 Nov 2026 15:14:45 -0800 Subject: [PATCH 10/10] docs(task): a run's sandbox providers are those of the deployments its context records A sandbox a step makes and keeps to itself, as an agent judge's or a sandbox verifier's, isn't among them; recording each sandbox's provider where the sandbox is made comes with the evidence of the image that ran. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 24 ++++++++++++------------ src/agent_env/task/run_lock.py | 8 +++++--- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ac1527ff9..181ad45b9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -489,18 +489,18 @@ orchestrators call it the same way. What callers rely on: code that ran it and what it was asked to do and read (`task/run_lock.py`, `run_recorded`), as the typed records `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`; 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`. + 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`. - A runner that must hear from a long step puts a zero-argument callable at `context.metadata[HEARTBEAT_KEY]` (`task_step/context.py`); a step that blocks for long calls `context.heartbeat()`, a no-op without one. The key is in `_REDACTED_KEYS`, so it is never persisted. diff --git a/src/agent_env/task/run_lock.py b/src/agent_env/task/run_lock.py index e739007ff..d4bcf48e7 100644 --- a/src/agent_env/task/run_lock.py +++ b/src/agent_env/task/run_lock.py @@ -15,7 +15,8 @@ ``Task.run`` records them through ``run_recorded``; a worker that runs a task's steps itself enters ``run_recorded`` around them the same way, once per attempt, in the process that runs all of the attempt's steps: a second block on the same attempt replaces the first's finished records. Reads made on a thread that doesn't carry the run's context, as the -computer composer's pool, aren't listed. +computer composer's pool, aren't listed, nor is the sandbox provider of a sandbox a step makes and keeps to itself, out +of the context's deployments, as an agent judge's or a sandbox verifier's. """ from __future__ import annotations @@ -207,8 +208,9 @@ def _started(instance_id: str, task: "Task", steps: Sequence[TaskStep], context: def _sandbox_types(context: TaskStepContext) -> dict[str, Any]: - """The sandbox types the run deployed on, each with its provider's ``module:Class`` or class as its registry holds - it; None for one this process doesn't register.""" + """The sandbox types of the deployments the run's context records, each with its provider's ``module:Class`` or + class as its registry holds it; None for one this process doesn't register. A sandbox a step keeps to itself, as an + agent judge's, isn't among them.""" names = {d.sandbox_type for d in [*context.deployed_sandboxes, *context.deployed_agents] if d.sandbox_type} names |= {d.sandbox_type for d in context.deployed_envs if getattr(d, "sandbox_type", None)} registry = get_config().sandbox_registry()