diff --git a/src/agent_env/a2a_agent/clock.py b/src/agent_env/a2a_agent/clock.py index c9f6be0b9..72bb227c6 100644 --- a/src/agent_env/a2a_agent/clock.py +++ b/src/agent_env/a2a_agent/clock.py @@ -15,6 +15,7 @@ import logging import secrets +from collections.abc import Awaitable, Callable from typing import TYPE_CHECKING, Optional import httpx @@ -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: @@ -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 @@ -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: @@ -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) diff --git a/src/agent_env/task_step/task_steps/sync_env_clock.py b/src/agent_env/task_step/task_steps/sync_env_clock.py index f14876926..20125a2f5 100644 --- a/src/agent_env/task_step/task_steps/sync_env_clock.py +++ b/src/agent_env/task_step/task_steps/sync_env_clock.py @@ -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 @@ -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"),) @@ -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) @@ -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 @@ -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 diff --git a/src/agent_env/task_step/task_steps/teardown_sandboxes.py b/src/agent_env/task_step/task_steps/teardown_sandboxes.py index 0257566ce..740411b97 100644 --- a/src/agent_env/task_step/task_steps/teardown_sandboxes.py +++ b/src/agent_env/task_step/task_steps/teardown_sandboxes.py @@ -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__) @@ -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]) diff --git a/tst/data/clock_follower_mcp/Dockerfile b/tst/data/clock_follower_mcp/Dockerfile new file mode 100644 index 000000000..cad684d9e --- /dev/null +++ b/tst/data/clock_follower_mcp/Dockerfile @@ -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"] diff --git a/tst/data/clock_follower_mcp/server.py b/tst/data/clock_follower_mcp/server.py new file mode 100644 index 000000000..9c9866d70 --- /dev/null +++ b/tst/data/clock_follower_mcp/server.py @@ -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() diff --git a/tst/integration/slow_durations.json b/tst/integration/slow_durations.json index 544da20cf..c767e1ff9 100644 --- a/tst/integration/slow_durations.json +++ b/tst/integration/slow_durations.json @@ -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, diff --git a/tst/integration/task_step/test_server_env_clock_local.py b/tst/integration/task_step/test_server_env_clock_local.py new file mode 100644 index 000000000..d11851353 --- /dev/null +++ b/tst/integration/task_step/test_server_env_clock_local.py @@ -0,0 +1,105 @@ +"""A backing server on a task env's clock, end to end on local Docker: its clock/v1 sync_time advertises the follower's +config, so sync_env_clock declares it a follower at the real gateway and hands it the in-compose watch URL; a clock +write that waits for followers waits for it, and once it is retired, writes stop waiting for it.""" + +import shutil +import subprocess +import tempfile +import time +import uuid +from pathlib import Path + +import pytest +from agentenv_protocol.client import ExtensionCallError + +from agent_env.a2a_agent.clock import SERVER_FOLLOWING_KEY, retire_server_followers +from agent_env.artifact import DockerImageArtifact +from agent_env.env import MCPServerEnv, MultiEnv +from agent_env.env.gateway.constants import EXT_CLOCK_URI +from agent_env.task_step.context import TaskStepContext +from agent_env.task_step.task_steps.sync_env_clock import SyncEnvClockTaskStep +from tst.integration.store.local_parallel_deploy_test import _seed_bootstrap_envs +from tst.integration.task_step.test_prompt_agent_live_trajectory_local import ( + local_registry as local_registry, +) + +pytestmark = [pytest.mark.integration, pytest.mark.int_test_slow] + +_REPO = Path(__file__).resolve().parents[3] +VIRTUAL = "2031-03-04T05:06:07Z" +LATER = "2031-03-05T10:00:00Z" +PAUSED = "2031-03-05T12:00:00Z" + + +def _put_clockapp_image(tag: str) -> DockerImageArtifact: + with tempfile.TemporaryDirectory() as build_dir: + bd = Path(build_dir) + shutil.copytree(_REPO / "packages" / "agentenv-protocol" / "src" / "agentenv_protocol", bd / "agentenv_protocol", + ignore=shutil.ignore_patterns("__pycache__")) + for name in ("server.py", "Dockerfile"): + shutil.copy(_REPO / "tst" / "data" / "clock_follower_mcp" / name, bd / name) + build = subprocess.run(["docker", "build", "-t", tag, str(bd)], capture_output=True, text=True) + assert build.returncode == 0, f"clockapp build failed: {build.stderr[-2000:]}" + return DockerImageArtifact.put(id=tag, description="server clock e2e", image_name=tag) + + +def _server_container(needle: str) -> str: + names = subprocess.run(["docker", "ps", "--format", "{{.Names}}"], capture_output=True, text=True, + check=True).stdout.split() + [name] = [n for n in names if needle in n] + return name + + +async def _followers(deployed) -> dict: + return (await deployed.invoke(EXT_CLOCK_URI, "state", {}, timeout=10)).get("followers") or {} + + +@pytest.mark.asyncio +async def test_a_backing_server_follows_the_envs_clock_until_it_is_retired(local_registry): + _seed_bootstrap_envs() + uid = uuid.uuid4().hex[:8] + server = MCPServerEnv.put(id=f"clockapp-{uid}", environment_name="warehouse", + docker_image_artifact=_put_clockapp_image(f"clockapp-{uid}")) + env = MultiEnv.put(id=f"serverclock-{uid}", mcp_server_envs=[server], name="suite") + deployed = await env.deploy(sandbox_type="local", ttl_seconds=900) + context = TaskStepContext(deployed_envs=[deployed], deployed_agents=[], metadata={}) + try: + await SyncEnvClockTaskStep(id="clock", version=None, env_id=env.id, virtual_time=VIRTUAL, + virtual_seconds_per_real_second=0, timeout_seconds=60).execute(context) + + [synced] = context.metadata["clock_configurations"][-1]["synced"] + print("sync outcome:", synced) + assert (synced["service"], synced["synced"], synced["follower"]) == ("warehouse", True, "svc-warehouse") + assert [r["follower"] for r in context.metadata[SERVER_FOLLOWING_KEY].values()] == ["svc-warehouse"] + assert "svc-warehouse" in await _followers(deployed) + + started = time.monotonic() + await deployed.invoke(EXT_CLOCK_URI, "advance", {"virtual_time": LATER, "wait_followers_s": 20}, timeout=30) + print(f"advance acknowledged by the server in {time.monotonic() - started:.2f}s") + state = await deployed.invoke(EXT_CLOCK_URI, "state", {}, timeout=10) + assert state["followers"]["svc-warehouse"]["version"] is not None + + container = _server_container("warehouse") + print("server container:", container) + subprocess.run(["docker", "pause", container], check=True, capture_output=True) + try: + with pytest.raises(ExtensionCallError) as frozen: + await deployed.invoke(EXT_CLOCK_URI, "advance", {"virtual_time": PAUSED, "wait_followers_s": 3}, + timeout=30) + finally: + subprocess.run(["docker", "unpause", container], check=True, capture_output=True) + print("advance while the server was frozen:", frozen.value.response.status_code, frozen.value.response.text[:200]) + assert frozen.value.response.status_code == 504 and frozen.value.response.json()["stale"] == ["svc-warehouse"] + + assert await retire_server_followers(context, [env.id]) == ["svc-warehouse"] + assert "svc-warehouse" not in await _followers(deployed) + assert not context.metadata[SERVER_FOLLOWING_KEY] + + started = time.monotonic() + await deployed.invoke(EXT_CLOCK_URI, "advance", {"virtual_time": "2031-03-06T00:00:00Z", + "wait_followers_s": 20}, timeout=30) + waited = time.monotonic() - started + print(f"advance after retiring answered in {waited:.2f}s") + assert waited < 5 + finally: + await env.close() diff --git a/tst/unit/task_step/sync_env_clock_test.py b/tst/unit/task_step/sync_env_clock_test.py index 191247b98..85c64a711 100644 --- a/tst/unit/task_step/sync_env_clock_test.py +++ b/tst/unit/task_step/sync_env_clock_test.py @@ -2,13 +2,16 @@ import json from types import SimpleNamespace +import httpx import pytest +from agent_env.a2a_agent import clock as agent_clock from agent_env.env.env import DeployedEnv, DeployedGatewayEnv, DeployedSandboxEnv from agent_env.env.gateway.constants import EXT_CLOCK_URI, WELL_KNOWN_PATH from agent_env.task_step.context import StepContextError, TaskStepContext from agent_env.task_step.task_steps import sync_env_clock as mod from agent_env.task_step.task_steps.sync_env_clock import SyncEnvClockTaskStep, resolve_virtual_time +from agent_env.task_step.task_steps.teardown_sandboxes import TeardownSandboxesTaskStep T0 = "2026-01-01T00:00:00Z" CLOCK_URL = "http://gateway:9000/clock/time" @@ -249,11 +252,145 @@ async def test_strict_execute_skips_websites_but_not_mcp_servers_that_do_not_fol await _step(tolerate_missing_sync_time=False).execute(unsynced) +@pytest.mark.asyncio +async def test_execute_declares_and_syncs_a_server_that_advertises_follower_fields(monkeypatch): + sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) + monkeypatch.setattr(mod, "_server_watch_url", lambda deployed: _COMPOSE_WATCH) + monkeypatch.setattr("agent_env.env.env.Env.get", lambda *a, **k: SimpleNamespace(environment_name="email")) + context = TaskStepContext(deployed_envs=[_carded(await _composed_card({"mcp-email": [_FOLLOWER_EXT]}))]) + + await _step().execute(context) + + declared = [r for r in sent if str(r.url) == f"{_CARD}/clock/followers"] + synced = [r for r in sent if str(r.url).endswith("/svc/mcp-email/agentenv/ext/sync_time")] + assert [r.method for r in declared] == ["PUT"] + declaration, config = json.loads(declared[0].content), json.loads(synced[0].content) + assert declaration == {"name": "svc-email", "read_token": config["read_token"]} and len(config["read_token"]) > 30 + assert config == {"env_get_time_url": CLOCK_URL, "watch_url": _COMPOSE_WATCH, "name": "svc-email", + "read_token": declaration["read_token"]} + assert [(s["service"], s["follower"]) for s in context.metadata["clock_configurations"][0]["synced"]] == [ + ("email", "svc-email")] + assert context.metadata[agent_clock.SERVER_FOLLOWING_KEY] == { + "e1:svc-email": {"service": "email", "env_id": "e1", "deploy_step_id": None, "follower": "svc-email"}} + + +@pytest.mark.asyncio +async def test_an_mcp_server_and_a_website_sharing_a_name_are_declared_distinct_followers(monkeypatch): + sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) + monkeypatch.setattr(mod, "_server_watch_url", lambda deployed: _COMPOSE_WATCH) + monkeypatch.setattr("agent_env.env.env.Env.get", lambda *a, **k: SimpleNamespace( + mcp_server_envs=[SimpleNamespace(environment_name="email")], website_envs=[SimpleNamespace(environment_name="email")])) + context = TaskStepContext(deployed_envs=[_carded(await _composed_card( + {"mcp-email": [_FOLLOWER_EXT], "email": [_FOLLOWER_EXT]}))]) + + await _step().execute(context) + + declared = [json.loads(r.content) for r in sent if str(r.url) == f"{_CARD}/clock/followers"] + assert [d["name"] for d in declared] == ["svc-email", "site-email"] + assert declared[0]["read_token"] != declared[1]["read_token"] + assert sorted(context.metadata[agent_clock.SERVER_FOLLOWING_KEY]) == ["e1:site-email", "e1:svc-email"] + + +@pytest.mark.asyncio +async def test_execute_syncs_a_server_without_follower_fields_the_legacy_way(monkeypatch): + sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) + monkeypatch.setattr(mod, "_server_watch_url", lambda deployed: _COMPOSE_WATCH) + monkeypatch.setattr("agent_env.env.env.Env.get", lambda *a, **k: SimpleNamespace(environment_name="email")) + context = TaskStepContext(deployed_envs=[_carded(await _composed_card({"mcp-email": [_CLOCK_EXT]}))]) + + await _step().execute(context) + + assert not any(str(r.url).endswith("/clock/followers") for r in sent) + sync = [r for r in sent if str(r.url).endswith("/svc/mcp-email/agentenv/ext/sync_time")] + assert len(sync) == 1 and json.loads(sync[0].content) == {"env_get_time_url": CLOCK_URL} + assert agent_clock.SERVER_FOLLOWING_KEY not in context.metadata + + +@pytest.mark.asyncio +async def test_a_server_without_a_compose_watch_url_is_not_declared_a_follower(monkeypatch): + sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) + monkeypatch.setattr(mod, "_server_watch_url", lambda deployed: None) + monkeypatch.setattr("agent_env.env.env.Env.get", lambda *a, **k: SimpleNamespace(environment_name="email")) + context = TaskStepContext(deployed_envs=[_carded(await _composed_card({"mcp-email": [_FOLLOWER_EXT]}))]) + + await _step().execute(context) + + assert not any(str(r.url).endswith("/clock/followers") for r in sent) + assert [s["service"] for s in context.metadata["clock_configurations"][0]["synced"]] == ["email"] + + +@pytest.mark.asyncio +async def test_a_follower_capable_server_on_a_gateway_that_takes_no_followers_is_synced_by_its_time_url(monkeypatch): + sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) + monkeypatch.setattr(mod, "_server_watch_url", lambda deployed: _COMPOSE_WATCH) + monkeypatch.setattr("agent_env.env.env.Env.get", lambda *a, **k: SimpleNamespace(environment_name="email")) + card = await _composed_card({"mcp-email": [_FOLLOWER_EXT]}) + [clock] = [e for e in card["capabilities"]["extensions"] if e["uri"] == EXT_CLOCK_URI] + del clock["params"]["methods"]["declare_follower"] + context = TaskStepContext(deployed_envs=[_carded(card)]) + + await _step(tolerate_missing_sync_time=False).execute(context) + + assert not any(str(r.url).endswith("/clock/followers") for r in sent) + sync = [r for r in sent if str(r.url).endswith("/svc/mcp-email/agentenv/ext/sync_time")] + assert len(sync) == 1 and json.loads(sync[0].content) == {"env_get_time_url": CLOCK_URL} + assert [s["service"] for s in context.metadata["clock_configurations"][0]["synced"]] == ["email"] + assert agent_clock.SERVER_FOLLOWING_KEY not in context.metadata + + +@pytest.mark.asyncio +async def test_a_server_follower_that_fails_after_declaring_is_retired_and_the_step_raises(monkeypatch): + real, sent = httpx.AsyncClient, [] + + def handle(request: httpx.Request) -> httpx.Response: + sent.append((request.method, request.url.path)) + if request.url.path.endswith("/agentenv/ext/sync_time"): + return httpx.Response(500, json={"detail": "boom"}) + return httpx.Response(200, json={"env_get_time_url": CLOCK_URL} if request.url.path.endswith("/clock/state") else {}) + + monkeypatch.setattr(httpx, "AsyncClient", lambda *a, **k: real(transport=httpx.MockTransport(handle))) + monkeypatch.setattr(mod, "_server_watch_url", lambda deployed: _COMPOSE_WATCH) + monkeypatch.setattr("agent_env.env.env.Env.get", lambda *a, **k: SimpleNamespace(environment_name="email")) + context = TaskStepContext(deployed_envs=[_carded(await _composed_card({"mcp-email": [_FOLLOWER_EXT]}))]) + + with pytest.raises(RuntimeError, match="server 'email' doesn't follow the clock of env 'e1'"): + await _step().execute(context) + + paths = [(method, "/" + "/".join(path.split("/")[-2:])) for method, path in sent] + assert ("PUT", "/clock/followers") in paths and ("DELETE", "/clock/followers") in paths + assert agent_clock.SERVER_FOLLOWING_KEY not in context.metadata + + +@pytest.mark.asyncio +async def test_a_teardown_retires_a_declared_server_follower(monkeypatch): + sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) + monkeypatch.setattr(mod, "_server_watch_url", lambda deployed: _COMPOSE_WATCH) + monkeypatch.setattr("agent_env.env.env.Env.get", lambda *a, **k: SimpleNamespace(environment_name="email")) + context = TaskStepContext(deployed_envs=[_carded(await _composed_card({"mcp-email": [_FOLLOWER_EXT]}))]) + await _step().execute(context) + del sent[:] + + async def nothing(*a, **k): + return SimpleNamespace(terminated=[], failed=[]) + + monkeypatch.setattr("agent_env.task_step.task_steps.teardown_sandboxes.before_teardown", nothing) + monkeypatch.setattr("agent_env.task_step.task_steps.teardown_sandboxes.tear_down", nothing) + await TeardownSandboxesTaskStep(id="down", version=1, env_ids=["e1"]).execute(context) + + assert [(r.method, str(r.url), json.loads(r.content)) for r in sent] == [ + ("DELETE", f"{_CARD}/clock/followers", {"name": "svc-email"})] + assert context.metadata[agent_clock.SERVER_FOLLOWING_KEY] == {} + + _CLOCK_EXT = {"uri": EXT_CLOCK_URI, "params": {"endpoint": "/agentenv/ext/sync_time", "methods": {"sync_time": {"method": "POST"}}}} _ZONE_EXT = {"uri": EXT_CLOCK_URI, "params": {"endpoint": "/agentenv/ext/sync_time", "methods": {"sync_time": {"method": "POST", "request": { "type": "object", "properties": {"env_get_time_url": {"type": "string"}, "timezone": {"type": "string"}}, "required": ["env_get_time_url"]}}}}} _OLD_EXT = {"uri": EXT_CLOCK_URI, "params": {"endpoint": "/agentenv/ext/sync_time", "methods": {"sync_time": {"method": "POST", "request": { "type": "object", "properties": {"env_get_time_url": {"type": "string"}}, "required": ["env_get_time_url"]}}}}} +_FOLLOWER_EXT = {"uri": EXT_CLOCK_URI, "params": {"endpoint": "/agentenv/ext/sync_time", "methods": {"sync_time": {"method": "POST", "request": { + "type": "object", "properties": {"env_get_time_url": {"type": "string"}, "watch_url": {"type": "string"}, + "name": {"type": "string"}, "read_token": {"type": "string"}}, "required": ["env_get_time_url"]}}}}} +_COMPOSE_WATCH = "http://gateway:18765/clock/watch" # The card's address differs from the gateway URL, so a call built from the stored card is told apart from one built from /svc/... itself. _CARD = "https://sandbox.example/sb-1" @@ -286,8 +423,6 @@ def _carded(card: dict) -> DeployedEnv: def _mock_http(monkeypatch, state: dict | None = None, set_time_status: int = 200): """Record every request: `/clock/state` answers `state`, `/clock/set-time` `set_time_status`, anything else an empty object.""" - import httpx - sent, real = [], httpx.AsyncClient def handle(request: httpx.Request) -> httpx.Response: