Skip to content

dask threads break filterwarnings on 3.14t #14077

Closed as not planned
Closed as not planned

Description

@crusaderky

I'm a Dask maintainer and I'm currently working on 3.14t support.

My test suite runs Dask with the default threading scheduler on 3.14t.
Dask spawns a thread, logs a RuntimeWarning inside the thread, and then joins it.

On all other Python interpreters, @pytest.mark.filterwarnings successfully suppresses the warning.
On Python 3.14t, if any other test previously spawned and rejoined dask threads, the warning is not suppressed.

Reproducer

import dask.array as da
import pytest


def test_1():
    a = da.zeros(1)
    a.compute()


@pytest.mark.filterwarnings("ignore:invalid value encountered in divide:RuntimeWarning")
def test_2():
    a = da.zeros(1) / da.zeros(1)
    a.compute()

Outcome:

  • Python 3.14.2, pytest: OK
  • Python 3.14.2t, pytest -k test_2: OK
  • Python 3.14.2t, pytest:
FAILED test1.py::test_2 - RuntimeWarning: invalid value encountered in divide
  • Python 3.14.2t, pytest, change compute() to compute(scheduler="sync"): OK

I've failed to further simplify the reproducer further. This works fine:

import numpy as np
import pytest
import threading
import dask.array as da

def test_1():
    a = da.zeros(1)
    a.compute()


@pytest.mark.filterwarnings("ignore:invalid value encountered in divide:RuntimeWarning")
def test2():
    t = threading.Thread(target=np.divide, args=(0, 0))
    t.start()
    t.join()

If I merge the two tests, ending up with a single test that spawns and destroys the dask thread pool twice, the issue disappears. This works fine:

import dask.array as da
import pytest


@pytest.mark.filterwarnings("ignore:invalid value encountered in divide:RuntimeWarning")
def test_1():
    a = da.zeros(1)
    a.compute()
    a = da.zeros(1) / da.zeros(1)
    a.compute()

Environment

pytest 9.0.2
numpy 2.4.0
dask 2025.12.0
Python 3.14.2

Activity

  1. added
    plugin: warnings
    on Jan 3, 2026
  2. Zac-HD commented on Jan 3, 2026

    @Zac-HD
    Member

    tagging @Liam-DeVoe if you're still looking at threading?

  3. RonnyPfannschmidt commented on Jan 4, 2026

    @RonnyPfannschmidt
    Member

    This looks like a threading vs warnings global state issue

  4. Liam-DeVoe commented on Jan 5, 2026

    @Liam-DeVoe
    Contributor

    This is an interaction with -X context_aware_warnings, enabled by default in 3.14t. When a thread is shared across tests, updates to the warnings filter under with catch_warnings() don't propagate to the existing thread.

    • test 1 executes
      • dask spawns a thread A
      • A inherits the global warnings ContextVar
    • test 2 executes
      • pytest enters with warnings.catch_warnings() from @pytest.mark.filterwarnings
      • this enters a new warnings ContextVar
      • thread A is re-used in a pool (I assume this is true for dask), still with its old ContextVar

    Here's a minimal reproducer:

    from concurrent.futures import ThreadPoolExecutor
    import numpy as np
    import pytest
    
    @pytest.fixture(scope="module")
    def pool():
        yield ThreadPoolExecutor(max_workers=1)
    
    def test_1(pool):
        # warm the thread
        pool.submit(lambda: None).result()
    
    @pytest.mark.filterwarnings("ignore::RuntimeWarning")
    def test_2(pool):
        pool.submit(lambda: np.array(0.0) / np.array(0.0)).result()
    python3.14 -m pytest sandbox.py -Werror # ok
    python3.14t -m pytest sandbox.py -Werror # warns
    python3.14t -X context_aware_warnings=0 -m pytest sandbox.py -Werror # ok

    pytest could recommend that threads are not shared across tests? This does seem unfortunate.

    (cc @ngoldbaum)

  5. ngoldbaum commented on Jan 5, 2026

    @ngoldbaum
    Contributor

    Hmm, I think Dask is going to need to do something here to update the warnings state in its thread pool when it re-uses workers. I'll surface this internally in our group...

  6. added
    status: needs information
    on Jan 5, 2026
  7. RonnyPfannschmidt commented on Jan 5, 2026

    @RonnyPfannschmidt
    Member

    Im going to consider this a upstream integration issue for cpython/ dask for now

  8. crusaderky commented on Jan 5, 2026

    @crusaderky
    Author

    thread A is re-used in a pool (I assume this is true for dask)

    Yes, threads remain alive across tests:
    https://github.com/dask/dask/blob/8d2cc26e68e300e9cb78e838684ad5fcd8d0948f/dask/threaded.py#L70-L81

    I guess that to cope with this I could change the module linked above as follows? I'm not too happy to reference CPython internals though...

    + def get_warnings_context():
    +     if warnings.get("_use_context", False):
    +         return warnings._warnings_context.get()
    +     return None
    
    main_thread = current_thread()
    + main_context = get_warnings_context()
    
    def get(...):
    [...]
        thread = current_thread()
    +   context = get_warnings_context()
    [...]
    -           if num_workers is None and thread is main_thread:
    +           if num_workers is None and thread is main_thread and context is main_context:
                    if default_pool is None:
                        default_pool = ThreadPoolExecutor(CPU_COUNT)
                        atexit.register(default_pool.shutdown)
                    pool = default_pool
    -           elif thread in pools and num_workers in pools[thread]:
    -              pool = pools[thread][num_workers]
    +           elif (thread, context) in pools and num_workers in pools[thread, context]:
    +              pool = pools[thread, context][num_workers]
                else:
                    pool = ThreadPoolExecutor(num_workers)
                    atexit.register(pool.shutdown)
    <              pools[thread][num_workers] = pool
    >              pools[thread, context][num_workers] = pool
  9. ngoldbaum commented on Jan 5, 2026

    @ngoldbaum
    Contributor

    @nascheme probably has insight about what is appropriate to do here

  10. nascheme commented on Jan 5, 2026

    @nascheme

    Possible solution, add the warnings filter decorator to the function being called by the worker, rather than inside the function that runs in the parent, e.g.

    from concurrent.futures import ThreadPoolExecutor
    import numpy as np
    import pytest
    
    @pytest.fixture(scope="module")
    def pool():
        yield ThreadPoolExecutor(max_workers=1)
    
    def test_1(pool):
        # warm the thread
        pool.submit(lambda: None).result()
    
    def test_2(pool):
        @pytest.mark.filterwarnings("ignore::RuntimeWarning")
        def work():
            return np.array(0.0) / np.array(0.0)
        pool.submit(work).result()
    

    This seems to work in 3.14t. Mutating the warning state of another thread doesn't seem like a good solution (hard to make thread-safe). Another option would be to make a ThreadPoolExecutor subclass that takes the warning state from the calling thread, pass it along with the task to run in the worker, establish the warnings context before calling the submitted function. I think all that could be done without modifying the test code, just change the ThreadPoolExecutor class being used. If it can be made both in free-threaded and default builds, decorating the submitted function seems like the cleanest solution to me.

  11. nascheme commented on Jan 5, 2026

    @nascheme

    Oh, that doesn't work the same. When using the -Werror option, the test fails while in the default build the test passes. It seems the @pytest.mark.filterwarnings decorator doesn't work on a nested function like that. I'm not sure if it could be made to work, looking into it.

  12. nascheme commented on Jan 5, 2026

    @nascheme

    I think this works:

    def test_2(pool):
        def work():
            with warnings.catch_warnings(category=RuntimeWarning, action='ignore'):
                return np.array(0.0) / np.array(0.0)
        pool.submit(work).result()
  13. crusaderky commented on Jan 6, 2026

    @crusaderky
    Author

    I think this works:

    def test_2(pool):
        def work():
            with warnings.catch_warnings(category=RuntimeWarning, action='ignore'):
                return np.array(0.0) / np.array(0.0)
        pool.submit(work).result()
    

    This is not practically feasible in a dask.array, dask.dataframe, or dask.bag workflow.
    The final user provides the data which triggers the warning, but has no direct control on the internals of the function that is being run inside the thread pool.

    The initial example was a good real life use case of what is exposed to the final user:

        a = da.zeros(1) / da.zeros(1)
        a.compute()

    To make it realistic, you just replace dask.zeros with an arbitrarily complicated chain of operations that ends up with a zero somewhere in the denominator.
    The user doesn't invoke np.ndarray.__truediv__; they invoke da.Array.__truediv__ which in turn will later cause compute() to internally call np.ndarray.__truediv__ in a thread.

    Another option would be to make a ThreadPoolExecutor subclass that takes the warning state from the calling thread, pass it along with the task to run in the worker, establish the warnings context before calling the submitted function.

    This is feasible. I'll play around with it.

  14. crusaderky commented on Jan 6, 2026

    @crusaderky
    Author

    Dask PR: dask/dask#12224
    Closing this, as the issue is clearly not about pytest anyway.
    Thanks for the help everybody!

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

    plugin: warningsstatus: needs information

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions