Repository navigation
Description
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 boundPacketizer.read_timercallback (packet.py,start_handshake/complete_handshake).- The
Transportowns 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
SubDictonce at module or class level instead of insidelookup().
Possibly related: #949.
Activity
hamarshehmhmd commentedon Nov 22, 2026
Reproduced with your script on
main(0e9ccb9), Python 3.12:[40, 40]with gc disabled,[0, 0]aftergc.collect().The two holders you found are real, but fixing just those still leaves the Transports around (
[40, 0]). A third cycle runs throughsaved_exception. On a normal close,run()stores theEOFErrorfromPacketizer.read_all(). Its__traceback__holds therun()frame and thereforeself. When it's raised insideexcept socket.error, its__context__OSError's traceback does the same. After that I checked withgc.DEBUG_SAVEALLand found nothing else.The open PR #2566 already covers the handler table and
SubDictparts. What's still missing on top of it is the handshake timer and thesaved_exceptioncycle, so here's a patch with all four parts and tests for each:The changes:
hostkeys.py: I movedSubDictout oflookup()to module level as_SubDict, with no behavior change. The only edit inside the class is in__setitem__. It used the closed-overhostnamefromlookup(), and now usesself._hostname, which holds the same value.Notes on behavior:
start_handshake()is only called once, at the top ofrun(), so dropping the timer aftercomplete_handshake()doesn't re-arm anything.handshake_timed_out()already returnedFalseonce the handshake was complete.EOFErrorbranch loses its traceback. That's the normal end-of-connection path, and the traceback only ever pointed intoread_all().SSHException/socket/unknown errors keep theirs, and those are already logged viatb_strings().get_exception()still returns the sameEOFErrorinstance._handler_tableoncerun()has finished.With the patch, a
gc.DEBUG_SAVEALLpass 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 deadtests/test_packetizer.py::test_complete_handshake_drops_timertests/test_hostkeys.py::test_lookup_does_not_create_a_class_per_callandtest_lookup_result_set_adds_entry_for_that_host, which covers the__setitem__path that I touchedWithout 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.