Skip to content

Preserve HTTP response headers and honor cancellation and read timeouts in Python SDK - #940

Open
ersinkoc wants to merge 4 commits into
google:mainfrom
ersinkoc:audit/python-http-transport
Open

ersinkoc wants to merge 4 commits into
google:mainfrom
ersinkoc:audit/python-http-transport

Conversation

@ersinkoc

Copy link
Copy Markdown

Three independently reproduced Python SDK HTTP transport defects.

  • Preserve repeated response fields through the HTTPX transport so callers receive both Set-Cookie values.
  • Give the libp2p stream a bounded, shielded close when a request fails or is cancelled before response headers arrive.
  • Honor the HTTPX read timeout between response body chunks. An explicitly disabled timeout still permits an unlimited wait.

Each commit includes a focused regression. All 173 Python SDK tests passed on Linux with Python 3.12.

@ersinkoc
ersinkoc requested a review from aojea as a code owner November 24, 2026 23:05

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request implements read timeout handling for the Python SDK's HTTPX transport using Trio, preserves raw response headers (allowing multiple headers like Set-Cookie to be retained), and ensures HTTP streams are safely closed on failure or cancellation. The review feedback suggests improving robustness by safely handling cases where the timeout extension is None to avoid an AttributeError, and optimizing performance by bypassing trio.fail_after when the read timeout is infinite.

Comment on lines +61 to 77
def __init__(self, response: StreamedResponse, request: httpx.Request) -> None:
self._response = response
self._request = request
timeout = request.extensions.get("timeout", {}).get("read")
self._read_timeout = math.inf if timeout is None else timeout

async def __aiter__(self) -> AsyncIterator[bytes]:
async for chunk in self._response.iter_body():
body = self._response.iter_body()
while True:
try:
with trio.fail_after(self._read_timeout):
chunk = await anext(body)
except StopAsyncIteration:
return
except trio.TooSlowError as err:
raise httpx.ReadTimeout("timed out reading the mesh response body", request=self._request) from err
yield chunk

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

There are two opportunities for improvement here:

  1. Defensive Programming / Robustness: If request.extensions.get("timeout") is explicitly set to None (rather than being absent), calling .get("read") on it will raise an AttributeError. We should safely check if the timeout extension is a dictionary before calling .get() on it.
  2. Performance / Efficiency: Wrapping every single chunk read in a trio.fail_after context manager when there is no timeout (i.e., self._read_timeout is math.inf) adds unnecessary overhead. We can bypass trio.fail_after entirely when the timeout is infinite.
    def __init__(self, response: StreamedResponse, request: httpx.Request) -> None:
        self._response = response
        self._request = request
        timeout_ext = request.extensions.get("timeout")
        timeout = timeout_ext.get("read") if isinstance(timeout_ext, dict) else None
        self._read_timeout = math.inf if timeout is None else timeout

    async def __aiter__(self) -> AsyncIterator[bytes]:
        body = self._response.iter_body()
        while True:
            try:
                if self._read_timeout == math.inf:
                    chunk = await anext(body)
                else:
                    with trio.fail_after(self._read_timeout):
                        chunk = await anext(body)
            except StopAsyncIteration:
                return
            except trio.TooSlowError as err:
                raise httpx.ReadTimeout("timed out reading the mesh response body", request=self._request) from err
            yield chunk

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

The first point is already in the PR: 211253d (pushed a minute after this review) reads the read value only when the timeout extension is a dict, and test_httpx_read_timeout.py covers an explicitly unset extension.

I'd rather not take the second. trio.fail_after(math.inf) opens a cancel scope with an infinite deadline; trio does not put an infinite deadline in its deadline queue, so entering it costs a few attribute writes, which is nothing next to awaiting a chunk from a libp2p stream. A separate branch for the infinite case would give the loop two read paths to keep in step, for no measurable gain.

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.

1 participant