-
Notifications
You must be signed in to change notification settings - Fork 422
fix: fix athrow() RuntimeError on streaming responses
#912
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
0c7874a
fix: fix `athrow()` RuntimeError on streaming responses
ishymko a41339a
Updates
ishymko 5c281bc
Merge branch '1.0-dev' into ishymko/generators
ishymko cf355ae
Updates
ishymko 06602d5
Update tests/integration/test_stream_generator_cleanup.py
ishymko f62f15d
Updates
ishymko 39e2f87
Revert fix to ensure tests catches the issue
ishymko 94d3902
Revert "Revert fix to ensure tests catches the issue"
ishymko File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| """Test that streaming SSE responses clean up without athrow() errors. | ||
|
|
||
| Reproduces https://github.com/a2aproject/a2a-python/issues/XXX — | ||
|
ishymko marked this conversation as resolved.
Outdated
|
||
| ``RuntimeError: athrow(): asynchronous generator is already running`` | ||
| during event-loop shutdown after consuming a streaming response. | ||
| """ | ||
|
|
||
| import asyncio | ||
| import gc | ||
|
|
||
| from typing import Any | ||
| from uuid import uuid4 | ||
|
|
||
| import httpx | ||
| import pytest | ||
|
|
||
| from starlette.applications import Starlette | ||
|
|
||
| from a2a.client.base_client import BaseClient | ||
| from a2a.client.client import ClientConfig | ||
| from a2a.client.client_factory import ClientFactory | ||
| from a2a.server.agent_execution import AgentExecutor, RequestContext | ||
| from a2a.server.events import EventQueue | ||
| from a2a.server.events.in_memory_queue_manager import InMemoryQueueManager | ||
| from a2a.server.request_handlers import DefaultRequestHandler | ||
| from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes | ||
| from a2a.server.tasks.inmemory_task_store import InMemoryTaskStore | ||
| from a2a.types import ( | ||
| AgentCapabilities, | ||
| AgentCard, | ||
| AgentInterface, | ||
| Message, | ||
| Part, | ||
| Role, | ||
| SendMessageRequest, | ||
| ) | ||
| from a2a.utils import TransportProtocol | ||
|
|
||
|
|
||
| class _MessageExecutor(AgentExecutor): | ||
| """Responds with a single Message event.""" | ||
|
|
||
| async def execute(self, ctx: RequestContext, eq: EventQueue) -> None: | ||
| await eq.enqueue_event( | ||
| Message( | ||
| role=Role.ROLE_AGENT, | ||
| message_id=str(uuid4()), | ||
| parts=[Part(text='Hello')], | ||
| context_id=ctx.context_id, | ||
| task_id=ctx.task_id, | ||
| ) | ||
| ) | ||
|
|
||
| async def cancel(self, ctx: RequestContext, eq: EventQueue) -> None: | ||
| pass | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def client(): | ||
| """Creates a JSON-RPC client backed by an in-process ASGI server.""" | ||
| card = AgentCard( | ||
| name='T', | ||
| description='T', | ||
| version='1', | ||
| capabilities=AgentCapabilities(streaming=True), | ||
| default_input_modes=['text/plain'], | ||
| default_output_modes=['text/plain'], | ||
| supported_interfaces=[ | ||
| AgentInterface( | ||
| protocol_binding=TransportProtocol.JSONRPC, | ||
| url='http://test', | ||
| ), | ||
| ], | ||
| ) | ||
| handler = DefaultRequestHandler( | ||
| agent_executor=_MessageExecutor(), | ||
| task_store=InMemoryTaskStore(), | ||
| queue_manager=InMemoryQueueManager(), | ||
| ) | ||
| app = Starlette( | ||
| routes=[ | ||
| *create_agent_card_routes(agent_card=card, card_url='/card'), | ||
| *create_jsonrpc_routes( | ||
| agent_card=card, | ||
| request_handler=handler, | ||
| extended_agent_card=card, | ||
| rpc_url='/', | ||
| ), | ||
| ] | ||
| ) | ||
| return ClientFactory( | ||
| config=ClientConfig( | ||
| httpx_client=httpx.AsyncClient( | ||
| transport=httpx.ASGITransport(app=app), | ||
| base_url='http://test', | ||
| ) | ||
| ) | ||
| ).create(card) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_stream_message_no_athrow(client: BaseClient) -> None: | ||
| """Consuming a streamed Message must not leave broken async generators.""" | ||
| errors: list[dict[str, Any]] = [] | ||
| loop = asyncio.get_event_loop() | ||
| orig = loop.get_exception_handler() | ||
| loop.set_exception_handler(lambda _l, ctx: errors.append(ctx)) | ||
|
|
||
| try: | ||
| msg = Message( | ||
| role=Role.ROLE_USER, | ||
| message_id=f'msg-{uuid4()}', | ||
| parts=[Part(text='hi')], | ||
| ) | ||
| events = [ | ||
| e | ||
| async for e in client.send_message( | ||
| request=SendMessageRequest(message=msg) | ||
| ) | ||
| ] | ||
| assert events | ||
| assert events[0][0].HasField('message') | ||
|
|
||
| gc.collect() | ||
| await loop.shutdown_asyncgens() | ||
|
|
||
| bad = [ | ||
| e | ||
| for e in errors | ||
| if 'asynchronous generator' in str(e.get('message', '')) | ||
| ] | ||
| assert not bad, '\n'.join(str(e.get('message', '')) for e in bad) | ||
| finally: | ||
| loop.set_exception_handler(orig) | ||
| await client.close() | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.