diff --git a/AGENTS.md b/AGENTS.md index 2b554dd2e..b0f9e6496 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -506,24 +506,30 @@ 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`, 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, the - trajectory formats it prescribes, its pins, each role's model and endpoint host as this process resolves them, the - overrides without secrets and the result rules version, computed as the eval plan computes its own, `eval/intent.py`; - each verifier's settings and version at the start and as graded, by the grades that graded, neither failed nor skipped, whose `attempt_epoch` is - this attempt's or a retry's within it; every entity version the run read, each image with its `image_identity`; and - the steps it ran, `steps_run`, and whether each reached its end, a verdict included, `completed`, from what `Task.run` - notes as it dispatches each step, `step_dispatched` and `step_ended`). Each is written `started` and then `finished`, - however the run ends, by writer threads of their own (`task/record_writer.py`, never awaited; `flush_run_records` - waits for them, and an exit waits 10 s at most), under a counter of their own (`run_records_rev`) that the instance's - other writes don't check, nor these theirs (on DynamoDB, which conditions a write on the whole item, one still retries - the other); the store keeps the finished record whichever lands last, and a resume adds its own. An instance leaves - out, with a warning, a record this version can't read. A worker that runs a task's steps itself enters `run_recorded` - around them, once per attempt in the process that runs them all, and notes each step as `Task.run` does, as it sets - `run_pins`. + run used, from `agent_env.plugins`' `distribution_of`, its sandbox providers those of the sandboxes it created and 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, the trajectory formats it prescribes, its pins, each role's model and endpoint host as this process + resolves them, the overrides without secrets and the result rules version, computed as the eval plan computes its + own, `eval/intent.py`; each verifier's settings and version at the start and as graded, by the grades that graded, + neither failed nor skipped, whose `attempt_epoch` is this attempt's or a retry's within it; every entity version the + run read, each image with its `image_identity`; and the steps it ran, `steps_run`, and whether each reached its end, a + verdict included, `completed`, from what `Task.run` notes as it dispatches each step, `step_dispatched` and + `step_ended`; and, as its evidence, every sandbox it created, `sandboxes`, each with the step whose work created it, + its provider, mode, platform and id, and whether it served, which it didn't when its create raised, the deploy on its + chain link or the agent deploy it was made for failed, the chain refused it or a probe made it: every provider's + `create_*` notes what it returns, `SandboxProvider.__init_subclass__`, in the run's context, so one a provider + allocates and tears down itself inside a create that raises isn't listed, `providers/sandbox_providers/created.py`). + Each is written `started` and then `finished`, however the run ends, by writer threads of their own + (`task/record_writer.py`, never awaited; `flush_run_records` waits for them, and an exit waits 10 s at most), under a + counter of their own (`run_records_rev`) that the instance's other writes don't check, nor these theirs (on DynamoDB, + which conditions a write on the whole item, one still retries the other); the store keeps the finished record + whichever lands last, and a resume adds its own. An instance leaves out, with a warning, a record this version can't + read. A worker that runs a task's steps itself enters `run_recorded` around them, once per attempt in the process that + runs them all, and notes each step as `Task.run` does, as it sets `run_pins`. - `task/drift.py` (`compare`) classes every difference between two attempts' records by the lock table, its rows `ROWS`: `hard` when they ran different things, `regrade` too for the result rules or a verifier's settings; `soft` for what's - meant to change under a run, as an upgraded package or where its sandboxes ran; `never`, recorded only. Every record + meant to change under a run, as an upgraded package or where its sandboxes were asked to run; `never`, recorded only, + as the sandboxes each step created and a sandbox provider only one attempt used, as a fallback's. Every record field is in a row or in `NOT_COMPARED`, and what a row can't compare it says why (`Comparison.not_compared`). `agent-env task diff` lists them, exiting 0 when the two ran the same thing, 1 on hard drift and 2 when they can't be compared. diff --git a/src/agent_env/a2a_agent/a2a_agent.py b/src/agent_env/a2a_agent/a2a_agent.py index 94fcddbca..54e43949e 100644 --- a/src/agent_env/a2a_agent/a2a_agent.py +++ b/src/agent_env/a2a_agent/a2a_agent.py @@ -36,6 +36,7 @@ ) from agent_env.a2a_agent.staging import transfer_store from agent_env.providers.sandbox_providers.chained_sandbox_provider import skip_refusing +from agent_env.providers.sandbox_providers.created import discarded from agent_env.providers.sandbox_providers.local_docker.provider import LOCAL_TRUST_ENV, local_grant_trust, start_trusting from agent_env.providers.sandbox_providers.sandbox_provider import ( SANDBOX_MODE_VM, @@ -597,6 +598,7 @@ async def deploy( else: provider = skip_refusing(provider, functools.partial(self._refusal, image), what=f"agent {self.id!r}") + created = None try: if provider is not None: logger.info(f"Provisioning sandbox for A2A agent '{self.id}' via {type(provider).__name__}...") @@ -607,7 +609,7 @@ async def deploy( attribution=attribution, network_policy=network_policy, ) - self._owns_sandbox = True + self._owns_sandbox, created = True, self._sandbox logger.info(f"Sandbox created: {self._sandbox.sandbox_id} (mode={self._sandbox.mode})") if problem := provider.sandbox_problem(self._sandbox, image): raise ValueError(problem) @@ -651,7 +653,9 @@ async def deploy( deployed = get_a2a_agent_instance_store().create_instance(deployed, ttl_seconds) logger.info(f"A2A agent '{self.id}' deployed at {a2a_url} (instance={deployed.instance_id})") return deployed - except BaseException: # a cancelled deploy closes its sandbox too + except BaseException: # a cancelled deploy closes its sandbox too, which served nothing + if created is not None: + discarded(created) await self.close() raise diff --git a/src/agent_env/env/envs/computer/utils/probing.py b/src/agent_env/env/envs/computer/utils/probing.py index e4bb77526..979c857a7 100644 --- a/src/agent_env/env/envs/computer/utils/probing.py +++ b/src/agent_env/env/envs/computer/utils/probing.py @@ -16,6 +16,7 @@ from agent_env.env.envs.computer.utils import boot from agent_env.env.envs.computer.utils.composed import Record, failed, now from agent_env.env.envs.computer.utils.install import for_os, platform_of +from agent_env.providers.sandbox_providers.created import probing from agent_env.store.ids import derive_id from agent_env.store.local_state import awaiting_lock @@ -165,10 +166,11 @@ async def _probe(links: list[SandboxProvider], env: ComputerEnv, driver: Compute problems = [] for link in links: try: - booted = await boot.boot(link, image=image, port=driver.port, environment=environment, token=token, - card=None, network_policy=None, timeout=_PROBE_TTL_S, attribution=None, - ready_s=boot.ready_timeout(env.composed_apps(), platform_of(env.computer.os)), - form=form, platform=platform_of(env.computer.os), shm_mb=env.shm_mb()) + with probing(): + booted = await boot.boot(link, image=image, port=driver.port, environment=environment, token=token, + card=None, network_policy=None, timeout=_PROBE_TTL_S, attribution=None, + ready_s=boot.ready_timeout(env.composed_apps(), platform_of(env.computer.os)), + form=form, platform=platform_of(env.computer.os), shm_mb=env.shm_mb()) except Exception as e: problems.append(f"{type(link).__name__}: {e}") continue diff --git a/src/agent_env/providers/env_providers/env_provider.py b/src/agent_env/providers/env_providers/env_provider.py index 3b71b1f0b..84c91af67 100644 --- a/src/agent_env/providers/env_providers/env_provider.py +++ b/src/agent_env/providers/env_providers/env_provider.py @@ -15,6 +15,7 @@ from agent_env.env.gateway.constants import WELL_KNOWN_PATH from agent_env.plugins import _registration from agent_env.providers.env_providers.stack_layout import DEFAULT_STACK_LAYOUT, StackLayout +from agent_env.providers.sandbox_providers.created import discarded_if_raises from agent_env.providers.sandbox_providers.sandbox import Sandbox from agent_env.providers.sandbox_providers.sandbox_provider import SANDBOX_MODE_CONTAINER @@ -177,7 +178,8 @@ async def _attempt(self, sandbox_provider: SandboxProvider, env_id: str | None, start = time.monotonic() provider_name = type(sandbox_provider).__name__ try: - result = await attempt(sandbox_provider) + with discarded_if_raises(): + result = await attempt(sandbox_provider) logger.info(f"env_deploy_provider_attempt env_id={env_id or 'unknown'} provider={provider_name} status=success duration_s={time.monotonic() - start:.1f}") except Exception as e: logger.warning(f"env_deploy_provider_attempt env_id={env_id or 'unknown'} provider={provider_name} status=failure duration_s={time.monotonic() - start:.1f} error_type={type(e).__name__} error={e!r}") diff --git a/src/agent_env/providers/sandbox_providers/chained_sandbox_provider.py b/src/agent_env/providers/sandbox_providers/chained_sandbox_provider.py index 53a7a0f3a..c92ad06cf 100644 --- a/src/agent_env/providers/sandbox_providers/chained_sandbox_provider.py +++ b/src/agent_env/providers/sandbox_providers/chained_sandbox_provider.py @@ -6,6 +6,7 @@ from typing import TYPE_CHECKING from agent_env.attribution import Attribution +from agent_env.providers.sandbox_providers.created import discarded from agent_env.providers.sandbox_providers.sandbox import NetworkPolicy, NetworkPolicyUnsupportedError, Sandbox from agent_env.providers.sandbox_providers.sandbox_provider import SandboxProvider @@ -97,6 +98,7 @@ async def _create(self, method: str, *, attribution: Attribution | None = None, if image is not None and (problem := p.sandbox_problem(sandbox, image)): logger.warning(f"{problem}; trying next provider") errors.append((name, ValueError(problem))) + discarded(sandbox) try: await sandbox.terminate() except Exception as e: diff --git a/src/agent_env/providers/sandbox_providers/created.py b/src/agent_env/providers/sandbox_providers/created.py new file mode 100644 index 000000000..e58c72a85 --- /dev/null +++ b/src/agent_env/providers/sandbox_providers/created.py @@ -0,0 +1,144 @@ +"""The sandboxes a run creates, noted as each is created: the step whose work created it, its provider and whether it +served the deploy that created it. Every provider's ``create_sandbox``, ``create_vm`` and ``create_container`` note what +they return (``SandboxProvider.__init_subclass__``), and a run lists them as evidence of where it ran +(``agent_env.task.run_lock``). Only a ``recording`` block's context notes, so a sandbox made outside a run, or on a +thread that doesn't carry its context, as a computer composer's build VMs, isn't listed. + +A sandbox is listed once a create call returns it, as created by the outermost one: a container a VM backend makes is a +container, though its ``create_vm`` noted it first. One a provider allocates and terminates itself inside a create that +then raises, as a VM whose setup fails, isn't listed: no create handed it to the run, and nothing of the run ran in it. +A listed sandbox didn't serve when a create call it was noted in raised, when a block of work that created it raised +(``discarded_if_raises``, as a deploy on one link of a chain), when its caller discarded it (``discarded``, as a chain +does one that can't run its image, or an agent's deploy that failed after its create returned), or when a probe created +it (``probing``).""" + +from __future__ import annotations + +import contextlib +import threading +from contextvars import ContextVar +from dataclasses import dataclass, replace +from typing import TYPE_CHECKING, Iterator, Optional + +if TYPE_CHECKING: + from agent_env.providers.sandbox_providers.sandbox import Sandbox + + +@dataclass(frozen=True) +class Created: + """A sandbox a run created: the step whose work created it, None outside a step; its provider's type + (``Sandbox.type``), its mode and platform as it was returned, and its id; and whether it ``served`` the deploy that + created it.""" + + step: Optional[str] + type: str + mode: Optional[str] + platform: Optional[str] + sandbox_id: Optional[str] + served: bool = True + + +class CreatedSandboxes: + """The sandboxes a ``recording`` block's run created, in the order each was first noted. Notes come from threads a + step's work runs on with its context, too.""" + + def __init__(self) -> None: + self._lock = threading.Lock() + # Each sandbox by its object, held so its id isn't reused while the run lasts. + self._by_object: dict[int, tuple[Sandbox, Created]] = {} + + def note(self, sandbox: Sandbox, step: Optional[str]) -> None: + with self._lock: + held = self._by_object.get(id(sandbox)) + created = Created(held[1].step if held else step, str(sandbox.type), getattr(sandbox, "mode", None), + getattr(sandbox, "platform", None), getattr(sandbox, "sandbox_id", None), + held[1].served if held else True) + self._by_object[id(sandbox)] = (sandbox, created) + + def discard(self, sandbox: Sandbox) -> None: + with self._lock: + if (held := self._by_object.get(id(sandbox))) is not None: + self._by_object[id(sandbox)] = (sandbox, replace(held[1], served=False)) + + def __iter__(self) -> Iterator[Created]: + with self._lock: + return iter([created for _, created in self._by_object.values()]) + + +class _Scope: + """The sandboxes noted within a block, which it discards when it raises, or always for a probe's.""" + + def __init__(self, always: bool) -> None: + self.always = always + self.sandboxes: list[Sandbox] = [] + + +_RECORDING: ContextVar[Optional[CreatedSandboxes]] = ContextVar("agentenv_created_sandboxes", default=None) +_STEP: ContextVar[Optional[str]] = ContextVar("agentenv_creating_step", default=None) +_SCOPES: ContextVar[tuple[_Scope, ...]] = ContextVar("agentenv_creating_scopes", default=()) + + +@contextlib.contextmanager +def recording() -> Iterator[CreatedSandboxes]: + """The sandboxes created in the block, by its work and the tasks and threads that carry its context.""" + created = CreatedSandboxes() + token, scopes = _RECORDING.set(created), _SCOPES.set(()) + try: + yield created + finally: + _SCOPES.reset(scopes) + _RECORDING.reset(token) + + +def in_step(step_id: Optional[str]) -> None: + """Attribute the sandboxes created from here on, in this task and those it starts, to ``step_id``; None ends a + step's.""" + _STEP.set(step_id) + + +def note(sandbox: Sandbox) -> None: + """Note ``sandbox`` as created, in the block ``recording`` lists, if any.""" + if (created := _RECORDING.get()) is None: + return + created.note(sandbox, _STEP.get()) + for scope in _SCOPES.get(): + scope.sandboxes.append(sandbox) + if scope.always: + created.discard(sandbox) + + +def discarded(sandbox: Sandbox) -> None: + """Note that ``sandbox`` didn't serve: its caller dropped it, as a chain does one that can't run its image.""" + if (created := _RECORDING.get()) is not None: + created.discard(sandbox) + + +@contextlib.contextmanager +def discarded_if_raises() -> Iterator[None]: + """Discard every sandbox created in the block if it raises, as its work failed and they served nothing.""" + with _scope(always=False): + yield + + +@contextlib.contextmanager +def probing() -> Iterator[None]: + """Discard every sandbox created in the block: a probe's serve no deploy.""" + with _scope(always=True): + yield + + +@contextlib.contextmanager +def _scope(always: bool) -> Iterator[None]: + if (created := _RECORDING.get()) is None: + yield + return + scope = _Scope(always) + token = _SCOPES.set((*_SCOPES.get(), scope)) + try: + yield + except BaseException: + for sandbox in list(scope.sandboxes): + created.discard(sandbox) + raise + finally: + _SCOPES.reset(token) diff --git a/src/agent_env/providers/sandbox_providers/sandbox_provider.py b/src/agent_env/providers/sandbox_providers/sandbox_provider.py index 0d314371c..63bea0aba 100644 --- a/src/agent_env/providers/sandbox_providers/sandbox_provider.py +++ b/src/agent_env/providers/sandbox_providers/sandbox_provider.py @@ -2,6 +2,8 @@ from __future__ import annotations +import functools +import inspect import logging import os import shlex @@ -16,6 +18,7 @@ from agent_env.config import ENV_REF_PREFIX from agent_env.config.errors import ConfigError from agent_env.utils.docker.build import DEFAULT_BUILD_PLATFORM +from agent_env.providers.sandbox_providers.created import discarded, discarded_if_raises, note as note_created from agent_env.providers.sandbox_providers.sandbox import ( NetworkPolicy, NetworkPolicyUnsupportedError, @@ -32,6 +35,8 @@ SANDBOX_MODE_VM = "vm" SANDBOX_MODE_CONTAINER = "container" +# The methods that create a sandbox, each of which notes what it returns as created (``created``). +_CREATE_METHODS = ("create_sandbox", "create_vm", "create_container") class SandboxProviderTypeError(ConfigError): @@ -255,6 +260,9 @@ def from_config(cls, **config: Any) -> Self: def __init_subclass__(cls, **kwargs: Any) -> None: super().__init_subclass__(**kwargs) + for name in _CREATE_METHODS: + if (method := cls.__dict__.get(name)) is not None and inspect.iscoroutinefunction(method): + setattr(cls, name, _noting(method)) cls.SUPPORTED_SANDBOX_MODES = frozenset( mode for mode, method in ((SANDBOX_MODE_CONTAINER, "create_sandbox"), (SANDBOX_MODE_VM, "create_vm")) if getattr(cls, method) is not getattr(SandboxProvider, method)) @@ -364,6 +372,28 @@ def effective_network_policy(cls, policy: Optional[NetworkPolicy]) -> NetworkPol return policy.with_hosts(all_sandbox_egress_hosts()) +def _noting(create): + """``create``, a provider's method that creates a sandbox, noting the sandbox it returns as created by the run it + serves, if any; one it noted in a nested call is discarded when it raises.""" + if getattr(create, "_notes_created", False): + return create + + @functools.wraps(create) + async def noting(self, *args, **kwargs): + with discarded_if_raises(): + sandbox = await create(self, *args, **kwargs) + if sandbox is not None: + note_created(sandbox) + return sandbox + + noting._notes_created = True + return noting + + +for _name in _CREATE_METHODS: + setattr(SandboxProvider, _name, _noting(SandboxProvider.__dict__[_name])) + + # --- Provider registry: built-ins + config.toml [sandbox.providers] --- _DEFAULT_SANDBOX_SPEC = "local" @@ -703,6 +733,7 @@ async def wrapper(*args, **kwargs): sandbox = await method(*args, **kwargs) if sandbox is not None and sandbox.type != name: actual = sandbox.type + discarded(sandbox) try: await sandbox.terminate() except Exception as e: diff --git a/src/agent_env/task/drift.py b/src/agent_env/task/drift.py index 0276aa75d..9598806df 100644 --- a/src/agent_env/task/drift.py +++ b/src/agent_env/task/drift.py @@ -17,6 +17,10 @@ a run's sandboxes run, and an endpoint, are soft, as a role's endpoint host is, which the role rows compare as it resolves; any other is hard, a role's model among them, which the role rows can't tell from a step's own. +The sandboxes each step of an attempt created, with their providers, are evidence of where it ran, never drift; so is +a sandbox provider only one attempt used: a fallback chain's next link serving a deploy changes where it ran, not what +ran. An override that asks for another provider is soft, by the override row. + What a row can't compare it says why in the comparison's ``not_compared``. A verifier's settings record how its grading went beside what it graded with: which trajectory formats its judge read, @@ -34,7 +38,7 @@ from typing import Any, Callable, Mapping, Optional from agent_env.config.model import RUN_ENDPOINT_OVERRIDES -from agent_env.plugins import TASK_STEPS +from agent_env.plugins import SANDBOX_PROVIDERS, TASK_STEPS from agent_env.task.run_records import RunLock, RunRuntime, Stage, registry_name from agent_env.task.store import TaskInstance from agent_env.task_step.context import SANDBOX_OVERRIDE_KEYS, redacted_key @@ -58,6 +62,9 @@ _NOT_GRADING_SETTINGS = GRADING_EVIDENCE_SETTINGS | PLACEMENT_SETTINGS # The registry of the types an attempt records from its start, its steps'; the others it records once it finishes. _STEP_TYPES = registry_name(TASK_STEPS) +_SANDBOX_PROVIDERS = registry_name(SANDBOX_PROVIDERS) +# What a type's package compares as when its attempt couldn't name it. +_UNKNOWN_PACKAGE = "unknown" _READ_FIELDS = ("version", "type", "image_identity", "latest", "alias") @@ -308,7 +315,10 @@ def _version_drift(key: Key, a: Records, b: Records) -> Drift: def _types(records: Records) -> dict[Key, Any]: - return {(group, name): found for group, types in records.runtime.types.items() for name, found in types.items()} + """The package of each type the attempt used, by its registry and name; ``_UNKNOWN_PACKAGE`` for one it used whose + package it couldn't name, as a class configuration registers, which is still one only it used.""" + return {(group, name): _UNKNOWN_PACKAGE if found is None else found + for group, types in records.runtime.types.items() for name, found in types.items()} def _types_recorded(key: Key, a: Records, b: Records) -> bool: @@ -318,7 +328,30 @@ def _types_recorded(key: Key, a: Records, b: Records) -> bool: def _types_one_sided(key: Key, a: Records, b: Records) -> Optional[str]: - return None if key[0] == _STEP_TYPES or not (a.finished and b.finished) else _one_sided("used")(key, a, b) + if key[0] in (_STEP_TYPES, _SANDBOX_PROVIDERS) or not (a.finished and b.finished): + return None + return _one_sided("used")(key, a, b) + + +def _type_drift(key: Key, a: Records, b: Records) -> Drift: + """A sandbox provider only one attempt used is where it ran, never drift; any other change of a type's package is + soft.""" + one_sided = key not in _types(a) or key not in _types(b) + return Drift.NEVER if key[0] == _SANDBOX_PROVIDERS and one_sided else Drift.SOFT + + +def _sandboxes(records: Records) -> Optional[dict[Key, Any]]: + """The sandboxes the attempt created, by the step that created each, none for one outside a step: each one's + provider, mode and platform, and whether it was discarded, sorted, as concurrent deploys create theirs in either + order; None when the attempt doesn't record them.""" + if records.lock.sandboxes is None: + return None + found: dict[Key, list[str]] = {} + for sandbox in records.lock.sandboxes: + described = " ".join(part for part in (sandbox.type, sandbox.mode, sandbox.platform) if part) + found.setdefault((sandbox.step,) if sandbox.step else (), []).append( + described if sandbox.served else f"{described} (discarded)") + return {key: tuple(sorted(described)) for key, described in found.items()} def _both_recorded(of: Callable[[RunLock], Any]) -> Callable[[Key, Records, Records], bool]: @@ -485,10 +518,12 @@ def _formats_unknown(key: Key, a: Records, b: Records) -> Optional[str]: _Row("plugin install", ("InstalledPlugin.origin",), Drift.SOFT, lambda r: {(name,): plugin.origin for name, plugin in r.runtime.plugins.items()}, compared=_in_both(_plugins)), - _Row("type's package", ("RunRuntime.types",), Drift.SOFT, _types, compared=_types_recorded, - unknown=_types_one_sided), + _Row("type's package", ("RunRuntime.types",), Drift.SOFT, _types, classify=_type_drift, + compared=_types_recorded, unknown=_types_one_sided), _Row("config found by", ("RunRuntime.config_selected_by",), Drift.NEVER, lambda r: _one(r.runtime.config_selected_by)), + _Row("sandboxes created", ("SandboxRecord.step", "SandboxRecord.type", "SandboxRecord.mode", + "SandboxRecord.platform", "SandboxRecord.served"), Drift.NEVER, _sandboxes), ) # The record fields no row compares, and why. @@ -504,4 +539,6 @@ def _formats_unknown(key: Key, a: Records, b: Records) -> Optional[str]: "RunIntent.roles": "compared by each role's fields", "RunLock.verifiers": "compared by each verifier's fields", "RunLock.reads": "compared by each read's fields", + "RunLock.sandboxes": "compared by each step's sandboxes", + "SandboxRecord.sandbox_id": "it names the sandbox, which each attempt creates anew", } diff --git a/src/agent_env/task/run_lock.py b/src/agent_env/task/run_lock.py index c92bcc580..357332eec 100644 --- a/src/agent_env/task/run_lock.py +++ b/src/agent_env/task/run_lock.py @@ -14,9 +14,9 @@ ``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, 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. +same attempt replaces the first's finished records. Its evidence is every sandbox it created, each with the step that +created it and its provider, a judge's own included (``providers.sandbox_providers.created``). Reads made, and sandboxes +created, on a thread that doesn't carry the run's context, as the computer composer's pool, aren't listed. """ from __future__ import annotations @@ -47,6 +47,8 @@ installed_plugins, ) from agent_env.plugins._requirements import CORE, installed +from agent_env.providers.sandbox_providers.created import Created, in_step +from agent_env.providers.sandbox_providers.created import recording as recording_sandboxes 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,6 +57,7 @@ RunIntent, RunLock, RunRuntime, + SandboxRecord, Stage, VerifierRecord, registry_name, @@ -90,7 +93,9 @@ class StepsRan: def step_dispatched(step_id: str) -> None: """Note that the attempt the running ``run_recorded`` block records dispatched ``step_id``, again for a retry. A - worker that runs a task's steps itself calls this and ``step_ended`` around each, as ``Task.run`` does.""" + worker that runs a task's steps itself calls this and ``step_ended`` around each, as ``Task.run`` does, in the task + that runs the step, whose sandboxes it then attributes to it.""" + in_step(step_id) if (ran := _STEPS_RAN.get()) is not None: ran.dispatched.add(step_id) ran.ended.discard(step_id) @@ -98,6 +103,7 @@ def step_dispatched(step_id: str) -> None: def step_ended(step_id: str, raised: Optional[BaseException] = None) -> None: """Note how ``step_id``'s dispatch ended: it reached its end unless it ``raised`` other than a verdict.""" + in_step(None) if (ran := _STEPS_RAN.get()) is not None and (raised is None or isinstance(raised, VERDICTS)): ran.ended.add(step_id) @@ -160,20 +166,22 @@ def steps_hash(steps: Sequence[TaskStep]) -> str: def finished_records(runtime: RunRuntime, lock: RunLock, reads: Iterable[Read], context: TaskStepContext, - ran: Optional[StepsRan] = None, steps: Sequence[TaskStep] = (), - stopped: bool = False) -> tuple[RunRuntime, RunLock]: + ran: Optional[StepsRan] = None, steps: Sequence[TaskStep] = (), stopped: bool = False, + sandboxes: Optional[Iterable[Created]] = None) -> tuple[RunRuntime, RunLock]: """The attempt's records once its run ends: in its lock, ``reads``, every entity version it read; each verifier whose grade graded, neither failed nor skipped, with the settings its grade records (``graded_settings``), which a judge completes as it calls; and, from ``ran``, the steps it ran in the order of ``steps`` and whether each reached its end, which it didn't when the block was ``stopped`` (an exception other than a verdict, or a cancel), both left - None when no step was noted and the block wasn't stopped, as for a worker that doesn't note its steps. In its - runtime, the types of the envs, artifacts and providers it used.""" + None when no step was noted and the block wasn't stopped, as for a worker that doesn't note its steps; and, as its + evidence, the ``sandboxes`` it created. In its runtime, the types of the envs, artifacts and providers it used, + every sandbox's provider among them.""" reads = list(reads) + created = None if sandboxes is None else list(sandboxes) 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 ((registry_name(SANDBOX_PROVIDERS), _sandbox_types(context)), + for group, used in ((registry_name(SANDBOX_PROVIDERS), _sandbox_types(context, created or ())), (registry_name(ENV_PROVIDERS), _env_provider_types(context))): for name, impl in used.items(): types.setdefault(group, {})[name] = distribution_of(impl) if impl is not None else None @@ -187,7 +195,8 @@ def finished_records(runtime: RunRuntime, lock: RunLock, reads: Iterable[Read], completed = not stopped and ran.dispatched <= ran.ended return (dataclasses.replace(runtime, types=types, stage=Stage.FINISHED), dataclasses.replace(lock, verifiers=verifiers, reads=read_records(reads), steps_run=steps_run, - completed=completed, stage=Stage.FINISHED)) + completed=completed, sandboxes=None if created is None else sandbox_records(created), + stage=Stage.FINISHED)) def _graded_in(grade: Any, attempt_epoch: int) -> bool: @@ -208,13 +217,18 @@ def read_records(reads: Iterable[Read]) -> list[ReadRecord]: return sorted(records, key=lambda record: (record.kind, record.id, record.version)) +def sandbox_records(created: Iterable[Created]) -> list[SandboxRecord]: + """The records of the sandboxes an attempt ``created``, in the order each was created.""" + return [SandboxRecord(c.step, c.type, c.mode, c.platform, c.sandbox_id, c.served) for c in created] + + @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 every step it notes - (``step_dispatched``, ``step_ended``), and record those when the block ends, however it ends. Without an instance, - as when registering the run failed, the block runs unrecorded. Neither write is awaited, so the block's cancel and - its end are the run's own.""" + """Record the attempt's start on ``instance_id``, list every entity the block reads, every sandbox it creates and + every step it notes (``step_dispatched``, ``step_ended``), and record those when the block ends, however it ends. + Without an instance, as when registering the run failed, the block runs unrecorded. Neither write is awaited, so the + block's cancel and its end are the run's own.""" started = _started(instance_id, task, steps, context, attempt_epoch) if instance_id else None if started is None: yield @@ -223,7 +237,7 @@ async def run_recorded(instance_id: Optional[str], task: "Task", steps: Sequence _write(instance_id, runtime, lock) ran, stopped = StepsRan(), True token = _STEPS_RAN.set(ran) - with recording() as reads: + with recording() as reads, recording_sandboxes() as sandboxes: try: yield stopped = False @@ -233,7 +247,7 @@ async def run_recorded(instance_id: Optional[str], task: "Task", steps: Sequence finally: _STEPS_RAN.reset(token) try: - runtime, lock = finished_records(runtime, lock, reads, context, ran, steps, stopped) + runtime, lock = finished_records(runtime, lock, reads, context, ran, steps, stopped, sandboxes) except Exception: logger.warning("The reads of attempt %s of %s couldn't be recorded", attempt_epoch, instance_id, exc_info=True) @@ -266,12 +280,13 @@ def _started(instance_id: str, task: "Task", steps: Sequence[TaskStep], context: return None -def _sandbox_types(context: TaskStepContext) -> dict[str, Any]: - """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.""" +def _sandbox_types(context: TaskStepContext, created: Iterable[Created]) -> dict[str, Any]: + """The sandbox types of the sandboxes the run ``created`` and of the deployments its context records, as a resume's + from an earlier attempt, 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)} + names |= {c.type for c in created} registry = get_config().sandbox_registry() return {name: (registry.get(name) or {}).get("impl") for name in sorted(names)} diff --git a/src/agent_env/task/run_records.py b/src/agent_env/task/run_records.py index da5c209e9..c7ac5100a 100644 --- a/src/agent_env/task/run_records.py +++ b/src/agent_env/task/run_records.py @@ -1,6 +1,6 @@ """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. +the code that ran it, and ``RunLock``, what it was asked to do, what it read and, as evidence, the sandboxes it created. +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, since a newer version may have written the record to a @@ -193,13 +193,37 @@ def from_dict(cls, data: dict) -> ReadRecord: image_identity=data.get("image_identity")) +@dataclass(frozen=True) +class SandboxRecord: + """A sandbox an attempt created (``providers.sandbox_providers.created``): the step whose work created it, None + outside a step; its provider's type, mode and platform, its id, and whether it ``served`` the deploy that created + it, which it didn't when that deploy, a fallback chain or a probe discarded it.""" + + step: Optional[str] + type: str + mode: Optional[str] = None + platform: Optional[str] = None + sandbox_id: Optional[str] = None + served: bool = True + + def to_dict(self) -> dict: + return {"step": self.step, "type": self.type, "mode": self.mode, "platform": self.platform, + "sandbox_id": self.sandbox_id, "served": self.served} + + @classmethod + def from_dict(cls, data: dict) -> SandboxRecord: + return cls(step=data.get("step"), type=data["type"], mode=data.get("mode"), platform=data.get("platform"), + sandbox_id=data.get("sandbox_id"), served=data.get("served", True) is not False) + + @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; the ids of the steps it ran (``steps_run``), in the task's order, a retry's included, as a resume runs only the rest; and whether it ``completed`` them, each reaching its end, a verdict that fails its step included; each None while ``started``, - and the last two for a record without them.""" + and the last two for a record without them. Its evidence, once ``finished``, is every sandbox it created + (``sandboxes``), in the order each was created; None while ``started`` and for a record without it.""" attempt_epoch: int intent: RunIntent @@ -207,6 +231,7 @@ class RunLock: reads: Optional[list[ReadRecord]] = None steps_run: Optional[list[str]] = None completed: Optional[bool] = None + sandboxes: Optional[list[SandboxRecord]] = None stage: Stage | str = Stage.STARTED record_version: int = RUN_RECORD_VERSION @@ -226,12 +251,16 @@ def to_dict(self) -> dict: "steps_run": None if self.steps_run is None else list(self.steps_run), "completed": self.completed, }, + "evidence": { + "sandboxes": None if self.sandboxes is None else [sandbox.to_dict() for sandbox in self.sandboxes], + }, } @classmethod def from_dict(cls, data: dict) -> RunLock: resolved = data.get("resolved") or {} reads = resolved.get("reads") + sandboxes = (data.get("evidence") or {}).get("sandboxes") return cls( attempt_epoch=data["attempt_epoch"], intent=RunIntent.from_dict(data["intent"]), @@ -240,6 +269,7 @@ def from_dict(cls, data: dict) -> RunLock: reads=None if reads is None else [ReadRecord.from_dict(read) for read in reads], steps_run=None if resolved.get("steps_run") is None else list(resolved["steps_run"]), completed=resolved.get("completed"), + sandboxes=None if sandboxes is None else [SandboxRecord.from_dict(sandbox) for sandbox in sandboxes], stage=_stage(data.get("stage", Stage.STARTED)), record_version=data.get("record_version", RUN_RECORD_VERSION), ) diff --git a/tst/integration/task_step/test_verify_sandbox_local.py b/tst/integration/task_step/test_verify_sandbox_local.py index 68c0a9d7b..7d4762c6f 100644 --- a/tst/integration/task_step/test_verify_sandbox_local.py +++ b/tst/integration/task_step/test_verify_sandbox_local.py @@ -23,6 +23,7 @@ from agent_env.config import configure, get_config, reset_config from agent_env.providers.sandbox_providers.local_docker.provider import LocalSandbox, LocalSandboxProvider from agent_env.task import Task +from agent_env.task.record_writer import flush_run_records from agent_env.task_step.context import DeployedAgent, DeployedSandbox, TaskStepContext from agent_env.task_step.task_steps.collect_artifacts import CollectArtifactsTaskStep from agent_env.task_step.task_steps.deploy_sandbox import DeploySandboxTaskStep @@ -154,6 +155,30 @@ async def test_each_verifier_of_a_run_leaves_its_named_grade_on_the_stored_run(l assert ctx.metadata["verifications"]["overall"]["score"] == 0.5 +@pytest.mark.asyncio +async def test_a_run_records_the_sandbox_its_deploy_created_as_evidence(local_backends): + tmp_path, _ = local_backends + suffix = uuid.uuid4().hex[:8] + universe = _greeting_universe(tmp_path / "greeting", suffix) + task = Task.put(id=f"evidence-{suffix}", steps=[ + DeploySandboxTaskStep(id="deploy", version=None, sandbox_name="box", sandbox_mode="vm", sandbox_type="local"), + LoadArtifactTaskStep( + id="load", version=None, artifact_id=universe.id, sandbox_name="box", destination_path="/app/greeting", + ), + _verify("hello", "hello", "python3 check.py"), + ]) + + ctx = await task.run() + + assert flush_run_records(10) + instance = Task.get_instance(ctx.instance_id) + [runtime], [lock] = instance.runtimes, instance.run_locks + (deployed,) = ctx.deployed_sandboxes + assert [(s.step, s.type, s.mode, s.sandbox_id, s.served) for s in lock.sandboxes] == [ + ("deploy", "local", "vm", deployed.sandbox_id, True)] + assert "local" in runtime.types["sandbox_providers"] + + @pytest.mark.asyncio async def test_file_artifacts_stage_beside_each_other(local_backends): tmp_path, _ = local_backends diff --git a/tst/unit/a2a_agent/deploy_cleanup_test.py b/tst/unit/a2a_agent/deploy_cleanup_test.py index 1a68c24a2..05b9a56c4 100644 --- a/tst/unit/a2a_agent/deploy_cleanup_test.py +++ b/tst/unit/a2a_agent/deploy_cleanup_test.py @@ -1,5 +1,6 @@ """``A2AAgent.deploy`` closes the sandbox it created when the deploy fails or is cancelled, so an agent that never -made it into a run's context doesn't outlive it. One that succeeds is recorded with a control token of its own.""" +made it into a run's context doesn't outlive it, and the run lists that sandbox as one that served nothing. One that +succeeds is recorded with a control token of its own.""" import asyncio @@ -9,6 +10,7 @@ from agent_env.a2a_agent.store import get_a2a_agent_instance_store from agent_env.artifact.artifacts.docker_image import DockerImageArtifact from agent_env.providers.sandbox_providers import sandbox_provider +from agent_env.providers.sandbox_providers.created import recording from agent_env.providers.sandbox_providers.sandbox_provider import SANDBOX_MODE_CONTAINER, SandboxProvider @@ -39,15 +41,17 @@ async def wait_for_card(self, url): monkeypatch.setattr(sandbox_provider, "build_sandbox_provider", lambda name: _Provider()) monkeypatch.setattr(A2AAgent, "_wait_for_agent_card", wait_for_card) agent = A2AAgent(id="solver", version=1, docker_image_artifact=DockerImageArtifact(id="img", description="d", image_name="img")) - deploying = asyncio.ensure_future(agent.deploy( - sandbox_type="fake", env_vars={"LITELLM_API_KEY": "k", "LITELLM_BASE_URL": "http://llm"})) - await waiting.wait() + with recording() as created: + deploying = asyncio.ensure_future(agent.deploy( + sandbox_type="fake", env_vars={"LITELLM_API_KEY": "k", "LITELLM_BASE_URL": "http://llm"})) + await waiting.wait() - deploying.cancel() - with pytest.raises((asyncio.CancelledError, RuntimeError)): - await deploying + deploying.cancel() + with pytest.raises((asyncio.CancelledError, RuntimeError)): + await deploying assert sandbox.terminated + assert [(c.sandbox_id, c.served) for c in created] == [("sb-agent", False)] @pytest.mark.asyncio diff --git a/tst/unit/cli/task_diff_test.py b/tst/unit/cli/task_diff_test.py index 416890d3a..f32a5bb6f 100644 --- a/tst/unit/cli/task_diff_test.py +++ b/tst/unit/cli/task_diff_test.py @@ -4,6 +4,7 @@ import asyncio import importlib import json +from dataclasses import replace import pytest from click.testing import CliRunner @@ -14,7 +15,7 @@ from agent_env.eval.lock import RoleModel from agent_env.task import Task from agent_env.task.record_writer import flush_run_records -from agent_env.task.run_records import RunIntent, RunLock, RunRuntime, Stage, VerifierRecord +from agent_env.task.run_records import RunIntent, RunLock, RunRuntime, SandboxRecord, Stage, VerifierRecord from agent_env.task.store import get_task_instance_store from agent_env.task_step.context import TaskStepContext from agent_env.task_step.task_step import TaskStep @@ -67,8 +68,9 @@ def stores(local_stores): yield -def _instance(*attempts) -> str: - """An instance whose attempts recorded the judge model and the threshold of each of ``attempts``.""" +def _instance(*attempts, sandboxes=()) -> str: + """An instance whose attempts recorded the judge model and the threshold of each of ``attempts``, and created + ``sandboxes``.""" store = get_task_instance_store() instance_id = store.create_instance("t", 1, 1).instance_id for epoch, (judge, threshold) in enumerate(attempts): @@ -77,7 +79,7 @@ def _instance(*attempts) -> str: verifiers = {"score": VerifierRecord("grade", "agentenv-framework", "1.0", {"threshold": threshold})} store.record_run_records_sync( instance_id, RunRuntime(epoch, {"agentenv-framework": "1.0"}, "3.12.4", stage=Stage.FINISHED), - RunLock(epoch, intent, verifiers, reads=[], stage=Stage.FINISHED)) + RunLock(epoch, intent, verifiers, reads=[], sandboxes=list(sandboxes), stage=Stage.FINISHED)) return instance_id @@ -126,6 +128,19 @@ def test_the_comparison_as_json(): "regrade": False}] +def test_a_deploy_a_fallback_served_on_another_provider_is_listed_and_ran_the_same_thing(): + local = SandboxRecord("deploy", "local", "container", None, "first") + tried = SandboxRecord("deploy", "modal", "container", "linux/amd64", "m", served=False) + + result = _diff(_instance(("j", 0.5), sandboxes=[local]), + _instance(("j", 0.5), sandboxes=[tried, replace(local, sandbox_id="second")])) + + assert result.exit_code == 0, result.output + assert ('never sandboxes created deploy: ["local container"] -> ' + '["local container", "modal container linux/amd64 (discarded)"]') in result.output + assert "0 hard, 0 soft, 1 never: the same thing ran" in result.output + + @pytest.mark.parametrize("args, message", [ (["nowhere"], "no task instance 'nowhere'"), (["ONE"], "has records of 1 attempt; name a second instance"), diff --git a/tst/unit/providers/sandbox_providers/created_test.py b/tst/unit/providers/sandbox_providers/created_test.py new file mode 100644 index 000000000..728551e73 --- /dev/null +++ b/tst/unit/providers/sandbox_providers/created_test.py @@ -0,0 +1,217 @@ +"""A run lists every sandbox its providers create, as each is created: the step whose work created it, its provider, +and whether it served, which it didn't when a fallback, a failed deploy or a probe discarded it. Nothing outside a run, +or on a thread without its context, is listed.""" + +from __future__ import annotations + +import asyncio +from types import SimpleNamespace + +import pytest + +from agent_env.artifact.artifacts.docker_image import DockerImageArtifact +from agent_env.providers.env_providers.env_provider import _SandboxEnvironmentProvider +from agent_env.providers.sandbox_providers.chained_sandbox_provider import ChainedSandboxProvider +from agent_env.providers.sandbox_providers.created import Created, in_step, probing, recording +from agent_env.providers.sandbox_providers.sandbox import Sandbox, VmSandbox +from agent_env.providers.sandbox_providers.sandbox_provider import ( + SandboxProvider, + SandboxProviderTypeError, + _install_sandbox_type_guard, +) + +pytestmark = pytest.mark.asyncio + + +class _Container(Sandbox): + type = "stub" + + def __init__(self, sandbox_id: str): + self.sandbox_id, self.tunnel_urls, self.vnc_url, self.mode = sandbox_id, {}, None, "container" + + async def terminate(self) -> None: + pass + + +class _Vm(VmSandbox): + type = "stub-vm" + + def __init__(self, sandbox_id: str, platform: str = "linux/amd64"): + self.sandbox_id, self.tunnel_urls, self.vnc_url, self.mode, self.platform = ( + sandbox_id, {}, None, "vm", platform) + + async def terminate(self) -> None: + pass + + async def exec_script(self, script: str) -> str: + return "" + + async def pull_images(self, images) -> None: + pass + + +class _Containers(SandboxProvider): + """Creates a container with each id it's given, in turn.""" + + def __init__(self, *ids: str): + self.ids = list(ids) + + async def create_sandbox(self, **kwargs) -> Sandbox: + return _Container(self.ids.pop(0)) + + +class _Gives(SandboxProvider): + """Creates each sandbox it's given, in turn, as a container-only backend whose create_sandbox may give a VM.""" + + def __init__(self, *sandboxes: Sandbox): + self.sandboxes = list(sandboxes) + + async def create_sandbox(self, **kwargs) -> Sandbox: + return self.sandboxes.pop(0) + + +class _Vms(SandboxProvider): + """Creates a VM of each id and platform it's given, in turn, and runs containers on them the default way; or, with + ``fail_start``, creates the VM and then fails to start its container.""" + + def __init__(self, *vms: _Vm, fail_start: bool = False): + self.vms, self.fail_start = list(vms), fail_start + + async def create_vm(self, **kwargs) -> VmSandbox: + return self.vms.pop(0) + + async def _start_container(self, sandbox, **kwargs) -> None: + if self.fail_start: + raise RuntimeError("the container didn't start") + + +def _listed(created) -> list[tuple]: + return [(c.step, c.type, c.mode, c.platform, c.sandbox_id, c.served) for c in created] + + +async def test_each_sandbox_created_in_a_run_is_listed_with_its_step_and_none_outside_one(): + provider = _Containers("before", "deploy-1", "outside-step", "after") + await provider.create_sandbox() + + with recording() as created: + in_step("deploy") + await provider.create_sandbox() + in_step(None) + await provider.create_sandbox() + await provider.create_sandbox() + + assert list(created) == [Created("deploy", "stub", "container", "linux/amd64", "deploy-1"), + Created(None, "stub", "container", "linux/amd64", "outside-step")] + + +async def test_concurrent_steps_each_have_their_own_sandboxes(): + provider = _Containers("a", "b") + + async def step(step_id: str, wait: float): + in_step(step_id) + await asyncio.sleep(wait) + await provider.create_sandbox() + + with recording() as created: + await asyncio.gather(step("first", 0.02), step("second", 0)) + + assert [(c.step, c.sandbox_id) for c in created] == [("second", "a"), ("first", "b")] + + +async def test_a_vm_backends_container_is_listed_once_as_the_container_its_outer_create_returned(): + with recording() as created: + in_step("deploy") + await _Vms(_Vm("vm-1", "linux/arm64")).create_container(image_name="img:v1", port=8000, env={}) + + assert _listed(created) == [("deploy", "stub-vm", "container", "linux/arm64", "vm-1", True)] + + +async def test_a_create_that_raises_after_a_nested_create_discards_the_sandbox_it_made(): + with recording() as created: + with pytest.raises(RuntimeError, match="didn't start"): + await _Vms(_Vm("vm-1"), fail_start=True).create_container(image_name="img:v1", port=8000, env={}) + + assert _listed(created) == [(None, "stub-vm", "vm", "linux/amd64", "vm-1", False)] + + +async def test_a_chain_discards_a_links_sandbox_that_cant_run_the_image_and_lists_the_one_that_served(): + arm64 = DockerImageArtifact(id="img", version=1, description="d", image_name="img:v1", platform="linux/arm64", + tar_gz_object_url="s3://bucket/img.tar.gz") + chain = ChainedSandboxProvider([_Gives(_Vm("amd", "linux/amd64")), _Gives(_Vm("arm", "linux/arm64"))]) + await chain.prepare_image(arm64) + + with recording() as created: + served = await chain.create_sandbox(image_name="img:v1", port=8000, env={}) + + assert served.sandbox_id == "arm" + assert [(c.sandbox_id, c.platform, c.served) for c in created] == [("amd", "linux/amd64", False), + ("arm", "linux/arm64", True)] + + +class _DeploysTwoSandboxes(_SandboxEnvironmentProvider): + """Deploys a gateway and a server on each link it's given, failing after both on the first.""" + + def __init__(self): + super().__init__() + self.attempts = 0 + + async def deploy(self, env, sandbox_provider, **options): + return await self._run(sandbox_provider, env.id, self._deploy_one) + + async def _deploy_one(self, sandbox_provider): + self.attempts += 1 + await sandbox_provider.create_sandbox() + await sandbox_provider.create_sandbox() + if self.attempts == 1: + raise RuntimeError("the gateway never answered") + return "deployed" + + async def close(self) -> None: + pass + + +async def test_an_env_deploy_that_fails_on_one_link_discards_every_sandbox_it_made_there(): + chain = ChainedSandboxProvider([_Containers("gw-1", "srv-1"), _Containers("gw-2", "srv-2")]) + + with recording() as created: + in_step("deploy-env") + assert await _DeploysTwoSandboxes().deploy(SimpleNamespace(id="office"), chain) == "deployed" + + assert [(c.step, c.sandbox_id, c.served) for c in created] == [ + ("deploy-env", "gw-1", False), ("deploy-env", "srv-1", False), ("deploy-env", "gw-2", True), + ("deploy-env", "srv-2", True)] + + +async def test_a_probes_sandboxes_are_listed_as_discarded(): + provider = _Containers("probe", "deploy") + + with recording() as created: + with probing(): + await provider.create_sandbox() + await provider.create_sandbox() + + assert [(c.sandbox_id, c.served) for c in created] == [("probe", False), ("deploy", True)] + + +async def test_a_sandbox_created_on_a_thread_is_listed_only_when_the_thread_carries_the_runs_context(): + provider = _Containers("carried", "bare") + + def create(): + return asyncio.run(provider.create_sandbox()) + + with recording() as created: + in_step("compose") + await asyncio.to_thread(create) + await asyncio.get_running_loop().run_in_executor(None, create) + + assert [(c.step, c.sandbox_id) for c in created] == [("compose", "carried")] + + +async def test_a_config_registered_provider_whose_sandbox_has_another_type_discards_it(): + provider = _install_sandbox_type_guard(_Containers("mistyped"), "acme") + + with recording() as created: + with pytest.raises(SandboxProviderTypeError): + await provider.create_sandbox() + + assert [(c.sandbox_id, c.served) for c in created] == [("mistyped", False)] diff --git a/tst/unit/task/drift_test.py b/tst/unit/task/drift_test.py index 18283fb4a..d1f035bbd 100644 --- a/tst/unit/task/drift_test.py +++ b/tst/unit/task/drift_test.py @@ -17,12 +17,14 @@ RunIntent, RunLock, RunRuntime, + SandboxRecord, Stage, VerifierRecord, ) from agent_env.task.store import TaskInstance -RECORD_CLASSES = (RunRuntime, InstalledPlugin, RunLock, RunIntent, RoleModel, VerifierRecord, ReadRecord) +RECORD_CLASSES = (RunRuntime, InstalledPlugin, RunLock, RunIntent, RoleModel, VerifierRecord, ReadRecord, + SandboxRecord) HARD, SOFT, NEVER = Drift.HARD, Drift.SOFT, Drift.NEVER @@ -31,7 +33,9 @@ def _records(instance_id="first", epoch=0) -> Records: runtime = RunRuntime(attempt_epoch=epoch, packages={"agentenv-framework": "1.0", "agentenv-framework-protocol": "1.0"}, python="3.12.4", plugins={"acme-steps": InstalledPlugin("1.2.0", "index")}, - config_selected_by="discovered", types={"task_steps": {"grade": "acme-steps"}}, + config_selected_by="discovered", + types={"task_steps": {"grade": "acme-steps"}, + "sandbox_providers": {"local": "agentenv-framework"}}, stage=Stage.FINISHED) intent = RunIntent(task_id="t", task_version=1, content_hash="sha256:c", steps_hash="sha256:s", trajectory_formats=["atif/1"], pins={"env": {"office": 1}}, @@ -51,8 +55,10 @@ def _records(instance_id="first", epoch=0) -> Records: ReadRecord("agent", "solver", 2, "a2a_agent", latest=True), ReadRecord("artifact", "solver-image", 1, "docker_image", image_identity="registry:sha256:h1"), ReadRecord("artifact", "macos-15", 1, "computer")] + sandboxes = [SandboxRecord("deploy", "local", "container", None, f"{instance_id}-1"), + SandboxRecord("score", "local", "container", None, f"{instance_id}-2")] return Records(instance_id, runtime, RunLock(epoch, intent, verifiers, reads, steps_run=["deploy", "score"], - completed=True, stage=Stage.FINISHED)) + completed=True, sandboxes=sandboxes, stage=Stage.FINISHED)) def _changed(change: Callable[[Records], None]) -> Records: @@ -66,8 +72,9 @@ def _read(records: Records, entity_id: str, **fields) -> None: def _unfinished(records: Records) -> None: - """As a killed attempt leaves its records: started, its reads not recorded.""" + """As a killed attempt leaves its records: started, its reads and sandboxes not recorded.""" records.lock.reads, records.lock.steps_run, records.lock.completed = None, None, None + records.lock.sandboxes = None records.lock.stage = records.runtime.stage = Stage.STARTED @@ -156,6 +163,8 @@ def change(records): Case("type's package", lambda r: r.runtime.types["task_steps"].update(grade="acme-grades"), ("task_steps", "grade"), SOFT), Case("config found by", _set("runtime.config_selected_by", "environment"), (), NEVER), + Case("sandboxes created", lambda r: r.lock.sandboxes.__setitem__(1, replace(r.lock.sandboxes[1], type="modal")), + ("score",), NEVER), ) @@ -439,7 +448,7 @@ def change(records): def test_an_attempt_that_didnt_finish_is_compared_without_its_reads_and_the_types_beyond_its_steps(): """As a killed run leaves it: started records, its step types alone and no reads.""" def change(records): - records.lock.reads = None + records.lock.reads = records.lock.sandboxes = None records.lock.stage = records.runtime.stage = Stage.STARTED records.runtime.types = {"task_steps": dict(records.runtime.types["task_steps"])} first = _records() @@ -452,6 +461,69 @@ def change(records): "beyond its steps' aren't recorded"] +def test_a_fallback_that_served_on_another_link_is_where_it_ran_never_drift(): + """The second attempt's deploy tried modal first, which gave a sandbox that couldn't run the image, and served on + local: each step's sandboxes and the provider only it used are listed, and they ran the same thing.""" + def change(records): + records.lock.sandboxes.insert(0, SandboxRecord("deploy", "modal", "container", "linux/amd64", "m-1", False)) + records.runtime.types["sandbox_providers"]["modal"] = "agentenv-framework" + + comparison = compare(_records(), _changed(change)) + + assert [(d.row, d.key, d.old, d.new, d.drift) for d in comparison.differences] == [ + ("type's package", ("sandbox_providers", "modal"), None, "agentenv-framework", NEVER), + ("sandboxes created", ("deploy",), ("local container",), + ("local container", "modal container linux/amd64 (discarded)"), NEVER)] + assert comparison.like_for_like and comparison.not_compared == [] + + +def test_a_sandbox_providers_package_both_used_is_soft_and_one_only_one_used_is_never_whatever_steps_they_ran(): + def change(records): + records.lock.completed = False + records.runtime.types["sandbox_providers"] = {"local": "acme-sandboxes", "e2b": "agentenv-framework"} + + comparison = compare(_records(), _changed(change)) + + assert [(d.row, d.key, d.drift) for d in comparison.differences] == [ + ("completed its steps", (), NEVER), ("type's package", ("sandbox_providers", "e2b"), NEVER), + ("type's package", ("sandbox_providers", "local"), SOFT)] + assert comparison.not_compared == [] + + +def test_a_type_only_one_attempt_used_is_a_difference_though_neither_can_name_its_package(): + """A provider configuration registers comes from no installed package, which its records keep as None.""" + def change(records): + records.runtime.types["sandbox_providers"]["kitflaky"] = None + records.runtime.types["envs"] = {"office": None} + + comparison = compare(_records(), _changed(change)) + + assert [(d.key, d.old, d.new, d.drift) for d in comparison.differences] == [ + (("envs", "office"), None, "unknown", SOFT), (("sandbox_providers", "kitflaky"), None, "unknown", NEVER)] + + +def test_sandboxes_are_compared_by_where_each_step_ran_not_by_their_ids_or_the_order_they_were_created_in(): + """Each attempt creates its sandboxes anew, and concurrent deploys create theirs in either order.""" + def change(records): + records.lock.sandboxes.append(SandboxRecord("deploy", "local", "vm", None, "third")) + first = _records() + first.lock.sandboxes.insert(0, SandboxRecord("deploy", "local", "vm", None, "zeroth")) + + assert compare(first, _changed(change)).differences == [] + + +def test_an_attempt_recorded_before_sandboxes_were_is_compared_without_them(): + def change(records): + records.lock.sandboxes = None + records.runtime.types.pop("sandbox_providers") + + comparison = compare(_records(), _changed(change)) + + assert [(d.row, d.key, d.drift) for d in comparison.differences] == [ + ("type's package", ("sandbox_providers", "local"), NEVER)] + assert comparison.like_for_like + + @pytest.mark.parametrize("gap, change, row", [ ("an unpinned harness version: the agent's image rebuilt with another one", lambda r: _read(r, "solver-image", image_identity="registry:sha256:h2"), "image identity"), diff --git a/tst/unit/task/run_lock_test.py b/tst/unit/task/run_lock_test.py index 2a9bddff7..f8143bf19 100644 --- a/tst/unit/task/run_lock_test.py +++ b/tst/unit/task/run_lock_test.py @@ -22,6 +22,8 @@ from agent_env.eval.lock import RoleModel from agent_env.plugins import _provenance from agent_env.plugins._requirements import installed +from agent_env.providers.sandbox_providers.sandbox import Sandbox +from agent_env.providers.sandbox_providers.sandbox_provider import SandboxProvider 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 @@ -33,6 +35,7 @@ RunIntent, RunLock, RunRuntime, + SandboxRecord, Stage, VerifierRecord, ) @@ -124,9 +127,54 @@ async def verify(self, context): return Verification(score=1.0) +class _Box(Sandbox): + type = "run_lock_test_box" + + def __init__(self, sandbox_id: str): + self.sandbox_id, self.tunnel_urls, self.vnc_url, self.mode = sandbox_id, {}, None, "container" + + async def terminate(self) -> None: + pass + + +class _Boxes(SandboxProvider): + made = 0 + + async def create_sandbox(self, **kwargs) -> Sandbox: + _Boxes.made += 1 + return _Box(f"box-{_Boxes.made}") + + +class _Deploys(TaskStep): + """Creates a sandbox, as a deploy does, keeping it in the context.""" + + type = "run_lock_test_deploys" + entity_refs = () + + @classmethod + def from_dict(cls, data): + return cls(**cls._base_from_dict(data)) + + async def execute(self, context): + await _Boxes().create_sandbox() + return context + + +class _JudgesInItsOwnSandbox(VerifierTaskStep): + """Grades in a sandbox it creates and keeps to itself, as an agent judge does.""" + + type = "run_lock_test_judges" + entity_refs = () + + async def verify(self, context): + await _Boxes().create_sandbox() + 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, _Flaky.type: _Flaky} + steps = {**Config().task_step_registry(), _Reads.type: _Reads, _Score.type: _Score, _Flaky.type: _Flaky, + _Deploys.type: _Deploys, _JudgesInItsOwnSandbox.type: _JudgesInItsOwnSandbox} monkeypatch.setattr(Config, "task_step_registry", lambda self: steps) entities.office(source_digest=SOURCE, agent_id=None) entities.agent("solver", image_digest=DIGEST) @@ -176,6 +224,17 @@ def test_a_run_records_what_ran_it_and_what_it_was_asked_and_read(): "data": None} +def test_an_attempt_records_each_sandbox_it_created_by_the_step_that_created_it_a_judges_own_included(): + _, context = _run(_task(_Deploys(id="deploy", version=None), + _JudgesInItsOwnSandbox(id="judge", version=None, verifier_id="judge"))) + instance = find_task_instance(context.instance_id) + + [runtime], [lock] = instance.runtimes, instance.run_locks + assert [(s.step, s.type, s.mode, s.served) for s in lock.sandboxes] == [ + ("deploy", "run_lock_test_box", "container", True), ("judge", "run_lock_test_box", "container", True)] + assert runtime.types["sandbox_providers"] == {"run_lock_test_box": None} + + @pytest.mark.parametrize("overrides, formats", [({}, []), ({"trajectory_formats": ["atif/1"]}, ["atif/1"]), ({"trajectory_formats": "atif/1"}, None)], ids=["the config's", "the run's", "named wrongly, the rest recorded"]) @@ -466,14 +525,18 @@ def test_every_field_of_the_records_survives_a_round_trip(): graded_settings={"a": 2}) read = ReadRecord(kind="env", id="office", version=2, type="multi", latest=True, alias=True, image_identity="source:sha256:x") + sandbox = SandboxRecord(step="deploy", type="modal", mode="container", platform="linux/arm64", sandbox_id="sb-1", + served=False) lock = RunLock(attempt_epoch=2, intent=intent, verifiers={"score": verifier}, reads=[read], - steps_run=["reads", "score"], completed=True, stage=Stage.FINISHED, record_version=7) - for sample in (plugin, runtime, intent, verifier, read, lock): + steps_run=["reads", "score"], completed=True, sandboxes=[sandbox], stage=Stage.FINISHED, + record_version=7) + for sample in (plugin, runtime, intent, verifier, read, sandbox, 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" + assert RunLock.from_dict({k: v for k, v in lock.to_dict().items() if k != "evidence"}).sandboxes is None def test_a_store_that_hangs_holds_up_neither_the_run_nor_its_loop(monkeypatch):