Repository navigation
Description
Things to check first
-
I have searched the existing issues and didn't find my bug already reported there
-
I have checked that my bug is still present in the latest release
AnyIO version
4.15.1 (also 4.14.2)
Python version
3.13.5
What happened?
When a TLSStream.send() is cancelled, the stream can be left corrupted for every later send.
_call_sslobject_method calls SSLObject.write(), which encrypts the data into the write BIO and uses up the next TLS record sequence number. It then flushes the BIO with await self.transport_stream.send(self._write_bio.read()). SocketStream.send checkpoints before it calls transport.write(). If the cancel lands at that checkpoint, the encrypted bytes have already been taken out of the BIO, so they are gone. The peer never receives that record. Every record after it has a sequence number the peer doesn't expect, so the peer fails with DECRYPTION_FAILED_OR_BAD_RECORD_MAC and closes the connection with a fatal alert.
I expected one of two outcomes. Either the cancelled send has no effect on the stream, or the record that was already encrypted is still delivered. In both cases later sends would keep working.
We hit this in production through httpcore's HTTP/2 client. Many requests share one TLS connection, and the task reading a response also writes to it (WINDOW_UPDATE frames, PING acks). When a client disconnects, the server framework cancels that task. If the cancel lands during one of those writes, the upstream answers with SSLV3_ALERT_BAD_RECORD_MAC and every other request on the connection fails with it.
Shielding the flush fixes the reproducer below:
else:
# Flush any pending writes first
if self._write_bio.pending:
with CancelScope(shield=True):
await self.transport_stream.send(self._write_bio.read())
return resultHow can we reproduce the bug?
import ssl
import anyio
import trustme
from anyio.streams.tls import TLSStream
ca = trustme.CA()
server_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ca.issue_cert("localhost").configure_cert(server_context)
client_context = ssl.create_default_context()
ca.configure_trust(client_context)
async def serve(stream):
tls = await TLSStream.wrap(stream, server_side=True, ssl_context=server_context)
try:
while True:
print("server got:", await tls.receive())
except ssl.SSLError as exc:
print("server error:", exc)
async def main():
async with await anyio.create_tcp_listener(local_host="127.0.0.1") as listener:
async with anyio.create_task_group() as tg:
tg.start_soon(listener.serve, serve)
port = listener.extra(anyio.abc.SocketAttribute.local_port)
client = await anyio.connect_tcp(
"127.0.0.1", port, ssl_context=client_context, tls_hostname="localhost"
)
await client.send(b"first")
# A send cancelled before it starts (e.g. the caller hung up).
with anyio.CancelScope() as scope:
scope.cancel()
await client.send(b"cancelled")
await client.send(b"second")
await anyio.sleep(0.5)
tg.cancel_scope.cancel()
anyio.run(main)Output:
server got: b'first'
server error: [SSL: DECRYPTION_FAILED_OR_BAD_RECORD_MAC] decryption failed or bad record mac (_ssl.c:2648)
With the shielded flush applied:
server got: b'first'
server got: b'cancelled'
server got: b'second'
Activity
agronholm commentedon Oct 5, 2026
Shielding the
send()seems risky, as it could potentially hang forever, and won't respect timeouts.agronholm commentedon Oct 5, 2026
I was thinking of stashing the chunk if sending is cancelled, but what happens if it gets partially sent?
gschaffner commentedon Oct 7, 2026
Agreed, we definitely cannot shield that.
TLSStream's cancellation semantics are consistent with the cancellation semantics oftrio.abc.SendStream.send_allandtrio.SSLStream.send_all:gschaffner commentedon Oct 7, 2026
Actually, AnyIO probably isn't making subsequent calls raise
BrokenResourceErrorin this case. I think that that is the right fix here.gschaffner commentedon Oct 7, 2026
You can never know if it got partially sent. So you must assume that
ByteSendStream.sendraising Cancelled left the stream in an unknown state, which (for almost all wire protocols) means that the stream is effectively lost/broken and you can't use it anymore.