Skip to content

TST Avoid segmentation fault with free-threaded and pytest-run-parallel - #33070

Merged
lesteve merged 4 commits into
scikit-learn:mainfrom
lesteve:fix-free-threaded-segmentation-fault
Jan 14, 2026
Merged

lesteve merged 4 commits into
scikit-learn:mainfrom
lesteve:fix-free-threaded-segmentation-fault

Conversation

@lesteve

@lesteve lesteve commented Jan 13, 2026 •

Copy link
Copy Markdown
Member

(As kind of expected) I can reliably reproduce the segfault with (every single time I tried actually):

pytest --parallel-threads 4 --iterations 10 sklearn/utils/tests/test_response.py -k test_response_values_output_shape_ -v

Using a clone fixes it. As we have seen before, the issue is that the parametrized estimators is shared between the pytest-run-parallel threads and you call .fit on it.

cc @ogrisel

Output of pytest command

================================================= test session starts =================================================
platform linux -- Python 3.14.0, pytest-9.0.1, pluggy-1.6.0 -- /home/lesteve/micromamba/envs/scikit-learn-dev/bin/python
cachedir: .pytest_cache
rootdir: /home/lesteve/dev/scikit-learn
configfile: pyproject.toml
plugins: xdist-3.8.0, cov-7.0.0, run-parallel-0.8.0
collected 51 items / 38 deselected / 13 selected                                                                      
Collected 51 items to run in parallel

sklearn/utils/tests/test_response.py::test_response_values_output_shape_[estimator0-predict-binary-expected_shape0] PARALLEL PASSED [  7%]
sklearn/utils/tests/test_response.py::test_response_values_output_shape_[estimator1-predict_proba-binary-expected_shape1] PARALLEL PASSED [ 15%]
sklearn/utils/tests/test_response.py::test_response_values_output_shape_[estimator2-decision_function-binary-expected_shape2] PARALLEL PASSED [ 23%]
sklearn/utils/tests/test_response.py::test_response_values_output_shape_[estimator3-predict-multiclass-expected_shape3] PARALLEL PASSED [ 30%]
sklearn/utils/tests/test_response.py::test_response_values_output_shape_[estimator4-predict_proba-multiclass-expected_shape4] PARALLEL PASSED [ 38%]
sklearn/utils/tests/test_response.py::test_response_values_output_shape_[estimator5-decision_function-multiclass-expected_shape5] PARALLEL PASSED [ 46%]
sklearn/utils/tests/test_response.py::test_response_values_output_shape_[estimator6-predict-multilabel-expected_shape6] PARALLEL FAILED [ 53%]
sklearn/utils/tests/test_response.py::test_response_values_output_shape_[estimator7-predict_proba-multilabel-expected_shape7] PARALLEL FAILED [ 61%]
sklearn/utils/tests/test_response.py::test_response_values_output_shape_[estimator8-decision_function-multilabel-expected_shape8] PARALLEL FAILED [ 69%]
sklearn/utils/tests/test_response.py::test_response_values_output_shape_[estimator9-predict-binary-expected_shape9] PARALLEL FAILED [ 76%]
sklearn/utils/tests/test_response.py::test_response_values_output_shape_[estimator10-predict-multiclass-expected_shape10] PARALLEL FAILED [ 84%]
sklearn/utils/tests/test_response.py::test_response_values_output_shape_[estimator11-predict-binary-expected_shape11] Fatal Python error: Segmentation fault

<Cannot show all threads while the GIL is disabled>
Stack (most recent call first):
  File "/home/lesteve/dev/scikit-learn/sklearn/tree/_classes.py", line 534 in predict
  File "/home/lesteve/dev/scikit-learn/sklearn/utils/_response.py", line 244 in _get_response_values
  File "/home/lesteve/dev/scikit-learn/sklearn/utils/tests/test_response.py", line 446 in test_response_values_output_shape_
  File "/home/lesteve/micromamba/envs/scikit-learn-dev/lib/python3.14t/site-packages/pytest_run_parallel/plugin.py", line 80 in closure
  File "/home/lesteve/micromamba/envs/scikit-learn-dev/lib/python3.14t/threading.py", line 1023 in run
  File "/home/lesteve/micromamba/envs/scikit-learn-dev/lib/python3.14t/threading.py", line 1081 in _bootstrap_inner
  File "/home/lesteve/micromamba/envs/scikit-learn-dev/lib/python3.14t/threading.py", line 1043 in _bootstrap

Current thread's C stack trace (most recent call first):
  Binary file "python", at _Py_DumpStack+0x4a [0x5567efa97f6b]
  Binary file "python", at +0x16b5c3 [0x5567efaa25c3]
  Binary file "/usr/lib/libc.so.6", at +0x3e4d0 [0x7f203963e4d0]
  Binary file "/home/lesteve/dev/scikit-learn/build/cp314t/sklearn/tree/_tree.cpython-314t-x86_64-linux-gnu.so", at +0x2987b [0x7f1fc355387b]
  Binary file "/home/lesteve/dev/scikit-learn/build/cp314t/sklearn/tree/_tree.cpython-314t-x86_64-linux-gnu.so", at +0x3f095 [0x7f1fc3569095]
  Binary file "/home/lesteve/dev/scikit-learn/build/cp314t/sklearn/tree/_tree.cpython-314t-x86_64-linux-gnu.so", at +0x3f89c [0x7f1fc356989c]
  Binary file "/home/lesteve/dev/scikit-learn/build/cp314t/sklearn/tree/_tree.cpython-314t-x86_64-linux-gnu.so", at +0x400ff [0x7f1fc356a0ff]
  Binary file "python", at PyObject_Vectorcall+0x37 [0x5567efadc5d7]
  Binary file "python", at _PyEval_EvalFrameDefault+0x11dc [0x5567efaf1fec]
  Binary file "python", at +0x1b6e60 [0x5567efaede60]
  Binary file "python", at +0x2267d6 [0x5567efb5d7d6]
  Binary file "python", at +0x22eaca [0x5567efb65aca]
  Binary file "python", at +0x2fcd81 [0x5567efc33d81]
  Binary file "python", at _PyEval_EvalFrameDefault+0x3841 [0x5567efaf4651]
  Binary file "python", at +0x1b6e60 [0x5567efaede60]
  Binary file "python", at +0x2267d6 [0x5567efb5d7d6]
  Binary file "python", at +0x2fc4d9 [0x5567efc334d9]
  Binary file "python", at +0x2fc465 [0x5567efc33465]
  Binary file "/usr/lib/libc.so.6", at +0x9698b [0x7f203969698b]
  Binary file "/usr/lib/libc.so.6", at +0x11a9cc [0x7f203971a9cc]

Extension modules: numpy._core._multiarray_umath, numpy.linalg._umath_linalg, sklearn.__check_build._check_build, cython.cimports.libc.math, _cyutility, scipy._cyutility, scipy._lib._ccallback_c, numpy.random._common, numpy.random.bit_generator, numpy.random._bounded_integers, numpy.random._pcg64, numpy.random._generator, numpy.random._mt19937, numpy.random._philox, numpy.random._sfc64, numpy.random.mtrand, scipy.sparse._sparsetools, _csparsetools, scipy.sparse._csparsetools, psutil._psutil_linux, scipy.special._ufuncs_cxx, scipy.special._ellip_harm_2, scipy.special._special_ufuncs, scipy.special._gufuncs, scipy.special._ufuncs, scipy.special._specfun, scipy.special._comb, scipy.linalg._fblas, scipy.linalg._flapack, scipy.linalg.cython_lapack, scipy.linalg._cythonized_array_utils, scipy.linalg._solve_toeplitz, scipy.linalg._decomp_lu_cython, scipy.linalg._matfuncs_schur_sqrtm, scipy.linalg._matfuncs_expm, scipy.linalg._linalg_pythran, scipy.linalg.cython_blas, scipy.linalg._decomp_update, scipy.sparse.linalg._dsolve._superlu, scipy.sparse.linalg._eigen.arpack._arpack, scipy.sparse.linalg._propack._spropack, scipy.sparse.linalg._propack._dpropack, scipy.sparse.linalg._propack._cpropack, scipy.sparse.linalg._propack._zpropack, scipy.spatial._ckdtree, scipy._lib.messagestream, scipy.spatial._qhull, scipy.spatial._voronoi, scipy.spatial._hausdorff, scipy.spatial._distance_wrap, scipy.spatial.transform._rotation, scipy.spatial.transform._rigid_transform, scipy.optimize._group_columns, scipy.optimize._trlib._trlib, scipy.optimize._lbfgsb, _moduleTNC, scipy.optimize._moduleTNC, scipy.optimize._slsqplib, scipy.optimize._minpack, scipy.optimize._lsq.givens_elimination, scipy.optimize._zeros, scipy._lib._uarray._uarray, scipy.linalg._decomp_interpolative, scipy.optimize._bglu_dense, scipy.optimize._lsap, scipy.optimize._direct, scipy.integrate._odepack, scipy.integrate._quadpack, scipy.integrate._vode, scipy.integrate._dop, scipy.integrate._lsoda, scipy.interpolate._fitpack, scipy.interpolate._dfitpack, scipy.interpolate._dierckx, scipy.interpolate._ppoly, scipy.interpolate._interpnd, scipy.interpolate._rbfinterp_pythran, scipy.interpolate._rgi_cython, scipy.special.cython_special, scipy.stats._stats, scipy.stats._biasedurn, scipy.stats._stats_pythran, scipy.stats._levy_stable.levyst, scipy.stats._ansari_swilk_statistics, scipy.sparse.csgraph._tools, scipy.sparse.csgraph._shortest_path, scipy.sparse.csgraph._traversal, scipy.sparse.csgraph._min_spanning_tree, scipy.sparse.csgraph._flow, scipy.sparse.csgraph._matching, scipy.sparse.csgraph._reordering, scipy.stats._sobol, scipy.stats._qmc_cy, scipy.stats._rcont.rcont, scipy.stats._qmvnt_cy, scipy.ndimage._nd_image, scipy.ndimage._rank_filter_1d, _ni_label, scipy.ndimage._ni_label, pandas._libs.tslibs.ccalendar, pandas._libs.tslibs.np_datetime, pandas._libs.tslibs.dtypes, pandas._libs.tslibs.base, pandas._libs.tslibs.nattype, pandas._libs.tslibs.timezones, pandas._libs.tslibs.fields, pandas._libs.tslibs.timedeltas, pandas._libs.tslibs.tzconversion, pandas._libs.tslibs.timestamps, pandas._libs.properties, pandas._libs.tslibs.offsets, pandas._libs.tslibs.strptime, pandas._libs.tslibs.parsing, pandas._libs.tslibs.conversion, pandas._libs.tslibs.period, pandas._libs.tslibs.vectorized, pandas._libs.ops_dispatch, pandas._libs.missing, pandas._libs.hashtable, pandas._libs.algos, pandas._libs.interval, pandas._libs.lib, pandas._libs.ops, pandas._libs.hashing, pandas._libs.arrays, pandas._libs.tslib, pandas._libs.sparse, pandas._libs.internals, pandas._libs.indexing, pandas._libs.index, pandas._libs.writers, pandas._libs.join, pandas._libs.window.aggregations, pandas._libs.window.indexers, pandas._libs.reshape, pandas._libs.groupby, pandas._libs.json, pandas._libs.parsers, pandas._libs.testing, sklearn._cyutility, sklearn.utils._isfinite, sklearn.utils.sparsefuncs_fast, sklearn.utils.murmurhash, sklearn.utils._openmp_helpers, sklearn.preprocessing._csr_polynomial_expansion, sklearn.preprocessing._target_encoder_fast, scipy.io.matlab._mio_utils, scipy.io.matlab._streams, scipy.io.matlab._mio5_utils, sklearn.datasets._svmlight_format_fast, sklearn.utils._random, sklearn.utils._vector_sentinel, sklearn.feature_extraction._hashing_fast, PIL._imaging, kiwisolver._cext, sklearn.metrics.cluster._expected_mutual_info_fast, sklearn.metrics._dist_metrics, sklearn.metrics._pairwise_distances_reduction._datasets_pair, sklearn.utils._cython_blas, sklearn.metrics._pairwise_distances_reduction._base, sklearn.metrics._pairwise_distances_reduction._middle_term_computer, sklearn.utils._heap, sklearn.utils._sorting, sklearn.metrics._pairwise_distances_reduction._argkmin, sklearn.metrics._pairwise_distances_reduction._argkmin_classmode, sklearn.metrics._pairwise_distances_reduction._radius_neighbors, sklearn.metrics._pairwise_distances_reduction._radius_neighbors_classmode, sklearn.metrics._pairwise_fast, sklearn.neighbors._partition_nodes, sklearn.neighbors._ball_tree, sklearn.neighbors._kd_tree, sklearn.utils.arrayfuncs, sklearn.utils._seq_dataset, sklearn.linear_model._cd_fast, _loss, sklearn._loss._loss, sklearn.linear_model._sag_fast, sklearn.svm._liblinear, sklearn.svm._libsvm, sklearn.svm._libsvm_sparse, sklearn.utils._weight_vector, sklearn.linear_model._sgd_fast, sklearn.decomposition._online_lda_fast, sklearn.decomposition._cdnmf_fast, sklearn.tree._utils, sklearn.neighbors._quad_tree, sklearn.tree._tree, sklearn.tree._partitioner, sklearn.tree._splitter, sklearn.tree._criterion, sklearn.ensemble._gradient_boosting, sklearn.ensemble._hist_gradient_boosting.common, sklearn.ensemble._hist_gradient_boosting._gradient_boosting, sklearn.ensemble._hist_gradient_boosting._binning, sklearn.ensemble._hist_gradient_boosting._bitset, sklearn.ensemble._hist_gradient_boosting.histogram, sklearn.ensemble._hist_gradient_boosting._predictor, sklearn.ensemble._hist_gradient_boosting.splitting (total: 198)

@ogrisel

ogrisel commented Jan 13, 2026 •

Copy link
Copy Markdown
Member

Good catch. I agree, we need the clone to guarantee correct results in the presence of concurrent test execution.

I am a bit worried about the fact that we get a segfault though. We might want to consider wrapping the fit and prediction functions with an instance level lock to protect against segfault, but I am not sure. Alternatively, there might be a way to write the fit method slightly differently to avoid the segfault when concurrently fitting and predicting on the same instance.

@lesteve

lesteve commented Jan 13, 2026 •

Copy link
Copy Markdown
Member Author

I am a bit worried about the fact that we get a segfault though.

I seem to remember that we have seen somewhat similar segfaults with pytest-run-parallel in the tree code before 1, maybe at least a first step would be to clarify the pattern?

Having said this I am not too sure using the same instance to fit in parallel would be a very such a common pattern that a user would try. Sure in an ideal world, it would be nice not to segfault. Predicting in parallel, maybe is a more reasonable pattern, like you predict on multiple batches of data in parallel? I don't have a clear intuition how likely estimator.predict is modifying estimator and is likely to cause issues.

Footnotes

  1. the stack-trace (even if partial) in this case is pointing at sklearn/tree/_tree.cpython-314t-x86_64-linux-gnu.so ↩

@lesteve

lesteve commented Jan 14, 2026

Copy link
Copy Markdown
Member Author

Let's merge this one and deal with the global_random_seed specific one later (which I can easily reproduce and need to debug).

@lesteve
lesteve enabled auto-merge (squash) January 14, 2026 07:24
@lesteve
lesteve merged commit a1c64ee into scikit-learn:main Jan 14, 2026
dschult pushed a commit to dschult/scikit-learn that referenced this pull request Jan 25, 2026
dschult pushed a commit to dschult/scikit-learn that referenced this pull request Jan 25, 2026
TejasAnalyst pushed a commit to TejasAnalyst/scikit-learn that referenced this pull request Feb 10, 2026
@lesteve
lesteve deleted the fix-free-threaded-segmentation-fault branch March 3, 2026 10:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

free-threading PRs and issues related to support for free-threaded CPython (a.k.a. nogil or no-GIL, PEP 703) module:utils No Changelog Needed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants