You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
It could be convenient if there is a utility module that provides a rust GlobalAlloc backed by PyMem_Raw - this is particularly important on free-threaded Python where Rust would still use the system allocator which usually performs much worse with contention (article provides some context). While the extension can compile in mimalloc, that's a pretty large library for what's already in the interpreter, multiplied by all extensions. And regardless of that, users can get tracemalloc integration for free.
The idea is to basically just have this alloc.rs available in PyO3 somewhere. I don't think it should be registered by default, notably it is questionable for libraries that allocate after detaching, normally it will be fine but tracemalloc would itself cause acquiring GIL on arbitrary possibly async Rust threads. But it's probably still applicable relatively broadly and some trickiesh code that may be helpful.
I notice #81 brought the idea up a long time ago, back then free-threaded may not have been well known as a motivation for this, so maybe it can be reconsidered.
I remember looking into this area previously and concluding (at the time) that PyMem_Malloc was not suitable for building a global allocator due to the need for the attached thread state.
I forget why I didn't look harder at the PyMem_Raw* methods - perhaps it was long enough ago that the free-threading case wasn't relevant, and I didn't see much advantage adding indirection over the system allocator.
Overall this seems like a good idea as an opt-in feature 👍
@anuraaga сan you share ur benchmark code? I mean, did you run benchmarks comparing default alloc, mimalloc, snmalloc, and PyMemRawAllocator? Or any others?
Overall this seems like a good idea as an opt-in feature 👍
To be clear, we wouldn't declare the global allocator, that's up to the user. We simply create a struct and implement GlobalAllocator for it by forwarding calls to PyMem_Raw*.
I got around 20% improvement across several runs using PyMemRawAllocator. Note that this is not a allocation-heavy test case, our code essentially only allocates a power-of-2 output buffer in Rust. More threads or more allocation-heavy code will benefit more I think.
I checked our other benches both with and without free-threaded to see no change, expected since the extra indirection is tiny.
I didn't check mimalloc / snmalloc in Rust since my main objective was to take advantage of what Python is providing. I'm sure it would be interesting though when upstreaming here as a reference point though.
@chirizxc BTW in case you used 3.14 etc, you will need to use python 3.15 rc to get the mimalloc backend for PyMem_Raw*, the improvement I found of 20% with Python 3.15 looks quite similar to your mimalloc number there.
Thanks @ngoldbaum - I couldn't find any indication the recent changes to have PyMem_Raw use mimalloc (not pymem_alloc) were backported to 3.14 (at least on the 3.14t I tried, there was no change in performance from using PyMem_Raw in my benchmark)
mimalloc was only used for the object allocator on 3.14 on free-threading, the change to use mimalloc for raw allocator is 3.15 only. See python/cpython#144914
I was chatting with @emmatyping about this and she brought up that there may be soundness issues around panic-unwinding. I thought about this today and came up with the following scenario, which doesn't require unwinding at all. However if you install the raw allocator as the global allocator, then this sort of allocation can happen in a Drop implementation, for example, and this becomes a process hang during panic unwinding.
Add this to pymem_alloc.rs on top of #6279 and then cargo test --lib should deadlock on this test.
I think the summary is that if your code never spawns threads or detaches, like a JSON marshaler, the allocations all happen under the GIL and there is no chance of issues. If you do, then tracemalloc can introduce possible issues including deadlock depending on what the code does.
importctypesimportsysimportthreadingimporttracemallocifnotsys.platform.startswith("linux"):
msg="This MRE requires Linux"raiseRuntimeError(msg)
pythonapi=ctypes.pythonapipythonapi.PyMem_RawMalloc.restype=ctypes.c_void_ppythonapi.PyMem_RawMalloc.argtypes= [ctypes.c_size_t]
pythonapi.PyMem_RawFree.argtypes= [ctypes.c_void_p]
# this is only needed to creat a native thread# without a `PyThreadState` attached to itlibc_cdll=ctypes.CDLL(None)
libc_cdll.pthread_create.restype=ctypes.c_intlibc_cdll.usleep.argtypes= [ctypes.c_uint]
# unlike CDLL, PyDLL does NOT release the GIL around the call# this is intentional, so that the main thread holds the GIL for# the full 5 seconds creating conditions under which the raw-allocator# hook cannot acquire the GIL, even if it were to request itblocking_libc=ctypes.PyDLL(None)
blocking_libc.sleep.argtypes= [ctypes.c_uint]
THREAD_FN=ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p)
done=threading.Event()
@THREAD_FNdefnative_thread_entry(_arg: ctypes.c_void_p) ->ctypes.c_void_p:
# this thread was created using `pthread_create()`, not# `threading.Thread` it does NOT have an associated `PyThreadState`libc_cdll.usleep(500_000)
# according to the `PyMem_SetAllocator` contract for `PYMEM_DOMAIN_RAW`# ("a thread state is not attached when the allocator is called"),# the call below MUST execute without blocking on the GILptr=pythonapi.PyMem_RawMalloc(64)
pythonapi.PyMem_RawFree(ptr)
# if the allocator internally calls `PyGILState_Ensure()`,# then this code will never reach this point while the GIL is busydone.set()
defmain() ->None:
# tracemalloc.start() sets a hook on `PYMEM_DOMAIN_RAW`tracemalloc.start()
thread_id=ctypes.c_ulong()
libc_cdll.pthread_create(ctypes.byref(thread_id), None, native_thread_entry, None)
# The main thread holds the GIL continuously for 5 seconds (`PyDLL.sleep` does not# release the GIL). If the raw-allocator hook requires the GIL, a deadlock occursblocking_libc.sleep(5)
# deadlockprint("DEADLOCK"ifnotdone.is_set() else"OK")
main()
Per documented contract, PyMem_RawMalloc / RawFree must be callable safely
from a thread with no attached thread state, regardless of tracemalloc
state, and must not require GIL acquisition to complete
@chirizxc note that in my example with a deadlock, there's already an attached thread state. So it's not, technically, violating the contract that one doesn't need an attached thread state.
I agree though that this is probably a CPython bug. Would you like to open an upstream issue?
Rather than using ctypes though it's better if you report issues like this using a small C extension. The triagers and core devs will probably look at that less askance than ctypes hacks, even if they are doing exactly the same thing.
Hi, coming from the CPython issue. I'm not so sure this is a bug on our end. The contract says that the caller doesn't hold an attached thread state for PYMEM_DOMAIN_RAW. It says nothing about what the callback can do. Where is this causing deadlocks in practice?
Nowhere yet but it could perhaps preclude PyO3 from including this functionality because of the deadlock risk. It may also be OK to simply document it.
And maybe also with some note in the docs that it's provisional and experimental as we shake out issues like the tracemalloc problem we ran into?
I also think if someone wanted to spend some time figuring out and documenting how to wrap mimalloc, tcmalloc, or jemalloc in a crate using PyO3, that would be even nicer.
Activity
davidhewitt commentedon Jul 31, 2026
I remember looking into this area previously and concluding (at the time) that
PyMem_Mallocwas not suitable for building a global allocator due to the need for the attached thread state.I forget why I didn't look harder at the
PyMem_Raw*methods - perhaps it was long enough ago that the free-threading case wasn't relevant, and I didn't see much advantage adding indirection over the system allocator.Overall this seems like a good idea as an opt-in feature 👍
chirizxc commentedon Jul 31, 2026
@anuraaga сan you share ur benchmark code? I mean, did you run benchmarks comparing
default alloc,mimalloc,snmalloc, andPyMemRawAllocator? Or any others?mejrs commentedon Jul 31, 2026
To be clear, we wouldn't declare the global allocator, that's up to the user. We simply create a struct and implement
GlobalAllocatorfor it by forwarding calls toPyMem_Raw*.So a feature is not necessary.
anuraaga commentedon Aug 3, 2026
Thanks for the help on this @chirizxc - I only did limited benchmarking in downstream code
https://github.com/bufbuild/protobuf-py/blob/main/packages/bench/tests/test_bench.py#L209
I got around 20% improvement across several runs using
PyMemRawAllocator. Note that this is not a allocation-heavy test case, our code essentially only allocates a power-of-2 output buffer in Rust. More threads or more allocation-heavy code will benefit more I think.I checked our other benches both with and without free-threaded to see no change, expected since the extra indirection is tiny.
I didn't check
mimalloc/snmallocin Rust since my main objective was to take advantage of what Python is providing. I'm sure it would be interesting though when upstreaming here as a reference point though.ngoldbaum commentedon Aug 7, 2026
mimalloc also scales better under multithreaded use, see section 5: https://labs.quansight.org/blog/scaling-numpy-on-free-threaded-python.
Ping @kumaraditya303, since he did the work to make the raw allocators in CPython use mimalloc on the free-threaded build.
chirizxc commentedon Aug 7, 2026
Also, based on my mini benchmarks at toml-rs, I get roughly the following results:
anuraaga commentedon Aug 10, 2026
@chirizxc BTW in case you used 3.14 etc, you will need to use python 3.15 rc to get the mimalloc backend for PyMem_Raw*, the improvement I found of 20% with Python 3.15 looks quite similar to your mimalloc number there.
ngoldbaum commentedon Aug 10, 2026
Free-threaded 3.14 uses mimalloc as well: https://docs.python.org/3/howto/free-threading-python.html#mimalloc-allocator-vs-pymalloc
anuraaga commentedon Aug 10, 2026
Thanks @ngoldbaum - I couldn't find any indication the recent changes to have
PyMem_Rawuse mimalloc (not pymem_alloc) were backported to 3.14 (at least on the 3.14t I tried, there was no change in performance from usingPyMem_Rawin my benchmark)davidhewitt commentedon Aug 10, 2026
https://docs.python.org/3.14/c-api/memory.html#default-memory-allocators seems to suggest mimalloc is indeed used for free threaded 3.14 for all allocator domains.
kumaraditya303 commentedon Aug 10, 2026
mimalloc was only used for the object allocator on 3.14 on free-threading, the change to use mimalloc for raw allocator is 3.15 only. See python/cpython#144914
chirizxc commentedon Aug 10, 2026
Chat GPT table:
ngoldbaum commentedon Aug 10, 2026
Thanks for clarifying Kumar!
ngoldbaum commentedon Aug 12, 2026
I was chatting with @emmatyping about this and she brought up that there may be soundness issues around panic-unwinding. I thought about this today and came up with the following scenario, which doesn't require unwinding at all. However if you install the raw allocator as the global allocator, then this sort of allocation can happen in a
Dropimplementation, for example, and this becomes a process hang during panic unwinding.Add this to
pymem_alloc.rson top of #6279 and thencargo test --libshould deadlock on this test.Maybe tracemalloc shouldn't use blocking calls for instrumenting the raw domain? But that's how it works right now, with a
PyGilState_Ensure.anuraaga commentedon Aug 13, 2026
Thanks @ngoldbaum - we have been trying to word out some docs on this topic
#6279 (comment)
I think the summary is that if your code never spawns threads or detaches, like a JSON marshaler, the allocations all happen under the GIL and there is no chance of issues. If you do, then tracemalloc can introduce possible issues including deadlock depending on what the code does.
chirizxc commentedon Aug 13, 2026
Maybe bug (maybe it's just a matter of updating the documentation)
To be honest, I think this is a CPython bug
tracemalloc's raw-domain allocator hook requires an attached thread
state (
PyGILState_Ensure():tracemalloc_alloc/tracemalloc_realloc) , which violates the documented PYMEM_DOMAIN_RAW contract:https://docs.python.org/3.15/c-api/memory.html#allocator-domains
https://docs.python.org/3.15/c-api/memory.html#raw-memory-interface
https://docs.python.org/3.15/c-api/memory.html#raw-memory-interface:~:text=PyMem%5FSetAllocator%28%29%20does%20have%20the%20following%20contract
MRE
Per documented contract,
PyMem_RawMalloc/RawFreemust be callable safelyfrom a thread with no attached thread state, regardless of tracemalloc
state, and must not require GIL acquisition to complete
ngoldbaum commentedon Aug 13, 2026
@chirizxc note that in my example with a deadlock, there's already an attached thread state. So it's not, technically, violating the contract that one doesn't need an attached thread state.
I agree though that this is probably a CPython bug. Would you like to open an upstream issue?
Rather than using ctypes though it's better if you report issues like this using a small C extension. The triagers and core devs will probably look at that less askance than ctypes hacks, even if they are doing exactly the same thing.
ZeroIntensity commentedon Aug 13, 2026
Hi, coming from the CPython issue. I'm not so sure this is a bug on our end. The contract says that the caller doesn't hold an attached thread state for
PYMEM_DOMAIN_RAW. It says nothing about what the callback can do. Where is this causing deadlocks in practice?ngoldbaum commentedon Aug 13, 2026
Nowhere yet but it could perhaps preclude PyO3 from including this functionality because of the deadlock risk. It may also be OK to simply document it.
chirizxc commentedon Aug 31, 2026
python/cpython#155725 (comment)
Should the new GlobalAlloc be
#[cfg(Py_3_15)]?ngoldbaum commentedon Sep 2, 2026
And maybe also with some note in the docs that it's provisional and experimental as we shake out issues like the
tracemallocproblem we ran into?I also think if someone wanted to spend some time figuring out and documenting how to wrap mimalloc, tcmalloc, or jemalloc in a crate using PyO3, that would be even nicer.