python / python/cpython

Improve `tarfile` streaming mode to handle very large archives

未關閉
#139,960 3 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

stdlib type-feature
主要語言
Python
星號
77.2k
分支
35.9k
PR 合併指標
PR 指標待擷取

描述

Bug report

Bug description:

I am trying to use tarfile to write very large archives, and the process is being killed by the OOM killer. I would expect+want to be able to use it in streaming mode (write an unlimited number of files) like the standard tar command line utility supports by default.

Reproduction case attached.

import gc
import io
import os
import psutil
import tarfile

if __name__ == "__main__":
    t = tarfile.open("a.tar", mode="w") # default compresslevel 9
    for i in range(1,100_000_000):
        if i % 10_000 == 0:
            gc.collect()
            process = psutil.Process(os.getpid())
            mem_info = process.memory_info()
            mem = mem_info.rss
            print(f"Iteration {i}, memory usage: {mem}")

        bs = (" "*1000 + str(i)).encode('utf8')
        with io.BytesIO(bs) as file:
            tarinfo = tarfile.TarInfo(name="cool_files/{i}.txt")
            tarinfo.size = len(bs)
            t.addfile(tarinfo, file)

The memory usage increases without bound because the list of this line in addfile():

self.members.append(tarinfo)

I'm not sure what the use-case is for this line. In write-only mode, it does not seem useful. Maybe mixed read/write? But in general it does not seem correct to assume you can fit all the tarinfo's in memory.

Edit: As a workaround, I'm setting t.members=[] manually.

CPython versions tested on:

3.13

Operating systems tested on:

Linux

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

從 tarfile 中 TarFile.addfile() 附近的實作以及 self.members.append(tarinfo) 這一行開始,使用報告中的重現來觀察記憶體成長。確定 write-only 或 streaming 模式的預期行為,然後驗證寫入超大型封存檔時記憶體使用量能夠維持在有界範圍內,同時不會破壞 tarfile 的其他使用情境。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python
領域
backend
Issue 類型
缺陷
難度
4/5
預估耗時
3-5 天
活躍度
停滯
描述清晰度
基本清楚
新手友好度
45/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。