Skip to content

Commit e1cbca0

Browse files
Fix memory safety race condition in CPython 3.13 free-threaded mode
Add per-object locking via Py_BEGIN_CRITICAL_SECTION at all public-facing entry points in the C extension to prevent use-after-free crashes when iterating and mutating a MultiDict concurrently. The root cause is _md_resize() reallocating md->keys without any synchronization, causing concurrent iterators to access freed memory. This fix wraps all public methods in Py_BEGIN_CRITICAL_SECTION(self), matching CPython's own dict locking model. On GIL builds the macros are no-ops (via pythoncapi_compat.h). Adds tests/test_free_threading.py with a concurrent stress test that previously crashed with SIGSEGV and now completes cleanly.
1 parent 7667c9e commit e1cbca0

6 files changed

Lines changed: 557 additions & 146 deletions

File tree

CHANGES/1317.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fixed a memory-safety race condition resulting in segmentation faults (Use-After-Free) when iterating and modifying a ``MultiDict`` concurrently in CPython free-threaded mode (3.13t+). Read/Write accesses to the internal ``keys`` buffer are now wrapped in ``Py_BEGIN_CRITICAL_SECTION``.

0 commit comments

Comments
 (0)