Repository navigation
Open
Labels
Build / CINeeds DecisionRequires decisionfree-threadingPRs and issues related to support for free-threaded CPython (a.k.a. nogil or no-GIL, PEP 703)module:test-suiteeverything related to our tests
Description
There is a new kid on the block that should help us find out whether scikit-learn and its dependencies can be reliably considered free-threading compatible:
Let's try to adopt it in scikit-learn.
Here is a possible plan:
- first run the tests locally a few times and see if they are tests (or a set of interacting tests) that cause a crash or a failure, open an issue for each of them, possibly upstream and then mark them as skipped under free-threading builds with a reference to the issue in the "reason" field;
- then upgrade our nightly free-threading scheduled CI run to use
pytest-freethreaded.
Any comments @lesteve @jeremiedbb @ngoldbaum?
EDIT: anyone interested in getting hands on the first item can find this resource useful:
EDIT 2: there is also the pytest-run-parallel plugin that can serve a similar purpose.
EDIT3: here is a TODO/plan for this problem:
- resync and simplify Make the test suite itself thread-safe to be able to detect thread-safety problems with or without free-threading #30041 to leverage Mark tests as single-threaded if warning handling takes place Quansight-Labs/pytest-run-parallel#19, Add a list of thread-unsafe fixtures and mark tests as thread-unsafe if usage is found Quansight-Labs/pytest-run-parallel#33 and Add a configuration file option to extend the thread-unsafe fixture list Quansight-Labs/pytest-run-parallel#34
- configure the
[free-threading]CI to run withpytest-run-parallelCI Run free-threaded test suite with pytest-run-parallel #32023 - enable the free-threading flag in Cython extension MNT Mark cython extensions as free-threaded compatible #31342
- investigate and fix crashes and test failures or open tracking issues and mark tests as
thread_unsafe;)
- investigate and fix crashes and test failures or open tracking issues and mark tests as
- benchmark the use of threading, in particular when we we expect nested parallelism between Python threads (e.g. in
GridSearchCVwith the "threading" backend of joblib) and BLAS or OpenMP native threading in the underlying estimators. - communicate results on a blog post / pydata presentation / social media.
Metadata
Metadata
Assignees
Labels
Build / CINeeds DecisionRequires decisionfree-threadingPRs and issues related to support for free-threaded CPython (a.k.a. nogil or no-GIL, PEP 703)module:test-suiteeverything related to our tests
Activity
ogrisel commentedon Oct 7, 2024
Discussing with @lesteve we have a problem with test fixture that use on
sklearn.with_configbecause the fixture is executed in the main thread while the test is run in a different thread: sincesklearn.with_configuses thread locals, the configuration change of the fixture is not visible in the test run in a parallel thread.Maybe there is a problem of scoping the fixture correctly, and somehow telling pytest to run the fixture in the thread running the test.
ogrisel commentedon Oct 7, 2024
I think that for a function-scoped fixture (the default fixture scope), it would make sense to ensure that the parallel runner runs the fixture on the same thread as the test function it-self.
Shall we open an issue upstream in the issue tracker of the pytest-freethreaded repo?
lesteve commentedon Oct 7, 2024
Here is a somewhat simple test file that reproduces the issue. Note this happens on vanilla CPython 3.13 not only free-threaded CPython 3.13.
As you can tell from the output, the fixture is run in the main thread and the test function in another thread (threadpool created by the pytest plugin).
Output:
ngoldbaum commentedon Oct 8, 2024
ping @andfoy
andfoy commentedon Oct 8, 2024
Hi, from the SciPy side, We've been testing using
pytest-run-parallel, which also supports untittest-style classes, it allows to mark individual tests as well as whole test suites to be run using multiple threads: https://github.com/Quansight-Labs/pytest-run-parallelIt also fully supports fixtures
ogrisel commentedon Oct 8, 2024
I tried @lesteve's reproducer with
pytest-run-paralleland I get exactly the same problem:The function-fixture is executed in a different thread (the main thread) than the thread used to execute the test function.
ogrisel commentedon Oct 8, 2024
I will open an issue in https://github.com/tonybaloney/pytest-freethreaded with Loic's reproducer.
ogrisel commentedon Oct 8, 2024
@andfoy let me know if you want me to open a similar issue in https://github.com/Quansight-Labs/pytest-run-parallel.
andfoy commentedon Oct 8, 2024
I think the issue at hand is that a separate threaded fixture is required here, which should be different from a global, pytest fixture. However, from a concurrency/distribution/parallelism point of view, each thread should get its own local atomic state, which should be independent from each other. As pytest fixtures are spawned globally from the main thread, the case exposed by @lesteve is the expected behaviour rather than a bug.
In order to fix this, there could be 2 different avenues:
@pytest.fixturedecorator to create a new@threaded_fixturethat allows for the creation of per-thread fixtures. Challenges here could include interfacing with global pytest fixtures.I support going for the second option rather than the first one, since it invites developers to think about concurrency, parallel and concurrent constructs explicitly, as opposed to having to rely on a separate machinery to (apparently) do the job without thinking about what is going on underneath. This is of uttermost importance if free-threaded is going to be the future of Python at some point.
ngoldbaum commentedon Oct 8, 2024
It's worth keeping in mind as well that Pytest itself is not thread safe and I don't think the maintainers are particularly open to making it thread safe. More on this under this page: https://docs.pytest.org/en/stable/explanation/flaky.html
lesteve commentedon Oct 9, 2024
I guess this is towards option 1. but pytest-parallel (archived and no longer maintained) seems run the fixture and the test function in the same thread, see tonybaloney/pytest-freethreaded#17 (comment) for more details.
ogrisel commentedon Oct 9, 2024
Thanks for your feedback @andfoy.
I am trying to see what that would entail for scikit-learn.
@lesteve I tried to grep our source code to find all the occurrences of
with sklearn.config_context():in a fixture and I only foundenable_slep006. However, this fixture alone already impacts many tests:https://github.com/search?q=repo%3Ascikit-learn%2Fscikit-learn+enable_slep006&type=code
Each of those tests would need to have its body indented under a
with sklearn.config_context(enable_metadata_routing=True):block. From a verbosity point of view, this is not too bad, but that requirement for an extra indentation level might be a bit annoying for the readability of tests that would already need several indentation levels in their body.So some form of thread-local fixtures would be nice in my opinion.
ogrisel commentedon Oct 9, 2024
Or maybe we could just write our own test function decorator instead of using a pytest fixture.
EDIT: the following might work for us:
I will open a quick PR.
EDIT 2: actually context managers can directly be used as decorators. So the following works and is even cleaner:
8 remaining items
ogrisel commentedon Oct 10, 2024
Thanks, @andfoy, I confirm that using
@pytest.mark.parallel_threads(1)make some previously flaky warning related tests (e.g.test_warning_recursion_non_constant_init) orcapsysfixtured test consistently (e.g.test_kmeans_verbose) pass.Still, I think
pytest.mark.threadunsafemight be more explicit and possibly more portable across different pytest plugins.ogrisel commentedon Oct 10, 2024
@andfoy Back to the original problem of function-scoped fixture. I found a problem with a simple use of the
tmpdirfixture:tonybaloney/pytest-freethreaded#17 (comment)
This fixture provides valid test isolation only if it is run around each function call within the same thread as the one actually executing the test. Otherwise, one would need an extra layer of thread protection to be able to correctly use it with a thread-based parallel execution plugin. That would be too invasive in my opinion.
ogrisel commentedon Oct 10, 2024
I started #30041 to investigate what would be needed to get our test suite to pass with parallel thread execution.
It's quite tedious to manually mark all the
capsys,monkeypatch,tmpdirfixtured tests and the tests that usepytest.warnswith@pytest.mark.parallel_threads(1)manually...I think we instead need:
pytest-run-parallelto investigate free-threading.ngoldbaum commentedon Oct 10, 2024
For temporary directories, I think you should either migrate to a function that doesn't use temporary directories with a specific name, or prepend the name of the directory with e.g. a UUID to make the directory name unique.
ogrisel commentedon Oct 10, 2024
But the point of the
tmpdirfixture is to not have to deal with test isolation within the code of the test logic itself. Having to update the test code to make more verbose and complex would be a serious step back. It would be much better if to have a thread-local initialization of the function-scopedtmpdirfixture.Granted, the
tmpdirfixture has been deprecated in favor of thetmp_pathfixture (to leverage thepathlib.PathAPI instead of a custom API). But the problem stays the same with thetmp_pathfixture:ngoldbaum commentedon Oct 10, 2024
I guess I don't see why you need to have a specific name that's specified in the test and why you want to go out of your way to keep that.
Since you're running the same test in many threads and are implicitly using global state (the file system), then of course that's not thread safe. IMO you should update your testing code to not use the global state, rather than expect the testing code to hide the global state from you.
ngoldbaum commentedon Oct 10, 2024
Also, I just created Quansight-Labs/free-threaded-compatibility#92 to mention these issues around writing thread-safe tests in the guide.
ogrisel commentedon Oct 10, 2024
But
tmpdirandtmp_pathare precisely in charge of creating a unique temp folder for your test. When you use them withpytest-xdist, there is no concurrency problem when using them naively, even if all Python worker processes managed bypytest-xdistshare the same file-system: each test sees only its own temp folder. The problem here is that their implicit usage contract is broken if their initialization is shared for several tests running in concurrent threads.ngoldbaum commentedon Oct 10, 2024
I want to double-check this, since I think if you were running the same test many times in parallel with xdist you'd have the same issue.
ogrisel commentedon Oct 10, 2024
andfoy commentedon Oct 10, 2024
As @ngoldbaum mentioned, tests that use
tmpdirshould append an extra UUID per thread, so that each file does not get overwritten/unexpectedly removed by other thread.This goes in line with the philosophy of being aware of concurrent computing, as opposed to having a complex and opaque machinery that tries to abstract the problem away.
I understand that going through each test in the library takes a lot of time, but doing so will ensure that each test function is thread-safe (even if the solution sometimes implies adding locks) and it will future-proof it for future contributors, as adding a CI (for example), will force them to not use global state patterns.
It is difficult to get away from thinking in global state, which is common in single-threaded imperative or object oriented computing. But free-threaded deals with a different paradigm, and requires different abstractions and patterns
ogrisel commentedon Oct 10, 2024
But it's sad to require the test to handle the thread-isolation by itself. It would be a much better separation of concern if those fixtures or the runner could handle the thread-aware isolation by them-selves. It goes against the DRY principle.
We could probably write a
threadsafe_tmp_pathfixture that would automatically append the thread id or a UUID as subcomponent of the tmp folder managed by the fixture, but it's sad to have each project reimplement this independently.ogrisel commentedon Oct 10, 2024
I suppose it's possible to maintain a per-project test utility wrapper such as:
ogrisel commentedon May 9, 2025
EDIT: moved TODO list to the issue description.
[-]Upgrade free-threading CI to run with pytest-freethreaded instead of pytest-xdist[/-][+]META: run free-threading tests on CI and assess what remains to be done for free-threading support[/+]