Skip to content

[BUG] - SFTPFile.read() is 25x slower than SFTPClient.get() / scp #2453

Open

Description

@mxmlnkn

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.5.0

What version(s) of Python are you using?

3.10.12

What operating system and version are you using?

Ubuntu 22.04 LTS

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

No response

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

No response

Expected/desired behavior

I want SFTPFile.read() to be reasonably fast.

Actual behavior

SFTPFile.read() achieves only 4 MB/s for a connection to localhost.

How to reproduce

Benchmark results are annotated with code comments in the benchmark code below. As can be seen, I also tried to vary the bufsize argument and window_size argument without any success. The test file is 68 MB large.

import io
import time
import paramiko

client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect("127.0.0.1")

sftp = client.open_sftp()

for bufsize in [0, 128*1024, 1024*1024, 128*1024*1024]:
    file = sftp.open('silesia.tar.gz', bufsize=bufsize)
    t0=time.time(); contents=file.read(); t1=time.time()
    print(
        f"Used buffer size {bufsize} B. "
        f"Read {len(contents)} in {t1-t0:.2f} s -> {len(contents)/(t1-t0)/1e6:.2f} MB/s"
    )
# Used buffer size 0 B. Read 68238807 in 17.21 s -> 3.97 MB/s
# Used buffer size 131072 B. Read 68238807 in 17.24 s -> 3.96 MB/s
# Used buffer size 1048576 B. Read 68238807 in 17.30 s -> 3.94 MB/s
# Used buffer size 134217728 B. Read 68238807 in 17.14 s -> 3.98 MB/s

for i in range(5):
    t0=time.time(); sftp.get("silesia.tar.gz", "/dev/shm/mimi"); t1=time.time()
    print(f"Read {len(contents)} in {t1-t0:.2f} s -> {len(contents)/(t1-t0)/1e6:.2f} MB/s")
# Read 68238807 in 0.67 s -> 101.72 MB/s
# Read 68238807 in 0.53 s -> 128.40 MB/s
# Read 68238807 in 0.60 s -> 113.68 MB/s
# Read 68238807 in 0.67 s -> 101.56 MB/s
# Read 68238807 in 0.57 s -> 120.20 MB/s

for i in range(5):
    t0=time.time(); size = sftp.getfo("silesia.tar.gz", io.BytesIO()); t1=time.time()
    print(f"Read {size} in {t1-t0:.2f} s -> {size/(t1-t0)/1e6:.2f} MB/s")
# Read 68238807 in 0.71 s -> 96.17 MB/s
# Read 68238807 in 0.66 s -> 103.47 MB/s
# Read 68238807 in 0.62 s -> 109.36 MB/s
# Read 68238807 in 0.70 s -> 97.23 MB/s
# Read 68238807 in 0.71 s -> 96.08 MB/s

for window_size in [0, 128*1024, 1024*1024, 128*1024*1024]:
    sftp = paramiko.SFTPClient.from_transport(client.get_transport())
    file = sftp.open('silesia.tar.gz')
    t0=time.time(); contents=file.read(); t1=time.time()
    print(
        f"Used window size size {window_size} B. "
        f"Read {len(contents)} in {t1-t0:.2f} s -> {len(contents)/(t1-t0)/1e6:.2f} MB/s"
    )
# Used window size size 0 B. Read 68238807 in 16.87 s -> 4.05 MB/s
# Used window size size 131072 B. Read 68238807 in 17.01 s -> 4.01 MB/s
# Used window size size 1048576 B. Read 68238807 in 16.96 s -> 4.02 MB/s
# Used window size size 134217728 B. Read 68238807 in 16.97 s -> 4.02 MB/s

import subprocess
for i in range(5):
    t0=time.time(); subprocess.run(['scp', 'scp://127.0.0.1/silesia.tar.gz', '.']); t1=time.time()
    print(f"Read {size} in {t1-t0:.2f} s -> {size/(t1-t0)/1e6:.2f} MB/s")
# Read 68238807 in 0.69 s -> 98.87 MB/s
# Read 68238807 in 0.66 s -> 103.43 MB/s
# Read 68238807 in 0.66 s -> 102.99 MB/s
# Read 68238807 in 0.71 s -> 96.09 MB/s
# Read 68238807 in 0.79 s -> 86.85 MB/s

