Title: `functools.lru_cache` critical section locks `self` but `_LockHeld` dict APIs assert `self->cache` is locked · Issue #148180 · python/cpython · GitHub
Open Graph Title: `functools.lru_cache` critical section locks `self` but `_LockHeld` dict APIs assert `self->cache` is locked · Issue #148180 · python/cpython
X Title: `functools.lru_cache` critical section locks `self` but `_LockHeld` dict APIs assert `self->cache` is locked · Issue #148180 · python/cpython
Description: Crash report What happened? On a debug free-threaded build, functools.lru_cache crashes with a critical section assertion failure when gc.get_objects() is called between cache uses. bounded_lru_cache_wrapper (line 1498) acquires Py_BEGIN...
Open Graph Description: Crash report What happened? On a debug free-threaded build, functools.lru_cache crashes with a critical section assertion failure when gc.get_objects() is called between cache uses. bounded_lru_cac...
X Description: Crash report What happened? On a debug free-threaded build, functools.lru_cache crashes with a critical section assertion failure when gc.get_objects() is called between cache uses. bounded_lru_cac...
Opengraph URL: https://github.com/python/cpython/issues/148180
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"`functools.lru_cache` critical section locks `self` but `_LockHeld` dict APIs assert `self->cache` is locked","articleBody":"# Crash report\n\n### What happened?\n\n\nOn a debug free-threaded build, `functools.lru_cache` crashes with a critical section assertion failure when `gc.get_objects()` is called between cache uses.\n\n`bounded_lru_cache_wrapper` (line 1498) acquires `Py_BEGIN_CRITICAL_SECTION(self)`, locking the lru_cache object's mutex. It then calls `bounded_lru_cache_get_lock_held` (line 1325) which calls `_PyDict_GetItemRef_KnownHash_LockHeld` on `self->cache`. The `_LockHeld` variant asserts that the **dict's** per-object mutex is held (`_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(mp)` at `dictobject.c:1254`), but only `self`'s mutex is held — `self` and `self->cache` have different mutexes.\n\nIn 3.15 we have this abort message:\n```\nAssertion \"(cs != ((void*)0) && cs->_cs_mutex == mutex)\" failed: Critical section of object is not held\n```\n\nThis was introduced in gh-131757 (PR #131758), which split the critical section to allow the cached function to execute concurrently. The same pattern was extended in gh-132641 (PR #133787) which added more `_LockHeld` calls following the same assumption.\n\nOn non-debug builds the assertion is compiled out and the code happens to work in practice (no actual contention in the reproducer), but the lock contract is violated.\n\n### Reproducer\n\nRequires a debug free-threaded build (e.g., `--with-pydebug --disable-gil`).\n\n```python\nfrom functools import lru_cache\nimport gc\n\n@lru_cache(maxsize=32)\ndef get_pep(num):\n return type('', (), {})()\n\nfor n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:\n pep = get_pep(n)\n print(n, pep)\n\nobjs = gc.get_objects()\nprint(dir(get_pep))\n\nfor n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:\n pep = get_pep(n)\n print(n, pep)\n```\n\n\nBacktrace on 3.14 (trimmed):\n```\npython: ./Include/internal/pycore_critical_section.h:226: void _PyCriticalSection_AssertHeld(PyMutex *): Assertion `cs != NULL && cs->_cs_mutex == mutex' failed.\n[...]\n#5 _PyCriticalSection_AssertHeld (mutex=...) at pycore_critical_section.h:226\n#6 _Py_dict_lookup (mp=...) at Objects/dictobject.c:1254\n#7 _PyDict_GetItemRef_KnownHash_LockHeld (...) at Objects/dictobject.c:2420\n#8 bounded_lru_cache_get_lock_held (...) at Modules/_functoolsmodule.c:1325\n#9 bounded_lru_cache_wrapper (...) at Modules/_functoolsmodule.c:1499\n```\n\nBacktrace on 3.15:\n```\n./Include/internal/pycore_critical_section.h:249: _PyCriticalSection_AssertHeldObj: Assertion \"(cs != ((void*)0) && cs->_cs_mutex == mutex)\" failed: Critical section of object is not held\nEnable tracemalloc to get the memory block allocation traceback\n\nobject address : 0x7bffb670ccd0\nobject refcount : 2\nobject type : 0x555556749840\nobject type name: dict\nobject repr : {8: \u003cfunctools._lru_list_elem object at 0x7bffb65701d0>, 290: \u003cfunctools._lru_list_elem object at 0x7bffb6570240>, 308: \u003cfunctools._lru_list_elem object at 0x7bffb65702b0>, 320: \u003cfunctools._lru_list_elem object at 0x7bffb6570320>, 218: \u003cfunctools._lru_list_elem object at 0x7bffb6570390>, 279: \u003cfunctools._lru_list_elem object at 0x7bffb6570400>, 289: \u003cfunctools._lru_list_elem object at 0x7bffb6570470>, 9991: \u003cfunctools._lru_list_elem object at 0x7bffb65704e0>}\n\nFatal Python error: _PyObject_AssertFailed: _PyObject_AssertFailed\nPython runtime state: initialized\n\nStack (most recent call first):\n File \"/home/danzin/crashers/yifei_01.py\", line 15 in \u003cmodule>\n\nProgram received signal SIGABRT, Aborted.\nDownload failed: Invalid argument. Continuing without source file ./nptl/./nptl/pthread_kill.c.\n__pthread_kill_implementation (threadid=\u003coptimized out>, signo=6, no_tid=0) at ./nptl/pthread_kill.c:44\nwarning: 44 ./nptl/pthread_kill.c: No such file or directory\n(gdb) bt\n#0 __pthread_kill_implementation (threadid=\u003coptimized out>, signo=6, no_tid=0) at ./nptl/pthread_kill.c:44\n#1 __pthread_kill_internal (threadid=\u003coptimized out>, signo=6) at ./nptl/pthread_kill.c:89\n#2 __GI___pthread_kill (threadid=\u003coptimized out>, signo=signo@entry=6) at ./nptl/pthread_kill.c:100\n#3 0x00007ffff7c45e2e in __GI_raise (sig=sig@entry=6) at ../sysdeps/posix/raise.c:26\n#4 0x00007ffff7c28888 in __GI_abort () at ./stdlib/abort.c:77\n#5 0x000055555606dd54 in fatal_error_exit (status=status@entry=-1) at Python/pylifecycle.c:3389\n#6 0x000055555606da1b in fatal_error (fd=fd@entry=2, header=header@entry=1, prefix=prefix@entry=0x555556405360 \u003c__func__._PyObject_AssertFailed> \"_PyObject_AssertFailed\",\n msg=msg@entry=0x555556405360 \u003c__func__._PyObject_AssertFailed> \"_PyObject_AssertFailed\", status=status@entry=-1) at Python/pylifecycle.c:3612\n#7 0x0000555556069730 in _Py_FatalErrorFunc (func=0x555556405360 \u003c__func__._PyObject_AssertFailed> \"_PyObject_AssertFailed\",\n msg=0x555556405360 \u003c__func__._PyObject_AssertFailed> \"_PyObject_AssertFailed\") at Python/pylifecycle.c:3635\n#8 0x00005555557fc43b in _PyObject_AssertFailed (obj=obj@entry=0x7bffb670ccd0, expr=\u003coptimized out>, msg=\u003coptimized out>, file=\u003coptimized out>, line=line@entry=249,\n function=\u003coptimized out>) at Objects/object.c:3259\n#9 0x0000555555bb7711 in _PyCriticalSection_AssertHeldObj (op=0x7bffb670ccd0) at ./Include/internal/pycore_critical_section.h:247\n#10 _Py_dict_lookup (mp=0x7bffb670ccd0, key=key@entry=0x55555693c4f8 \u003c_PyRuntime+30776>, hash=hash@entry=8, value_addr=value_addr@entry=0x7fffffff9d00) at Objects/dictobject.c:1305\n#11 0x0000555555bbbc61 in _PyDict_GetItemRef_KnownHash_LockHeld (op=0x196f39, key=0x196f39, key@entry=0x55555693c4f8 \u003c_PyRuntime+30776>, hash=6, hash@entry=8,\n result=result@entry=0x7fffffff9e80) at Objects/dictobject.c:2480\n#12 0x00005555562ed221 in bounded_lru_cache_get_lock_held (self=0x7bffb6826c90, args=0x7bffb69bb290, kwds=0x0, result=\u003coptimized out>, key=\u003coptimized out>, hash=\u003coptimized out>)\n at ./Modules/_functoolsmodule.c:1416\n#13 bounded_lru_cache_wrapper (self=0x7bffb6826c90, args=0x7bffb69bb290, kwds=0x0) at ./Modules/_functoolsmodule.c:1590\n#14 0x0000555555ac6b5d in _PyObject_MakeTpCall (tstate=0x555556997d60 \u003c_PyRuntime+405664>, callable=0x7bffb6826c90, args=0x7fffffffa048, nargs=1, keywords=0x0) at Objects/call.c:242\n#15 0x0000555555ea9e3b in _Py_VectorCallInstrumentation_StackRefSteal (callable=..., arguments=arguments@entry=0x7e8ff6fe0290, total_args=total_args@entry=1, kwnames=kwnames@entry=...,\n call_instrumentation=false, frame=frame@entry=0x7e8ff6fe0220, this_instr=0x7bffb6405394, tstate=0x555556997d60 \u003c_PyRuntime+405664>) at Python/ceval.c:775\n#16 0x0000555555ee754d in _PyEval_EvalFrameDefault (tstate=\u003coptimized out>, frame=\u003coptimized out>, throwflag=\u003coptimized out>) at Python/generated_cases.c.h:1841\n#17 0x0000555555ea8d04 in _PyEval_EvalFrame (tstate=0x555556997d60 \u003c_PyRuntime+405664>, frame=0x7e8ff6fe0220, throwflag=0) at ./Include/internal/pycore_ceval.h:118\n#18 _PyEval_Vector (tstate=tstate@entry=0x555556997d60 \u003c_PyRuntime+405664>, func=func@entry=0x7bffb64c3e30, locals=locals@entry=0x7bffb670ca90, args=args@entry=0x0,\n argcount=argcount@entry=0, kwnames=kwnames@entry=0x0) at Python/ceval.c:2179\n#19 0x0000555555ea80db in PyEval_EvalCode (co=co@entry=0x7bffb6405210, globals=globals@entry=0x7bffb670ca90, locals=locals@entry=0x7bffb670ca90) at Python/ceval.c:686\n#20 0x00005555560c6ca0 in run_eval_code_obj (tstate=tstate@entry=0x555556997d60 \u003c_PyRuntime+405664>, co=co@entry=0x7bffb6405210, globals=0x7bffb670ca90, locals=locals@entry=0x7bffb670ca90)\n at Python/pythonrun.c:1369\n```\n\n\n### Possible fix\n\nEither lock both objects:\n```c\n// Line 1498, 1511: lock both self and self->cache\nPy_BEGIN_CRITICAL_SECTION2(self, self->cache);\n```\n\nOr use the regular (self-locking) dict APIs instead of `_LockHeld` variants for the get path.\n\nThe initial crash and reproducer were found by @zhuyifei1999. Root cause analysis and issue draft done with assistance from Claude Code.\n\n\n### CPython versions tested on:\n\n3.15, CPython main branch, 3.14\n\n### Operating systems tested on:\n\nLinux\n\n### Output from running 'python -VV' on the command line:\n\nPython 3.15.0a7+ free-threading build (heads/main:4d0e8ee649c, Mar 29 2026, 23:20:29) [Clang 21.1.2 (2ubuntu6)]","author":{"url":"https://github.com/devdanzin","@type":"Person","name":"devdanzin"},"datePublished":"2026-04-06T17:06:19Z","url":"https://github.com/python/cpython/issues/148180"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:44fec397-aeb7-890d-cd4c-0e4d5ef0b78d |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | D7C6:20AA01:4B03896:5EF91BA:6B023F32 |
| html-safe-nonce | 685c234f66fb984f1c361d65291eaeced0b100273c4611e6fb2b8358811c7f7a |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJEN0M2OjIwQUEwMTo0QjAzODk2OjVFRjkxQkE6NkIwMjNGMzIiLCJ2aXNpdG9yX2lkIjoiNzgyODIyMjczNjU1NTE5NjIxMCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 275d84ce03d7181f18b68b430f2cdbc6494661cae1dfd3efb185dcaa5c3790d1 |
| hovercard-subject-tag | issue:4212959178 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/cpython/148180/issue_layout |
| twitter:image | https://opengraph.githubassets.com/119d06991b2a99e711047d0bf71024386042b582b8b40376c5741ee28f71874c/python/cpython/issues/148180 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/119d06991b2a99e711047d0bf71024386042b582b8b40376c5741ee28f71874c/python/cpython/issues/148180 |
| og:image:alt | Crash report What happened? On a debug free-threaded build, functools.lru_cache crashes with a critical section assertion failure when gc.get_objects() is called between cache uses. bounded_lru_cac... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | devdanzin |
| hostname | github.com |
| expected-hostname | github.com |
| None | 87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456 |
| turbo-cache-control | no-preview |
| go-import | github.com/python/cpython git https://github.com/python/cpython.git |
| octolytics-dimension-user_id | 1525981 |
| octolytics-dimension-user_login | python |
| octolytics-dimension-repository_id | 81598961 |
| octolytics-dimension-repository_nwo | python/cpython |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 81598961 |
| octolytics-dimension-repository_network_root_nwo | python/cpython |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 423dbb54c5e7bfecc838eb387c1435eb3d0e760d |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width