Title: `with lock`: can skip `__exit__` when a signal handler raises right after `__enter__` · Issue #148874 · python/cpython · GitHub
Open Graph Title: `with lock`: can skip `__exit__` when a signal handler raises right after `__enter__` · Issue #148874 · python/cpython
X Title: `with lock`: can skip `__exit__` when a signal handler raises right after `__enter__` · Issue #148874 · python/cpython
Description: Bug report A with X: statement can return without calling X.__exit__ when a Python signal handler raises between __enter__ returning and the body starting. This leaks whatever resource __enter__ acquired (e.g. a threading.Lock stays lock...
Open Graph Description: Bug report A with X: statement can return without calling X.__exit__ when a Python signal handler raises between __enter__ returning and the body starting. This leaks whatever resource __enter__ ac...
X Description: Bug report A with X: statement can return without calling X.__exit__ when a Python signal handler raises between __enter__ returning and the body starting. This leaks whatever resource __enter__ ac...
Opengraph URL: https://github.com/python/cpython/issues/148874
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"`with lock`: can skip `__exit__` when a signal handler raises right after `__enter__`","articleBody":"# Bug report\n\nA `with X:` statement can return without calling `X.__exit__` when a Python signal handler raises between `__enter__` returning and the body starting.\n\nThis leaks whatever resource `__enter__` acquired (e.g. a `threading.Lock` stays locked forever).\n\n### Cause\n\nIn 3.14, the following changed how `with X:` compiles:\n\n* GH-120507\n\nBefore 3.14:\n\n```\nLOAD X\nBEFORE_WITH # single op: calls enter, sets up exit on stack\nPOP_TOP # \u003c- exception table starts here\n... body ...\n```\n\n`BEFORE_WITH` has no periodic/eval-breaker check, so there was no window for a signal handler to fire between `__enter__` returning and the with-statement's exception handler being established.\n\nFrom 3.14 onward:\n```\nLOAD X\nCOPY 1\nLOAD_SPECIAL exit\nSWAP 2 / SWAP 3\nLOAD_SPECIAL enter\nCALL 0 # ends with _CHECK_PERIODIC_AT_END\nPOP_TOP # \u003c- exception table starts here\n... body ...\n```\n\n`CALL` includes _CHECK_PERIODIC_AT_END, which runs the Python signal handler. If that handler raises, `JUMP_TO_LABEL(error)` fires with `frame->instr_ptr` still pointing at `CALL` (set before the micro-ops run).\n\n### Reproducer (via Claude Code)\n\n\u003cdetails>\n\u003csummary>test_with_signal_leak.py\u003c/summary>\n\n```python\nimport ctypes, ctypes.util, signal, sys, threading\n\n# signal.pthread_kill / os.kill both call PyErr_CheckSignals after the syscall,\n# which perturbs timing enough to suppress the race. Use libc.pthread_kill\n# directly.\n_pthread_kill = ctypes.CDLL(ctypes.util.find_library(\"c\")).pthread_kill\n_pthread_kill.argtypes = [ctypes.c_ulong, ctypes.c_int]\n_pthread_kill.restype = ctypes.c_int\n\n_MAIN_TID = threading.get_ident()\n\ndef _handler(signum, frame):\n raise RuntimeError(\"signal\")\n\ndef _send():\n _pthread_kill(_MAIN_TID, signal.SIGUSR1)\n\ndef run_trial(lock, iterations=200):\n t = threading.Thread(target=_send)\n t.start()\n try:\n for _ in range(iterations):\n with lock:\n pass\n except BaseException:\n pass\n try:\n t.join()\n except BaseException:\n pass\n if lock.locked():\n lock.release()\n return True\n return False\n\nsignal.signal(signal.SIGUSR1, _handler)\nlock = threading.Lock()\nleaked = 0\nfor _ in range(2000):\n try:\n if run_trial(lock):\n leaked += 1\n except BaseException:\n if lock.locked():\n lock.release()\nprint(f\"leaked={leaked}/2000\")\n```\n\u003c/details>\n\ncc @markshannon \n\n\u003c!-- gh-linked-prs -->\n### Linked PRs\n* gh-149019\n* gh-150911\n* gh-154830\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/colesbury","@type":"Person","name":"colesbury"},"datePublished":"2026-04-22T14:33:01Z","url":"https://github.com/python/cpython/issues/148874"}
| 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:8e786f2d-01bb-9502-5117-ad514aafc406 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | D380:65478:3AF924C:4E2FE8F:6B021B79 |
| html-safe-nonce | 120f8f7da807176a5463a00b9138cebe78bd987a4fc26a5ccd37c34baf4016ba |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJEMzgwOjY1NDc4OjNBRjkyNEM6NEUyRkU4Rjo2QjAyMUI3OSIsInZpc2l0b3JfaWQiOiI4NjgwMzQ4NTM0NDU4OTQ4NDczIiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | bb3e63425c48ddff95a6ea14741b9cba400ae406647167bfc935938585b00418 |
| hovercard-subject-tag | issue:4309733651 |
| 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/148874/issue_layout |
| twitter:image | https://opengraph.githubassets.com/aa8021a50f7cbe27be5994d9685d7a4f5a82f63808b5189b0a1a628a24fdc757/python/cpython/issues/148874 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/aa8021a50f7cbe27be5994d9685d7a4f5a82f63808b5189b0a1a628a24fdc757/python/cpython/issues/148874 |
| og:image:alt | Bug report A with X: statement can return without calling X.__exit__ when a Python signal handler raises between __enter__ returning and the body starting. This leaks whatever resource __enter__ ac... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | colesbury |
| 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