Skip to content

gh-158820: Add null checks to avoid segfaults with lazy imports at shutdown - #158821

Open
brittanyrey wants to merge 4 commits into
python:mainfrom
brittanyrey:b-lazy-fini-null-state
Open

brittanyrey wants to merge 4 commits into
python:mainfrom
brittanyrey:b-lazy-fini-null-state

Conversation

@brittanyrey

@brittanyrey brittanyrey commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Additional finalizers can run after finalize_modules() has cleared the interpreter's lazy_modules set and lazy_pending_submodules dict. In the perfect storm, this can lead to a seg fault when accessing either container without checking if the object is still allocated.

  • Add null checks to call sites interacting with possibly cleared objects.
  • Adds tests repro-ing the issue

Destructors can run after finalization has cleared the interpreter's
lazy_modules set and lazy_pending_submodules dict. Declaring or
resolving a lazy import from one of them passed NULL to PySet_Add(),
PySet_Discard() or the pending-submodules lookup.

Treat the bookkeeping as a no-op once the state is gone, as the other
readers of this state already do.
Comment thread Python/import.c
Comment thread Misc/NEWS.d/next/Core_and_Builtins/2026-10-05-01-59-22.gh-issue-158820.3KLyOT.rst Outdated
Comment thread Python/import.c
@brittanyrey

Copy link
Copy Markdown
Contributor Author

Addressed comments in new commit

@brettcannon
brettcannon removed their request for review October 5, 2026 21:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants