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
114 changes: 76 additions & 38 deletions src/agent_env/a2a_agent/clock.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import logging
import secrets
from collections.abc import Awaitable, Callable
from typing import TYPE_CHECKING, Optional

import httpx
Expand Down Expand Up @@ -44,6 +45,9 @@
RETIRE_TIMEOUT_S = 10
#: ``metadata`` key of the env each agent follows: ``{slot: {"agent", "env_id", "follower"}}``, one slot per agent.
FOLLOWING_KEY = "agent_clock_following"
#: ``metadata`` key of the env each declared server follower follows: ``{slot: {"service", "env_id", "follower"}}``,
#: one slot per (env, follower).
SERVER_FOLLOWING_KEY = "server_clock_following"


def follower_name(agent: DeployedAgent) -> str:
Expand All @@ -60,6 +64,41 @@ def _fields(method: dict) -> set[str]:
return {*request.get("required", ()), *request.get("optional", ()), *(request.get("properties") or {})}


def advertises_follower_fields(method: Optional[dict]) -> bool:
return method is not None and set(FOLLOWER_FIELDS) <= _fields(method)


async def declare_and_sync_follower(env: DeployedEnv, *, method: Optional[dict], name: str, watch_url: str,
env_get_time_url: Optional[str], timezone: Optional[str],
send_sync_time: Callable[[dict], Awaitable[tuple[bool, object]]],
timeout: float, subject: str) -> dict:
"""Declare ``name`` a follower at ``env``'s gateway and send its config through ``send_sync_time(body)``, which
answers ``(followed, result_or_why)``; a raise from it counts as not following."""
if method is None:
return {"synced": False, "reason": "not_advertised"}
if not advertises_follower_fields(method):
return {"synced": False, "reason": "no_follower_fields"}
if timezone is not None and "timezone" not in _fields(method):
raise StepContextError(f"{subject} serves {EXT_CLOCK_URI} sync_time without a timezone; "
f"rebuild its image or drop timezone={timezone!r} from the task")
token = secrets.token_urlsafe(READ_TOKEN_BYTES)
try:
await env.invoke(EXT_CLOCK_URI, "declare_follower", {"name": name, "read_token": token}, timeout=timeout)
except EnvCapabilityUnsupported:
return {"synced": False, "reason": "gateway_takes_no_followers"}
body = {"env_get_time_url": env_get_time_url or "", "watch_url": watch_url, "name": name,
"read_token": token, **({"timezone": timezone} if timezone is not None else {})}
try:
followed, detail = await send_sync_time(body)
except Exception as e:
followed, detail = False, f"({type(e).__name__}): {e}"
if followed:
return {"synced": True, "follower": name, "result": detail}
# Declared and not following: the gateway would wait for it on every later write, and nothing records it to retire.
await _retire(env, name, timeout=RETIRE_TIMEOUT_S)
raise RuntimeError(f"{subject} doesn't follow the clock of env '{env.env_id}' {str(detail)[:ERROR_TEXT_CHARS]}")


