python / python/cpython

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

Aberta
#153,279 0 comentários 1 reação 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

stdlib topic-multiprocessing type-bug
Linguagem predominante
Python
Estrelas
77.2k
Forks
35.9k
Métricas de merge de PRs
Métricas de PR pendentes

Descrição

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

Guia de contribuição

Abrir o guia de contribuição

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Direção de pesquisa

Comece em multiprocessing.shared_memory.SharedMemory.init e reproduza a falha de attach com o mock mostrado na issue. Verifique o comportamento de cleanup e resource-tracker tanto para os caminhos de attach quanto de create. Considera-se concluído quando um attach com falha deixa o bloco existente utilizável e não produz um erro espúrio do tracker; a issue inclui o PR vinculado gh-153280.

Escrita pelo modelo de indexação a partir do texto da issue.

Avaliação

Stack de tecnologia
python
Domínio
operating-systems
Tipo de issue
Bug
Dificuldade
3/5
Tempo estimado
1-2 dias
Status de atividade
Estagnada
Clareza
Razoavelmente clara
Facilidade para iniciantes
25/100

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.