Repository navigation
gh-162822: Fix bytearray(list) race in the free-threaded build - #162826
Open
JakeHuneau wants to merge 2 commits into
Open
JakeHuneau wants to merge 2 commits into
JakeHuneau wants to merge 2 commits into
Conversation
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.
sobolevn
reviewed
Nov 29, 2026
Co-authored-by: sobolevn <mail@sobolevn.me>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
In the free-threaded build,
bytearray.__init__()read the items of an exact list throughPySequence_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 waybytes(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_objectcrashed inPyLong_AsLongAndOverflowin 4 of 5 runs on a--disable-gil --with-address-sanitizerbuild without the fix. With the fix it passed 10 of 10 runs, andtest_bytespasses.