Skip to content

gh-158336: Fix race in lock_tests test_set_and_clear - #158337

Merged
vstinner merged 4 commits into
python:mainfrom
matthiasgoergens:fix-test-set-and-clear-flake
Nov 9, 2026
Merged

vstinner merged 4 commits into
python:mainfrom
matthiasgoergens:fix-test-set-and-clear-flake

Conversation

@matthiasgoergens

@matthiasgoergens matthiasgoergens commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Instead of sleeping for 50 ms, wait until all five threads are registered as waiters on the event's condition before calling set() and clear(). Condition.wait() appends the waiter to _waiters while holding the lock, and notify_all() wakes every waiter in that list, so set() then wakes all of them.

With the reproducer from the issue, the test failed in 0 of 40 runs, against 9 of 40 before. The test still catches gh-57711 about as often as before: with Event.wait() changed back to return the flag after waking, it failed in 8 of 20 runs, against 7 of 20 without this change.

The other callers of wait_threads_blocked() are not affected, because a thread that arrives late still finds the lock released, the semaphore available or the event set.

This PR was prepared with the help of an AI assistant (Claude Code) and reviewed by me.

test_set_and_clear started N threads calling event.wait() and then slept
50 ms (wait_threads_blocked) before calling event.set() and event.clear().
If a thread only reached wait() after clear(), it saw the flag unset and
blocked for LONG_TIMEOUT, and Bunch.__exit__ gave up after SHORT_TIMEOUT.
This happened on CI in the TSan free-threading job.

Wait until all N threads are in the Condition's waiter list instead.
Condition.wait() appends the waiter while holding the lock, and
notify_all() releases every waiter in the list, so each of those threads
is guaranteed to be woken by set().

On a TSan free-threading debug build, pinned to 2 CPUs shared with 4
busy-looping processes, the test failed in 9 of 40 runs before this
change and 0 of 40 after.

@vstinner vstinner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I hate wait_threads_blocked() sleep, it's a bad synchronization primitive!

Comment thread Lib/test/lock_tests.py Resolved
Comment thread Lib/test/lock_tests.py
# and clear() would block until the timeout, so a fixed sleep
# is not enough on a busy machine.
for _ in support.sleeping_retry(support.SHORT_TIMEOUT):
if len(event._cond._waiters) >= N:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If possible, I would prefer to avoid accessing private attributes.

Can you try instead to test if len(results) >= N: break?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO, test might be something like below:

    def test_set_and_clear(self):
        # gh-57711: check that wait() returns true even when the event is
        # cleared before the waiting thread is woken up.
        event = self.eventtype()
        N = 5
        ready = []
        results = []
        def f():
            ready.append(True)
            results.append(event.wait(support.LONG_TIMEOUT))

        with Bunch(f, N):
            # Threads blocked on event.wait()
            for _ in support.sleeping_retry(support.SHORT_TIMEOUT):
                if len(ready) >= N:
                    break

            # Threads unblocked
            event.set()
            for _ in support.sleeping_retry(support.SHORT_TIMEOUT):
                if len(results) >= N:
                    break
            event.clear()

        self.assertEqual(results, [True] * N)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

with Bunch(...): already waits until all started threads complete. Is it really needed to wait until len(results) >= N before calling event.clear()?

The test description says:

check that wait() returns true even when the event is cleared before the waiting thread is woken up.

Waiting for theads between set() and clear() seems to go against the test description.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right. The assertEqual will fail if there is a missing value or a false value So we can remove the last support.sleeping_retry that tests the results.

@YvesDup YvesDup Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If possible, I would prefer to avoid accessing private attributes.

Is it acceptable to check from the representation string of Condition ? The last value is the number of waiting threads.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If my suggested if len(results) >= N: break test works, there is no need to query Condition internals.

@YvesDup YvesDup Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When entering in the Bunch block, run your suggestion if len(results) >= N: break test hangs.
The results list is only updated when we quit the wait method in each thread, that is triggered from the call to the setmethod of Event in the main thread, later.
Query Condition internals seems necessary and the only way to proceed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vstinner , sorry to bother you, but the test_set_and_clear test still fails in CI. Could we fix this, please? The OP’s suggestion seems to me to be the only valid one.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the reminder, I forgot about this change. So using only public attributes doesn't work, ok. So I just added @support.cpython_only marker on the test.

@YvesDup

YvesDup commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

@vstinner I suggest opening a PR to replace all wait_threads_blocked calls in the /Lib/test/lock_tests.py test file.

@vstinner

vstinner commented Oct 5, 2026

Copy link
Copy Markdown
Member

