Skip to content

Fix infinite iter_chunks() on empty response #11397

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
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

agners
Copy link

@agners agners commented Aug 7, 2025

What do these changes do?

When aiohttp returns an empty reader, the first time the iter_chunks() iterator stops after the first read as expected. However, on the second empty reader return, iter_chunks() loops forever.

This is due to state sharing caused by the global EmptyStreamReader instance. It has been noticed during review in #7645, but so far hasn't been addressed.

This PR attempts to address the issue by returning a new instance.

Are there changes in behavior for the user?

The change makes it safe to read content of empty responses using iter_chunks().

Is it a substantial burden for the maintainers to support this?

Related issue number

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt
    • The format is <Name> <Surname>.
    • Please keep alphabetical order, the file is sorted by names.
  • Add a new news fragment into the CHANGES/ folder
    • name it <issue_or_pr_num>.<type>.rst (e.g. 588.bugfix.rst)

    • if you don't have an issue number, change it to the pull request
      number after creating the PR

      • .bugfix: A bug fix for something the maintainers deemed an
        improper undesired behavior that got corrected to match
        pre-agreed expectations.
      • .feature: A new behavior, public APIs. That sort of stuff.
      • .deprecation: A declaration of future API removals and breaking
        changes in behavior.
      • .breaking: When something public is removed in a breaking way.
        Could be deprecated in an earlier release.
      • .doc: Notable updates to the documentation structure or build
        process.
      • .packaging: Notes for downstreams about unobvious side effects
        and tooling. Changes in the test invocation considerations and
        runtime assumptions.
      • .contrib: Stuff that affects the contributor experience. e.g.
        Running tests, building the docs, setting up the development
        environment.
      • .misc: Changes that are hard to assign to any of the above
        categories.
    • Make sure to use full sentences with correct case and punctuation,
      for example:

      Fixed issue with non-ascii contents in doctest text files
      -- by :user:`contributor-gh-handle`.

      Use the past tense or the present tense a non-imperative mood,
      referring to what's changed compared to the last released version
      of this project.

When aiohttp returns an empty reader, the first time the iter_chunks()
iterator stops after the first read as expected. However, on the second
empty reader return, iter_chunks() loops forever.

This is due to state sharing caused by the global EmptyStreamReader
instance. It has been noticed during review in aio-libs#7645, but so far hasn't
been addressed.

This PR attempts to address the issue by returning a new instance.
@agners agners requested a review from asvetlov as a code owner August 7, 2025 09:48
@agners
Copy link
Author

agners commented Aug 7, 2025

This came up in Home Assistant Core PR home-assistant/core#147899. The PR now avoids reading empty responses as a work around. /cc @bdraco

@@ -54,7 +54,7 @@
TransferEncodingError,
)
from .http_writer import HttpVersion, HttpVersion10
from .streams import EMPTY_PAYLOAD, StreamReader
from .streams import EMPTY_PAYLOAD, StreamReader, empty_stream_reader

Check notice

Code scanning / CodeQL

Unused import Note

Import of 'EMPTY_PAYLOAD' is not used.
Copy link

codecov bot commented Aug 7, 2025

Codecov Report

❌ Patch coverage is 80.64516% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 98.74%. Comparing base (48082a7) to head (c08dce1).
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
tests/test_streams.py 76.92% 4 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #11397      +/-   ##
==========================================
- Coverage   98.76%   98.74%   -0.02%     
==========================================
  Files         129      129              
  Lines       43416    43444      +28     
  Branches     2324     2328       +4     
==========================================
+ Hits        42879    42899      +20     
- Misses        383      388       +5     
- Partials      154      157       +3     
Flag Coverage Δ
CI-GHA 98.63% <80.64%> (-0.02%) ⬇️
OS-Linux 98.36% <80.64%> (-0.02%) ⬇️
OS-Windows 96.78% <80.64%> (-0.03%) ⬇️
OS-macOS 97.67% <80.64%> (-0.02%) ⬇️
Py-3.10.11 97.30% <74.19%> (-0.03%) ⬇️
Py-3.10.18 97.70% <74.19%> (-0.03%) ⬇️
Py-3.11.13 97.90% <74.19%> (-0.02%) ⬇️
Py-3.11.9 97.50% <74.19%> (-0.03%) ⬇️
Py-3.12.10 97.60% <74.19%> (-0.03%) ⬇️
Py-3.12.11 98.00% <74.19%> (-0.02%) ⬇️
Py-3.13.5 98.25% <74.19%> (-0.03%) ⬇️
Py-3.9.13 97.19% <80.64%> (-0.03%) ⬇️
Py-3.9.23 97.60% <80.64%> (-0.02%) ⬇️
Py-pypy7.3.16 86.76% <74.19%> (+1.06%) ⬆️
VM-macos 97.67% <80.64%> (-0.02%) ⬇️
VM-ubuntu 98.36% <80.64%> (-0.02%) ⬇️
VM-windows 96.78% <80.64%> (-0.03%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

codspeed-hq bot commented Aug 7, 2025

CodSpeed Performance Report

Merging #11397 will not alter performance

Comparing agners:fix-infinte-iter-chunks-on-empty-response (c08dce1) with master (48082a7)

Summary

✅ 59 untouched benchmarks

@Dreamsorcerer Dreamsorcerer added backport-3.12 Trigger automatic backporting to the 3.12 release branch by Patchback robot backport-3.13 Trigger automatic backporting to the 3.13 release branch by Patchback robot labels Aug 7, 2025
@@ -604,6 +605,18 @@ def read_nowait(self, n: int = -1) -> bytes:
EMPTY_PAYLOAD: Final[StreamReader] = EmptyStreamReader()


def empty_stream_reader() -> "EmptyStreamReader":
Copy link
Member

Choose a reason for hiding this comment

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

Is there a point to having a function here, and not just importing EmptyStreamReader?

@@ -38,7 +38,11 @@ from .http_writer import (
HttpVersion10 as _HttpVersion10,
HttpVersion11 as _HttpVersion11,
)
from .streams import EMPTY_PAYLOAD as _EMPTY_PAYLOAD, StreamReader as _StreamReader
from .streams import (
EMPTY_PAYLOAD as _EMPTY_PAYLOAD,
Copy link
Member

Choose a reason for hiding this comment

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

This one is presumably also unused now.

@@ -604,6 +605,18 @@ def read_nowait(self, n: int = -1) -> bytes:
EMPTY_PAYLOAD: Final[StreamReader] = EmptyStreamReader()
Copy link
Member

Choose a reason for hiding this comment

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

We'll probably want a followup PR to remove EMPTY_PAYLOAD too, without backporting.

@Dreamsorcerer Dreamsorcerer requested a review from bdraco August 7, 2025 16:48
Comment on lines +1156 to +1159
async for chunk in reader1.iter_chunks():
chunks.append(chunk)
if len(chunks) > 5: # Safety break
break
Copy link
Member

Choose a reason for hiding this comment

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

Coverage doesn't seem happy with these. Not sure if it's just confused, as it seems to suggest that the break line is reached without any of the above lines being reached...

Comment on lines +1155 to +1161
chunks = []
async for chunk in reader1.iter_chunks():
chunks.append(chunk)
if len(chunks) > 5: # Safety break
break

assert len(chunks) == 0 # Should terminate normally with no chunks
Copy link
Member

Choose a reason for hiding this comment

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

If the expected behaviour is that we don't iterate here, then we should do something like:

Suggested change
chunks = []
async for chunk in reader1.iter_chunks():
chunks.append(chunk)
if len(chunks) > 5: # Safety break
break
assert len(chunks) == 0 # Should terminate normally with no chunks
with pytest.raises(StopIteration):
await anext(reader1.iter_chunks())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport-3.12 Trigger automatic backporting to the 3.12 release branch by Patchback robot backport-3.13 Trigger automatic backporting to the 3.13 release branch by Patchback robot
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants