`ZipFile.close()` writes wrong offsets after a failed `repack()`
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 36k
- PR 合併指標
- PR 指標待擷取
描述
Bug description:
_ZipRepacker.repack() updates ZipInfo.header_offset for each member before moving that member's bytes, so a failing _copy_bytes() leaves the in-memory offsets describing a layout that was never written. remove() has already set _didModify, so a later normal close() commits a central directory built from those offsets: the caller handles the OSError, closes cleanly, and gets an archive that zipfile itself cannot read.
import io, zipfile
class Flaky(io.BytesIO):
countdown = None
def write(self, b):
if self.countdown is not None:
self.countdown -= 1
if self.countdown < 0:
raise OSError(28, 'No space left on device')
return super().write(b)
buf = io.BytesIO()
with zipfile.ZipFile(buf, 'w') as zf:
for c in 'abcd':
zf.writestr(c + '.txt', c.upper().encode() * 5000)
flaky = Flaky(buf.getvalue())
with zipfile.ZipFile(flaky, 'a') as zf:
flaky.countdown = 1
try:
zf.repack([zf.remove('b.txt')], chunk_size=4096)
except OSError as exc:
print('repack raised:', exc)
flaky.countdown = None # space freed; the caller closes normally
with zipfile.ZipFile(flaky) as zf:
print('testzip:', zf.testzip())
repack raised: [Errno 28] No space left on device
testzip: c.txt
Expected: after the caller has handled the OSError, close() should either leave a readable archive or raise, rather than committing offsets that no write produced.
remove() and repack() are new in 3.16, so no released version is affected.
CPython versions tested on:
CPython main branch
Operating systems tested on:
Linux
Linked PRs
- gh-156435
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
從 zipfile._ZipRepacker.repack()、_copy_bytes()、remove() 和 close() 開始,使用 Flaky BytesIO reproducer 追蹤 OSError 之後的偏移量。完成的標準是,錯誤後的 close 路徑要麼留下可讀取的封存檔,要麼引發例外,而不是提交未寫入資料的偏移量;開始之前請檢查關聯的 PR gh-156435。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- backend
- Issue 類型
- 缺陷
- 難度
- 3/5
- 預估耗時
- 1-2 天
- 活躍度
- 停滯
- 描述清晰度
- 描述清楚
- 新手友好度
- 25/100