Chunked File Copy with Bounded Memory
Description
Model checkpoints are tens of gigabytes, far more than the RAM on the box that moves them. Write a file copy that streams in fixed-size chunks so its memory use does not depend on the file size.
def copy_file(src_path, dst_path, chunk_size: int = 65536) -> int: ...src_path and dst_path may be str or pathlib.Path.
Rules
- Copy the bytes of
src_pathtodst_pathexactly, binary-safe, and return the number of bytes copied. - Read and write at most
chunk_sizebytes at a time. Never load the whole file. Binary files need not contain any newline bytes, so iterating the file by lines is not chunking. - Create
dst_pathif it does not exist. If it exists, replace its contents completely, so a shorter source leaves no trailing old bytes. - Validate before touching the destination. On any of these errors
dst_pathmust be left exactly as it was:chunk_size <= 0raisesValueError- a missing
src_pathraisesFileNotFoundError src_pathanddst_pathreferring to the same file raisesValueError. That includes different paths to one file, such as a symlink. Opening the destination for writing would truncate the source before it is read.
Example
Path("a.bin").write_bytes(b"hello world")
copy_file("a.bin", "b.bin", chunk_size=4) # 11, read as b"hell", b"o wo", b"rld"
Path("b.bin").read_bytes() # b"hello world"
copy_file("a.bin", "a.bin") # ValueError, a.bin untouchedConstraints
- Files can be larger than memory. The tests copy 8 MB and check with
tracemallocthat peak Python memory stays under 1 MB. - Standard library only.
Solution
Reference solution and explanationTry it first. The explanation covers the approach, complexity, pitfalls and follow-ups.Reveal solution
Approach
Validate first, then stream. Reject a bad chunk_size. Then, if the destination exists, ask os.path.samefile whether both paths are the same file. It compares device and inode numbers, so it catches symlinks, hard links and dir/./file spellings that a string comparison would miss. It also stats the source, so a missing source raises FileNotFoundError at that point.
Then open the source for reading before opening the destination for writing, and loop while chunk := src.read(chunk_size). An empty bytes object means end of file. Only one chunk is alive at a time, so peak memory is about chunk_size however big the file is.
The ordering is the whole point of the validation rules. open(dst, "wb") truncates immediately. If it runs before the source is known to exist, or when the destination is the source, the data is gone before a single byte is read.
Complexity
O(n) time for an n-byte file, O(chunk_size) memory. Throughput depends on the chunk size. 64 KB to 1 MB is a common sweet spot, and tiny chunks cost a syscall per few bytes.
Pitfalls
dst.write(src.read()). It is correct for small files and holds the whole file in memory for large ones.src_path == dst_pathas the same-file check. It misses symlinks, hard links and relative versus absolute paths.- Opening the destination first, or in the same
withbefore the source. A missing source still truncates the destination. - Iterating the file with
for line in f. Binary files may have no newlines, so one "line" can be the whole file. - Validating
chunk_sizeafter opening the destination.
Follow-ups interviewers ask
- Make the copy atomic. Write to a temporary file in the same directory,
flushandos.fsyncit, thenos.replaceit over the destination, so a crash never leaves a half-written file. - Verify integrity. Feed each chunk into
hashlib.sha256while copying and compare with the source's checksum. - Resume an interrupted copy. Seek both files to the destination's current size and continue, after checking the overlap.
- Use the kernel.
shutil.copyfileobj,os.sendfileorcopy_file_rangeavoid copying through user space at all. - Do it in asyncio without blocking the loop. File I/O is blocking, so run the copy in
asyncio.to_thread.
Reference solution
import os
def copy_file(src_path, dst_path, chunk_size: int = 65536) -> int:
if chunk_size <= 0:
raise ValueError("chunk_size must be > 0")
# samefile stats src, so a missing source raises FileNotFoundError here too.
if os.path.exists(dst_path) and os.path.samefile(src_path, dst_path):
raise ValueError("source and destination are the same file")
copied = 0
# Open src first: if it is missing we fail before "wb" truncates the destination.
with open(src_path, "rb") as src, open(dst_path, "wb") as dst:
while chunk := src.read(chunk_size):
dst.write(chunk)
copied += len(chunk)
return copiedNotes
import os
def copy_file(src_path, dst_path, chunk_size: int = 65536) -> int:
"""
Copy src_path to dst_path in chunks of at most chunk_size bytes. Return bytes copied.
ValueError for chunk_size <= 0 or when both paths are the same file.
FileNotFoundError when src_path is missing. Leave dst_path untouched on any error.
"""
raise NotImplementedErrorRun checks the 2 example tests. Submit runs all 13 and marks the problem solved when they pass.