Skip to content

Commit 5e0d415

Browse files
fix(server): close the event queues when ActiveTask.start() fails (a2aproject#1422)
# Description Thank you for opening a Pull Request! Before submitting your PR, there are a few things you can do to make sure it goes smoothly: - [x] Follow the [`CONTRIBUTING` Guide](https://github.com/a2aproject/a2a-python/blob/main/CONTRIBUTING.md). - [x] Make your Pull Request title in the <https://www.conventionalcommits.org/> specification. - Important Prefixes for [release-please](https://github.com/googleapis/release-please): - `fix:` which represents bug fixes, and correlates to a [SemVer](https://semver.org/) patch. - `feat:` represents a new feature, and correlates to a SemVer minor. - `feat!:`, or `fix!:`, `refactor!:`, etc., which represent a breaking change (indicated by the `!`) and will result in a SemVer major. - [x] Ensure the tests and linter pass (Run `bash scripts/format.sh` from the repository root to format) - [x] Appropriate docs were updated (if necessary) Fixes a2aproject#1421 🦕 ## Problem Each `EventQueueSource` starts its dispatcher task when it is created, and `ActiveTask` creates two of them in `__init__`. When the setup in `start()` fails, because the stored task is in a terminal state or is missing, the `except` block re-raises without closing them: ```python except Exception: logger.debug('ActiveTask[%s]: Setup failed, cleaning up', self._task_id) self._is_finished.set() if self._reference_count == 0 and self._on_cleanup: self._on_cleanup(self) raise # _event_queue_agent and _event_queue_subscribers stay open ``` A `SendMessage` to a completed task goes through this path, so every rejected request leaves two `_dispatch_loop` tasks pending until they are garbage collected and logged as `Task was destroyed but it is pending!`. ## Fix The `except` block in `start()` (`src/a2a/server/agent_execution/active_task.py`) now closes `_event_queue_agent` and `_event_queue_subscribers` with `close(immediate=True)` before calling `_on_cleanup`, the same way `aclose()` closes them. `aclose()` itself can't be used here because it takes `_lock`, which `start()` already holds. The change only touches the failure path, so a successful `start()` is not affected. ## Test A test was added to the existing suite at `tests/server/agent_execution/test_active_task.py`: - `test_active_task_start_setup_failure_closes_event_queues`: after `start()` fails on a completed task (`UnsupportedOperationError`) or a missing one (`TaskNotFoundError`), both dispatcher tasks are done. Both cases fail on `main` with the dispatcher tasks still pending and pass with the fix. No existing test was modified or removed. Happy to adapt the test approach based on maintainer feedback. Co-authored-by: mykytanetipa <mykytanetipa@google.com>
1 parent 05aaff6 commit 5e0d415

2 files changed

Lines changed: 46 additions & 1 deletion

File tree

‎src/a2a/server/agent_execution/active_task.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -637,6 +637,8 @@ async def start(
637637
self._task_id,
638638
)
639639
self._is_finished.set()
640+
await self._event_queue_agent.close(immediate=True)
641+
await self._event_queue_subscribers.close(immediate=True)
640642
if self._reference_count == 0 and self._on_cleanup:
641643
self._on_cleanup(self)
642644
raise

‎tests/server/agent_execution/test_active_task.py‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
TaskStatusUpdateEvent,
2424
)
2525
from a2a.utils._async_queue_compat import QueueShutDown, create_async_queue
26-
from a2a.utils.errors import UnsupportedOperationError
26+
from a2a.utils.errors import TaskNotFoundError, UnsupportedOperationError
2727

2828

2929
logger = logging.getLogger(__name__)
@@ -1503,3 +1503,46 @@ async def slow_execute(req, q):
15031503
for t in background:
15041504
t.cancel()
15051505
await asyncio.gather(*background, return_exceptions=True)
1506+
1507+
1508+
@pytest.mark.timeout(5)
1509+
@pytest.mark.asyncio
1510+
@pytest.mark.parametrize(
1511+
('stored_task', 'expected_error'),
1512+
[
1513+
(
1514+
Task(
1515+
id='test-task-id',
1516+
status=TaskStatus(state=TaskState.TASK_STATE_COMPLETED),
1517+
),
1518+
UnsupportedOperationError,
1519+
),
1520+
(None, TaskNotFoundError),
1521+
],
1522+
)
1523+
async def test_active_task_start_setup_failure_closes_event_queues(
1524+
stored_task, expected_error
1525+
):
1526+
"""A failed start() closes both event queues.
1527+
1528+
Each EventQueueSource starts its dispatcher task when it is created, so
1529+
without this the dispatchers stay pending until garbage collection and
1530+
surface as ``Task was destroyed but it is pending!``.
1531+
"""
1532+
task_manager = Mock()
1533+
task_manager.get_task = AsyncMock(return_value=stored_task)
1534+
1535+
active_task = ActiveTask(
1536+
agent_executor=Mock(),
1537+
task_id='test-task-id',
1538+
task_manager=task_manager,
1539+
push_sender=Mock(),
1540+
)
1541+
1542+
with pytest.raises(expected_error):
1543+
await active_task.start(
1544+
call_context=ServerCallContext(), create_task_if_missing=False
1545+
)
1546+
1547+
assert active_task._event_queue_agent._dispatcher_task.done()
1548+
assert active_task._event_queue_subscribers._dispatcher_task.done()

0 commit comments

Comments
 (0)