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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 22 additions & 16 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
8 changes: 6 additions & 2 deletions src/agent_env/a2a_agent/a2a_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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__}...")
Expand All @@ -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)
Expand Down Expand Up @@ -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

Expand Down
10 changes: 6 additions & 4 deletions src/agent_env/env/envs/computer/utils/probing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion src/agent_env/providers/env_providers/env_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down
144 changes: 144 additions & 0 deletions src/agent_env/providers/sandbox_providers/created.py
Original file line number Diff line number Diff line change
@@ -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)
31 changes: 31 additions & 0 deletions src/agent_env/providers/sandbox_providers/sandbox_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

from __future__ import annotations

import functools
import inspect
import logging
import os
import shlex
Expand All @@ -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,
Expand All @@ -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):
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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)
Comment thread
earakely-scale marked this conversation as resolved.
Resolved
return sandbox
Comment thread
earakely-scale marked this conversation as resolved.
Resolved

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"
Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading