Title: Sharing `PySeqIter` across threads use-after-frees the sequence under free-threading · Issue #156310 · python/cpython · GitHub
Open Graph Title: Sharing `PySeqIter` across threads use-after-frees the sequence under free-threading · Issue #156310 · python/cpython
X Title: Sharing `PySeqIter` across threads use-after-frees the sequence under free-threading · Issue #156310 · python/cpython
Description: Crash report What happened? On a free-threaded build, advancing a single, shared iterator over a legacy sequence (a type implementing __getitem__/sq_item but not __iter__/tp_iter) from multiple threads use-after-frees the underlying sequ...
Open Graph Description: Crash report What happened? On a free-threaded build, advancing a single, shared iterator over a legacy sequence (a type implementing __getitem__/sq_item but not __iter__/tp_iter) from multiple thr...
X Description: Crash report What happened? On a free-threaded build, advancing a single, shared iterator over a legacy sequence (a type implementing __getitem__/sq_item but not __iter__/tp_iter) from multiple thr...
Opengraph URL: https://github.com/python/cpython/issues/156310
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Sharing `PySeqIter` across threads use-after-frees the sequence under free-threading","articleBody":"# Crash report\n\n### What happened?\n\nOn a free-threaded build, advancing a single, shared iterator over a legacy sequence (a type implementing `__getitem__`/`sq_item` but not `__iter__`/`tp_iter`) from multiple threads use-after-frees the underlying sequence object. \n\nThe defect is in the fallback iterator itself, so it affects pure-Python classes and C extension types alike. `list` (whose `list_iterator` was hardened for free-threading in https://github.com/python/cpython/pull/115605) is clean.\n\n`iter_iternext()` in `Objects/iterobject.c` has no synchronization:\n \nhttps://github.com/python/cpython/blob/9cbd578e38a5ef59f9462b61d1e03338b208cba6/Objects/iterobject.c#L52-L83\n\n\nThe iterator owns exactly one reference to `it_seq` and releases it exactly once, on exhaustion. With the GIL that invariant holds because only one thread is ever inside `tp_iternext`. Without the GIL:\n\n1. **Double DECREF on exhaustion.** Several threads read the same non-`NULL` `it->it_seq`, all observe out-of-bounds from `PySequence_GetItem`, and each executes the `Py_DECREF(seq)`. The single owned reference is released N times, so the sequence can be freed while other code is still holding refs to it.\n2. **Borrowed pointer outliving the object.** Thread A is inside `PySequence_GetItem(seq, ...)` (an arbitrarily long call) and thread B takes the exhaustion path and drops what may be the last reference. A then operates on freed memory.\n\n(There's also a data race for `index` that #115605 fixed for lists with atomic stores, but per #124397, that's acceptable.)\n\n`calliter_iternext` has the same defect: `it_callable`/`it_sentinel` are cleared with non-atomic `Py_CLEAR` on the exhaustion path and read without protection, so a shared `callable_iterator` can double-release and use-after-free them the same way.\n\nThere's prior art for this issue class in #154043, #154108, #154130 and the same fixes can be applied here.\n\n### Reproducer\n\n```python\nimport sys, threading\n\nTHREADS = 16\nROUNDS = 2000\n\n\nclass PySeq: # sq_item only -> iter() falls back to PySeqIter\n def __init__(self, n):\n self.n = n\n\n def __len__(self):\n return self.n\n\n def __getitem__(self, i):\n if i >= self.n:\n raise IndexError(i)\n return i\n\n\ndef drain(it, barrier):\n barrier.wait()\n while True:\n try:\n next(it)\n except StopIteration:\n return\n except Exception:\n return # torn it_index can walk off the end; benign\n\n\ndef hammer(make):\n for _ in range(ROUNDS):\n it = make()\n barrier = threading.Barrier(THREADS)\n ws = [\n threading.Thread(target=drain, args=(it, barrier))\n for _ in range(THREADS)\n ]\n for w in ws:\n w.start()\n for w in ws:\n w.join()\n del it\n\n\nseq = PySeq(4)\nprint(\"gil enabled:\", sys._is_gil_enabled())\nprint(\"iter type:\", type(iter(seq)).__name__)\nbefore = sys.getrefcount(seq)\nhammer(lambda: iter(seq))\nafter = sys.getrefcount(seq)\nprint(\n f\"before={before} after={after} -> {'CORRUPTED' if after != before else 'ok'}\"\n)\n```\n\n#### Observed results\n\nAll on macOS / arm64 (Apple Silicon):\n\n| Build | `PySeq` (`PySeqIter`) | `[0, 1, 2, 3]` (`list_iterator`) |\n| --- | --- | --- |\n| main (`3.16.0a0`, free-threading debug build) | SIGSEGV | clean, refcount ok |\n| 3.14.6 free-threaded | SIGSEGV (3/3 runs) | clean (3/3 runs) |\n| 3.13.8 free-threaded | SIGSEGV (3/3 runs) | not run |\n| 3.14.6 GIL-enabled | clean, refcount ok | clean |\n| 3.15.x free-threaded | refcount bad (on some runs; see below) | not run |\n\nDepending on allocator timing the failure may show up as refcount corruption, type confusion in\nunrelated code once the freed memory is reused, or as SIGSEGV, or nothing at all:\n\n```\n~/Desktop $ uv run --python=3.15t --isolated repro.py\ngil enabled: False\niter type: iterator\n~/Desktop $ uv run --python=3.15t --isolated repro.py\ngil enabled: False\niter type: iterator\nbefore=2 after=1152921504606846749 -> CORRUPTED\n```\n\n### CPython versions tested on:\n\nCPython main branch, 3.13, 3.14, 3.15\n\n### Operating systems tested on:\n\nmacOS\n\n### Output from running 'python -VV' on the command line:\n\nPython 3.16.0a0 free-threading build (heads/main:53d2e14a308, Aug 24 2026, 09:57:36) [Clang 17.0.0 (clang-1700.3.19.1)]\n\n\u003c!-- gh-linked-prs -->\n### Linked PRs\n* gh-156311\n* gh-162006\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/akx","@type":"Person","name":"akx"},"datePublished":"2026-08-24T08:20:09Z","url":"https://github.com/python/cpython/issues/156310"}
| 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:a321e447-efb7-a508-cb68-d5ecbf5b946f |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 804E:2A7C1C:18D575F:20CF09B:6B020F7D |
| html-safe-nonce | 73560e04259dc1003e20c46687f315f392eaf1a2f22a08d6dedd865f6b099596 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4MDRFOjJBN0MxQzoxOEQ1NzVGOjIwQ0YwOUI6NkIwMjBGN0QiLCJ2aXNpdG9yX2lkIjoiNDU3MDU4NTMzNDk3ODU4MDM0OSIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | b79862208c4e5b60d6f15e00ebcfbf3a3ec80accc72951b8c7ca2573f3bec32e |
| hovercard-subject-tag | issue:5232596127 |
| 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/156310/issue_layout |
| twitter:image | https://opengraph.githubassets.com/70d11b9244125d605e5b43ab4093eb571abd12a2433c5f23d66b05641fd73405/python/cpython/issues/156310 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/70d11b9244125d605e5b43ab4093eb571abd12a2433c5f23d66b05641fd73405/python/cpython/issues/156310 |
| og:image:alt | Crash report What happened? On a free-threaded build, advancing a single, shared iterator over a legacy sequence (a type implementing __getitem__/sq_item but not __iter__/tp_iter) from multiple thr... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | akx |
| 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