Skip to content

Handle HTTP/2 stream limit reductions without blocking reads - #1217

Merged
Kludex merged 7 commits into
pydantic:mainfrom
ericbuehl:eb-max-streams
Oct 17, 2026
Merged

Kludex merged 7 commits into
pydantic:mainfrom
ericbuehl:eb-max-streams

Conversation

@ericbuehl

@ericbuehl ericbuehl commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

this is an attempt at reproducing, fixing, and guarding regressions for #1216

fixes #1216

Checklist

  • I understand that this PR may be closed in case there was no previous discussion. (This doesn't apply to typos!)
  • I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
  • I've updated the documentation accordingly.

Review in cubic

@codspeed

codspeed Bot commented Sep 18, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 17 untouched benchmarks
⏩ 7 skipped benchmarks1


Comparing ericbuehl:eb-max-streams (37570a0) with main (a712efd)

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. ↩

@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.

1 issue found across 4 files

You’re at about 94% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact contact@cubic.dev.

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="src/httpcore2/httpcore2/_synchronization.py">

<violation number="1" location="src/httpcore2/httpcore2/_synchronization.py:183">
P2: When `acquire_if_available()` is the first operation on an `AsyncSemaphore`, `_backend` is still empty, so this method falsely returns `False` even when a permit is available. Initialize the backend here before attempting the nonblocking acquire, matching `acquire()`.</violation>
</file>

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

Re-trigger cubic

Acquire a permit if one is immediately available, without blocking.
Returns True if a permit was acquired.
"""
if self._backend == "trio":

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 acquire_if_available() is the first operation on an AsyncSemaphore, _backend is still empty, so this method falsely returns False even when a permit is available. Initialize the backend here before attempting the nonblocking acquire, matching acquire().

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

<comment>When `acquire_if_available()` is the first operation on an `AsyncSemaphore`, `_backend` is still empty, so this method falsely returns `False` even when a permit is available. Initialize the backend here before attempting the nonblocking acquire, matching `acquire()`.</comment>

<file context>
@@ -175,6 +175,25 @@ async def acquire(self) -> None:
+        Acquire a permit if one is immediately available, without blocking.
+        Returns True if a permit was acquired.
+        """
+        if self._backend == "trio":
+            try:
+                self._trio_semaphore.acquire_nowait()
</file context>
Suggested change
if self._backend == "trio":
if not self._backend:
self.setup()
if self._backend == "trio":

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.

This is true for a freshly constructed semaphore in isolation, but that state is unreachable from the only call site. acquire_if_available is called solely from _receive_remote_settings_change, which only runs when a RemoteSettingsChanged event is read off the wire — necessarily after the connection-init block has created the semaphore and called acquire (the init pre-acquire loop plus the per-request acquire in handle_async_request), which performs setup().

This also matches the existing convention in this class: release() directly below has the identical precondition and no setup guard. Re-adding the guard here would reintroduce an uncoverable line, which is what failed the 100% coverage gate on an earlier revision of this PR.

I've documented the precondition in the docstring instead: "Like release(), this requires setup() to have run, which any prior acquire() call ensures."

@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.

No issues found across 4 files

You’re at about 94% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact contact@cubic.dev.

Re-trigger cubic

@ericbuehl

Copy link
Copy Markdown
Contributor Author

@Kludex mind taking a look at this?

@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 5 files

Reply to a comment to ask cubic a question or push back. It learns from your replies.

View guided diff | Re-trigger cubic

Comment thread src/httpcore2/httpcore2/_sync/http2.py Resolved

@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 (changes from recent commits).

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

View guided diff | Re-trigger cubic

Comment thread tests/httpcore2/test_cancellations.py Resolved
@Kludex Kludex changed the title respect lowering of max streams from peer Handle HTTP/2 stream limit reductions without blocking reads Oct 17, 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.

1 issue found across 3 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. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="src/httpcore2/httpcore2/_async/http2.py">

<violation number="1" location="src/httpcore2/httpcore2/_async/http2.py:445">
P2: This block does not serialize inbound h2 processing with concurrent outbound h2 mutations: `_state_lock` is different from `_write_lock`, and event bookkeeping plus the flush happen after this block. Keep `receive_data`, event bookkeeping, and the corresponding `_write_outgoing_data` under `_write_lock`, while leaving the network read and settings semaphore adjustment outside it.

(Based on your team's feedback about serializing inbound HTTP/2 event processing under the write lock.)</violation>
</file>

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

View guided diff | Re-trigger cubic

# Apply settings and stream admission limits atomically.
with AsyncShieldCancellation():
async with self._state_lock:
events: list[h2.events.Event] = self._h2_state.receive_data(data)

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: This block does not serialize inbound h2 processing with concurrent outbound h2 mutations: _state_lock is different from _write_lock, and event bookkeeping plus the flush happen after this block. Keep receive_data, event bookkeeping, and the corresponding _write_outgoing_data under _write_lock, while leaving the network read and settings semaphore adjustment outside it.

(Based on your team's feedback about serializing inbound HTTP/2 event processing under the write lock.)

View Feedback

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At src/httpcore2/httpcore2/_async/http2.py, line 445:

<comment>This block does not serialize inbound h2 processing with concurrent outbound h2 mutations: `_state_lock` is different from `_write_lock`, and event bookkeeping plus the flush happen after this block. Keep `receive_data`, event bookkeeping, and the corresponding `_write_outgoing_data` under `_write_lock`, while leaving the network read and settings semaphore adjustment outside it.

(Based on your team's feedback about serializing inbound HTTP/2 event processing under the write lock.) </comment>

<file context>
@@ -441,7 +439,13 @@ async def _read_incoming_data(self, request: Request) -> list[h2.events.Event]:
+        # Apply settings and stream admission limits atomically.
+        with AsyncShieldCancellation():
+            async with self._state_lock:
+                events: list[h2.events.Event] = self._h2_state.receive_data(data)
+                for event in events:
+                    if isinstance(event, h2.events.RemoteSettingsChanged):
</file context>

@Kludex
Kludex merged commit 81e58ad into pydantic:main Oct 17, 2026
16 checks passed
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.

HTTP/2 connection deadlocks when the peer lowers MAX_CONCURRENT_STREAMS below the in-flight stream count

2 participants