Anything else?

Possibly related issue:

Activity

  1. mxmlnkn commented on Sep 22, 2024

    @mxmlnkn
    Author

    After adding some debug output into STPFile._read, I thought I saw the issue:

        def _read(self, size):
            self.sftp._log(
                DEBUG, "_read({}, {})".format(hexlify(self.handle), size)
            )
    DEB [20240922-02:29:51.384] thr=2   paramiko.transport.sftp: [chan 0] _read(b'00000000', 8192)
    DEB [20240922-02:29:51.384] thr=2   paramiko.transport.sftp: [chan 0] _read(b'00000000', 8192)
    DEB [20240922-02:29:51.385] thr=2   paramiko.transport.sftp: [chan 0] _read(b'00000000', 8192)
    DEB [20240922-02:29:51.385] thr=2   paramiko.transport.sftp: [chan 0] _read(b'00000000', 8192)
    DEB [20240922-02:29:51.386] thr=2   paramiko.transport.sftp: [chan 0] _read(b'00000000', 8192)
    DEB [20240922-02:29:51.386] thr=2   paramiko.transport.sftp: [chan 0] _read(b'00000000', 8192)
    

    The issue is similar to the one I recently had with my own Python file object, i.e., the default Python buffer size of 8 KiB is used for some reason.

    One issue is that the configured bufsize is ignored when doing a full read. This should be changed to use self._bufsize instead of self._DEFAULT_BUFSIZE, imho. Unfortunately, while the benchmarks now return slightly different timings, they are still too slow:

    Used buffer size 0 B. Read 68238807 in 17.79 s -> 3.84 MB/s
    Used buffer size 131072 B. Read 68238807 in 14.44 s -> 4.73 MB/s
    Used buffer size 1048576 B. Read 68238807 in 14.36 s -> 4.75 MB/s
    Used buffer size 134217728 B. Read 68238807 in 14.47 s -> 4.72 MB/s
    

    On the user site, another workaround would be to specify a very large read size, e.g., 1 TB, i.e., read(1<<40) instead of read(). However, for some weird reason, it actually slows the benchmark down:

    Used buffer size 0 B. Read 68238807 in 48.07 s -> 1.42 MB/s
    Used buffer size 131072 B. Read 68238807 in 40.17 s -> 1.70 MB/s
    Used buffer size 1048576 B. Read 68238807 in 40.51 s -> 1.68 MB/s
    Used buffer size 134217728 B. Read 68238807 in 40.08 s -> 1.70 MB/s
    

    Looking at the log further, _read is called 2k times even though the read size is 128 MiB. I also added debug output in BufferedFile.read and it is only called once.

    The problem now is SFTPFile.MAX_REQUEST_SIZE, which is 32 KiB.

    I am not the first one to notice issues with the maximum request size. There even is an ancient pull request to make it configurable:

    After increasing MAX_REQUEST_SIZE to 32 MiB, I get slightly better performance, but still not quite there yet and there still is more than one read call, so there still is something that limits the read chunk size.

    Used buffer size 0 B. Read 68238807 in 18.08 s -> 3.77 MB/s
    Used buffer size 131072 B. Read 68238807 in 7.86 s -> 8.68 MB/s
    Used buffer size 1048576 B. Read 68238807 in 7.33 s -> 9.31 MB/s
    Used buffer size 134217728 B. Read 68238807 in 7.48 s -> 9.13 MB/s
    

    After adding debug output in SFTPClient._request, I see Requested 134217728, got 261120. So, for some reason, the server only returns 255 KiB even though more is requested. This does not explain why a simple SFTPClient.get is still 10x faster than SFTPFile.read.

    Setting the MAX_REQUEST_SIZE to exactly 261120 also does not improve performance any further, contrary to this comment.

    Looking at it from the other end, the much faster STPClient.getfo does not look that different. It also opens an STPFile object and reads from it.

    After commenting out the if prefetch path, I get the same performance that I get with STPFile.read, 4.9 MB/s vs. 97 MB/s with it. So it seems that this is the magic ingredient. Note that I can increase performance to 125 MB/s by increasing buf_size here.

    with self.open(remotepath, "rb", bufsize=255*1024) as fr:

    So, I guess I should enable prefetching. But for my use case, the file may be read in a random order and the file may be 1 TB in size. Will the prefetched chunks be released in some kind of least-recently-used cache manner to avoid out-of-memory problems?

    I wanted to try this on a 100 GB file (wikidata.json.gz), but I only did see the memory increase very very slowly, so I added some debug output, and I noticed that the transfer speed decreases the longer the more data has been transferred...

    import io
    import time
    import paramiko
    
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.connect("127.0.0.1")
    
    sftp = client.open_sftp()
    
    remotepath = "wikidata-20220103-all.json.gz"
    file_size = sftp.stat(remotepath).st_size
    with sftp.open(remotepath, "rb", bufsize=255 * 1024) as reader:
        reader.prefetch(file_size)
        size = 0
        threshold = 1 * 1024 * 1024
        t0 = time.time()
        while True:
            data = reader.read(255 * 1024)
            size += len(data)
    
            if size >= threshold:
                t1 = time.time()
                print(f"Read {size / 1e6} MB in {t1-t0:.2f} s -> {size/(t1-t0)/1e6:.2f} MB/s")
                threshold += 1 * 1024 * 1024
    
            if len(data) == 0:
                break

    After ~300 MB was transferred (after 3 minutes), the bandwidth suddenly increased again and is stable from there on. Very weird behavior, but I was able to reproduce it every time out of the 3 times I had the patience for. Here is a quick plot:

    benchmark-paramiko-wikidata

    The good news is that memory really seems to be freed at some point. During the initial period where performance decreases, I can see the memory usage of the Python process increasing up to 1.5 GB. At this point, the memory does not increase any further and the speed now suddenly increases again to full speed. So there seems to be some memory allocation issue that resolves itself only until after the ceiling is hit.

    If this prefetch memory is per-file, then 1.5 GB per file is possibly also too much. It would be nice if this memory limit, if it is a consciously intended bound, to be configurable.

    Here are some heaptrack charts to show the memory usage over time:

    Screenshot_2024-09-22_04-22-24

    Screenshot_2024-09-22_04-22-28

    Screenshot_2024-09-22_04-23-07

    Note that heaptrack shows only ~ 400 MB of consumed memory even though grep Peak /proc/<pid>/status and htop show ~1.5 GB. This may be a memory allocator or alignment or whatever issue. The memory allocations are supposedly very small, which may explain it.

    Screenshot_2024-09-22_04-22-22

  2. mxmlnkn commented on Sep 22, 2024

    @mxmlnkn
    Author

    Trace generated with Score-P Python bindings when prefetching is disabled:

    Screenshot_2024-09-22_10-25-08

    Most of the time is spent in paramiko.packet.Packetizer.read_all while the main thread is mostly waiting in the condition variable. I did this trace first without prefetching because, when I enabled prefetching, I was unable to preemptively quit. It seems that the background prefetching threads are not correctly stopped.

    With prefetching, it looks like this:

    Screenshot_2024-09-22_14-13-43

    There are 3 threads, one of them does nothing, the other is the same as in the case without prefetching, and the new third thread spends most of its time sending messages. In these short 20s of trace time, it has sent 360k messages!

    Screenshot_2024-09-22_10-57-09

    Screenshot_2024-09-22_10-55-48

    Screenshot_2024-09-22_10-56-23

    With the max packet size of 32 KiB, sending 360k requests would correspond to ~11.5 GB if I understand this correctly. With the file being ~102 GiB, this means that it will still need to send the remaining 90% of requests, which should take about 200s in total. This fits the observed performance change after ~3 min. Therefore, it seems to me that the prefetching is done without regard for anything for the whole file. I am honestly surprised that the SSH server is fine with that because it seems that ~ 3 million messages for data requests are sent without the data actually being received. It seems that this data is only really received after the sending of the request messages is finished.

    It is another matter altogether why sending request messages would throttle data receival.

    The calls to paramiko.packet:compute_hmac / hmac.HMAC._init_hmac also seem to make up a significant amount of time but that is probably just compute-intensive hashing being done on the messages.

    The calls to paramiko.packet.Packetizer.read_all have quite some variability in their durations and I don't see in the trace why. My best guess is that this is an issue in the OpenSSH server, which gets overwhelmed by the large number of request messages and therefore is slow to send replies.

    Turns out that this can be avoided by specifying max_concurrent_requests, e.g., reader.prefetch(file_size, max_concurrent_requests=1024). The default value is simply unusable. I have spent hours(!) trying to debug what a better default could have done out of the box. With that, I can get pretty stable bandwidths of 115 MB/s.

  3. mxmlnkn commented on Sep 28, 2024

    @mxmlnkn
    Author

    The same as my initial applies to uplading/writing, but the performance ratio is > 100x:

    import io
    import time
    import paramiko
    
    port = 22
    
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.connect("127.0.0.1", port=port)
    
    sftp = client.open_sftp()
    
    file_path = '/dev/shm/silesia.tar.gz'
    
    with open(file_path, 'rb') as file:
        contents = file.read()
    
    for i in range(5):
        t0=time.time(); sftp.put(file_path, "/dev/shm/foo"); t1=time.time()
        print(f"[put] Wrote {len(contents)} in {t1-t0:.2f} s -> {len(contents)/(t1-t0)/1e6:.2f} MB/s")
    
    for i in range(5):
        t0=time.time(); size = sftp.putfo(io.BytesIO(contents), "foo").st_size; t1=time.time()
        print(f"[putfo] Wrote {size} in {t1-t0:.2f} s -> {size/(t1-t0)/1e6:.2f} MB/s")
    
    import subprocess
    for i in range(5):
        t0=time.time(); subprocess.run(['scp', '-P', str(port), file_path, 'scp://127.0.0.1/foo']); t1=time.time()
        print(f"[scp] Wrote {size} in {t1-t0:.2f} s -> {size/(t1-t0)/1e6:.2f} MB/s")
    
    file = sftp.open('foo', 'wb')
    t0=time.time(); file.write(contents); t1=time.time()
    assert file.tell() == len(contents)
    print(f"[open/write] Write {len(contents)} in {t1-t0:.2f} s -> {len(contents)/(t1-t0)/1e6:.2f} MB/s")
    
    sftp.close()
    client.close()

    Output:

    [put] Wrote 68238807 in 0.81 s -> 84.11 MB/s
    [put] Wrote 68238807 in 0.85 s -> 79.92 MB/s
    [put] Wrote 68238807 in 0.72 s -> 94.32 MB/s
    [put] Wrote 68238807 in 0.72 s -> 95.09 MB/s
    [put] Wrote 68238807 in 0.69 s -> 98.69 MB/s
    [putfo] Wrote 68238807 in 0.56 s -> 121.71 MB/s
    [putfo] Wrote 68238807 in 0.90 s -> 75.57 MB/s
    [putfo] Wrote 68238807 in 1.15 s -> 59.25 MB/s
    [putfo] Wrote 68238807 in 0.72 s -> 95.33 MB/s
    [putfo] Wrote 68238807 in 0.73 s -> 92.98 MB/s
    [scp] Wrote 68238807 in 0.58 s -> 118.59 MB/s
    [scp] Wrote 68238807 in 0.52 s -> 130.71 MB/s
    [scp] Wrote 68238807 in 0.54 s -> 126.16 MB/s
    [scp] Wrote 68238807 in 0.54 s -> 126.41 MB/s
    [scp] Wrote 68238807 in 0.58 s -> 116.75 MB/s
    [open/write] Wrote 68238807 in 68.85 s -> 0.99 MB/s
    [open/write] Write 68238807 in 61.86 s -> 1.10 MB/s
    
    Exception ignored in: <function SFTPFile.__del__ at 0x7f5ca0b46b90>
    Traceback (most recent call last):
      File "./paramiko/paramiko/sftp_file.py", line 76, in __del__
      File "./paramiko/paramiko/sftp_file.py", line 102, in _close
      File "./paramiko/paramiko/sftp_client.py", line 875, in _async_request
      File "./paramiko/paramiko/message.py", line 279, in add_string
    TypeError: 'NoneType' object is not callable
    
  4. erikvanzijst commented on Nov 20, 2024

    @erikvanzijst

    That's a very thorough investigation. I've lost hours debugging on this same issue.

    The performance is just all over the place with a variance of multiple orders of magnitude like your tests.

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions