Skip to content

BUG: thread-based Parallel can corrupt the process-wide warning filters #35089

Open

Description

@cakedev0

Warning

This issue is not yet ready for a PR. If you are interested in contributing to scikit-learn, please have a look at our contributing guidelines, and in particular the sections for new contributors and the "Needs triage" label.

Describe the bug and give evidence about its user-facing impact

On Python without context-aware warnings (every GIL build, and free-threaded 3.13), sklearn.utils.parallel.Parallel with a thread-based backend can corrupt the process-wide warning filters. The user's own filters can be silently lost, and spurious "sklearn.utils.parallel.delayed should be used with sklearn.utils.parallel.Parallel" warnings are raised.

To propagate the caller's warning filters to joblib workers (#30380), every task runs:

with warnings.catch_warnings():  # save the global filter list, swap in a copy
    warnings.resetwarnings()  # empty it
    for f in captured_filters:  # re-add the caller's filters one by one
        warnings.filterwarnings(...)
    return func(*args, **kwargs)
# on exit: restore the saved list

Without context-aware warnings, warnings.filters is one list shared by the whole process, and catch_warnings isn't thread-safe (the Python docs say so). With threads, tasks enter and exit these blocks out of order:

  1. Thread 1 enters: it saves the user's list (L0), the global becomes a copy (L1), and it starts emptying and refilling L1.
  2. Thread 2 enters while L1 is half-refilled: it saves L1, the global becomes L2.
  3. Thread 1 exits and restores L0.
  4. Thread 2 exits and restores L1: the half-reset copy.

A task's resetwarnings() can also run while the global list is the very list captured by Parallel (after another thread restored it), and empty it: the next tasks then see no filters and raise the warning above.

It needs a thread switch at the wrong moment, so it's rare with the default switch interval (5 ms) and a few threads. It's more frequent with many threads, with catch_warnings calls inside the tasks (check_array and get_params do that), and when tests run in several threads at once: I think this is the intermittent failure of #32631 on free-threaded 3.13, xfailed in #33320.

On free-threaded 3.14 (context-aware warnings) there is no race, but the same code takes the warnings module lock in every task, which makes many threads queue on it.

Steps/Code to Reproduce

import sys
import warnings

from sklearn.utils.parallel import Parallel, delayed

sys.setswitchinterval(1e-5)  # makes the race frequent

warnings.filterwarnings("ignore", message="my filter")
n_before = len(warnings.filters)
for _ in range(3):
    Parallel(n_jobs=32, prefer="threads")(delayed(int)() for _ in range(200))

my_filter_kept = any(f[1] is not None and f[1].pattern == "my filter" for f in warnings.filters)
print(f"{n_before} -> {len(warnings.filters)} filters, my filter kept: {my_filter_kept}")

Expected Results

11 -> 11 filters, my filter kept: True

and no warning.

Actual Results

On every run (3 runs, GIL 3.14.7, 344-thread machine):

11 -> 0 filters, my filter kept: False

and 88 to 172 spurious warnings per run:

sklearn/utils/parallel.py:144: UserWarning: `sklearn.utils.parallel.delayed` should be used with `sklearn.utils.parallel.Parallel` to make it possible to propagate the scikit-learn configuration of the current thread to the joblib workers.

On a 14-core laptop (GIL 3.14.6) it happens as well, for instance 11 -> 4 filters with hundreds of warnings.

Versions

System:
    python: 3.14.7 | packaged by conda-forge | (main, Sep  2 2026, 21:08:32) [GCC 15.3.0]
   machine: Linux-7.0.0-27-generic-x86_64-with-glibc2.43

Python dependencies:
      sklearn: 1.10.dev0
          pip: 26.2.1
   setuptools: None
        numpy: 2.5.3
        scipy: 1.18.1
       Cython: 3.3.0
       pandas: 3.0.6
   matplotlib: None
       joblib: 1.6.0
threadpoolctl: 3.7.0
     narwhals: 2.26.0

Built with OpenMP: True

Interest in fixing the bug

I have a fix, I'll open a PR.

Activity

  1. added
    Needs Triage
    on Oct 6, 2026
  2. added
    free-threading
    and removed
    Needs Triage
    on Oct 6, 2026
  3. lesteve commented on Oct 7, 2026

    @lesteve
    Member

    Small aside: I didn't read the full thing very carefully but in case there is something specific to free-threaded 3.13, it is not worth fixing. Anyone using free-threaded "seriously" kind of knows that you should use at least 3.14.

  4. cakedev0 commented on Oct 7, 2026

    @cakedev0
    MemberAuthor

    It's also a bug on GIL Python, but much less likely: I couldn't reproduce it without sys.setswitchinterval (0 out of 20 runs on GIL 3.13 and 3.14, up to 10k tasks per run), versus every run on free-threaded 3.13. On free-threaded 3.14+, context-aware warnings avoid the bug, but resetting the filters in each task takes the warnings module lock, so it's a performance concern there.

  5. cakedev0 commented on Oct 7, 2026

    @cakedev0
    MemberAuthor

    I tried hard and I couldn't trigger this race on GIL Python with any realistic workload.

    So the performance impact on free-threaded Python is the only motivation. Each task takes the warnings module lock about 15 times (catch_warnings, resetwarnings, and once per filter it re-adds), and it's a PyMutex, which collapses with a few tens of threads (python/cpython#158901). So I think it can have a real performance impact on many-core machines, but I haven't measured it yet. If python/cpython#158901 gets fixed, it should be much less of a problem.

    Conclusion: for now, I'll wait ^^

  6. added
    Needs Investigation
    on Oct 13, 2026
  7. andrew-chung-au commented on Nov 12, 2026

    @andrew-chung-au

    I can trigger this on a GIL build with an ordinary workload (GridSearchCV over RandomForestClassifier) and the default switch interval, so it does not need free-threaded Python or a shortened sys.setswitchinterval. I traced the list objects involved. It is intermittent, and I have tested two machines and one dataset (limits at the end).

    Setup. Python 3.14.6 (GIL build), scikit-learn 1.9.1, joblib 1.6.0. GridSearchCV(n_jobs=16) over RandomForestClassifier(n_estimators=200, n_jobs=16), 6 candidates, 5 folds, 8,844 rows and 30 features, on a 4-core machine. No sys.setswitchinterval. One fresh process tree per attempt.

    Rate. The delayed / Parallel warning appeared in 21 of 30 attempts with a tracer loaded and in 5 of 10 without it. With PYTHON_CONTEXT_AWARE_WARNINGS=1: 0 of 30 and 0 of 10. With RandomForestClassifier(n_jobs=1) inside the same grid search: 0 of 30 and 0 of 10. On a 16-core machine (Python 3.14.5) with plain n_jobs=-1 for both levels: 13 of 15 with a tracer loaded and 3 of 10 without it, against 0 of 15 and 0 of 10 for each of the two changes. The rate depends on the layout: with 4 worker processes of 4 threads each I saw none in 10 attempts, and none in 8 with a sequential grid search and 16 forest threads.

    Trace. The tracer records, under warnings._lock, the id() and length of the list that each catch_warnings.__enter__, catch_warnings.__exit__ and resetwarnings() acts on, plus the list each _FuncWrapper task was handed. In the 30 baseline attempts on the 4-core machine (366,000 thread tasks, 1,830 thread-backed Parallel calls), all 9,190 warnings fall into two paths:

    1. The handed list is emptied during the call (2,390 warnings, 20 calls). Parallel.__call__ hands the tasks warnings._get_filters(), which is the live warnings.filters object. A thread enters catch_warnings, another thread's exit makes the handed list global again, and the first thread's resetwarnings() then empties it. All 21 recorded resets have that order. The remaining tasks of the call warn.
    2. The next call captures an empty list (6,800 warnings, 34 calls). After fit, the global list is a copy created by a worker thread's __enter__ and left behind by an out-of-order __exit__. The Parallel.__call__ in predict_proba captures it, and all 200 of its tasks warn.

    A third outcome gives no warning. The leftover list is shortened but not empty, so line 143 does not fire and the tasks run with some filters missing (26 calls; 5,679 tasks ran with a shortened list).

    Copying the list is not enough. With Parallel.__call__ patched to hand tasks list(warnings._get_filters()), path 1 disappears (0 resets of a handed list in 30 attempts). However, 12 of 30 attempts still warn through path 2, and 20 of 30 still run tasks with a damaged list.

    A user's own filter does not hide it. With warnings.filterwarnings("ignore", message=...) set before fit, 4,759 of 5,451 raised warnings were still shown, because the list in force when the warning is raised is usually one of the damaged ones.

    Deterministic reproducer. This script forces path 1 with two threads and four trivial tasks by ordering the two threads' entry and exit. It does not change the switch interval, and on every run it shows 11 filters becoming 0 and two warnings. It shows that this interleaving is sufficient to produce the warning. It does not show how often the interleaving happens.

    Limits. Two machines, one scikit-learn version, one dataset and grid. The rates describe these setups only. The tracer adds work to each task and may change how often the race happens (21 of 30 traced against 5 of 10 untraced on the 4-core machine; the difference is not significant, Fisher p = 0.28). I did not examine whether PYTHON_CONTEXT_AWARE_WARNINGS=1 has other effects, such as the cost on free-threaded builds mentioned earlier in this thread.

    Report, tracer, analyzer and raw traces of the affected processes: ROOT_CAUSE.md.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugNeeds Investigationfree-threading

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions