Skip to content

Avoid leaking module object on numpy C-API import failure - #263

Merged
antonwolfy merged 2 commits into
mainfrom
fix-ufuncs-module-leak
Sep 1, 2026
Merged

Avoid leaking module object on numpy C-API import failure#263
antonwolfy merged 2 commits into
mainfrom
fix-ufuncs-module-leak

Conversation

@antonwolfy

Copy link
Copy Markdown
Collaborator

Summary

import_array() and import_umath() are macros that expand to return NULL; on failure. In PyInit__ufuncs they were called after PyModule_Create(), so a failing numpy C-API import returned directly out of the init function without releasing the module object — leaking the strong reference created by PyModule_Create().

This moves the imports before the module is created, so there is no owned reference to leak when an import fails. This is the pattern documented for the numpy import macros, which are designed to be called from a context where a bare return NULL; is valid.

Notes

Latent, pre-existing bug; only triggers on the (rare, usually fatal) failure of numpy's C-API import at module init. No behavior change on the success path.

Comment thread mkl_umath/src/ufuncsmodule.c Outdated
ndgrigorian
ndgrigorian previously approved these changes Aug 31, 2026

@ndgrigorian ndgrigorian left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

other than nit LGTM

import_array() and import_umath() are macros that expand to `return NULL;`
on failure. When they were called after PyModule_Create(), a failing import
would return directly out of PyInit__ufuncs without releasing the module
object, leaking the strong reference created by PyModule_Create().

Move the imports before the module is created so there is no owned
reference to leak when an import fails.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@antonwolfy
antonwolfy merged commit 9445ecd into main Sep 1, 2026
98 of 110 checks passed
@antonwolfy
antonwolfy deleted the fix-ufuncs-module-leak branch September 1, 2026 13:48
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.

2 participants