Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,22 @@ dev
**API Changes (Backward Compatible)**

- Support for Python 3.15 has been added.
- Support graceful shutdown by the remote peer (RFC 9113, Section 6.8). After
a GOAWAY with error code ``NO_ERROR``, the connection enters graceful
shutdown: its state is ``CLOSED`` and no new local streams may be opened,
but frames for open streams are still processed, PING and SETTINGS frames
are still acknowledged, and the outbound data buffer is kept. The client and
server rules of the open connection still apply. A further graceful GOAWAY
keeps graceful shutdown active; a GOAWAY with an error code, an invalid
input or ``close_connection()`` ends it, and a connection that is already
closed is never reopened by a later GOAWAY.
``H2Connection.is_in_graceful_shutdown`` reports the state.
``ConnectionTerminated`` is still fired for every GOAWAY. (#1181, #1199)

**Bugfixes**

-
- Ignore leftover frames received after the connection has closed, instead of
raising ``ProtocolError``. Further GOAWAY frames are still processed.

4.4.1 (2026-08-03)
------------------
Expand Down
145 changes: 137 additions & 8 deletions src/h2/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ class ConnectionInputs(Enum):
RECV_PRIORITY = 17
SEND_ALTERNATIVE_SERVICE = 18 # Added in 2.3.0
RECV_ALTERNATIVE_SERVICE = 19 # Added in 2.3.0
RECV_GRACEFUL_GOAWAY = 20 # Added in 4.5.0


class AllowedStreamIDs(IntEnum):
Expand Down Expand Up @@ -128,7 +129,25 @@ class H2ConnectionStateMachine:
# contains all allowed transitions: anything not in this map is invalid
# and immediately causes a transition to ``closed``.

_transitions = {
# During graceful shutdown: the state the connection would be in had the
# GOAWAY not arrived (IDLE, CLIENT_OPEN or SERVER_OPEN). It keeps the
# normal client and server rules in force. None otherwise.
_graceful_shutdown_state: ConnectionState | None

def _start_graceful_shutdown(self, previous_state: ConnectionState) -> list[Event]:
"""
Enter graceful shutdown after receiving GOAWAY(NO_ERROR) from the peer,
preserving ``previous_state`` so normal client/server rules stay in
force while already-open streams finish.
"""
assert previous_state is not ConnectionState.CLOSED
self._graceful_shutdown_state = previous_state
return []

_transitions: dict[
tuple[ConnectionState, ConnectionInputs],
tuple[Callable[[H2ConnectionStateMachine, ConnectionState], list[Event]] | None, ConnectionState],
] = {
# State: idle
(ConnectionState.IDLE, ConnectionInputs.SEND_HEADERS):
(None, ConnectionState.CLIENT_OPEN),
Expand All @@ -150,6 +169,8 @@ class H2ConnectionStateMachine:
(None, ConnectionState.CLOSED),
(ConnectionState.IDLE, ConnectionInputs.RECV_GOAWAY):
(None, ConnectionState.CLOSED),
(ConnectionState.IDLE, ConnectionInputs.RECV_GRACEFUL_GOAWAY):
(_start_graceful_shutdown, ConnectionState.CLOSED),
(ConnectionState.IDLE, ConnectionInputs.SEND_PRIORITY):
(None, ConnectionState.IDLE),
(ConnectionState.IDLE, ConnectionInputs.RECV_PRIORITY):
Expand Down Expand Up @@ -182,6 +203,8 @@ class H2ConnectionStateMachine:
(None, ConnectionState.CLIENT_OPEN),
(ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_GOAWAY):
(None, ConnectionState.CLOSED),
(ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_GRACEFUL_GOAWAY):
(_start_graceful_shutdown, ConnectionState.CLOSED),
(ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_WINDOW_UPDATE):
(None, ConnectionState.CLIENT_OPEN),
(ConnectionState.CLIENT_OPEN, ConnectionInputs.RECV_PING):
Expand Down Expand Up @@ -221,6 +244,8 @@ class H2ConnectionStateMachine:
(None, ConnectionState.SERVER_OPEN),
(ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_GOAWAY):
(None, ConnectionState.CLOSED),
(ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_GRACEFUL_GOAWAY):
(_start_graceful_shutdown, ConnectionState.CLOSED),
(ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_WINDOW_UPDATE):
(None, ConnectionState.SERVER_OPEN),
(ConnectionState.SERVER_OPEN, ConnectionInputs.RECV_PING):
Expand All @@ -245,10 +270,53 @@ class H2ConnectionStateMachine:
(None, ConnectionState.CLOSED),
(ConnectionState.CLOSED, ConnectionInputs.RECV_GOAWAY):
(None, ConnectionState.CLOSED),
(ConnectionState.CLOSED, ConnectionInputs.RECV_GRACEFUL_GOAWAY):
(None, ConnectionState.CLOSED),
}

# Inputs that stay valid in the CLOSED state while the connection is in
# graceful shutdown after the remote peer sent GOAWAY(NO_ERROR).
# RFC 9113, Section 6.8: streams that were already open may still
# complete, and only the *receiver* of the GOAWAY is barred from opening
# new streams. SEND_PUSH_PROMISE is therefore absent (and H2Connection
# refuses new local streams via send_headers()), whereas inputs from the
# GOAWAY sender — including RECV_PUSH_PROMISE and peer-initiated
# RECV_HEADERS — remain valid. An input is accepted only if the open
# connection would also accept it (see _graceful_shutdown_state).
_graceful_shutdown_inputs = frozenset({
ConnectionInputs.SEND_HEADERS,
ConnectionInputs.SEND_DATA,
ConnectionInputs.SEND_WINDOW_UPDATE,
ConnectionInputs.SEND_PING,
ConnectionInputs.SEND_SETTINGS,
ConnectionInputs.SEND_RST_STREAM,
ConnectionInputs.SEND_PRIORITY,
ConnectionInputs.SEND_ALTERNATIVE_SERVICE,
ConnectionInputs.RECV_HEADERS,
ConnectionInputs.RECV_PUSH_PROMISE,
Comment thread
Kriechi marked this conversation as resolved.
Resolved
ConnectionInputs.RECV_DATA,
ConnectionInputs.RECV_WINDOW_UPDATE,
ConnectionInputs.RECV_PING,
ConnectionInputs.RECV_SETTINGS,
ConnectionInputs.RECV_RST_STREAM,
ConnectionInputs.RECV_PRIORITY,
ConnectionInputs.RECV_ALTERNATIVE_SERVICE,
})

def __init__(self) -> None:
self.state = ConnectionState.IDLE
self._graceful_shutdown_state = None

@property
def is_in_graceful_shutdown(self) -> bool:
"""
Whether the connection is in graceful shutdown: the remote peer sent a
GOAWAY with error code ``NO_ERROR``, so the state is CLOSED and this
side may not open new streams, but frames for open streams are still
processed. The peer that sent the GOAWAY may still open streams
(RFC 9113, Section 6.8).
"""
return self._graceful_shutdown_state is not None

def process_input(self, input_: ConnectionInputs) -> list[Event]:
"""
Expand All @@ -258,6 +326,22 @@ def process_input(self, input_: ConnectionInputs) -> list[Event]:
msg = "Input must be an instance of ConnectionInputs"
raise ValueError(msg) # noqa: TRY004

if self.is_in_graceful_shutdown:
if input_ is ConnectionInputs.RECV_GRACEFUL_GOAWAY:
return []
assert self._graceful_shutdown_state is not None
transition = self._transitions.get((self._graceful_shutdown_state, input_))
if input_ in self._graceful_shutdown_inputs and transition is not None:
self._graceful_shutdown_state = transition[1]
return []
# Anything else (a non-graceful GOAWAY, or an input the open
# connection would also reject) ends graceful shutdown. self.state
# is already CLOSED and _transitions has no path back out of
# CLOSED, so falling through either handles a GOAWAY (staying
# CLOSED) or raises ProtocolError.
assert self.state is ConnectionState.CLOSED
self._graceful_shutdown_state = None

try:
func, target_state = self._transitions[(self.state, input_)]
except KeyError as e:
Expand All @@ -266,9 +350,10 @@ def process_input(self, input_: ConnectionInputs) -> list[Event]:
msg = f"Invalid input {input_} in state {old_state}"
raise ProtocolError(msg) from e
else:
previous_state = self.state
self.state = target_state
if func is not None: # pragma: no cover
return func()
if func is not None:
return func(self, previous_state)

return []

Expand Down Expand Up @@ -470,6 +555,18 @@ def inbound_flow_control_window(self) -> int:
"""
return self._inbound_flow_control_window_manager.current_window_size

@property
def is_in_graceful_shutdown(self) -> bool:
"""
Whether the connection is in graceful shutdown after receiving a
GOAWAY frame with error code ``NO_ERROR`` from the remote peer
(RFC 9113, Section 6.8). While ``True``, no new local streams may be
opened, but frames for already-open streams are still processed.

.. versionadded:: 4.5.0
"""
return self.state_machine.is_in_graceful_shutdown

def _begin_new_stream(self, stream_id: int, allowed_ids: AllowedStreamIDs) -> H2Stream:
"""
Initiate a new stream.
Expand Down Expand Up @@ -609,6 +706,19 @@ def initiate_upgrade_connection(self, settings_header: bytes | None = None) -> b
self.streams[1].upgrade(self.config.client_side)
return frame_data

def _check_graceful_shutdown(self, stream_id: int) -> None:
"""
The receiver of a GOAWAY must not open new streams (RFC 9113, Section
6.8). Raise before any state changes, so graceful shutdown continues
for the streams that are already open.
"""
if self.is_in_graceful_shutdown:
msg = (
f"Cannot open stream {stream_id}: the remote peer sent GOAWAY, "
"so no new streams may be opened"
)
raise ProtocolError(msg)

def _get_or_create_stream(self, stream_id: int, allowed_ids: AllowedStreamIDs) -> H2Stream:
"""
Gets a stream by its stream ID. Will create one if one does not already
Expand Down Expand Up @@ -794,6 +904,7 @@ def send_headers(self,

# Check we can open the stream.
if stream_id not in self.streams:
self._check_graceful_shutdown(stream_id)
max_open_streams = self.remote_settings.max_concurrent_streams
value = self.open_outbound_streams # take a copy due to the property accessor having side affects
if (value + 1) > max_open_streams:
Expand Down Expand Up @@ -1010,6 +1121,7 @@ def push_stream(self,
msg = "Remote peer has disabled stream push"
raise ProtocolError(msg)

self._check_graceful_shutdown(promised_stream_id)
self.state_machine.process_input(ConnectionInputs.SEND_PUSH_PROMISE)
stream = self._get_stream_by_id(stream_id)

Expand Down Expand Up @@ -1541,6 +1653,16 @@ def _receive_frame(self, frame: Frame) -> list[Event]:
"""
events: list[Event]
self.config.logger.trace("Received frame: %s", repr(frame))
# Leftover frames can still be in the TCP buffer after we closed.
# Extra GOAWAYs are already valid; anything else is not a protocol error.
# During graceful shutdown after a GOAWAY(NO_ERROR), frames are still
# processed.
if (
self.state_machine.state == ConnectionState.CLOSED
and not self.is_in_graceful_shutdown
and not isinstance(frame, GoAwayFrame)
):
return []
try:
# I don't love using __class__ here, maybe reconsider it.
frames, events = self._frame_dispatch_table[frame.__class__](frame)
Expand Down Expand Up @@ -1894,12 +2016,19 @@ def _receive_goaway_frame(self, frame: GoAwayFrame) -> tuple[list[Frame], list[E
"""
Receive a GOAWAY frame on the connection.
"""
events = self.state_machine.process_input(
ConnectionInputs.RECV_GOAWAY,
input_ = (
ConnectionInputs.RECV_GRACEFUL_GOAWAY
if frame.error_code == ErrorCodes.NO_ERROR
else ConnectionInputs.RECV_GOAWAY
)

# Clear the outbound data buffer: we cannot send further data now.
self.clear_outbound_data_buffer()
events = self.state_machine.process_input(input_)

if not self.is_in_graceful_shutdown:
# Clear the outbound data buffer: we cannot send further data now.
# During graceful shutdown (RFC 9113, Section 6.8), keep the buffer
# because it may hold WINDOW_UPDATE, SETTINGS, or PING ACK frames
# that in-flight streams still need.
self.clear_outbound_data_buffer()

# Fire an appropriate ConnectionTerminated event.
new_event = ConnectionTerminated()
Expand Down
19 changes: 17 additions & 2 deletions src/h2/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -562,8 +562,23 @@ def __repr__(self) -> str:
class ConnectionTerminated(Event):
"""
The ConnectionTerminated event is fired when a connection is torn down by
the remote peer using a GOAWAY frame. Once received, no further action may
be taken on the connection: a new connection must be established.
the remote peer using a GOAWAY frame. Once received, no new streams may be
opened on the connection: a new connection must be established for them.

If ``error_code`` is ``NO_ERROR``, this is a graceful shutdown (RFC 9113,
Section 6.8): streams up to ``last_stream_id`` may still complete. On a
connection that was not already closed, h2 enters (or continues) graceful
shutdown and keeps processing frames for open streams; check
:attr:`H2Connection.is_in_graceful_shutdown
<h2.connection.H2Connection.is_in_graceful_shutdown>` for the current
state. Locally initiated streams above ``last_stream_id`` were not
processed by the peer and are safe to retry elsewhere. h2 does not reset
or filter them, and does not check that a later GOAWAY keeps
``last_stream_id`` from increasing: the application decides. With any
other error code, no further action may be taken on the connection.

.. versionchanged:: 4.5.0
A graceful GOAWAY no longer prevents open streams from completing.
"""

def __init__(self) -> None:
Expand Down
29 changes: 29 additions & 0 deletions tests/test_basic_logic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1788,6 +1788,35 @@ def test_receiving_goaway_frame(self, frame_factory) -> None:

assert not c.data_to_send()

def test_frames_after_goaway_are_ignored(self, frame_factory) -> None:
"""
Frames already in the receive buffer after a GOAWAY with an error code
must not raise ProtocolError. Further GOAWAY frames are still accepted.
(After a graceful GOAWAY the connection enters graceful shutdown
instead; see test_graceful_goaway.py.)
"""
c = h2.connection.H2Connection(config=self.server_config)
c.initiate_connection()
c.receive_data(frame_factory.preamble())
c.clear_outbound_data_buffer()

goaway = frame_factory.build_goaway_frame(
last_stream_id=0, error_code=h2.errors.ErrorCodes.PROTOCOL_ERROR,
)
events = c.receive_data(goaway.serialize())
assert len(events) == 1
assert isinstance(events[0], h2.events.ConnectionTerminated)

ping = frame_factory.build_ping_frame(b"\x01\x02\x03\x04\x05\x06\x07\x08")
events = c.receive_data(ping.serialize())
assert events == []
assert not c.data_to_send()
assert c.state_machine.state == h2.connection.ConnectionState.CLOSED

events = c.receive_data(goaway.serialize())
assert len(events) == 1
assert isinstance(events[0], h2.events.ConnectionTerminated)

def test_receiving_multiple_goaway_frames(self, frame_factory) -> None:
"""
Multiple GOAWAY frames can be received at once, and are allowed. Each
Expand Down
Loading