Repository navigation
Description
Tracks the development and state of supporting sub-interpreters in PyO3.
This issue really only tracks progress, for discussing everything else, feel free to join over here: Aequitosh#1
Summary
As of 13.09.2023
PyO3 currently doesn't support sub-interpreters, which will lead to an ImportError being raised if a module using PyO3 is initialized more than once per interpreter process. As stated in #2523, this is necessary in order to prevent soundness holes (as in, prevent things that use PyO3 from randomly breaking, having nasty undefined behaviour, etc.).
Even though this prevents soundness holes on the one hand, it can lead to modules / applications using a sub-interpreter model to "break" in certain situations. For examples, see pyca/cryptography#9016 and bazaah/aur-ceph#20.
Implementing sub-interpreter support isn't straightforward and requires quite a substantial redesign of PyO3's API. This issue shall track this redesign and provide as much relevant information as possible for all that wish to contribute.
Goals
Adapted from #576 (comment), as of 13.09.2023.
Mid-Term
- Rework synchronization primitives to not rely on the GIL. See Add support for nogil Python #2885
- Develop transition plan so that existing users can migrate their code without enormous amounts of work
- Remove
staticdata from PyO3's implementation, either move things toPyModule_GetState(preferred) orPyInterpreterState_GetDict(alternative)
- Allow extension authors to use
unsafein order to opt in to sub-interpreter support - it is their responsibility to guarantee to not storePy<T>in any static data. - Document all conditions that extension authors' modules need to satisfy so that they may be used within sub-interpreters
Long-Term
Possibly remove the need for extension authors to audit their own code once we're confident enough.
Tasks
TBA - might them here (or some other place) once more concrete pieces of work have been identified.
Relevant Issues & Interesting Reads
Listing relevant things here. Some things might already be linked above, but it's nevertheless nice to have everything in one place.
- Initial discussion regarding sub-interpreter support:
Support sub-interpreters #576 - PR regarding nogil Python support, contains lots of additional information:
Add support for nogil Python #2885 - Discussion regarding making Python's C-API more friendly for Rust; linking to comment what would need to happen in PyO3 internally:
How can we make Python's C-API more friendly for Rust? #2346 (comment) cryptographyissue regarding sub-interpreters in PyO3:
Different behaviour between 41.0.0, 41.0.1 and 40.0.2 - PyO3 modules may only be initialized once per interpreter process pyca/cryptography#9016aur-cephmaintainer's issue regarding Ceph's sub-interpreter model, and why Ceph Dashboard breaks:
ceph-mgr/dashboard: python-cryptography PyO3 modules may only be initialized once per interpreter process bazaah/aur-ceph#20- Idea by @GoldsteinE - using a
ghostcell-ish pattern:
Support sub-interpreters #576 (comment)
Activity
Aequitosh commentedon Sep 13, 2023
Note that I will update this issue whenever updates, new infos, etc. appear in order to keep everything relatively tidy.
cristiancmrg commentedon Sep 16, 2023
@Aequitosh, just in case you didn't have seen, David have redirected the Multiple Gill Acquire to here and close the other one to don't have two lines of the same subject, so now we will continue the subject here ;)
Aequitosh commentedon Feb 6, 2024
Hi there!
For those following this issue, I've got a short update: I'm slowly able to pick up on all this again, now that there are less things going on in my private life.
Currently, I'm working on properly drafting up and implementing a prototype of an idea that's been living rent-free in my head the past few weeks - I figured it's finally time I brought it to life in the form of code. More details will follow as soon as I'm more confident with the idea - that is, once I've actually implemented it in prototypical form and seen it in action.
See this more as a sign that this issue is still alive; I'm still very eager to work on this, even though I wasn't able to for a while.
Aequitosh commentedon Apr 4, 2024
So, I have been working on and off on this. The more I begin to understand how CPython's insides work, the more I realize how complicated this actually is.
Nevertheless, I've got a rough plan for removing
staticdata from PyO3. I think this is a good first "milestone" (or whatever you'd like to call it) for this issue - I will elaborate on this further below.Per-Module State
From what I've been experimenting with, it's probably best to move
staticdata into the per-module memory-area (which can be accessed viaPyModule_GetState) as was initially preferred.The absolutely fantastic thing about per-module state is that, according to the CPython docs, it's an arbitrarily-sized block of memory allocated on the Python interpreter's heap that is sub-interpreter safe to access. This makes it the ideal place to store more than just
staticdata - I will elaborate on this below.Relocating currently
staticdata to this per-module memory region will require a new mechanism to actually put stuff on there during the initialization of a module. To give a more concrete example, instead of statically allocating docstrings, they should instead perhaps be allocated in a separate container, and then be moved / cloned / etc. on the per-module memory block.To provide an analogy, this mechanism (or API) would work similar to something like
lazy_staticorOnceLock, just quite a bit more elaborate. This "pseudo-static docstring container" would be mutable during the module initialization phase and made immutable once put onto the Python heap.But obviously this goes beyond just storing docstrings - and in my opinion, also beyond just storing static data.
A Place For More Than
staticsI reckon that implementing this hypothetical mechanism described above will require quite a lot of changes to PyO3's internals; at least that's what it looks like to me right now.
Nevertheless, I think it can be leveraged for more than just
staticdata - for example, depending on how we'll actually make the current synchronization primitives independent from the GIL, we could definitely store other per-module state there, including e.g. a per-module lock that emulates the GIL (really just an example!).What can (and what should) be in the per-module state is still up for discussion (some of it perhaps beyond the current scope of this issue), but I think it's safe to say that we should start with relocating
staticdata there - and that's where I'm currently at.Next Steps
Because working on the synchronization primitives first (the prototype I had mentioned in my prior post) was maybe a too big of a chunk up front, this is what I'll be working on in the next couple weeks:
structliving on the Python heap representing per-module state where currentlystaticdata will be moved tostaticdata for now, but once the flow's been worked out, I don't see why this couldn't also be used for other purposespub(or have apublayer, rather) once the details have been fleshed outAlso, I'll probably open a developer diary or something over at the discussions of my fork in order to keep this thread rather clean - if you'd like to comment on this, feel free to open a discussion there too.
I was initially intending to report back once I had something more concrete, but I feel it's better to share some bits and pieces here and there - maybe it encourages somebody to share their ideas or comments as well.
Example of Per-Module State
There is a fantastic example that just so happened to be added in the meantime, which demonstrates this; moreover, it shows how to make a sub-interpreter safe module using PyO3's FFI bindings. Leaving this here as it shows mostly what I mean.
davidhewitt commentedon Apr 6, 2024
Agreed that per module state is a necessary first step which can have general value beyond subinterpreters. I've actually been playing around with the first step for supporting that, which is changing PyO3 to do something compatible with pep 489. Ideally I can push this soon!
Aequitosh commentedon Apr 6, 2024
That's actually fantastic - I've got multi-phase initialization to almost work at the moment; I still have to change a bunch of the proc macro stuff so I can actually attach functions, classes, etc. to my module. It otherwise loads just fine (though I get a double-free when the garbage collector picks it up, woops).
Let me know if I can lend a hand or anything! I haven't pushed my stuff yet, but might soon. I'll ping you over at my fork once I do (if that's alright).
mejrs commentedon Apr 6, 2024
I think part of this would be to have an optional
state: &Stateargument in functions and methods that passes in some user defined (part of) the module state, so that users can also put their static data in it. Much like how web frameworks pass in a Context struct so users don't have to use global variables.Thanks! I mostly wrote it to get some experience with it and to get a feel of what it should look like. I'm happy if it does the same for others :)
Aequitosh commentedon May 6, 2024
Back with an update! I opened up PR #4162, which implements almost fully functional multi-phase module initialization. See the PR for more information.
More work will continue off and on in the meantime. Exams are coming up, but I'll try to make some time every now and then.
Aequitosh commentedon Jul 18, 2024
Healthcheck: Now that university stuff has cooled down, I can finally dedicate some more time to this again. Just rebased my PR on
mainand added some notes for future me.Aequitosh commentedon Jul 23, 2024
Back with some good news! Multi-phase initialization now works, even for submodules.
I've updated PR #4162 correspondingly; it's now an RFC. See the PR's description for more details.
It's still a little rough around the edges, but we're getting much closer to merging now, I feel. (Unless something unexpected pops up, that is.)
@davidhewitt Kindly pinging you here and asking you to take a look whenever you have time. ;)
src/impl_: add ff unsafe-allow-subinterpreters
src/impl_: add ff unsafe-allow-subinterpreters
Ensure Horizon mod_wsgi uses global WSGI subinterpreter
Ensure Horizon mod_wsgi uses global WSGI subinterpreter
12 remaining items
bazaah commentedon Oct 13, 2025
Okay, great. I'll start poking around with #5142, and we'll see where we go from there.
alex commentedon Oct 13, 2025
FWIW, I think the other reason many of us are low-motivation to solve this is that we have no way to ensure a module is ultimately fully sound -- users will need
unsafeto promise that they don't have any static state or sharePyObject *across sub-interpreters.bazaah commentedon Oct 13, 2025
Yes, ultimately each pyo3 consumer is just going to to have to promise in some way that they don't stick PyObjects in statics. I did that for python-bcrypt via a forked pyo3 + feature flag and it worked fine. There maybe some way to eventually construct the problem space such that it is possible to apply the
std::thread::scopetreatment, but not without a fundamental change to pyo3's current API. From what I've seen subinterpreters are fairly rare, so I want to keep the happy subinterpreter-less pyo3 path, happy, but allow for advanced users to adopt into a higher constraint bound. Which is basically what cpython does, ideally with much better documentation :DAequitosh commentedon Oct 13, 2025
Maybe to chime in here—the main reason why this hasn't really seen any progress from my side is because I simply cannot find any time for this at the moment, though I'll happily pick this up again once I got some time to spare, whenever that is. I don't expect this to be any time soon though, unfortunately (I'm a working student and I currently have ~60h weeks).
@bazaah In case it helps, I could rebase and push my second draft of my original PR regarding multi-phase init (#4162) some time soon. It contains a bunch of improvements and should also handle multi-phase init of modules created at runtime, but it's not completely finished yet, though. (On a different note, regarding Ceph, I've backported ceph/ceph#62951 not too long ago for Proxmox VE and it's been working neatly for us, in case that helps.)
If you need any pointers or if there's anything I can weigh in on, feel free to ping me whenever, though. I'll try to respond as soon as I can.
bazaah commentedon Oct 13, 2025
Thanks @Aequitosh, I may indeed reach out. Don't worry about rebasing, I'll deal with it as I need. I've recently come into some extra free time myself. I've also backported the same PR to my Ceph build (bazaah/aur-ceph@07d5272), which replaces the hacks I had to do with python-bcrypt nicely, plus enables the dashboard again. But the cephadm part of the mgr is still broken, I think because the mgr
restfulmodule is always loaded (it's removed completely in v20).The "right" solution is to fix
cryptography, but I need module state to actually pull that off, and after a lot of thinking and trying different stuff, there's really no good way to avoid just sitting down and doing the work on pyo3Aequitosh commentedon Oct 13, 2025
Alright, gotcha!
(FWIW, I've provided a similar workaround for the
restfulmodule if you need a band-aid fix, but I don't wanna hijack this thread for Ceph stuff now. :P)Yeah, there really isn't; doing the work in PyO3 is the way to go. The main "problem" with multi-phase init is that you're required to return a pointer to
PyModuleDefinPyInit_$MODULE(instead ofPyObject, IIRC), which will require a lot of churn in PyO3 (adapting tests etc.).I wish you good luck!
Ninja edit: I forgot to add, the remaining things for adding multi-phase init are rather straightforward (as you might have seen if you've browsed my PR and others); the only really "finicky" thing is adding multi-phase init support for modules created at runtime. I really do not know if runtime-created modules can just stay the same and use single-phase init, but for supporting multi-phase init, you can just recycle a
staticPyModuleDef_Slot*with sane defaults. At least, that's how I solved it in my non-public rebase / refactor of #4162.davidhewitt commentedon Oct 16, 2025
For what it's worth, the latest attempt (mine) to start the refactor to use multi-phase init is in #5142. The PR is looking reasonably functional, but GraalPy tests crashed and I haven't yet investigated.
bazaah commentedon Oct 16, 2025
Yes, I'm using 5142 as my base, rebased onto main -- working through proc-macro /
synerrors which is not my forte, but I think I grokk the rust part now. The primary difference on an implementation level that I see is what @Aequitosh mentioned above:made_modulereturning a*mut PyModuleDefinstead of aPy<PyModule>. Your PR handles this via ffi::PyModule_FromDefAndSpec, which I think works just fine for PEP489, so I don't think that API breakage is needed but I could be wrong somehowngoldbaum commentedon Jan 29, 2026
FWIW, multi-phase init is merged now. Not sure what is next for adding subinterpreter support.
bazaah commentedon Jan 29, 2026
Basically, reworking pyo3 modules to use per-module state, plus a couple of tricky changes to the internals of pyo3 to make it safe in the face of multiple interpreters (changes to
statics, mostly).I just don't have bandwidth at the moment, as my break from a
$dayJobended with the start of 2026. I will get back around to it when work gets a bit less busy.You can see the conversation thread here: #2274 & the work as it stands here: github.com//pull/5600
ngoldbaum commentedon Jan 29, 2026
OK, FYI I'm currently working on updating module initialization to use the new PEP 793 hooks on Python 3.15 and newer. I think it's orthogonal to the subinterpreters work but it'll probably cause conflicts because it'll touch the same parts of the codebase.
ZeroIntensity commentedon Apr 19, 2026
Coming here after Nathan noted that PyO3 doesn't support subinterpreters -- is there anything we could do upstream to help move this along? With the 3.15 beta freeze coming up soon, it'd be ideal to request any new APIs sooner rather than later.
davidhewitt commentedon Apr 23, 2026
I think we should not worry about landing any subinterpreter APIs specifically for PyO3 in 3.15, thanks though. The main thing we're blocked by is per-module state, which we're still working out the right shape for, see #5600. Just one of many things which we're slowly moving forwards :)
ddxd commentedon Sep 23, 2026
Hi all. Following the 2023 advice in #576 to experiment in a fork and come back with reviewable pieces: we have been running PyO3 extensions (polars included, unmodified) in own-GIL sub-interpreters on a fork, and want to share what we measured. It may be useful input whatever shape per-module state (#5600) ends up taking.
Fork: https://github.com/leocaolab/pyo3 (tag
subinterp-2026-09-23, on top of currentmain, 0.29.2). What changed, with evidence:CHANGELOG-FORK.md. Defect list, each with its regression test:SUBINTERP-FIXES.md→ Bug ledger.What it covers: mostly the "changes to
statics" part @bazaah mentioned.#[pyclass]types, exception types, the module object,intern!,PyOnceLockand the conversion-layer class caches are all per interpreter, and modules declarePy_MOD_PER_INTERPRETER_GIL_SUPPORTED(on abi3 it is resolved at run time). One difference from #5600: our storage is a registry inPyInterpreterState_GetDict, not per-module state. We are not proposing that storage choice. The pitfalls below apply to either design.Pitfalls we hit, each with a repro and a regression test:
.sowe measured the other interpreter applying the decref 5 out of 5 times, both for a drop on a foreign thread and for a drop insidepy.detachwhile another interpreter attaches. The fix needs the owner at enqueue time (the thread's thread state, else the extension copy's interpreter). At drain time the owner can no longer be recovered.Python::attachon a thread with no thread state lands in the main interpreter. It goes throughPyGILState_Ensure, and every rayon/tokio callback has this shape. We send it to the extension copy's own interpreter, and fail loudly if the copy is loaded by several interpreters. For the shared case there isInterpreterHandle(capture on the owning thread, attach elsewhere). It is independent of the storage design, so it could be a first small PR.intern!shares a live refcount across GILs.LazyTypeObject's initializing-threads list must be per interpreter. Otherwise one interpreter's finished init clears another's in-flight entry, which then re-enters an enum-variant singletonPyOnceLockand deadlocks (4 interpreters importing polars at once).Py<T>drops were therefore deferred into a pool that nothing ever drains: 2.6 MB leaked per interpreter, without bound.PyGILState_Checkfor good. In a test binary that also creates sub-interpreters,test_acquire_gilthen depends on test order, so sub-interpreter tests need their own processes.Validation:
#[pyclass]types, abi3-py310, submodules) runs unmodified in strict own-GIL mode.pl.Int64class; now all 80 checks pass.We're happy to split any of this into PRs in whatever order you prefer, and to follow #5600's per-module state and @ngoldbaum's PEP 793 work where they overlap (we also touch module init). Or we can just contribute the probes and tests to your design. Thanks for all the work on this.
Aequitosh commentedon Sep 23, 2026
Oh, man. I so wish I could dive into this again, but unfortunately
${LIFE}has been quite busy and eventful.I highly appreciate it that you guys have been driving this forward. Seems like it's been making a lot of progress as well :))
I might chime in on a whim every now and then again, since I'm still very much interested in the whole sub-interpreter affair, but I can't guarantee anything. However, feel free to ping me though if you need somebody to run some tests or maybe review some code. I'll try to help out whenever I can.