Skip to content

Commit 2cc1dd5

Browse files
fix(server): run after_handler_run when a handler call is cancelled (a2aproject#1427)
# Description Follow-up to a2aproject#1402, as asked in the review there. `server_plugin_hooks` handled cancellation differently for unary and streaming methods, and neither told the plugin about it. - The unary wrapper only called `after_handler_run` from `except Exception`. A cancelled call (a client timeout, a disconnect, `asyncio.wait_for` around the handler) got `before_handler_run` and then nothing, so a plugin that opens a span or takes a slot in `before_handler_run` never got to close it. - The stream wrapper does call it from `finally`, but with `error=None`, so a cancelled stream looked the same as one that finished normally. Both wrappers now catch `asyncio.CancelledError` alongside `Exception`, pass it to `after_handler_run` as `error`, and re-raise it. `ServerResponse.error` is already typed `BaseException | None`. A stream closed with `aclose()` still reports `error=None`, so `test_stream_closed_early_still_gets_final_call` is unchanged. The two new tests use a task store whose `get` blocks, so they cancel inside `on_get_task` and `on_subscribe_to_task` without going through `ActiveTask.subscribe` and don't depend on a2aproject#1402. Without the `src` change the unary test gets no `after_handler_run` call at all and the stream test gets `error=None`. Full suite on 3.10: 2544 passed, 207 skipped, 4 xfailed, 1 xpassed. `./scripts/lint.sh` passes (the three ty warnings it prints are the existing unused `type: ignore` in the client transports). I left the client side alone. `BaseClient._execute_with_interceptors` has the same `except Exception` shape for `after_client_request`, and `PluginAgentExecutor.execute` passes `None` to `after_execution` when the execution is cancelled. I can send those separately if you want them. - [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. - [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) Co-authored-by: Mateusz Iwaniuk <45974414+Iwaniukooo11@users.noreply.github.com>
1 parent 076e0ec commit 2cc1dd5

2 files changed

Lines changed: 63 additions & 2 deletions

File tree

‎src/a2a/server/request_handlers/_plugin_hooks.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import asyncio
56
import functools
67
import inspect
78

@@ -82,7 +83,7 @@ async def stream_wrapper(
8283
)
8384
)
8485
yield event
85-
except Exception as e:
86+
except (Exception, asyncio.CancelledError) as e:
8687
error = e
8788
raise
8889
finally:
@@ -110,7 +111,8 @@ async def unary_wrapper(
110111
)
111112
try:
112113
result = await func(self, params, context, *args, **kwargs)
113-
except Exception as e:
114+
except (Exception, asyncio.CancelledError) as e:
115+
# A cancelled call still gets its after call, as streams do.
114116
await plugins.after_handler_run(
115117
ServerResponse(method, None, context, error=e)
116118
)

‎tests/server/request_handlers/test_default_request_handler_v2_plugins.py‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
Role,
5151
SendMessageConfiguration,
5252
SendMessageRequest,
53+
SubscribeToTaskRequest,
5354
Task,
5455
TaskPushNotificationConfig,
5556
TaskState,
@@ -353,6 +354,64 @@ async def test_stream_error_reaches_final_call():
353354
assert isinstance(final.error, TaskNotFoundError)
354355

355356

357+
class BlockingTaskStore(InMemoryTaskStore):
358+
"""Blocks every `get` until cancelled."""
359+
360+
def __init__(self) -> None:
361+
super().__init__()
362+
self.waiting = asyncio.Event()
363+
364+
async def get(self, task_id, context):
365+
self.waiting.set()
366+
await asyncio.Event().wait()
367+
368+
369+
@pytest.mark.asyncio
370+
async def test_cancelled_call_reaches_after_handler_run():
371+
recorder = Recorder()
372+
store = BlockingTaskStore()
373+
handler = make_handler(recorder, task_store=store)
374+
375+
call = asyncio.create_task(
376+
handler.on_get_task(GetTaskRequest(id='t-1'), ServerCallContext())
377+
)
378+
await asyncio.wait_for(store.waiting.wait(), timeout=5)
379+
call.cancel()
380+
381+
with pytest.raises(asyncio.CancelledError):
382+
await call
383+
384+
(response,) = recorder.hooks('after_handler_run')
385+
assert response.method == 'get_task'
386+
assert isinstance(response.error, asyncio.CancelledError)
387+
assert response.is_final
388+
389+
390+
@pytest.mark.asyncio
391+
async def test_cancelled_stream_reports_the_cancellation():
392+
recorder = Recorder()
393+
store = BlockingTaskStore()
394+
handler = make_handler(recorder, task_store=store)
395+
396+
async def consume() -> None:
397+
async for _ in handler.on_subscribe_to_task(
398+
SubscribeToTaskRequest(id='t-1'), ServerCallContext()
399+
):
400+
pass
401+
402+
reader = asyncio.create_task(consume())
403+
await asyncio.wait_for(store.waiting.wait(), timeout=5)
404+
reader.cancel()
405+
406+
with pytest.raises(asyncio.CancelledError):
407+
await reader
408+
409+
(response,) = recorder.hooks('after_handler_run')
410+
assert response.method == 'subscribe'
411+
assert isinstance(response.error, asyncio.CancelledError)
412+
assert response.is_final
413+
414+
356415
@pytest.mark.asyncio
357416
async def test_before_handler_run_can_reject_the_request():
358417
class Deny(plugins.ServerPlugin):

0 commit comments

Comments
 (0)