Skip to content

[mypyc] Stop list loops on free-threaded builds if the list shrinks concurrently - #22565

Open
Jahongir-Qurbonov wants to merge 2 commits into
python:masterfrom
Jahongir-Qurbonov:mypyc-ft-list-loop-shrink
Open

Jahongir-Qurbonov wants to merge 2 commits into
python:masterfrom
Jahongir-Qurbonov:mypyc-ft-list-loop-shrink

Conversation

@Jahongir-Qurbonov

Copy link
Copy Markdown
Contributor

On free-threaded builds, a for loop over a list checks the index against the current length of the list and then reads the item with CPyList_GetItemInt64. If another thread shrinks the list between these two steps, the read raises IndexError. The list iterator in CPython stops the iteration instead, so a loop like this could fail only when compiled.

Read the item using a new CPyList_GetItemOrNull helper on free-threaded builds, and stop the loop if the index is out of range. This also applies to reversed(), enumerate(), zip() and comprehensions over lists, since they all use ForSequence. Builds with the GIL are not affected, since nothing can change the list between the length check and the read there.

The new test in run-threading.test iterates over a list in a few ways while other threads add and remove items. It's a race, so it doesn't fail every time without the fix (it failed in 2 of 5 runs on a free-threaded 3.14 build on a busy machine), but it can't fail with the fix. I also ran a separate script that iterates over a list while another thread pops items: without the fix, hundreds of loops raised IndexError, and none did with the fix.

…oncurrently

On free-threaded builds, another thread could shrink a list between the
length check and the item read in a for loop, and the read then raised
IndexError. Stop the loop instead, like the list iterator.
On free-threaded builds, the list item is read as part of the loop
condition, so skipping the first condition check for a sequence with a
known non-zero length left the item uninitialized in the first iteration.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant