Skip to content

Restore async iterator compatibility - #1168

Closed
Kludex wants to merge 8 commits into
mainfrom
aiter-bytes-iterator
Closed

Kludex wants to merge 8 commits into
mainfrom
aiter-bytes-iterator

Conversation

@Kludex

@Kludex Kludex commented Aug 27, 2026

Copy link
Copy Markdown
Member

Summary

  • Restore AsyncIterator[bytes] as the return type of Response.aiter_bytes() and Response.aiter_raw().
  • Keep contextlib.aclosing() for async generators while allowing plain async iterator overrides.
  • Add typed subclass overrides to prevent the compatibility regression.

Closes #1158.

Validation

  • uv run ruff format --check --diff src/httpx2/httpx2/_models.py tests/httpx2/models/test_responses.py
  • uv run ruff check src/httpx2/httpx2/_models.py tests/httpx2/models/test_responses.py
  • uv run mypy src/httpx2 tests/httpx2 src/httpcore2 tests/httpcore2
  • uv run python scripts/unasync.py --check
  • GITHUB_ACTIONS=1 scripts/test && scripts/coverage - 1,998 passed, 1 skipped, 100% coverage

AI Disclaimer

This PR was developed with the assistance of either Claude or Codex. I've reviewed and verified the changes.

`#1126` widened the return annotation of `Response.aiter_bytes()` and
`Response.aiter_raw()` from `AsyncIterator[bytes]` to
`AsyncGenerator[bytes, None]`, so that `contextlib.aclosing()` would accept
them. That made overriding either method in a `Response` subclass a typing
error, and made it a runtime error to return anything other than an async
generator, since `aclosing()` calls `aclose()` unconditionally.

Narrow both annotations back, and close the iterator only when it is
actually an async generator. This is the same guard `aiter_raw()` already
applies to `self.stream`.

The sync counterparts are unaffected: `iter_bytes()` and `iter_raw()` were
never widened, and neither uses `contextlib.closing()`.

Closes #1158
@Kludex
Kludex deployed to cloudflare August 27, 2026 05:52 — with GitHub Actions Active
@Kludex
Kludex deployed to cloudflare August 27, 2026 05:52 — with GitHub Actions Active
@github-actions

github-actions Bot commented Aug 27, 2026

Copy link
Copy Markdown

Docs preview:

Comment thread src/httpx2/httpx2/_models.py Outdated
@codspeed-hq

codspeed-hq Bot commented Aug 27, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 17 untouched benchmarks
⏩ 7 skipped benchmarks1


Comparing aiter-bytes-iterator (8975595) with main (289155d)

Open in CodSpeed

Footnotes

  1. 7 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

@Kludex Kludex closed this Aug 27, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d32f860e3d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/httpx2/httpx2/_models.py Outdated
@akx

akx commented Aug 29, 2026

Copy link
Copy Markdown

#1036?

@Kludex Kludex changed the title Restore AsyncIterator[bytes] on aiter_bytes() and aiter_raw() Restore async iterator compatibility Sep 14, 2026
@Kludex Kludex reopened this Sep 14, 2026

@cubic-dev-ai cubic-dev-ai 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.

All reported issues were addressed across 3 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread src/httpx2/httpx2/_models.py Outdated
Comment thread src/httpx2/httpx2/_models.py Outdated
Comment thread src/httpx2/httpx2/_models.py Outdated

@cubic-dev-ai cubic-dev-ai 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.

2 issues found across 2 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="tests/httpx2/models/test_responses.py">

<violation number="1" location="tests/httpx2/models/test_responses.py:497">
P2: These rewritten tests only exercise async-generator overrides, so they pass without exercising the two behaviors this PR claims to restore/preserve: subclass overrides returning plain async iterators without `aclose()`, and custom iterators whose `aclose()` gets called on cleanup. The previous `PlainAsyncIterator` and `ClosableAsyncIterator` regression tests for those paths were removed here. At the current implementation, `aread()` and `aiter_bytes()` wrap the `aiter_bytes()`/`aiter_raw()` results in `contextlib.aclosing(...)`, which unconditionally awaits `.aclose()` and raises AttributeError on a plain async iterator (verified). Keep a regression test that overrides with a plain async iterator lacking `aclose()`, and one asserting a custom iterator's `aclose()` is invoked.</violation>
</file>

<file name="src/httpx2/httpx2/_models.py">

<violation number="1" location="src/httpx2/httpx2/_models.py:1059">
P2: When an `AsyncByteStream` returns a custom iterator with `aclose()`, `aiter_raw()` skips that cleanup because `AsyncGenerator` is not a structural check for custom iterators. Detect and await an exposed `aclose()` method instead.</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Comment thread src/httpx2/httpx2/_models.py Outdated


@pytest.mark.anyio
async def test_aiter_bytes_override() -> None:

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.

P2: These rewritten tests only exercise async-generator overrides, so they pass without exercising the two behaviors this PR claims to restore/preserve: subclass overrides returning plain async iterators without aclose(), and custom iterators whose aclose() gets called on cleanup. The previous PlainAsyncIterator and ClosableAsyncIterator regression tests for those paths were removed here. At the current implementation, aread() and aiter_bytes() wrap the aiter_bytes()/aiter_raw() results in contextlib.aclosing(...), which unconditionally awaits .aclose() and raises AttributeError on a plain async iterator (verified). Keep a regression test that overrides with a plain async iterator lacking aclose(), and one asserting a custom iterator's aclose() is invoked.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At tests/httpx2/models/test_responses.py, line 497:

<comment>These rewritten tests only exercise async-generator overrides, so they pass without exercising the two behaviors this PR claims to restore/preserve: subclass overrides returning plain async iterators without `aclose()`, and custom iterators whose `aclose()` gets called on cleanup. The previous `PlainAsyncIterator` and `ClosableAsyncIterator` regression tests for those paths were removed here. At the current implementation, `aread()` and `aiter_bytes()` wrap the `aiter_bytes()`/`aiter_raw()` results in `contextlib.aclosing(...)`, which unconditionally awaits `.aclose()` and raises AttributeError on a plain async iterator (verified). Keep a regression test that overrides with a plain async iterator lacking `aclose()`, and one asserting a custom iterator's `aclose()` is invoked.</comment>

<file context>
@@ -523,49 +494,25 @@ async def test_aiter_raw_with_chunksize() -> None:
 
 @pytest.mark.anyio
-async def test_aiter_bytes_override_with_plain_async_iterator() -> None:
+async def test_aiter_bytes_override() -> None:
     class CustomResponse(httpx2.Response):
-        def aiter_bytes(self, chunk_size: int | None = None) -> typing.AsyncIterator[bytes]:
</file context>

@@ -972,11 +972,12 @@ async def aread(self) -> bytes:
Read and return the response content.

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.

P2: When an AsyncByteStream returns a custom iterator with aclose(), aiter_raw() skips that cleanup because AsyncGenerator is not a structural check for custom iterators. Detect and await an exposed aclose() method instead.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/httpx2/httpx2/_models.py, line 1059:

<comment>When an `AsyncByteStream` returns a custom iterator with `aclose()`, `aiter_raw()` skips that cleanup because `AsyncGenerator` is not a structural check for custom iterators. Detect and await an exposed `aclose()` method instead.</comment>

<file context>
@@ -1066,7 +1056,7 @@ async def aiter_raw(self, chunk_size: int | None = None) -> typing.AsyncIterator
                 yield chunk
         finally:
-            if isinstance(stream, _AsyncClosable):
+            if isinstance(stream, AsyncGenerator):
                 await stream.aclose()
             await self.aclose()
</file context>

@Kludex Kludex closed this Sep 14, 2026
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.

Please revert aiter_bytes signature to AsyncIterator

2 participants