Skip to content

fix(utils): close underlying async generator when rest_stream_error_handler wrapper closes - #1526

Open
xgbtxy wants to merge 2 commits into
a2aproject:mainfrom
xgbtxy:fix/utils-rest-stream-error-handler-aclose
Open

xgbtxy wants to merge 2 commits into
a2aproject:mainfrom
xgbtxy:fix/utils-rest-stream-error-handler-aclose

Conversation

@xgbtxy

@xgbtxy xgbtxy commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Description

Explicitly closes the wrapped original_iterator inside a finally block in rest_stream_error_handler's error_catching_iterator, ensuring underlying SSE async generators release resources promptly when a streaming response is closed early (e.g., on client disconnect).

Root Cause

In src/a2a/utils/error_handlers.py, rest_stream_error_handler wraps response.body_iterator when it is an async generator (which is true for sse-starlette's EventSourceResponse used by REST streaming endpoints):

async def error_catching_iterator() -> AsyncGenerator[Any, None]:
    try:
        async for item in original_iterator:
            yield item
    except Exception as stream_error:
        _log_error(stream_error)
        raise stream_error

When a client disconnects mid-stream, EventSourceResponse._stream_response calls await self.body_iterator.aclose(). Because error_catching_iterator uses a bare async for without closing original_iterator in finally, GeneratorExit terminates the outer wrapper without calling await original_iterator.aclose(). As documented in src/a2a/server/request_handlers/request_handler.py (validate_request_params / validate), bare async for leaves the inner async generator's finally cleanup unexecuted until garbage collection.

Changes

  • src/a2a/utils/error_handlers.py: Add finally: await original_iterator.aclose() to error_catching_iterator in rest_stream_error_handler.
  • tests/utils/test_error_handlers.py:
    • Added test_rest_stream_error_handler_closes_underlying_generator_on_aclose: verifies calling await response.body_iterator.aclose() after reading one chunk closes the wrapped async generator immediately.
    • Added test_rest_stream_error_handler_event_source_disconnect_closes_inner_generator: wraps a real create_event_source_response(...) stream with @rest_stream_error_handler, simulates an SSE consumer disconnecting and calling aclose(), and verifies the underlying generator's finally block runs without logging a spurious error.
    • Verified both new tests fail on main (b5597a23) prior to the fix (closed remains False) and pass with the fix.

Verification

  • uv run pytest tests/utils/test_error_handlers.py tests/server/routes/test_rest_routes.py tests/server/routes/test_rest_dispatcher.py -v --cov=a2a.utils.error_handlers --cov-report=term-missing: 61 passed (src/a2a/utils/error_handlers.py 97% coverage, 100% of modified lines covered).
  • uv run ruff check src tests: All checks passed.
  • uv run ruff format --check src tests: 274 files already formatted.
  • uv run ty check: 0 new diagnostics (only the 3 pre-existing unused type: ignore warnings in client_factory.py and transports/__init__.py).
  • uv run pytest --ignore=tests/integration/cross_version/client_server/test_client_server.py --ignore=tests/integration/push_notifications/test_default_push_notification_support.py --cov=a2a -q: 2711 passed, 215 skipped, 4 xfailed, 1 xpassed (DB tests without Postgres/MySQL DSNs skipped; the two live subprocess integration test files excluded locally).

Checklist

  • Follow the CONTRIBUTING Guide.
  • Make your Pull Request title in the https://www.conventionalcommits.org/ specification.
  • Ensure the tests and linter pass (ruff check, ruff format --check, ty check, pytest).
  • Appropriate docs were updated (no documentation changes needed).

AI Assistance

Produced with AI assistance and verified locally by reproducing both early-close generator leak tests before applying the fix and running the repository checks above.

…andler wrapper closes

In rest_stream_error_handler, error_catching_iterator wraps
response.body_iterator with a bare `async for item in original_iterator:
yield item`. When a streaming consumer or SSE client disconnect calls
`aclose()` on the wrapper (e.g., sse-starlette's EventSourceResponse
disconnect path), GeneratorExit terminates the wrapper without closing
`original_iterator`, delaying or skipping its cleanup until GC.

Close `original_iterator` in a `finally` block (matching
validate_request_params and validate in a2a.server.request_handlers).
@xgbtxy
xgbtxy requested a review from a team as a code owner November 25, 2026 16:48
Copilot AI balanced review requested due to automatic review settings November 25, 2026 16:48

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

🧪 Code Coverage (vs main)

⬇️ Download Full Report

Base PR Delta
src/a2a/utils/error_handlers.py 96.97% 97.00% 🟢 +0.03%
Total 94.27% 94.27% ⚪️ 0.00%

Generated by coverage-comment.yml

@mykytanetipa
mykytanetipa self-requested a review November 26, 2026 10:21
@mykytanetipa mykytanetipa self-assigned this Nov 26, 2026
Comment thread src/a2a/utils/error_handlers.py Outdated
Comment on lines +258 to +259
finally:
await original_iterator.aclose()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To be consistent with the rest of the codebase (_plugin_hooks.py, base_client.py, default_request_handler_v2.py), please use contextlib.aclosing here instead of the explicit finally:

try:
    async with aclosing(original_iterator) as events:
        async for item in events:
            yield item
except Exception as stream_error:
    _log_error(stream_error)
    raise stream_error

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in ad3e6ec to use contextlib.aclosing(original_iterator), thanks!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants