Skip to content

Make the test suite itself thread-safe to be able to detect thread-safety problems with or without free-threading - #30041

Merged
thomasjpfan merged 77 commits into
scikit-learn:mainfrom
ogrisel:thread-parallel-tests
Aug 22, 2025
Merged

thomasjpfan merged 77 commits into
scikit-learn:mainfrom
ogrisel:thread-parallel-tests

Conversation

@ogrisel

@ogrisel ogrisel commented Oct 10, 2024 •

Copy link
Copy Markdown
Member

This is an investigative branch, not meant to be merged as such, to investigate what effort would be required to tackle #30007 as a whole (using pytest-run-parallel instead of pytest-freethreaded).

It includes commits from:

That can be merged independently.

On top of this, I started to use @pytest.mark.parallel_threads(1) (EDIT: now @pytest.mark.thread_unsafe) on tests that are fundamentally not thread-safe or that use other fixtures such as tmpdir that would require to be initialized in the thread running the test to function properly (as opposed to running in the main pytest thread).

Many more similar changes to silence all the non-informative failures, but I will stop there for now.

This already highlights that the most common patterns are:

  • testing for warnings with pytest.warns;
  • testing for sys.stdout with capsys;
  • usage of the tmpdir fixture;
  • usage of the monkeypatch fixture.

EDIT: since the first version of this PR, pytest-run-parallel has been updated to make the tmpdir and tmp_path fixture work by default and automatically detect tests that use problematic fixtures and code patterns involving warnings automatically. The remaining problematic fixtures can probably be added by configuration.

I have also found a failure in test_minibatch_kmeans_partial_fit_init with the lambda init case using:

pytest --parallel-threads=4  sklearn/cluster/tests/test_k_means.py -k test_minibatch_kmeans_partial_fit_init

and I cannot explain it yet (using regular Python with GIL enabled).

@github-actions

github-actions Bot commented Oct 10, 2024 •

Copy link
Copy Markdown

✔️ Linting Passed

All linting checks passed. Your pull request is in excellent shape! ☀️

Generated for commit: f8f78a3. Link to the linter CI: here

@ogrisel

ogrisel commented Oct 10, 2024

Copy link
Copy Markdown
Member Author

Note that, I don't plan to continue manually flagging test functions individually. It's too tedious and invasive.

Comment thread sklearn/cluster/tests/test_birch.py Resolved
Comment thread sklearn/cluster/tests/test_birch.py Resolved
Comment thread sklearn/cluster/tests/test_k_means.py Resolved
Comment thread sklearn/datasets/tests/test_openml.py Resolved
Comment thread sklearn/datasets/tests/test_openml.py Resolved
Comment thread sklearn/datasets/tests/test_openml.py Resolved
Comment thread sklearn/datasets/tests/test_openml.py Resolved
Comment thread sklearn/datasets/tests/test_openml.py Resolved
@ogrisel

ogrisel commented May 9, 2025 •

Copy link
Copy Markdown
Member Author

I updated the PR to simplify it and rely on automated thread-unsafety heuristics of the latest version of pytest-run-parallel as much as possible. The heuristics seem to work as expected and the amount of manual annotation is much reduced as a result.

I started to run pytest --parallel-threads=4 --iterations=3 on a nogil install. However, I interrupted it after 12% because it's very slow and using all the RAM available on my machine.

Note that tests collection itself is slow, but still bearable compared to the actual test execution time and the memory usage problem. I guess we will need to profile a run on submodule of scikit-learn to check whether the slowdown is expected: when running with --parallel-threads=4 --iterations=3 there are 4 x 3 more tests to run compared to a regular pytest run.

For the record, I created the nogil env using conda-forge:

mamba create -n nogil -c conda-forge python-freethreading ipython numpy scipy cython meson-python compilers

@ogrisel

ogrisel commented May 10, 2025 •

Copy link
Copy Markdown
Member Author

To avoid the memory usage problem, I reduced the parallelism to 2 threads and run 1 iteration of the tests per thread:

pytest -v --parallel-threads=2 --iterations=1  2>&1 | tee pytest_all.log

Here are the result: pytest_all.log

There are 146 errors. Many of those are caused by the use of stateful generators in @pytest.mark.parametrize.

EDIT: the specific problem with generators is now tracked at: Quansight-Labs/pytest-run-parallel#57

EDIT 2: actually, the generator state is not the culprit, but state within objects returned by the generators. Those tests are fundamentally thread-unsafe and need to be updated if we want to use pytest-run-parallel.

],
)
@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
@pytest.mark.thread_unsafe # manually captured stdout

@ogrisel ogrisel May 13, 2025 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Note: If we want to avoid having to manually add those thread_unsafe annotations, we should use the capsys fixture instead of manually monkey patching sys.stdout and pytest-run-parallel will automatically treat this test as thread-unsafe.

@ogrisel

ogrisel commented Aug 8, 2025

Copy link
Copy Markdown
Member Author

I fixed another batch of failures I keep on discovering with:

pytest -v --parallel-threads=4 --iterations=1 -n 4 2>&1 | tee pytest_all.log

Note that I use --iterations=1 because otherwise we would need to annotate individual tests with @pytest.mark.iterations(1) to avoid repetition related false positives. In particular, there are all the tests that use temporary folders. I reported the issue upstream:

Quansight-Labs/pytest-run-parallel#109

However, there are also scikit-learn specific tests that mutate some inputs, and do not expect to be run several times in a row with mutated inputs. We could annotate those, but it does not really make sense to do so while there is no automated solution for tmp_path and related fixtured tests.

@lesteve

lesteve commented Aug 11, 2025

Copy link
Copy Markdown
Member

I discovered a few more failures by running the tests locally and I fixed in my last commit. I ran the same command as you:

pytest -v --parallel-threads=4 --iterations=1 -n 4 2>&1 | tee pytest_all.log

I also saw a loky ShutdownExecutorError one but was not able to reproduce in an isolated manner (i.e. running the test file and -k test_name_goes_here), so I left it for later ...

FAILED sklearn/neighbors/tests/test_neighbors.py::test_knn_forcing_backend[ball_tree-loky] - joblib.externals.loky.process_executor.ShutdownExecutorError:

@lesteve lesteve 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.

A bit tedious, but in an ideal world it would be nice to have a uniform comment for the additional clone? Maybe something like this?

# Avoid side effects from shared instances when running tests in parallel

Maybe git blame is enough to be able to go back to this PR and realize this is linked to running the tests in parallel with pytest-run-parallel ...

Comment thread sklearn/svm/tests/test_sparse.py Resolved
@ogrisel

ogrisel commented Aug 12, 2025

Copy link
Copy Markdown
Member Author

Note that cloning estimators can also be necessary to isolate tests even when not run in parallel with threads. For instance, when the list of parametrized estimator instances is shared across several tests it can cause side effects that cause test failures in https://github.com/scikit-learn/scikit-learn/pull/31543/files#diff-d6ffd0947e0ae3e7cc5dc9ff4eb687c9d53de094d1c6b06ab13d17ab78cc391cR146-R148 .

@ogrisel

ogrisel commented Aug 12, 2025

Copy link
Copy Markdown
Member Author

I also saw a loky ShutdownExecutorError one but was not able to reproduce in an isolated manner.

Same for me. But I managed to write a reproducer that reproduces the necessary conditions that happens when running many successive parallel tests of our test suite without using pytest in joblib/loky#458.

@ogrisel

ogrisel commented Aug 12, 2025

Copy link
Copy Markdown
Member Author

Also, w.r.t. #30041 (review) : some side effect problem can also happen if you run the same test several times in a row sequentially. So the (thread-)parallel condition is not always necessary to trigger this class of bugs.

@lesteve

lesteve commented Aug 12, 2025

Copy link
Copy Markdown
Member

I push another fix replacing SVC(probability=True) by LogisticRegression in f8f78a3

Before my last commit, I was able to reproduce the failure locally with:

pytest -v --parallel-threads=4 --iterations=50 sklearn/semi_supervised/tests/test_self_training.py -k selects_best

@lesteve lesteve 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 think this is good to be merged and we can iterate in further PRs if needed.

@thomasjpfan thomasjpfan 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'm seeing clone(est) in many places so that we work with pytest-run-parallel. Is this always going to be the case for tests that mutates the object?

@ogrisel

ogrisel commented Aug 22, 2025

Copy link
Copy Markdown
Member Author

I'm seeing clone(est) in many places so that we work with pytest-run-parallel. Is this always going to be the case for tests that mutates the object?

Yes. But note that when an estimators list is shared between tests, we also need to clone the inputs to avoid side effects across tests.

@thomasjpfan
thomasjpfan merged commit f19ff9c into scikit-learn:main Aug 22, 2025
@ogrisel
ogrisel deleted the thread-parallel-tests branch August 25, 2025 12:34
@ogrisel

ogrisel commented Aug 25, 2025

Copy link
Copy Markdown
Member Author

Thanks for the reviews and merge. We will have to follow-up with actual free-threading testing now.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants