From a582953d5f982156994b100aa08275207f967e42 Mon Sep 17 00:00:00 2001 From: Can Ersoz Date: Wed, 2 Dec 2026 13:06:18 -0800 Subject: [PATCH 1/6] feat(clock): let a backing server follow the gateway clock through its own follower A backing server whose sync_time advertises the follower fields (watch_url, name, read_token) is now declared a follower of its env's gateway, as an agent is, and handed the in-compose watch URL, so every program in its image reads the env's time. Teardown retires it. Servers without those fields keep today's sync, and a website whose image runs the follower takes the same path. Co-Authored-By: Claude Opus 5.5 --- .../agentenv_protocol/website/environment.py | 14 +- .../tests/test_website_environment.py | 54 ++++++++ src/agent_env/a2a_agent/clock.py | 125 ++++++++++++------ .../task_step/task_steps/sync_env_clock.py | 44 +++++- .../task_steps/teardown_sandboxes.py | 3 +- tst/unit/task_step/sync_env_clock_test.py | 108 ++++++++++++++- 6 files changed, 299 insertions(+), 49 deletions(-) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/website/environment.py b/packages/agentenv-protocol/src/agentenv_protocol/website/environment.py index 2c8cf0f2c..d6861b5ac 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/website/environment.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/website/environment.py @@ -43,6 +43,7 @@ from starlette.responses import FileResponse, JSONResponse, Response from starlette.routing import Route +from ..a2a_agent import clock as agent_clock from ..agent_env_environment import ( AgentEnvEnvironment, _RESOURCE_ATTR, @@ -289,9 +290,18 @@ def served_extensions(self, extensions: list[EnvironmentExtension]) -> list[Envi return served @extension(CLOCK_EXTENSION_URI, description="Sync this site to the gateway's virtual clock.") - async def sync_time(self, env_get_time_url: str, timezone: Optional[str] = None) -> dict: + async def sync_time(self, env_get_time_url: str, timezone: Optional[str] = None, **follower: object) -> dict: """Follow the gateway's virtual time at ``env_get_time_url`` from now on, in ``timezone`` when the task names - one; an empty ``env_get_time_url`` goes back to wall time.""" + one; an empty ``env_get_time_url`` goes back to wall time. An image that runs the computer-base clock follower, + and is handed that follower's config (``watch_url``, ``name``, ``read_token``), follows the gateway's watch as + an agent does instead, so every program the site starts reads the env's time; the config fields are taken + through ``**follower`` so the base card keeps advertising only ``env_get_time_url`` and ``timezone`` and a site + whose image runs no follower is unaffected.""" + watch_url, name, read_token = (follower.get("watch_url"), follower.get("name"), follower.get("read_token")) + if watch_url and name and read_token: + if agent_clock.follows(): + return await agent_clock.sync_time(env_get_time_url, timezone=timezone, watch_url=watch_url, + name=name, read_token=read_token) virtual = await self._clock().sync(env_get_time_url, timezone.strip() if timezone else None) return {"env_get_time_url": env_get_time_url, "gateway_virtual_time": iso(virtual), **({"timezone": self.timezone} if self.timezone else {})} diff --git a/packages/agentenv-protocol/tests/test_website_environment.py b/packages/agentenv-protocol/tests/test_website_environment.py index bd300e55d..e29ffbb36 100644 --- a/packages/agentenv-protocol/tests/test_website_environment.py +++ b/packages/agentenv-protocol/tests/test_website_environment.py @@ -21,6 +21,7 @@ from starlette.routing import Route from starlette.testclient import TestClient +import agentenv_protocol.a2a_agent.clock as agent_clock from agentenv_protocol import DataPart, add_data, get_data, reset_data from agentenv_protocol.website import ( SESSION_COOKIE, @@ -776,3 +777,56 @@ def test_a_time_parses_whatever_its_fraction_of_a_second(value: str, microsecond moment = parse_time(value) assert moment.astimezone(datetime.timezone.utc).replace(microsecond=0) == datetime.datetime( 2031, 1, 1, tzinfo=datetime.timezone.utc) and moment.microsecond == microseconds + + +def test_the_clock_card_advertises_no_follower_fields(client: TestClient) -> None: + """The base site reads the clock itself (UniverseClock), so it must not advertise a follower's config fields: were + it to, sync_env_clock would declare every virtual-clock site a follower and hand it a watch its image can't run.""" + card = client.get("/.well-known/agent-env.json").json() + schema = _extension(card, "urn:agentenv:clock/v1")["params"]["methods"]["sync_time"]["request"] + assert set(schema.get("properties", {})) == {"env_get_time_url", "timezone"} + + +@pytest.mark.asyncio +async def test_sync_time_follows_the_gateway_watch_when_the_image_runs_the_follower(shop, monkeypatch) -> None: + async def never_sync(self, url, timezone=None): + raise AssertionError("a follower-running site must not read the gateway clock itself") + + calls = {} + + async def fake_agent_sync(env_get_time_url, *, timezone=None, watch_url=None, name=None, read_token=None): + calls.update(env_get_time_url=env_get_time_url, timezone=timezone, watch_url=watch_url, name=name, + read_token=read_token) + return {"synced": True, "follower": {"name": name}} + + monkeypatch.setattr(agent_clock, "follows", lambda: True) + monkeypatch.setattr(agent_clock, "sync_time", fake_agent_sync) + monkeypatch.setattr(clock_module.UniverseClock, "sync", never_sync) + + out = await shop.sync_time("http://gw/clock/time", timezone="America/Chicago", + watch_url="http://gateway:18765/clock/watch", name="svc-shop", read_token="tok") + + assert out == {"synced": True, "follower": {"name": "svc-shop"}} + assert calls == {"env_get_time_url": "http://gw/clock/time", "timezone": "America/Chicago", + "watch_url": "http://gateway:18765/clock/watch", "name": "svc-shop", "read_token": "tok"} + + +@pytest.mark.asyncio +async def test_sync_time_ignores_follower_fields_when_the_image_runs_no_follower(shop, monkeypatch) -> None: + synced = {} + + async def fake_sync(self, url, timezone=None): + synced.update(url=url, timezone=timezone) + return datetime.datetime(2031, 1, 1, tzinfo=datetime.timezone.utc) + + async def fail(*a, **k): + raise AssertionError("a site whose image runs no follower must take the UniverseClock path") + + monkeypatch.setattr(agent_clock, "follows", lambda: False) + monkeypatch.setattr(agent_clock, "sync_time", fail) + monkeypatch.setattr(clock_module.UniverseClock, "sync", fake_sync) + + out = await shop.sync_time("http://gw/clock/time", watch_url="w", name="n", read_token="t") + + assert synced == {"url": "http://gw/clock/time", "timezone": None} + assert out["env_get_time_url"] == "http://gw/clock/time" and "gateway_virtual_time" in out diff --git a/src/agent_env/a2a_agent/clock.py b/src/agent_env/a2a_agent/clock.py index c9f6be0b9..5e095735b 100644 --- a/src/agent_env/a2a_agent/clock.py +++ b/src/agent_env/a2a_agent/clock.py @@ -44,6 +44,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, service), so steps that save the context at once never overwrite another's. +SERVER_FOLLOWING_KEY = "server_clock_following" def follower_name(agent: DeployedAgent) -> str: @@ -60,6 +63,48 @@ 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: + """Whether a ``sync_time`` method takes a follower's config fields (``FOLLOWER_FIELDS``), so the server or agent + that serves it can be declared a follower rather than only handed the env's time URL.""" + 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, + timeout: float, subject: str) -> dict: + """Declare a follower named ``name`` at ``env``'s gateway and hand its server or agent that follower's config: the + shared core of a follower's sync, for an agent (``follow``) and for an env's own server (``sync_env_clock``) alike. + ``method`` is the target's advertised ``clock/v1`` ``sync_time``. ``{"synced": False, "reason": ...}`` for a target + that can't follow: it serves no ``sync_time`` (``not_advertised``) or one without the follower's fields + (``no_follower_fields``), or the gateway takes no followers (``gateway_takes_no_followers``); raises for one that + serves it and fails, having retired the follower it declared, or can't take the task's zone. ``send_sync_time(body)`` + sends the config and answers ``(True, result)`` once the target follows or ``(False, why)`` when it doesn't; a + transport error it raises is taken as a failure. ``subject`` names the target in the errors raised.""" + 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: # noqa: BLE001 - any send failure retires the declared follower, then fails the step + 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 +121,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 +250,41 @@ 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: + """Record that ``env``'s backing server ``service`` was declared the follower ``follower`` in this run, keyed per + (env, service) so steps saving the context at once never overwrite another's, so a teardown retires it.""" + context.metadata.setdefault(SERVER_FOLLOWING_KEY, {})[_slot(f"{env.env_id}:{service}")] = { + "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]: + """Retire the followers recorded under ``metadata[key]`` for ``slots``, forgetting each the gateway stops waiting + for. Best-effort, as a teardown is: a gateway that's gone or takes no retirement is logged and its record kept. The + followers retired.""" + 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]: + """Have each env in ``env_ids`` being torn down stop waiting for the backing-server followers it declared this run, + as ``retire_followers`` does for agents. Best-effort. The followers retired.""" + 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..8713c7add 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,18 @@ 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 as a sibling backing server reaches it, or None when the deployment isn't a + VM/compose one. On Modal VM and KubeVirt the gateway and its servers are siblings on the one env-network compose + bridge, so a server reaches the gateway by service name; ``watch_url_for``/``gateway_url_of`` give the external + tunnel URL, which a compose sibling can't use. Real-app multi envs run in VM mode, so a declared server follower + reaches its gateway here.""" + 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 +199,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 +229,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 +255,24 @@ 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-{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"]) + 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/unit/task_step/sync_env_clock_test.py b/tst/unit/task_step/sync_env_clock_test.py index 191247b98..25d6b5db4 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,114 @@ 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:email": {"service": "email", "env_id": "e1", "deploy_step_id": None, "follower": "svc-email"}} + + +@pytest.mark.asyncio +async def test_execute_syncs_a_server_without_follower_fields_the_legacy_way(monkeypatch): + """Today's date-rewrite servers advertise no follower fields, so they keep being handed only the time URL and are + never declared followers, even where a server could be (the in-compose watch URL is available).""" + 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): + """A deployment that isn't a VM/compose one has no in-compose watch URL, so even a follower-capable server falls + back to today's behaviour rather than being handed a URL it can't reach.""" + 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_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"]}}}}} +# A step-5 server image whose sync_time takes a follower's config, so the harness declares it a follower. +_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 +392,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: From 0339a90a441753570186b0fe9a0992d79e5deaa5 Mon Sep 17 00:00:00 2001 From: Can Ersoz Date: Wed, 2 Dec 2026 13:23:06 -0800 Subject: [PATCH 2/6] fix(clock): name website followers apart from MCP servers and drop the website follower path An MCP server and a website may share a name, so a website is declared site- and each server follower is recorded under its follower name, not its service. The website's sync_time no longer takes follower fields: its card never advertised them, so sync_env_clock never sent them, and the path imported the agent package, which plain website installs don't have. Co-Authored-By: Claude Opus 5.5 --- .../agentenv_protocol/website/environment.py | 14 +---- .../tests/test_website_environment.py | 54 ------------------- src/agent_env/a2a_agent/clock.py | 6 +-- .../task_step/task_steps/sync_env_clock.py | 2 +- tst/unit/task_step/sync_env_clock_test.py | 21 +++++++- 5 files changed, 25 insertions(+), 72 deletions(-) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/website/environment.py b/packages/agentenv-protocol/src/agentenv_protocol/website/environment.py index d6861b5ac..2c8cf0f2c 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/website/environment.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/website/environment.py @@ -43,7 +43,6 @@ from starlette.responses import FileResponse, JSONResponse, Response from starlette.routing import Route -from ..a2a_agent import clock as agent_clock from ..agent_env_environment import ( AgentEnvEnvironment, _RESOURCE_ATTR, @@ -290,18 +289,9 @@ def served_extensions(self, extensions: list[EnvironmentExtension]) -> list[Envi return served @extension(CLOCK_EXTENSION_URI, description="Sync this site to the gateway's virtual clock.") - async def sync_time(self, env_get_time_url: str, timezone: Optional[str] = None, **follower: object) -> dict: + async def sync_time(self, env_get_time_url: str, timezone: Optional[str] = None) -> dict: """Follow the gateway's virtual time at ``env_get_time_url`` from now on, in ``timezone`` when the task names - one; an empty ``env_get_time_url`` goes back to wall time. An image that runs the computer-base clock follower, - and is handed that follower's config (``watch_url``, ``name``, ``read_token``), follows the gateway's watch as - an agent does instead, so every program the site starts reads the env's time; the config fields are taken - through ``**follower`` so the base card keeps advertising only ``env_get_time_url`` and ``timezone`` and a site - whose image runs no follower is unaffected.""" - watch_url, name, read_token = (follower.get("watch_url"), follower.get("name"), follower.get("read_token")) - if watch_url and name and read_token: - if agent_clock.follows(): - return await agent_clock.sync_time(env_get_time_url, timezone=timezone, watch_url=watch_url, - name=name, read_token=read_token) + one; an empty ``env_get_time_url`` goes back to wall time.""" virtual = await self._clock().sync(env_get_time_url, timezone.strip() if timezone else None) return {"env_get_time_url": env_get_time_url, "gateway_virtual_time": iso(virtual), **({"timezone": self.timezone} if self.timezone else {})} diff --git a/packages/agentenv-protocol/tests/test_website_environment.py b/packages/agentenv-protocol/tests/test_website_environment.py index e29ffbb36..bd300e55d 100644 --- a/packages/agentenv-protocol/tests/test_website_environment.py +++ b/packages/agentenv-protocol/tests/test_website_environment.py @@ -21,7 +21,6 @@ from starlette.routing import Route from starlette.testclient import TestClient -import agentenv_protocol.a2a_agent.clock as agent_clock from agentenv_protocol import DataPart, add_data, get_data, reset_data from agentenv_protocol.website import ( SESSION_COOKIE, @@ -777,56 +776,3 @@ def test_a_time_parses_whatever_its_fraction_of_a_second(value: str, microsecond moment = parse_time(value) assert moment.astimezone(datetime.timezone.utc).replace(microsecond=0) == datetime.datetime( 2031, 1, 1, tzinfo=datetime.timezone.utc) and moment.microsecond == microseconds - - -def test_the_clock_card_advertises_no_follower_fields(client: TestClient) -> None: - """The base site reads the clock itself (UniverseClock), so it must not advertise a follower's config fields: were - it to, sync_env_clock would declare every virtual-clock site a follower and hand it a watch its image can't run.""" - card = client.get("/.well-known/agent-env.json").json() - schema = _extension(card, "urn:agentenv:clock/v1")["params"]["methods"]["sync_time"]["request"] - assert set(schema.get("properties", {})) == {"env_get_time_url", "timezone"} - - -@pytest.mark.asyncio -async def test_sync_time_follows_the_gateway_watch_when_the_image_runs_the_follower(shop, monkeypatch) -> None: - async def never_sync(self, url, timezone=None): - raise AssertionError("a follower-running site must not read the gateway clock itself") - - calls = {} - - async def fake_agent_sync(env_get_time_url, *, timezone=None, watch_url=None, name=None, read_token=None): - calls.update(env_get_time_url=env_get_time_url, timezone=timezone, watch_url=watch_url, name=name, - read_token=read_token) - return {"synced": True, "follower": {"name": name}} - - monkeypatch.setattr(agent_clock, "follows", lambda: True) - monkeypatch.setattr(agent_clock, "sync_time", fake_agent_sync) - monkeypatch.setattr(clock_module.UniverseClock, "sync", never_sync) - - out = await shop.sync_time("http://gw/clock/time", timezone="America/Chicago", - watch_url="http://gateway:18765/clock/watch", name="svc-shop", read_token="tok") - - assert out == {"synced": True, "follower": {"name": "svc-shop"}} - assert calls == {"env_get_time_url": "http://gw/clock/time", "timezone": "America/Chicago", - "watch_url": "http://gateway:18765/clock/watch", "name": "svc-shop", "read_token": "tok"} - - -@pytest.mark.asyncio -async def test_sync_time_ignores_follower_fields_when_the_image_runs_no_follower(shop, monkeypatch) -> None: - synced = {} - - async def fake_sync(self, url, timezone=None): - synced.update(url=url, timezone=timezone) - return datetime.datetime(2031, 1, 1, tzinfo=datetime.timezone.utc) - - async def fail(*a, **k): - raise AssertionError("a site whose image runs no follower must take the UniverseClock path") - - monkeypatch.setattr(agent_clock, "follows", lambda: False) - monkeypatch.setattr(agent_clock, "sync_time", fail) - monkeypatch.setattr(clock_module.UniverseClock, "sync", fake_sync) - - out = await shop.sync_time("http://gw/clock/time", watch_url="w", name="n", read_token="t") - - assert synced == {"url": "http://gw/clock/time", "timezone": None} - assert out["env_get_time_url"] == "http://gw/clock/time" and "gateway_virtual_time" in out diff --git a/src/agent_env/a2a_agent/clock.py b/src/agent_env/a2a_agent/clock.py index 5e095735b..0e21fb1fb 100644 --- a/src/agent_env/a2a_agent/clock.py +++ b/src/agent_env/a2a_agent/clock.py @@ -45,7 +45,7 @@ #: ``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, service), so steps that save the context at once never overwrite another's. +#: one slot per (env, follower), so steps that save the context at once never overwrite another's. SERVER_FOLLOWING_KEY = "server_clock_following" @@ -252,8 +252,8 @@ async def follow_armed_clocks(context: TaskStepContext, agent: DeployedAgent, *, def record_server_follower(context: TaskStepContext, env: DeployedEnv, service: str, follower: str) -> None: """Record that ``env``'s backing server ``service`` was declared the follower ``follower`` in this run, keyed per - (env, service) so steps saving the context at once never overwrite another's, so a teardown retires it.""" - context.metadata.setdefault(SERVER_FOLLOWING_KEY, {})[_slot(f"{env.env_id}:{service}")] = { + (env, follower), as an MCP server and a website may share a name, so a teardown retires it.""" + 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} 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 8713c7add..3bc8de8c0 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 @@ -265,7 +265,7 @@ async def send(body: dict) -> tuple[bool, object]: headers=deployed.control_headers) outcome = await declare_and_sync_follower( - gateway_env, method=method, name=f"svc-{service}", watch_url=watch_url, env_get_time_url=env_get_time_url, + 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"]) diff --git a/tst/unit/task_step/sync_env_clock_test.py b/tst/unit/task_step/sync_env_clock_test.py index 25d6b5db4..6eba0105e 100644 --- a/tst/unit/task_step/sync_env_clock_test.py +++ b/tst/unit/task_step/sync_env_clock_test.py @@ -271,7 +271,24 @@ async def test_execute_declares_and_syncs_a_server_that_advertises_follower_fiel 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:email": {"service": "email", "env_id": "e1", "deploy_step_id": None, "follower": "svc-email"}} + "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 @@ -355,7 +372,7 @@ async def nothing(*a, **k): "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"]}}}}} -# A step-5 server image whose sync_time takes a follower's config, so the harness declares it a follower. +# A server image whose sync_time takes a follower's config, so the harness declares it a follower. _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"]}}}}} From 511a5e30663767acc08006fce4f01705456cfca7 Mon Sep 17 00:00:00 2001 From: Can Ersoz Date: Wed, 2 Dec 2026 15:06:32 -0800 Subject: [PATCH 3/6] refactor(clock): trim the server follower comments and type send_sync_time Co-Authored-By: Claude Opus 5.5 --- src/agent_env/a2a_agent/clock.py | 29 ++++++------------- .../task_step/task_steps/sync_env_clock.py | 7 ++--- tst/unit/task_step/sync_env_clock_test.py | 5 ---- 3 files changed, 11 insertions(+), 30 deletions(-) diff --git a/src/agent_env/a2a_agent/clock.py b/src/agent_env/a2a_agent/clock.py index 0e21fb1fb..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 @@ -45,7 +46,7 @@ #: ``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), so steps that save the context at once never overwrite another's. +#: one slot per (env, follower). SERVER_FOLLOWING_KEY = "server_clock_following" @@ -64,22 +65,15 @@ def _fields(method: dict) -> set[str]: def advertises_follower_fields(method: Optional[dict]) -> bool: - """Whether a ``sync_time`` method takes a follower's config fields (``FOLLOWER_FIELDS``), so the server or agent - that serves it can be declared a follower rather than only handed the env's time URL.""" 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, + env_get_time_url: Optional[str], timezone: Optional[str], + send_sync_time: Callable[[dict], Awaitable[tuple[bool, object]]], timeout: float, subject: str) -> dict: - """Declare a follower named ``name`` at ``env``'s gateway and hand its server or agent that follower's config: the - shared core of a follower's sync, for an agent (``follow``) and for an env's own server (``sync_env_clock``) alike. - ``method`` is the target's advertised ``clock/v1`` ``sync_time``. ``{"synced": False, "reason": ...}`` for a target - that can't follow: it serves no ``sync_time`` (``not_advertised``) or one without the follower's fields - (``no_follower_fields``), or the gateway takes no followers (``gateway_takes_no_followers``); raises for one that - serves it and fails, having retired the follower it declared, or can't take the task's zone. ``send_sync_time(body)`` - sends the config and answers ``(True, result)`` once the target follows or ``(False, why)`` when it doesn't; a - transport error it raises is taken as a failure. ``subject`` names the target in the errors raised.""" + """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): @@ -96,7 +90,7 @@ async def declare_and_sync_follower(env: DeployedEnv, *, method: Optional[dict], "read_token": token, **({"timezone": timezone} if timezone is not None else {})} try: followed, detail = await send_sync_time(body) - except Exception as e: # noqa: BLE001 - any send failure retires the declared follower, then fails the step + except Exception as e: followed, detail = False, f"({type(e).__name__}): {e}" if followed: return {"synced": True, "follower": name, "result": detail} @@ -251,16 +245,12 @@ async def follow_armed_clocks(context: TaskStepContext, agent: DeployedAgent, *, def record_server_follower(context: TaskStepContext, env: DeployedEnv, service: str, follower: str) -> None: - """Record that ``env``'s backing server ``service`` was declared the follower ``follower`` in this run, keyed per - (env, follower), as an MCP server and a website may share a name, so a teardown retires it.""" 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]: - """Retire the followers recorded under ``metadata[key]`` for ``slots``, forgetting each the gateway stops waiting - for. Best-effort, as a teardown is: a gateway that's gone or takes no retirement is logged and its record kept. The - followers retired.""" + """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: @@ -283,8 +273,7 @@ async def retire_followers(context: TaskStepContext, agent_names, *, timeout: fl async def retire_server_followers(context: TaskStepContext, env_ids, *, timeout: float = RETIRE_TIMEOUT_S) -> list[str]: - """Have each env in ``env_ids`` being torn down stop waiting for the backing-server followers it declared this run, - as ``retire_followers`` does for agents. Best-effort. The followers retired.""" + """``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 3bc8de8c0..c2ed32784 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 @@ -72,11 +72,8 @@ def resolve_virtual_time(virtual_time: str, timezone: Optional[str]) -> str: def _server_watch_url(deployed) -> Optional[str]: - """The gateway's clock-watch URL as a sibling backing server reaches it, or None when the deployment isn't a - VM/compose one. On Modal VM and KubeVirt the gateway and its servers are siblings on the one env-network compose - bridge, so a server reaches the gateway by service name; ``watch_url_for``/``gateway_url_of`` give the external - tunnel URL, which a compose sibling can't use. Real-app multi envs run in VM mode, so a declared server follower - reaches its gateway here.""" + """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 diff --git a/tst/unit/task_step/sync_env_clock_test.py b/tst/unit/task_step/sync_env_clock_test.py index 6eba0105e..059fe1617 100644 --- a/tst/unit/task_step/sync_env_clock_test.py +++ b/tst/unit/task_step/sync_env_clock_test.py @@ -293,8 +293,6 @@ async def test_an_mcp_server_and_a_website_sharing_a_name_are_declared_distinct_ @pytest.mark.asyncio async def test_execute_syncs_a_server_without_follower_fields_the_legacy_way(monkeypatch): - """Today's date-rewrite servers advertise no follower fields, so they keep being handed only the time URL and are - never declared followers, even where a server could be (the in-compose watch URL is available).""" 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")) @@ -310,8 +308,6 @@ async def test_execute_syncs_a_server_without_follower_fields_the_legacy_way(mon @pytest.mark.asyncio async def test_a_server_without_a_compose_watch_url_is_not_declared_a_follower(monkeypatch): - """A deployment that isn't a VM/compose one has no in-compose watch URL, so even a follower-capable server falls - back to today's behaviour rather than being handed a URL it can't reach.""" 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")) @@ -372,7 +368,6 @@ async def nothing(*a, **k): "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"]}}}}} -# A server image whose sync_time takes a follower's config, so the harness declares it a follower. _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"]}}}}} From e07bd7f2432f6258c13249ce4aa17b1f9b8bbdd8 Mon Sep 17 00:00:00 2001 From: Can Ersoz Date: Wed, 2 Dec 2026 15:39:19 -0800 Subject: [PATCH 4/6] test(clock): follow a backing server through the real gateway on local Docker A server whose sync_time takes the follower's config is declared svc- by sync_env_clock, reaches the gateway's watch from inside the compose network, is waited for by a write that waits for followers (504 naming it while paused), and is no longer waited for once retired. Co-Authored-By: Claude Opus 5.5 --- tst/data/clock_follower_mcp/Dockerfile | 9 ++ tst/data/clock_follower_mcp/server.py | 52 +++++++++ tst/integration/slow_durations.json | 1 + .../task_step/test_server_env_clock_local.py | 105 ++++++++++++++++++ 4 files changed, 167 insertions(+) create mode 100644 tst/data/clock_follower_mcp/Dockerfile create mode 100644 tst/data/clock_follower_mcp/server.py create mode 100644 tst/integration/task_step/test_server_env_clock_local.py 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..3d182e4e9 --- /dev/null +++ b/tst/data/clock_follower_mcp/server.py @@ -0,0 +1,52 @@ +"""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 httpx + +from agentenv_protocol import AgentEnvEnvironment, environment_card, extension, tool + + +@environment_card(name="clockapp") +class ClockAppEnv(AgentEnvEnvironment): + 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=60) 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(0.5) + 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)) + for _ in range(100): + if self.shown is not None: + return {"synced": True, "version": self.shown.get("version")} + await asyncio.sleep(0.1) + 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() From a2870d94b1e8f6cc6c040e14ee3b00ba8ecf8c40 Mon Sep 17 00:00:00 2001 From: Can Ersoz Date: Wed, 2 Dec 2026 15:55:21 -0800 Subject: [PATCH 5/6] fix(clock): sync a follower-capable server by its time URL on a gateway that takes no followers A gateway from before declare_follower can still arm the clock and serve env_get_time_url, so a server that could follow is synced the old way there instead of being left unsynced. Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/sync_env_clock.py | 3 ++- tst/unit/task_step/sync_env_clock_test.py | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) 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 c2ed32784..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 @@ -266,7 +266,8 @@ async def send(body: dict) -> tuple[bool, object]: 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"]) - return outcome + 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: if "timezone" not in (((method or {}).get("request") or {}).get("properties") or {}): diff --git a/tst/unit/task_step/sync_env_clock_test.py b/tst/unit/task_step/sync_env_clock_test.py index 059fe1617..85c64a711 100644 --- a/tst/unit/task_step/sync_env_clock_test.py +++ b/tst/unit/task_step/sync_env_clock_test.py @@ -319,6 +319,25 @@ async def test_a_server_without_a_compose_watch_url_is_not_declared_a_follower(m 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, [] From 8453dc023302ed23d6ad50b27aa1121c3120b928 Mon Sep 17 00:00:00 2001 From: Can Ersoz Date: Wed, 2 Dec 2026 16:46:41 -0800 Subject: [PATCH 6/6] test(clock): name the follower test server's timings Co-Authored-By: Claude Opus 5.5 --- tst/data/clock_follower_mcp/server.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/tst/data/clock_follower_mcp/server.py b/tst/data/clock_follower_mcp/server.py index 3d182e4e9..9c9866d70 100644 --- a/tst/data/clock_follower_mcp/server.py +++ b/tst/data/clock_follower_mcp/server.py @@ -2,6 +2,7 @@ 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 @@ -10,6 +11,11 @@ @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 @@ -17,14 +23,14 @@ def __init__(self) -> None: async def _follow(self, watch_url: str, name: str, read_token: str) -> None: after = "" - async with httpx.AsyncClient(timeout=60) as client: + 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(0.5) + await asyncio.sleep(self.WATCH_RETRY_S) continue self.shown = answer.json() after = self.shown.get("version") or "" @@ -36,10 +42,11 @@ async def sync_time(self, env_get_time_url: str, watch_url: str = "", name: str self.loop.cancel() self.shown = None self.loop = asyncio.create_task(self._follow(watch_url, name, read_token)) - for _ in range(100): + 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(0.1) + await asyncio.sleep(self.FIRST_ANSWER_POLL_S) raise RuntimeError(f"no answer from {watch_url}") @tool(name="{environment_name}_clock")