Skip to content

gh-162822: Fix bytearray(list) race in the free-threaded build - #162826

Closed
JakeHuneau wants to merge 2 commits into
python:mainfrom
JakeHuneau:gh-162822-bytearray-list-race
Closed

JakeHuneau wants to merge 2 commits into
python:mainfrom
JakeHuneau:gh-162822-bytearray-list-race

Conversation

@JakeHuneau

@JakeHuneau JakeHuneau commented Nov 29, 2026 •

Copy link
Copy Markdown

In the free-threaded build, bytearray.__init__() read the items of an exact list through PySequence_Fast_ITEMS() without holding the list's lock. Another thread could replace and free an item while _getbytevalue() was converting it.

The fast path now runs under Py_BEGIN_CRITICAL_SECTION_SEQUENCE_FAST, the same way bytes(list) does (_PyBytes_FromSequence_lock_held). It moved into a helper so that falling back to the iterator path doesn't jump out of the critical section. Items that are exact ints don't run Python code, so nothing runs while the lock is held.

The new test in test_free_threading.test_bytes_object crashed in PyLong_AsLongAndOverflow in 4 of 5 runs on a --disable-gil --with-address-sanitizer build without the fix. With the fix it passed 10 of 10 runs, and test_bytes passes.

bytearray.__init__() read the items of an exact list through
PySequence_Fast_ITEMS() without holding the list's lock, so another
thread could replace and free an item while it was being converted.

Run the fast path under Py_BEGIN_CRITICAL_SECTION_SEQUENCE_FAST, as
bytes(list) already does.
@python-cla-bot

python-cla-bot Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

Comment thread Objects/bytearrayobject.c Resolved
Co-authored-by: sobolevn <mail@sobolevn.me>
@shashankrxj

Copy link
Copy Markdown

Thanks for working on this fix. I reported issue #162822 and have been investigating it as well. I noticed that when the helper returns 1 for a non-exact integer, the code releases the list’s critical section and then continues into the old fast-path loop, which reads the list items without the lock. Could that case go directly to slowpath after the critical section? My patch handles this by falling back to the iterator path immediately after unlocking.

@picnixz

picnixz commented Nov 29, 2026

Copy link
Copy Markdown
Member

The OP eventually opened a PR for it #162839 and I'd like to prioritize their work as they were also the reporter.

@picnixz picnixz closed this Nov 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants