Skip to content

test_asyncio test_to_thread_concurrent flaky #122957

Description

@colesbury

The call_count counter on mock.Mock is not atomic, so updates may be lost:

async def test_to_thread_concurrent(self):
func = mock.Mock()
futs = []
for _ in range(10):
fut = asyncio.to_thread(func)
futs.append(fut)
await asyncio.gather(*futs)
self.assertEqual(func.call_count, 10)

This leads to occasional errors like:

File "Lib/test/test_asyncio/test_threads.py", line 41, in test_to_thread_concurrent
self.assertEqual(func.call_count, 10)
~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^
AssertionError: 9 != 10

I think the update is not actually atomic even with the GIL because of the use of _delegating_property in Mock, but I'm not entirely sure. The failures are definitely more likely to occur in the free-threaded build.

Linked PRs

Activity

  1. kumaraditya303 commented on Aug 13, 2024

    @kumaraditya303
    Contributor

    I can't think of good way to fix this, maybe mock should be made atomic?

  2. colesbury commented on Aug 13, 2024

    @colesbury
    ContributorAuthor

    Seems easier to just use a regular function instead of a mock.Mock(). In other places, Python has for a long time used lists to count atomically. It's not clean, but it works:

            calls = []
            def func():
                calls.append(1)
    ...
    
            self.assertEqual(sum(calls), 10)
    
  3. lesteve commented on Sep 13, 2024

    @lesteve
    Contributor

    I was able to reproduce the failures locally with a free-threaded build so I opened #124039 with the recommended fix (using a list instead of a Mock).

  4. added a commit that references this issue on Sep 13, 2024
  5. moved this from Todo to Done in asyncioon Sep 13, 2024
  6. added a commit that references this issue on Sep 13, 2024
  7. added a commit that references this issue on Sep 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    • Status
      Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions