Skip to content

Tracking Issue: Sub-Interpreter Support #3451

Open

Description

@Aequitosh

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 static data from PyO3's implementation, either move things to PyModule_GetState (preferred) or PyInterpreterState_GetDict (alternative)
  • Allow extension authors to use unsafe in order to opt in to sub-interpreter support - it is their responsibility to guarantee to not store Py<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.

Activity

  1. Aequitosh commented on Sep 13, 2023

    @Aequitosh
    Author

    Note that I will update this issue whenever updates, new infos, etc. appear in order to keep everything relatively tidy.

  2. cristiancmrg commented on Sep 16, 2023

    @cristiancmrg

    @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 ;)

  3. Aequitosh commented on Feb 6, 2024

    @Aequitosh
    Author

    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.

  4. Aequitosh commented on Apr 4, 2024

    @Aequitosh
    Author

    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 static data 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 static data into the per-module memory-area (which can be accessed via PyModule_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 static data - I will elaborate on this below.

    Relocating currently static data 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_static or OnceLock, 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 statics

    I 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 static data - 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 static data 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:

    • Some kind of struct living on the Python heap representing per-module state where currently static data will be moved to
    • An internal API regarding per-module state
      • Only for per-module static data for now, but once the flow's been worked out, I don't see why this couldn't also be used for other purposes
      • Perhaps something that can be made pub (or have a pub layer, rather) once the details have been fleshed out

    Also, 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.

  5. davidhewitt commented on Apr 6, 2024

    @davidhewitt
    Member

    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!

  6. Aequitosh commented on Apr 6, 2024

    @Aequitosh
    Author

    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).

  7. mejrs commented on Apr 6, 2024

    @mejrs
    Member

    I think part of this would be to have an optional state: &State argument 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.

    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.

    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 :)

  8. Aequitosh commented on May 6, 2024

    @Aequitosh
    Author

    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.

  9. Aequitosh commented on Jul 18, 2024

    @Aequitosh
    Author

    Healthcheck: Now that university stuff has cooled down, I can finally dedicate some more time to this again. Just rebased my PR on main and added some notes for future me.

  10. Aequitosh commented on Jul 23, 2024

    @Aequitosh
    Author

    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. ;)

  11. 12 remaining items

  12. bazaah commented on Oct 13, 2025

    @bazaah
    Contributor

    Okay, great. I'll start poking around with #5142, and we'll see where we go from there.

  13. alex commented on Oct 13, 2025

    @alex
    Member

    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 unsafe to promise that they don't have any static state or share PyObject * across sub-interpreters.

  14. bazaah commented on Oct 13, 2025

    @bazaah
    Contributor

    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::scope treatment, 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 :D

  15. Aequitosh commented on Oct 13, 2025

    @Aequitosh
    Author

    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.

  16. bazaah commented on Oct 13, 2025

    @bazaah
    Contributor

    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 restful module 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 pyo3

  17. Aequitosh commented on Oct 13, 2025

    @Aequitosh
    Author

    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 restful module is always loaded (it's removed completely in v20).

    Alright, gotcha!

    (FWIW, I've provided a similar workaround for the restful module if you need a band-aid fix, but I don't wanna hijack this thread for Ceph stuff now. :P)

    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 pyo3

    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 PyModuleDef in PyInit_$MODULE (instead of PyObject, 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 static PyModuleDef_Slot* with sane defaults. At least, that's how I solved it in my non-public rebase / refactor of #4162.

  18. davidhewitt commented on Oct 16, 2025

    @davidhewitt
    Member

    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.

  19. bazaah commented on Oct 16, 2025

    @bazaah
    Contributor

    Yes, I'm using 5142 as my base, rebased onto main -- working through proc-macro / syn errors 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_module returning a *mut PyModuleDef instead of a Py<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 somehow

  20. ngoldbaum commented on Jan 29, 2026

    @ngoldbaum
    Contributor

    FWIW, multi-phase init is merged now. Not sure what is next for adding subinterpreter support.

  21. bazaah commented on Jan 29, 2026

    @bazaah
    Contributor

    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 $dayJob ended 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

  22. ngoldbaum commented on Jan 29, 2026

    @ngoldbaum
    Contributor

    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.

  23. ZeroIntensity commented on Apr 19, 2026

    @ZeroIntensity

    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.

  24. davidhewitt commented on Apr 23, 2026

    @davidhewitt
    Member

    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 :)

  25. ddxd commented on Sep 23, 2026

    @ddxd

    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 current main, 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!, PyOnceLock and the conversion-layer class caches are all per interpreter, and modules declare Py_MOD_PER_INTERPRETER_GIL_SUPPORTED (on abi3 it is resolved at run time). One difference from #5600: our storage is a registry in PyInterpreterState_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:

    1. The deferred-decref pool is process-wide. Interpreter B applies decrefs queued by interpreter A: SIGABRT on macOS, silent heap corruption on glibc. With one shared .so we measured the other interpreter applying the decref 5 out of 5 times, both for a drop on a foreign thread and for a drop inside py.detach while 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.
    2. Python::attach on a thread with no thread state lands in the main interpreter. It goes through PyGILState_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 is InterpreterHandle (capture on the owning thread, attach elsewhere). It is independent of the storage design, so it could be a first small PR.
    3. Interned strings are mortal on 3.12–3.14 (measured), so a process-wide intern! shares a live refcount across GILs.
    4. 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 singleton PyOnceLock and deadlocks (4 interpreters importing polars at once).
    5. Values freed at interpreter teardown arrive through a capsule destructor, with PyO3's attach count at zero. Their Py<T> drops were therefore deferred into a pool that nothing ever drains: 2.6 MB leaked per interpreter, without bound.
    6. Test suite: once a process creates a sub-interpreter, CPython disables PyGILState_Check for good. In a test binary that also creates sub-interpreters, test_acquire_gil then depends on test order, so sub-interpreter tests need their own processes.

    Validation:

    • polars (77 #[pyclass] types, abi3-py310, submodules) runs unmodified in strict own-GIL mode.
    • Before the fixes, 3 of 4 interpreters got another interpreter's pl.Int64 class; now all 80 checks pass.
    • Before the fixes, destroying interpreters after writes segfaulted 5 times in 10; now 10 of 10 runs are clean.
    • CI runs the unit tests, a regression test per runtime defect, and probes that each check the fork against an upstream control. All but one of those tests were mutation-checked: each fails when its fix is reverted. The build-level fixes (the abi3 slot, submodules) are covered by the probes instead.

    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.

  26. Aequitosh commented on Sep 23, 2026

    @Aequitosh
    Author

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions