python / python/cpython

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

Abierto
#153,279 0 comentarios 1 reacción 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

stdlib topic-multiprocessing type-bug
Lenguaje dominante
Python
Estrellas
77.2k
Forks
35.9k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

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

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza en multiprocessing.shared_memory.SharedMemory.init y reproduce el fallo de attach con el mock mostrado en el issue. Comprueba el comportamiento de cleanup y resource-tracker tanto para las rutas de attach como de create. Se considera terminado cuando un attach fallido deja utilizable el bloque existente y no produce un error espurio del tracker; el issue incluye el PR enlazado gh-153280.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
operating-systems
Tipo de issue
Error
Dificultad
3/5
Tiempo estimado
1-2 días
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.