Repository navigation
Preserve HTTP response headers and honor cancellation and read timeouts in Python SDK #940
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
Open
ersinkoc
wants to merge
4
commits into
google:main
Choose a base branch
from
ersinkoc:audit/python-http-transport
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
d69a4de
sdk/python: preserve repeated HTTP response headers
ersinkoc 7fa1c9b
sdk/python: close HTTP streams on request cancellation
ersinkoc 8767803
sdk/python: honor HTTPX body read timeouts
ersinkoc 211253d
sdk/python: accept an explicitly unset HTTPX timeout extension
ersinkoc 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
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,53 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import pytest | ||
| import trio | ||
|
|
||
| from agent_mesh import libp2p_http | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("cancel", [False, True]) | ||
| def test_http_request_closes_stream_on_failure(monkeypatch, cancel): | ||
| closed = [] | ||
|
|
||
| class Stream: | ||
| async def write(self, data): | ||
| await trio.lowlevel.checkpoint() | ||
| raise OSError("write failed") | ||
|
|
||
| async def close(self): | ||
| await trio.lowlevel.checkpoint() | ||
| closed.append(True) | ||
|
|
||
| async def open_stream(*args): | ||
| return Stream() | ||
|
|
||
| monkeypatch.setattr(libp2p_http, "open_stream", open_stream) | ||
|
|
||
| async def request(): | ||
| await libp2p_http.open_http_request(None, "peer", b"fixture", "GET", "/a2a/example/message") | ||
|
|
||
| async def run(): | ||
| if cancel: | ||
| with trio.CancelScope() as scope: | ||
| scope.cancel() | ||
| await request() | ||
| assert scope.cancelled_caught | ||
| else: | ||
| with pytest.raises(OSError, match="write failed"): | ||
| await request() | ||
| assert closed == [True] | ||
|
|
||
| trio.run(run) |
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,62 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from types import SimpleNamespace | ||
|
|
||
| import httpx | ||
| import pytest | ||
| import trio | ||
| from trio.testing import MockClock | ||
|
|
||
| from agent_mesh import httpx_transport | ||
| from agent_mesh.httpx_transport import MeshTransport | ||
|
|
||
|
|
||
| def test_mesh_transport_applies_httpx_read_timeout_to_body(monkeypatch): | ||
| closed = [] | ||
|
|
||
| class Response: | ||
| status = 200 | ||
| headers = {} | ||
| raw_headers = () | ||
|
|
||
| async def iter_body(self): | ||
| yield b"first" | ||
| await trio.sleep(2) | ||
| yield b"second" | ||
|
|
||
| async def aclose(self): | ||
| closed.append(True) | ||
|
|
||
| async def open_request(*args, **kwargs): | ||
| return Response() | ||
|
|
||
| async def egress_peer(peer, service): | ||
| return peer | ||
|
|
||
| monkeypatch.setattr(httpx_transport, "open_http_request", open_request) | ||
| session = SimpleNamespace(host=None, biscuit=b"fixture", _egress_peer=egress_peer) | ||
|
|
||
| async def run(): | ||
| path = "http://mesh/mesh/peer/a2a/example" | ||
| async with httpx.AsyncClient(transport=MeshTransport(session)) as client: | ||
| assert (await client.get(path, timeout=None)).content == b"firstsecond" | ||
| request = httpx.Request("GET", path, extensions={"timeout": None}) | ||
| assert (await client.send(request)).content == b"firstsecond" | ||
| with pytest.raises(httpx.ReadTimeout) as caught: | ||
| await client.get(path, timeout=httpx.Timeout(10, read=1)) | ||
| assert str(caught.value.request.url) == path | ||
| assert closed == [True, True, True] | ||
|
|
||
| trio.run(run, clock=MockClock(autojump_threshold=0)) |
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,55 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from types import SimpleNamespace | ||
|
|
||
| import httpx | ||
| import trio | ||
|
|
||
| from agent_mesh import libp2p_http | ||
| from agent_mesh.httpx_transport import MeshTransport | ||
|
|
||
|
|
||
| def test_mesh_transport_keeps_multiple_set_cookie_fields(monkeypatch): | ||
| class Stream: | ||
| async def write(self, data): | ||
| pass | ||
|
|
||
| async def read(self, size): | ||
| return ( | ||
| b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n" | ||
| b"Set-Cookie: one=1\r\nSet-Cookie: two=2\r\n\r\nok" | ||
| ) | ||
|
|
||
| async def close(self): | ||
| pass | ||
|
|
||
| async def open_stream(*args): | ||
| return Stream() | ||
|
|
||
| async def egress_peer(peer, service): | ||
| return peer | ||
|
|
||
| monkeypatch.setattr(libp2p_http, "open_stream", open_stream) | ||
| session = SimpleNamespace(host=None, biscuit=b"fixture", _egress_peer=egress_peer) | ||
|
|
||
| async def run(): | ||
| async with httpx.AsyncClient(transport=MeshTransport(session)) as client: | ||
| response = await client.get("http://mesh/mesh/peer/a2a/example/message") | ||
| assert response.text == "ok" | ||
| assert response.headers.get_list("set-cookie") == ["one=1", "two=2"] | ||
| assert client.cookies.get("one") == "1" | ||
| assert client.cookies.get("two") == "2" | ||
|
|
||
| trio.run(run) |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There are two opportunities for improvement here:
request.extensions.get("timeout")is explicitly set toNone(rather than being absent), calling.get("read")on it will raise anAttributeError. We should safely check if the timeout extension is a dictionary before calling.get()on it.trio.fail_aftercontext manager when there is no timeout (i.e.,self._read_timeoutismath.inf) adds unnecessary overhead. We can bypasstrio.fail_afterentirely when the timeout is infinite.There was a problem hiding this comment.
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
readvalue only when thetimeoutextension is a dict, andtest_httpx_read_timeout.pycovers 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.