Skip to content

Fix SharedMemoryArray.__del__ AttributeError during interpreter shutdown - #1386

Draft
rootkiller6788 wants to merge 1 commit into
google:mainfrom
rootkiller6788:fix-shm-del-shutdown-attrerror
Draft

Fix SharedMemoryArray.__del__ AttributeError during interpreter shutdown#1386
rootkiller6788 wants to merge 1 commit into
google:mainfrom
rootkiller6788:fix-shm-del-shutdown-attrerror

Conversation

@rootkiller6788

@rootkiller6788 rootkiller6788 commented Aug 20, 2026

Copy link
Copy Markdown

Problem

At interpreter shutdown, SharedMemoryArray.__del__ can raise:

Exception ignored in: <function SharedMemoryArray.__del__ at ...>
  File ".../shared_memory_array.py", line 170, in __del__
AttributeError: 'NoneType' object has no attribute 'mmap'

This is reported in #398 and clutters shutdown logs in data pipelines that use shared memory (e.g. BatchOperation._enable_shared_memory()).

Root cause

__del__ referenced module-level names directly:

def __del__(self):
    if not isinstance(self.base, mmap.mmap):   # mmap -> None at shutdown
        ...

During interpreter shutdown CPython clears module dicts, setting these globals to None. A SharedMemoryArray instance that outlives the module then hits None.mmap and raises.

Fix

Bind the mmap.mmap and shared_memory.SharedMemory types and the _del_shm helper as default arguments (bound at import time, so they survive module teardown), and reach the class attributes via type(self) instead of the SharedMemoryArray global.

Test

Added test_del_after_module_globals_cleared, which clears mmap, shared_memory, SharedMemoryArray and _del_shm on the module and verifies deletion still unlinks the shared memory block without raising.


📚 Documentation preview 📚: https://google-grain--1386.org.readthedocs.build/

During interpreter shutdown, module-level names in shared_memory_array.py
(such as mmap and shared_memory) may be set to None. The __del__ method
referenced these globals directly, so a lingering SharedMemoryArray raised
AttributeError: 'NoneType' object has no attribute 'mmap' at shutdown,
cluttering logs (issue google#398).

Bind the mmap.mmap and shared_memory.SharedMemory types and the _del_shm
helper as default arguments (bound at import time), and access the class
attributes via type(self), so __del__ no longer depends on module globals.

Adds a regression test that clears the relevant module globals and verifies
deletion still unlinks the shared memory block.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant