Skip to content

Commit fef190e

Browse files
fix(a2a_agent): a trajectory follower ends with its step (#618)
1 parent 75f03d9 commit fef190e

2 files changed

Lines changed: 68 additions & 7 deletions

File tree

‎src/agent_env/a2a_agent/trajectory_follower.py‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from __future__ import annotations
33

44
import asyncio
5+
import contextlib
56
import logging
67
from collections.abc import Awaitable, Callable
78
from contextlib import nullcontext
@@ -71,7 +72,8 @@ async def follow_trajectory(
7172
events and the last one, until the task has ended and every event is read.
7273
7374
Between reads it waits ``poll_interval_seconds``, or less once ``stop`` is set. Transport errors
74-
and 5xx answers are retried with backoff; a task the agent no longer knows (404) ends following."""
75+
and 5xx answers are retried with backoff until ``stop`` is set, and end following after it; a
76+
task the agent no longer knows (404) ends following."""
7577
after = 0
7678
failures = 0
7779
async with nullcontext(client) if client is not None else httpx.AsyncClient() as http:
@@ -113,11 +115,15 @@ async def follow_trajectory(
113115
if page.has_more:
114116
continue
115117
if stop.is_set():
118+
if failures:
119+
# The turn has ended, so an agent that stops answering now is gone, not busy: retrying
120+
# would poll a dead address until the step's drain gives up. The step marks the turn's end.
121+
logger.warning("Agent stopped answering after task %s ended; stopped following its trajectory", task_id)
122+
return
116123
await asyncio.sleep(_STOPPED_INTERVAL_SECONDS)
117124
continue
118-
try:
119-
await asyncio.wait_for(
120-
stop.wait(), timeout=min(poll_interval_seconds + failures * 5, _MAX_BACKOFF_SECONDS)
121-
)
122-
except TimeoutError:
123-
pass
125+
# Not `wait_for`: on 3.11 it drops a cancel that lands as `stop` is set, the step's own
126+
# teardown, and the follower then outlives its step.
127+
with contextlib.suppress(TimeoutError):
128+
async with asyncio.timeout(min(poll_interval_seconds + failures * 5, _MAX_BACKOFF_SECONDS)):
129+
await stop.wait()

‎tst/unit/a2a_agent/test_trajectory_follower.py‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import asyncio
2+
import contextlib
23
import json
34
import time
45

@@ -124,6 +125,60 @@ async def test_a_server_error_is_retried(monkeypatch):
124125
assert batches[-1].events == [{"i": 0}]
125126

126127

128+
@contextlib.asynccontextmanager
129+
async def _following(agent: _Agent, stop: asyncio.Event, *, poll_interval_seconds: float):
130+
"""A follower of ``agent``'s task, yielded once it has made its first read; cancelled on the way out
131+
if it is still running, so a failing test leaves no follower behind."""
132+
133+
async def sink(batch: TrajectoryBatch) -> None:
134+
pass
135+
136+
async def follow() -> None:
137+
async with agent.client() as client:
138+
await follow_trajectory(
139+
_ENDPOINT, "task-1", sink, poll_interval_seconds=poll_interval_seconds, stop=stop, client=client
140+
)
141+
142+
follower = asyncio.create_task(follow())
143+
try:
144+
async with asyncio.timeout(5):
145+
while not agent.afters:
146+
await asyncio.sleep(0.01)
147+
yield follower
148+
finally:
149+
follower.cancel()
150+
await asyncio.wait({follower})
151+
152+
153+
@pytest.mark.asyncio
154+
async def test_a_follower_cancelled_as_it_is_stopped_ends():
155+
"""A step's teardown sets ``stop`` and cancels its follower in the same tick. The agent keeps
156+
answering, so only the cancel can end the follower; on Python 3.11 ``asyncio.wait_for`` dropped it."""
157+
agent = _Agent(*[httpx.Response(200, json=_page(0, [], "running"))] * 100)
158+
stop = asyncio.Event()
159+
async with _following(agent, stop, poll_interval_seconds=30) as follower:
160+
stop.set()
161+
follower.cancel()
162+
163+
done, _ = await asyncio.wait({follower}, timeout=2)
164+
165+
assert done == {follower}
166+
assert follower.cancelled()
167+
168+
169+
@pytest.mark.asyncio
170+
async def test_an_agent_that_fails_after_the_turn_ends_ends_following():
171+
agent = _Agent(httpx.Response(200, json=_page(0, [], "running")), *[httpx.Response(503)] * 100)
172+
stop = asyncio.Event()
173+
async with _following(agent, stop, poll_interval_seconds=30) as follower:
174+
stop.set()
175+
176+
async with asyncio.timeout(2):
177+
await follower
178+
179+
assert agent.afters == [0, 0]
180+
181+
127182
@pytest.mark.asyncio
128183
async def test_a_task_the_agent_no_longer_knows_ends_following():
129184
agent = _Agent(httpx.Response(404, json={"detail": "Unknown task"}))

0 commit comments

Comments
 (0)