def watch_url_for(agent: DeployedAgent, env: DeployedEnv) -> str:
"""The gateway's watch URL as ``agent``'s sandbox reaches it, as its MCP URL is (``deploy_agent``)."""
url = gateway_url_of(env).rstrip("/") + CLOCK_WATCH_PATH
Expand All @@ -76,36 +115,20 @@ async def follow(agent: DeployedAgent, env: DeployedEnv, *, env_get_time_url: Op
for one that serves it and fails, having retired the follower it declared, or can't take the task's zone, as for
a server."""
method, path = _sync_time(agent)
if method is None:
return {"synced": False, "reason": "not_advertised"}
fields = _fields(method)
if not set(FOLLOWER_FIELDS) <= fields:
return {"synced": False, "reason": "no_follower_fields"}
if timezone is not None and "timezone" not in fields:
raise StepContextError(f"agent '{agent.agent_name}' serves {EXT_CLOCK_URI} sync_time without a timezone; "
f"rebuild its image or drop timezone={timezone!r} from the task")
name, token = follower_name(agent), secrets.token_urlsafe(READ_TOKEN_BYTES)
try:
await env.invoke(EXT_CLOCK_URI, "declare_follower", {"name": name, "read_token": token}, timeout=timeout)
except EnvCapabilityUnsupported:
return {"synced": False, "reason": "gateway_takes_no_followers"}
body = {"env_get_time_url": env_get_time_url or "", "watch_url": watch_url_for(agent, env), "name": name,
"read_token": token, **({"timezone": timezone} if timezone is not None else {})}
url = (agent.a2a_url or agent.api_url).rstrip("/") + path
try:

async def send(body: dict) -> tuple[bool, object]:
url = (agent.a2a_url or agent.api_url).rstrip("/") + path
async with httpx.AsyncClient() as client:
answer = await client.post(url, json=body, timeout=timeout,
headers={**sandbox_request_headers_for_url(url), **agent.control_headers})
except httpx.HTTPError as e:
why = f"({type(e).__name__}): {e}"
else:
if answer.status_code < 400:
return {"synced": True, "follower": name, "result": answer.json()}
why = f"(HTTP {answer.status_code}): {answer.text}"
# Declared and not following: the gateway would wait for it on every later write, and nothing records it to retire.
await _retire(env, name, timeout=RETIRE_TIMEOUT_S)
raise RuntimeError(f"agent '{agent.agent_name}' doesn't follow the clock of env '{env.env_id}' "
f"{why[:ERROR_TEXT_CHARS]}")
return True, answer.json()
return False, f"(HTTP {answer.status_code}): {answer.text}"

return await declare_and_sync_follower(
env, method=method, name=follower_name(agent), watch_url=watch_url_for(agent, env),
env_get_time_url=env_get_time_url, timezone=timezone, send_sync_time=send, timeout=timeout,
subject=f"agent '{agent.agent_name}'")


async def _retire(env: DeployedEnv, follower: str, *, timeout: float) -> bool:
Expand Down Expand Up @@ -221,21 +244,36 @@ async def follow_armed_clocks(context: TaskStepContext, agent: DeployedAgent, *,
return outcomes


async def retire_followers(context: TaskStepContext, agent_names, *, timeout: float = RETIRE_TIMEOUT_S) -> list[str]:
"""Have the gateway whose clock each of ``agent_names`` follows in this run stop waiting for it, as its agent is
torn down, so later writes that wait for followers don't wait for it or answer 504 naming it. Best-effort, as a
teardown is: a gateway that's gone or takes no retirement is logged and its agent left recorded. The followers
retired."""
following, retired = context.metadata.get(FOLLOWING_KEY) or {}, []
for name in dict.fromkeys(agent_names):
if (record := following.get(_slot(name))) is None:
def record_server_follower(context: TaskStepContext, env: DeployedEnv, service: str, follower: str) -> None:
context.metadata.setdefault(SERVER_FOLLOWING_KEY, {})[_slot(f"{env.env_id}:{follower}")] = {
"service": service, "env_id": env.env_id, "deploy_step_id": _deploy_step_of(env), "follower": follower}


async def _retire_recorded(context: TaskStepContext, key: str, slots, *, timeout: float) -> list[str]:
"""The followers recorded under ``metadata[key]`` for ``slots`` that were retired; the rest keep their record."""
recorded, retired = context.metadata.get(key) or {}, []
for slot in dict.fromkeys(slots):
if (record := recorded.get(slot)) is None:
continue
env = next((d for d in context.deployed_envs if d.env_id == record["env_id"]
and record.get("deploy_step_id", _deploy_step_of(d)) == _deploy_step_of(d)), None)
if env is None:
continue
if not await _retire(env, record["follower"], timeout=timeout):
if env is None or not await _retire(env, record["follower"], timeout=timeout):
continue
del following[_slot(name)]
del recorded[slot]
retired.append(record["follower"])
return retired


async def retire_followers(context: TaskStepContext, agent_names, *, timeout: float = RETIRE_TIMEOUT_S) -> list[str]:
"""Have the gateway whose clock each of ``agent_names`` follows in this run stop waiting for it, as its agent is
torn down, so later writes that wait for followers don't wait for it or answer 504 naming it. Best-effort, as a
teardown is: a gateway that's gone or takes no retirement is logged and its agent left recorded. The followers
retired."""
return await _retire_recorded(context, FOLLOWING_KEY, [_slot(name) for name in agent_names], timeout=timeout)


async def retire_server_followers(context: TaskStepContext, env_ids, *, timeout: float = RETIRE_TIMEOUT_S) -> list[str]:
"""``retire_followers`` for the backing-server followers each env in ``env_ids`` declared this run."""
wanted, recorded = set(env_ids), context.metadata.get(SERVER_FOLLOWING_KEY) or {}
return await _retire_recorded(context, SERVER_FOLLOWING_KEY,
[slot for slot, rec in recorded.items() if rec["env_id"] in wanted], timeout=timeout)
42 changes: 36 additions & 6 deletions src/agent_env/task_step/task_steps/sync_env_clock.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,14 @@
import tzdata # noqa: F401
from agentenv_protocol import client as protocol_v1

from agent_env.a2a_agent.clock import follow_agents, on_deployment, torn_down
from agent_env.a2a_agent.clock import (advertises_follower_fields, declare_and_sync_follower, follow_agents,
on_deployment, record_server_follower, torn_down)
from agent_env.env.env import Env, EnvCapabilityUnsupported, gateway_url_of
from agent_env.env.gateway.constants import EXT_CLOCK_URI
from agent_env.env.gateway import AGENT_ENV_GATEWAY_MCP_PORT
from agent_env.env.gateway.constants import CLOCK_WATCH_PATH, EXT_CLOCK_URI
from agent_env.providers.env_providers.constants import GATEWAY_SERVICE_NAME
from agent_env.providers.env_providers.env_gateway_provider import EnvironmentGatewayProvider
from agent_env.providers.sandbox_providers.sandbox_provider import build_sandbox_provider, get_env_sandbox_provider
from agent_env.task_step.context import StepContextError, TaskStepContext
from agent_env.entity.refs import EntityRef
from agent_env.task_step.task_step import TaskStep, TaskStepDependency
Expand Down Expand Up @@ -66,6 +71,15 @@ def resolve_virtual_time(virtual_time: str, timezone: Optional[str]) -> str:
return parsed.astimezone(_utc_tz.utc).isoformat().replace("+00:00", "Z")


def _server_watch_url(deployed) -> Optional[str]:
"""The gateway's clock-watch URL by compose service name, as a sibling server in the same VM reaches it; None
outside VM mode. ``gateway_url_of`` gives the external tunnel URL, which a compose sibling can't use."""
provider = build_sandbox_provider(deployed.sandbox_type) if deployed.sandbox_type else get_env_sandbox_provider()
if not EnvironmentGatewayProvider.in_vm(provider):
return None
return f"http://{GATEWAY_SERVICE_NAME}:{AGENT_ENV_GATEWAY_MCP_PORT}{CLOCK_WATCH_PATH}"


class SyncEnvClockTaskStep(TaskStep):
type: ClassVar[str] = "sync_env_clock"
entity_refs = (EntityRef.env("env_id"),)
Expand Down Expand Up @@ -182,7 +196,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext:
service = server.environment_name
outcome = await self._sync_one(server.owner(deployed), gateway_url_of(deployed), service, env_get_time_url,
mcp=server.mcp, tolerate=self.tolerate_missing_sync_time or not server.mcp,
server=server)
server=server, gateway_env=deployed, context=context)
entry = {"service": service, "environment": service, **({} if server.mcp else {"website": True}), **outcome}
(synced if outcome.get("synced") else skipped).append(entry)

Expand Down Expand Up @@ -212,7 +226,8 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext:
return context

async def _sync_one(self, deployed, gateway_url: str, service: str, env_get_time_url: Optional[str], mcp: bool = True,
tolerate: Optional[bool] = None, server: Optional[BackingServer] = None) -> dict:
tolerate: Optional[bool] = None, server: Optional[BackingServer] = None,
gateway_env=None, context: Optional[TaskStepContext] = None) -> dict:
"""Invoke sync_time on one server, an MCP server or with ``mcp=False`` a website, if its card advertises
clock/v1; skip a server with no card or no clock/v1 when ``tolerate`` (tolerate_missing_sync_time by default),
else raise. ``execute`` tolerates every website, so one that doesn't follow the clock never fails the step; one
Expand All @@ -237,10 +252,25 @@ async def _sync_one(self, deployed, gateway_url: str, service: str, env_get_time
raise StepContextError(f"{service} does not advertise {EXT_CLOCK_URI}")
if not env_get_time_url:
raise RuntimeError(f"gateway did not expose env_get_time_url; cannot sync {service}")
method = protocol_v1.find_extension_method(card, EXT_CLOCK_URI, "sync_time")
follows = context is not None and gateway_env is not None and advertises_follower_fields(method)
watch_url = _server_watch_url(gateway_env) if follows else None
if watch_url is not None:
async def send(body: dict) -> tuple[bool, object]:
return True, await protocol_v1.invoke_extension(base_url, card, EXT_CLOCK_URI, params=body,
timeout=self.timeout_seconds,
headers=deployed.control_headers)

outcome = await declare_and_sync_follower(
gateway_env, method=method, name=f"{'svc' if mcp else 'site'}-{service}", watch_url=watch_url, env_get_time_url=env_get_time_url,
timezone=self.timezone, send_sync_time=send, timeout=self.timeout_seconds, subject=f"server '{service}'")
if outcome.get("synced"):
record_server_follower(context, gateway_env, service, outcome["follower"])
if outcome.get("reason") != "gateway_takes_no_followers":
return outcome
params = {"env_get_time_url": env_get_time_url}
if self.timezone is not None:
method = protocol_v1.find_extension_method(card, EXT_CLOCK_URI, "sync_time") or {}
if "timezone" not in ((method.get("request") or {}).get("properties") or {}):
if "timezone" not in (((method or {}).get("request") or {}).get("properties") or {}):
raise StepContextError(f"{service} advertises {EXT_CLOCK_URI} but its sync_time takes no timezone; "
f"rebuild its image or drop timezone={self.timezone!r} from the task")
params["timezone"] = self.timezone
Expand Down
3 changes: 2 additions & 1 deletion src/agent_env/task_step/task_steps/teardown_sandboxes.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
tear_down,
)
from agent_env.task_step.context import TaskStepContext
from agent_env.a2a_agent.clock import retire_followers
from agent_env.a2a_agent.clock import retire_followers, retire_server_followers
from agent_env.task_step.task_step import TaskStep, TaskStepDependency

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -90,6 +90,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext:
doomed = {sandbox.sandbox_id for sandbox in sandboxes}
await retire_followers(context, [*self.agent_names, *(a.agent_name for a in context.deployed_agents
if a.sandbox_id in doomed)])
await retire_server_followers(context, [env.env_id for env in envs])
report = await tear_down(context, sandboxes, envs, timeout=TERMINATE_TIMEOUT_SECONDS)
for sandbox, why in report.failed:
logger.warning(f"teardown_sandboxes: {sandbox.sandbox_id}: {why}"[:300])
Expand Down
9 changes: 9 additions & 0 deletions tst/data/clock_follower_mcp/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
FROM mirror.gcr.io/library/python:3.12-slim@sha256:423ed6ab25b1921a477529254bfeeabf5855151dc2c3141699a1bfc852199fbf
WORKDIR /app
RUN pip install --no-cache-dir starlette pydantic httpx "mcp>=1.25,<2"
COPY agentenv_protocol /app/agentenv_protocol
COPY server.py /app/server.py
ENV PYTHONPATH=/app
RUN useradd --create-home --uid 10001 appuser
USER appuser
CMD ["python", "server.py"]
59 changes: 59 additions & 0 deletions tst/data/clock_follower_mcp/server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""An MCP server that follows its gateway's clock as a declared follower: its clock/v1 sync_time takes the follower's
config, and a background loop long-polls the gateway's watch with it, acknowledging each version it has seen."""
import asyncio
import json
import time

import httpx

from agentenv_protocol import AgentEnvEnvironment, environment_card, extension, tool


@environment_card(name="clockapp")
class ClockAppEnv(AgentEnvEnvironment):
WATCH_TIMEOUT_S = 60
WATCH_RETRY_S = 0.5
FIRST_ANSWER_WAIT_S = 10
FIRST_ANSWER_POLL_S = 0.1

def __init__(self) -> None:
self.shown: dict | None = None
self.loop: asyncio.Task | None = None
self.create_app()

async def _follow(self, watch_url: str, name: str, read_token: str) -> None:
after = ""
async with httpx.AsyncClient(timeout=self.WATCH_TIMEOUT_S) as client:
while True:
try:
answer = await client.get(watch_url, params={"after": after, "follower": name},
headers={"Authorization": f"Bearer {read_token}"})
answer.raise_for_status()
except httpx.HTTPError:
await asyncio.sleep(self.WATCH_RETRY_S)
continue
self.shown = answer.json()
after = self.shown.get("version") or ""

@extension(uri="urn:agentenv:clock/v1", description="Follow the gateway's clock as a declared follower.")
async def sync_time(self, env_get_time_url: str, watch_url: str = "", name: str = "", read_token: str = "",
timezone: str | None = None) -> dict:
if self.loop is not None:
self.loop.cancel()
self.shown = None
self.loop = asyncio.create_task(self._follow(watch_url, name, read_token))
deadline = time.monotonic() + self.FIRST_ANSWER_WAIT_S
while time.monotonic() < deadline:
if self.shown is not None:
return {"synced": True, "version": self.shown.get("version")}
await asyncio.sleep(self.FIRST_ANSWER_POLL_S)
raise RuntimeError(f"no answer from {watch_url}")

@tool(name="{environment_name}_clock")
def clock(self) -> str:
"""The gateway clock state this server last saw."""
return json.dumps(self.shown)


if __name__ == "__main__":
ClockAppEnv().serve()
1 change: 1 addition & 0 deletions tst/integration/slow_durations.json
Original file line number Diff line number Diff line change
Expand Up @@ -1218,6 +1218,7 @@
"tst/integration/task_step/test_next_env_event_hook_local.py": 218.6,
"tst/integration/task_step/test_prompt_agent_notifications_local.py": 121.0,
"tst/integration/task_step/test_register_env_triggers_local.py": 188.0,
"tst/integration/task_step/test_server_env_clock_local.py": 110.0,
"tst/integration/training/harness_test.py": 38.2,
"tst/integration/training/trl_test.py": 47.7,
"tst/integration/utils/docker/prune_test.py": 13.7,
Expand Down
Loading
Loading