@vstinner I suggest opening a PR to replace all wait_threads_blocked calls in the /Lib/test/lock_tests.py test file.

Well. Let's start by fixing this test :-)

Comment thread Lib/test/lock_tests.py Resolved

@vstinner vstinner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@vstinner

vstinner commented Nov 9, 2026

Copy link
Copy Markdown
Member

Ah, there is now a conflict, a new test_nan_timeout() method was added in the meanwhile. I solved the merge confict.

@vstinner
vstinner enabled auto-merge (squash) November 9, 2026 15:21
@vstinner vstinner added needs backport to 3.14 bugs and security fixes needs backport to 3.15 bugs and security fixes labels Nov 9, 2026
@vstinner
vstinner merged commit 9e22078 into python:main Nov 9, 2026
54 checks passed
@miss-islington-app

Copy link
Copy Markdown

Thanks @matthiasgoergens for the PR, and @vstinner for merging it 🌮🎉.. I'm working now to backport this PR to: 3.14, 3.15.
🐍🍒⛏🤖

@bedevere-app

bedevere-app Bot commented Nov 9, 2026

Copy link
Copy Markdown

GH-161682 is a backport of this pull request to the 3.15 branch.

@bedevere-app bedevere-app Bot removed the needs backport to 3.15 bugs and security fixes label Nov 9, 2026
@bedevere-app

bedevere-app Bot commented Nov 9, 2026

Copy link
Copy Markdown

GH-161683 is a backport of this pull request to the 3.14 branch.

@bedevere-app bedevere-app Bot removed the needs backport to 3.14 bugs and security fixes label Nov 9, 2026
@vstinner

vstinner commented Nov 9, 2026

Copy link
Copy Markdown
Member

Merged. Thanks for the fix. I marked the test as @support.cpython_only since it uses private attributes.

vstinner added a commit that referenced this pull request Nov 9, 2026
… (#161683)

gh-158336: Fix race in lock_tests test_set_and_clear (GH-158337)

test_set_and_clear() started N threads calling event.wait() and then slept
50 ms (wait_threads_blocked) before calling event.set() and event.clear().
If a thread only reached wait() after clear(), it saw the flag unset and
blocked for LONG_TIMEOUT, and Bunch.__exit__ gave up after SHORT_TIMEOUT.
This happened on CI in the TSan free-threading job.

Wait until all N threads are in the Condition's waiter list instead.
Condition.wait() appends the waiter while holding the lock, and
notify_all() releases every waiter in the list, so each of those threads
is guaranteed to be woken by set().

On a TSan free-threading debug build, pinned to 2 CPUs shared with 4
busy-looping processes, the test failed in 9 of 40 runs before this
change and 0 of 40 after.
(cherry picked from commit 9e22078)

Co-authored-by: Matthias Görgens <matthias.goergens@gmail.com>
Co-authored-by: Victor Stinner <vstinner@python.org>
vstinner added a commit that referenced this pull request Nov 9, 2026
… (#161682)

gh-158336: Fix race in lock_tests test_set_and_clear (GH-158337)

test_set_and_clear() started N threads calling event.wait() and then slept
50 ms (wait_threads_blocked) before calling event.set() and event.clear().
If a thread only reached wait() after clear(), it saw the flag unset and
blocked for LONG_TIMEOUT, and Bunch.__exit__ gave up after SHORT_TIMEOUT.
This happened on CI in the TSan free-threading job.

Wait until all N threads are in the Condition's waiter list instead.
Condition.wait() appends the waiter while holding the lock, and
notify_all() releases every waiter in the list, so each of those threads
is guaranteed to be woken by set().

On a TSan free-threading debug build, pinned to 2 CPUs shared with 4
busy-looping processes, the test failed in 9 of 40 runs before this
change and 0 of 40 after.
(cherry picked from commit 9e22078)

Co-authored-by: Matthias Görgens <matthias.goergens@gmail.com>
Co-authored-by: Victor Stinner <vstinner@python.org>
@YvesDup

YvesDup commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

@vstinner I suggest opening a PR to replace all wait_threads_blocked calls in the /Lib/test/lock_tests.py test file.

Well. Let's start by fixing this test :-)

Is it worth removing all wait_threads_blocked, given that it isn’t causing any errors—at least for now?

@vstinner

Copy link
Copy Markdown
Member

Is it worth removing all wait_threads_blocked, given that it isn’t causing any errors—at least for now?

I would suggest opening a new issue if you plan to work on fixing other tests using wait_threads_blocked().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

skip news tests Tests in the Lib/test dir

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants