python / python/cpython

multiprocessing.shared_memory: failed attach unlinks another process's block

未关闭
#153,279 0 条评论 1 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

stdlib topic-multiprocessing type-bug
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Bug report

Bug description

SharedMemory.__init__ calls self.unlink() from its OSError cleanup handler:

try:
    if create and size:
        os.ftruncate(self._fd, size)
    stats = os.fstat(self._fd)
    size = stats.st_size
    self._mmap = mmap.mmap(self._fd, size)
except OSError:
    self.unlink()
    raise

This runs unconditionally, including on the attach path (create=False).
unlink() calls shm_unlink(), which permanently destroys the named block.
So if mmap() fails while attaching to a block created by another process
(e.g. ENOMEM under memory pressure), the failing attach destroys another
owner's live shared memory block
.

Reproduction (simulating an mmap failure during attach):

from unittest import mock
from multiprocessing import shared_memory

owner = shared_memory.SharedMemory(create=True, size=1024)
try:
    with mock.patch("multiprocessing.shared_memory.mmap.mmap",
                    side_effect=OSError("ENOMEM")):
        shared_memory.SharedMemory(owner.name)   # attach
except OSError:
    pass

shared_memory.SharedMemory(owner.name)   # FileNotFoundError: block destroyed

Secondary issue: resource_tracker.register() runs after this try/except, so
on the create=True path the block is not yet registered. unlink() still
calls resource_tracker.unregister(), so the resource_tracker does
cache[rtype].remove(name) on an unknown name → KeyError printed as a
traceback, with the tracker's exit code set to 3.

Expected behavior

A failed attach must not unlink a block it does not own. On error the fd should
just be closed; the block should be unlinked only when it was created in this
call, and without a spurious unregister for a never-registered block.

Your environment

  • CPython main (3.16.0a0); also affects earlier versions
  • Linux / POSIX shared memory (_USE_POSIX)
Linked PRs
  • gh-153280

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 multiprocessing.shared_memory.SharedMemory.init 开始,使用 issue 中展示的 mock 重现 attach 失败。检查 attach 和 create 路径中的 cleanup 和 resource-tracker 行为。完成的标准是:attach 失败后,现有 block 仍可使用,并且不会产生多余的 tracker 错误;issue 中包含链接的 PR gh-153280。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
operating-systems
Issue 类型
缺陷
难度
3/5
预计耗时
1-2 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。