Skip to content

fix: avoid O(n²) buffer copying in BufferedFile.read - #2690

Open
VenkateswarluNagineni wants to merge 1 commit into
paramiko:mainfrom
VenkateswarluNagineni:fix/buffered-file-read-quadratic
Open

VenkateswarluNagineni wants to merge 1 commit into
paramiko:mainfrom
VenkateswarluNagineni:fix/buffered-file-read-quadratic

Conversation

@VenkateswarluNagineni

Copy link
Copy Markdown

What this fixes

Closes #2688.

BufferedFile.read(size) compacts the read buffer after every call:

self._rbuffer = self._rbuffer[size:]

Slicing bytes always copies. Reading N bytes one byte at a time
allocates and copies roughly N + (N-1) + … + 1 = O(N²) bytes total.
On a large SFTP file this causes multi-second stalls and eventually
memory exhaustion.

Fix

Track a _rbuffer_start integer offset instead of slicing on every
read. Compact the underlying bytes object (copy once) only when more
than half of it has been consumed — amortised O(1) per byte read.

Changes:

  • paramiko/file.py: add _rbuffer_start = 0 in __init__; replace
    slice-after-read with offset arithmetic in read(); compact in
    readline() at entry to keep its logic simple.
  • tests/test_file.py: test_read_small_chunks_linear — fills an
    8 192-byte buffer then reads it back one byte at a time; asserts
    correct data and that the internal buffer stays compact.

Testing

python -m pytest tests/test_file.py -v
# 15 passed, 1 skipped

Track a _rbuffer_start offset instead of slicing the buffer on every
read.  Compact when more than half the buffer has been consumed so
memory usage stays bounded.  Reading N bytes one byte at a time goes
from O(N²) copies to O(N).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] - BufferedFile.read() re-slices the full buffer on every call, causing quadratic cost with small chunk sizes

1 participant