Skip to content

Closed Transport, handshake Timer and HostKeys.lookup classes are only freed by cyclic GC #2732

Open

Description

@focusnetmf

Tested with Paramiko 5.1.0 and CPython 3.14.8 using client and server Transport instances connected by socket.socketpair(). The fixture authenticates with an ephemeral test key and closes and joins both transports after every connection.

In a long-running process that opens and closes many short SSH connections (for example a periodic health check), memory grows until a full cyclic garbage collection runs. With a large, long-lived heap, CPython runs the oldest-generation collection rarely, so these objects stay around for a long time.

1. Closed Transport and its handshake Timer are only freed by the cyclic GC

The handshake completes and the descriptors close, but each side still contributes one Transport and one handshake Timer until cyclic garbage collection runs:

  • Packetizer.complete_handshake() cancels the timer, but the packetizer still owns the timer and the timer still owns its bound Packetizer.read_timer callback (packet.py, start_handshake / complete_handshake).
  • The Transport owns its dispatch table of bound instance methods (transport.py, Transport.__init__, _handler_table).

Reproduction:

import gc
import socket
from threading import Event, Timer

import paramiko

class AcceptTestKey(paramiko.ServerInterface):
    def check_auth_publickey(self, username, key):
        return paramiko.AUTH_SUCCESSFUL

def connect_and_close(key):
    left, right = socket.socketpair()
    client, server = paramiko.Transport(left), paramiko.Transport(right)
    try:
        server.add_server_key(key)
        server.start_server(event=Event(), server=AcceptTestKey())
        client.connect(username="test", pkey=key)
    finally:
        client.close()
        server.close()
        client.join(2)
        server.join(2)
    assert not client.is_alive() and not server.is_alive()
    assert left.fileno() == right.fileno() == -1

def counts():
    objects = gc.get_objects()
    return [sum(type(obj) is kind for obj in objects) for kind in (paramiko.Transport, Timer)]

test_key = paramiko.RSAKey.generate(2048)
connect_and_close(test_key)
gc.collect()
baseline = counts()
gc.disable()
try:
    for _ in range(20):
        connect_and_close(test_key)
    print([now - then for now, then in zip(counts(), baseline)])  # [40, 40]
finally:
    gc.enable()
gc.collect()
print([now - then for now, then in zip(counts(), baseline)])  # [0, 0]

2. HostKeys.lookup() defines a new class on every call

HostKeys.lookup() defines the SubDict(MutableMapping) class inside the method (hostkeys.py, lookup), so every lookup creates a new class object. Class objects are self-referencing and are also only freed by the cyclic GC. SSHClient.connect() looks up both host key tables per connection, so each connection adds new class objects. In our measurement this was the largest remaining allocation per connection after working around point 1.

Request

  • Release the handshake timer and its callback once the timer has completed or been cancelled, and release the dispatch callbacks once the transport has finished, while keeping shutdown and handshake-timeout behaviour.
  • Define SubDict once at module or class level instead of inside lookup().

Possibly related: #949.

Activity

  1. hamarshehmhmd commented on Nov 22, 2026

    @hamarshehmhmd

    Reproduced with your script on main (0e9ccb9), Python 3.12: [40, 40] with gc disabled, [0, 0] after gc.collect().

    The two holders you found are real, but fixing just those still leaves the Transports around ([40, 0]). A third cycle runs through saved_exception. On a normal close, run() stores the EOFError from Packetizer.read_all(). Its __traceback__ holds the run() frame and therefore self. When it's raised inside except socket.error, its __context__ OSError's traceback does the same. After that I checked with gc.DEBUG_SAVEALL and found nothing else.

    The open PR #2566 already covers the handler table and SubDict parts. What's still missing on top of it is the handshake timer and the saved_exception cycle, so here's a patch with all four parts and tests for each:

    The changes:

    diff --git a/paramiko/packet.py b/paramiko/packet.py
    index f1de4b0..8c1e676 100644
    --- a/paramiko/packet.py
    +++ b/paramiko/packet.py
    @@ -294,6 +294,9 @@ class Packetizer:
             """
             if self.__timer:
                 self.__timer.cancel()
    +            # Drop the timer: it holds our bound read_timer, and that cycle
    +            # would otherwise keep both alive until a full gc run.
    +            self.__timer = None
                 self.__timer_expired = False
                 self.__handshake_complete = True
     
    diff --git a/paramiko/transport.py b/paramiko/transport.py
    index cdfa203..e2f6d39 100644
    --- a/paramiko/transport.py
    +++ b/paramiko/transport.py
    @@ -2147,6 +2147,14 @@ class Transport(threading.Thread, ClosingContextManager):
                     self.saved_exception = e
                 except EOFError as e:
                     self._log(DEBUG, "EOF in transport thread")
    +                # EOF is the normal way this loop ends. Its traceback (and
    +                # that of the socket error it may have been raised from)
    +                # only points into packet reading, but it holds this frame,
    +                # and so self, in a reference cycle. Keep the bare exception.
    +                exc = e
    +                while exc is not None:
    +                    exc.__traceback__ = None
    +                    exc = exc.__context__
                     self.saved_exception = e
                 except socket.error as e:
                     if type(e.args) is tuple:
    @@ -2180,6 +2188,9 @@ class Transport(threading.Thread, ClosingContextManager):
                     finally:
                         self.lock.release()
                 self.sock.close()
    +            # The handler table holds bound methods of self; nothing reads it
    +            # once the thread is done, so drop it to break that cycle.
    +            self._handler_table = {}
             except:
                 # Don't raise spurious 'NoneType has no attribute X' errors when we
                 # wake up during interpreter shutdown. Or rather -- raise

    hostkeys.py: I moved SubDict out of lookup() to module level as _SubDict, with no behavior change. The only edit inside the class is in __setitem__. It used the closed-over hostname from lookup(), and now uses self._hostname, which holds the same value.

    Notes on behavior:

    • start_handshake() is only called once, at the top of run(), so dropping the timer after complete_handshake() doesn't re-arm anything. handshake_timed_out() already returned False once the handshake was complete.
    • Only the EOFError branch loses its traceback. That's the normal end-of-connection path, and the traceback only ever pointed into read_all(). SSHException/socket/unknown errors keep theirs, and those are already logged via tb_strings(). get_exception() still returns the same EOFError instance.
    • Nothing reads _handler_table once run() has finished.
    your script (20 connections, gc disabled) Transport Timer
    main 40 40
    timer + handler table only 40 0
    this patch 0 0

    With the patch, a gc.DEBUG_SAVEALL pass after one connect/close finds no cyclic garbage at all (on main it finds Transport, Packetizer, AuthHandler, frames, tracebacks, etc.).

    Tests added:

    • tests/test_transport.py::test_closed_transports_are_freed_without_cyclic_gc: connects over a socketpair, closes and joins, then with gc disabled checks that weakrefs to both transports and packetizers are dead
    • tests/test_packetizer.py::test_complete_handshake_drops_timer
    • tests/test_hostkeys.py::test_lookup_does_not_create_a_class_per_call and test_lookup_result_set_adds_entry_for_that_host, which covers the __setitem__ path that I touched

    Without the source changes, 4 of these fail: the transport, the packetizer, and the class test in both HostKeys test classes. The __setitem__ test passes either way.

    pytest tests                 # 553 passed, 18 skipped (main: 547 passed)
    flake8 <changed files>       # clean; ruff format --check clean
    
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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions