Skip to content

[BUG] - With max_concurrent_prefetch_requests, the prefetch thread outlives the download #2717

Open

Description

@Vitalik-Hakim

Are you using paramiko as a client or server?

Client

What feature(s) aren't working right?

SFTP

What version(s) of paramiko are you using?

3.4.0, 3.4.1, 3.5.0, 3.5.1, 4.0.0, 5.0.0, 5.0.1 and 5.1.0

What version(s) of Python are you using?

3.12.14 and 3.13.16

What operating system and version are you using?

macOS 26.5.1

If you're connecting as a client, which SSH server are you connecting to?

OpenSSH_10.3

If you're using paramiko as part of another tool, which tool/version?

Found while adding max_concurrent_prefetch_requests to pysftp-ng. The scripts below use paramiko alone.

Expected/desired behavior

When getfo() or get() returns, the prefetch thread has finished, as it has when there is no limit, and closing the client raises nothing. Closing an SFTPFile part-way through a prefetch stops its thread.

Actual behavior

With max_concurrent_prefetch_requests lower than the number of 32 KiB blocks in the file, getfo() returns while _prefetch_thread is still running. The data is correct. What the thread does next depends on the connection:

  • If the client is closed straight away, the thread raises OSError: Socket is closed:

    Exception in thread Thread-3 (_prefetch_thread):
    Traceback (most recent call last):
      ...
      File ".../paramiko/sftp_file.py", line 561, in _prefetch_thread
        num = self.sftp._async_request(
      File ".../paramiko/sftp_client.py", line 881, in _async_request
        self._send_packet(t, msg)
      File ".../paramiko/sftp.py", line 209, in _send_packet
        self._write_all(out)
      File ".../paramiko/sftp.py", line 173, in _write_all
        n = self.sock.send(out)
      File ".../paramiko/channel.py", line 799, in send
        return self._send(s, m)
      File ".../paramiko/channel.py", line 1196, in _send
        raise socket.error("Socket is closed")
    OSError: Socket is closed
    
  • If the connection stays open, the thread never finishes. It keeps checking every io_sleep, and closing the client doesn't stop it. After 21 downloads with a limit of 3 on one connection, 4 such threads were alive, and they were still alive 3 s after close().

Closing a prefetching SFTPFile before reading to the end leaves the thread running in the same way, even after the client is closed.

With a 7-block file and the client closed right after getfo(), the thread was still running after 30 of 30 downloads with a limit of 3, 30 of 30 with a limit of 6, and 0 of 30 with a limit of 7, on both 5.1.0 (Python 3.13.16) and 3.4.0 (Python 3.12.14). Line numbers are from 5.1.0.

How to reproduce

import io
import threading

import paramiko

HOST, PORT, USER, PASSWORD = "localhost", 22, "me", "secret"  # any SFTP server
DATA = b"x" * 200_000  # 7 read requests of 32 KiB

client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect(HOST, PORT, USER, PASSWORD)
sftp = client.open_sftp()
with sftp.open("prefetch-repro.bin", "wb") as fobj:
    fobj.write(DATA)

buf = io.BytesIO()
sftp.getfo("prefetch-repro.bin", buf, max_concurrent_prefetch_requests=3)
print("data correct:", buf.getvalue() == DATA)
running = [t for t in threading.enumerate() if "_prefetch_thread" in t.name]
print("still running:", [t.name for t in running])
client.close()
for thread in running:
    thread.join()  # the thread fails with OSError: Socket is closed

Output, in 10 of 10 runs on 5.1.0 and on 3.4.0:

data correct: True
still running: ['Thread-3 (_prefetch_thread)']
Exception in thread Thread-3 (_prefetch_thread):
Traceback (most recent call last):
  ...
OSError: Socket is closed

For the other case, add import time and replace the last three lines with:

time.sleep(1)  # keep the connection open for a moment
client.close()
for thread in running:
    thread.join(5)
print("alive after close():", [t.name for t in running if t.is_alive()])

That printed alive after close(): ['Thread-3 (_prefetch_thread)'] in 5 of 5 runs on 5.1.0 and on 3.4.0. The script leaves prefetch-repro.bin on the server.

Anything else?

Two things combine:

  1. _async_response sets _prefetch_done as soon as _prefetch_extents is empty. With a limit, _prefetch_thread sends requests up to the limit and then checks again every io_sleep. If the reader has taken in every reply by the next check, which on a fast link is the usual case, _prefetch_done is set while blocks are still waiting to be requested. _read_prefetch then stops prefetching, _read fetches the rest with synchronous reads, and getfo() closes the file and returns while the thread carries on. fix a race in ftp prefetching when using max_concurrent_requests #2519 describes the same race (from the memory side) and fixes it by recording when the thread has queued its last request. With fix a race in ftp prefetching when using max_concurrent_requests #2519 applied to 5.1.0, the counts above drop to 0 of 30 for every limit, the script prints still running: [], and no thread was left after the 21 downloads.

  2. The thread doesn't stop when its file is closed. Its later reads use the closed handle. Nothing reads their replies until the next SFTP call, and then the server's status reply (OSError('Failure') from OpenSSH) is saved by _async_response, which returns without removing the request from _prefetch_extents. The count of requests in flight stays at the limit, so the thread waits forever. fix a race in ftp prefetching when using max_concurrent_requests #2519 doesn't change this, so closing a file part-way through a limited prefetch still leaves the thread behind. Checking self._closed in _prefetch_thread fixes that in my tests, with or without fix a race in ftp prefetching when using max_concurrent_requests #2519:

--- a/paramiko/sftp_file.py
+++ b/paramiko/sftp_file.py
@@ -556,8 +556,11 @@
                         pf_len = len(self._prefetch_extents)
                         if pf_len < max_concurrent_requests:
                             break
+                    if self._closed:
+                        return
                     time.sleep(io_sleep)
-
+            if self._closed:
+                return
             num = self.sftp._async_request(
                 self, CMD_READ, self.handle, int64(offset), int(length)
             )

I'm happy to open a PR for that, or to test other fixes.

Related: #1788 (the hang the limit was added for), #2058 (the PR that added it), #2454 (cancelling a prefetch) and #2418 (another case where prefetching stops early).

Activity

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