Skip to content

asyncio: SSL transport raises AttributeError after close() in connection_lost() #160964

Open

Description

@asvetlov

Bug report

If a protocol closes its SSL transport in connection_lost(), which is a common pattern, later calls on the transport fail:

import asyncio
from test.test_asyncio import utils as tu

class Proto(asyncio.Protocol):
    def connection_made(self, tr):
        self.tr = tr
    def connection_lost(self, exc):
        self.tr.close()
        self.lost.set_result(None)

async def main():
    async def handler(reader, writer):
        writer.close()
    srv = await asyncio.start_server(handler, '127.0.0.1', 0,
                                     ssl=tu.simple_server_sslcontext())
    port = srv.sockets[0].getsockname()[1]
    loop = asyncio.get_running_loop()
    proto = Proto()
    proto.lost = loop.create_future()
    tr, _ = await loop.create_connection(
        lambda: proto, '127.0.0.1', port, ssl=tu.simple_client_sslcontext())
    await proto.lost
    tr.write(b'x')  # AttributeError: 'NoneType' object has no attribute '_write_appdata'
    srv.close()

asyncio.run(main())

set_protocol(), get_write_buffer_size() and get_extra_info() fail the same way. Plain TCP transports don't have this problem.

It also breaks the loop.sendfile() fallback over SSL: if the peer disconnects mid-transfer, restore() calls set_protocol() and raises AttributeError instead of the expected connection error.

The cause is in _SSLProtocolTransport.close(). When it's called on a transport already marked closed, it sets _ssl_protocol = None. That was added in gh-98539 so the transport doesn't keep the SSL context alive, but it leaves the transport unusable.

Affects 3.11 and later.

Linked PRs

Activity

  1. added
    stdlibStandard Library Python modules in the Lib/ directory
    on Oct 30, 2026
  2. cornopaez commented on Oct 30, 2026

    @cornopaez

    A proposed fix for this very issue can be found here: #160069

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytopic-asynciotype-bugAn unexpected behavior, bug, or error

    Projects

    • Status
      Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions