Skip to content

a race condition in click.testing.StreamMixer's finalization #2993

Closed

Description

@neutrinoceros

xref python/cpython#136248
xref neutrinoceros/inifix#421

Replicating my reproducer from the CPython report:

# t.py
from concurrent.futures import ThreadPoolExecutor

import pytest
from typer import Exit, Typer
from typer.testing import CliRunner

app = Typer()


@app.command()
def cmd(_: list[str]) -> None:
    with ThreadPoolExecutor() as executor:
        executor.submit(lambda: None).result()

    raise Exit(code=1)

runner = CliRunner()

@pytest.mark.parametrize("_", range(10_000))
def test_cmd(_):
    runner.invoke(app, ["cmd"])

run with

❯ pytest t.py -x

outputs

warning: Using incompatible environment (`.venv`) due to `--no-sync` (The project environment's Python version does not satisfy the request: `Python >=3.11`)
========================================== test session starts ===========================================
platform darwin -- Python 3.14.0b3, pytest-8.4.1, pluggy-1.6.0
rootdir: /Users/clm/dev/inifix
configfile: pyproject.toml
plugins: hypothesis-6.135.11
collected 10000 items                                                                                    

t.py ............................................................................................. [  0%]
.................................................................................................. [  1%]
.................................................................................................. [  2%]
.................................................................................................. [  3%]
.................................................................................................. [  4%]
.................................................................................................. [  5%]
.................................................................................................. [  6%]
.................................................................................................. [  7%]
.................................................................................................. [  8%]
.................................................................................................. [  9%]
.................................................................................................. [ 10%]
.................................................................................................. [ 11%]
.................................................................................................. [ 12%]
.................................................................................................. [ 13%]
.................................................................................................. [ 14%]
.................................................................................................. [ 15%]
.................................................................................................. [ 16%]
.................................................................................................. [ 17%]
.................................................................................................. [ 18%]
.................................................................................................. [ 19%]
.................................................................................................. [ 20%]
.................................................................................................. [ 21%]
.................................................................................................. [ 22%]
.................................................................................................. [ 23%]
.................................................................................................. [ 24%]
.................................................................................................. [ 25%]
.................................................................................................. [ 26%]
.................................................................................................. [ 27%]
.................................................................................................. [ 28%]
.................................................................................................. [ 29%]
.................................................................................................. [ 30%]
.................................................................................................. [ 31%]
.................................................................................................. [ 32%]
.................................................................................................. [ 33%]
.................................................................................................. [ 34%]
.................................................................................................. [ 35%]
.................................................................................................. [ 36%]
.................................................................................................. [ 37%]
.................................................................................................. [ 38%]
.................................................................................................. [ 39%]
.................................................................................................. [ 40%]
.................................................................................................. [ 41%]
.................................................................................................. [ 42%]
.................................................................................................. [ 43%]
.................................................................................................. [ 44%]
.................................................................................................. [ 45%]
.................................................................................................. [ 46%]
.................................................................................................. [ 46%]
.................................................................................................. [ 47%]
.................................................................................................. [ 48%]
.................................................................................................. [ 49%]
.................................................................................................. [ 50%]
.................................................................................................. [ 51%]
.................................................................................................. [ 52%]
.................................................................................................. [ 53%]
.................................................................................................. [ 54%]
.................................................................................................. [ 55%]
.................................................................................................. [ 56%]
.................................................................................................. [ 57%]
.................................................................................................. [ 58%]
.................................................................................................. [ 59%]
.................................................................................................. [ 60%]
.................................................................................................. [ 61%]
.................................................................................................. [ 62%]
.................................................................................................. [ 63%]
.................................................................................................. [ 64%]
.................................................................................................. [ 65%]
.................................................................................................. [ 66%]
.................................................................................................. [ 67%]
............................................F

================================================ FAILURES ================================================
_____________________________________________ test_cmd[6801] _____________________________________________

item = <Option help>

    def sort_key(item: Parameter) -> tuple[bool, float]:
        try:
>           idx: float = invocation_order.index(item)
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E           ValueError: list.index(x): x not in list

_click/src/click/core.py:133: ValueError

During handling of the above exception, another exception occurred:

self = <click.testing.BytesIOCopy object at 0x498c711ff00>

    def flush(self) -> None:
        super().flush()
>       self.copy_to.flush()
E       ValueError: I/O operation on closed file.

_click/src/click/testing.py:82: ValueError

The above exception was the direct cause of the following exception:

cls = <class '_pytest.runner.CallInfo'>
func = <function call_and_report.<locals>.<lambda> at 0x498c9a760c0>, when = 'call'
reraise = (<class '_pytest.outcomes.Exit'>, <class 'KeyboardInterrupt'>)

    @classmethod
    def from_call(
        cls,
        func: Callable[[], TResult],
        when: Literal["collect", "setup", "call", "teardown"],
        reraise: type[BaseException] | tuple[type[BaseException], ...] | None = None,
    ) -> CallInfo[TResult]:
        """Call func, wrapping the result in a CallInfo.
    
        :param func:
            The function to call. Called without arguments.
        :type func: Callable[[], _pytest.runner.TResult]
        :param when:
            The phase in which the function is called.
        :param reraise:
            Exception or exceptions that shall propagate if raised by the
            function, instead of being wrapped in the CallInfo.
        """
        excinfo = None
        instant = timing.Instant()
        try:
>           result: TResult | None = func()
                                     ^^^^^^

.venv/lib/python3.14t/site-packages/_pytest/runner.py:344: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
.venv/lib/python3.14t/site-packages/_pytest/runner.py:246: in <lambda>
    lambda: runtest_hook(item=item, **kwds), when=when, reraise=reraise
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.14t/site-packages/pluggy/_hooks.py:512: in __call__
    return self._hookexec(self.name, self._hookimpls.copy(), kwargs, firstresult)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.14t/site-packages/pluggy/_manager.py:120: in _hookexec
    return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.14t/site-packages/_pytest/logging.py:850: in pytest_runtest_call
    yield
.venv/lib/python3.14t/site-packages/_pytest/capture.py:900: in pytest_runtest_call
    return (yield)
            ^^^^^
.venv/lib/python3.14t/site-packages/pluggy/_callers.py:53: in run_old_style_hookwrapper
    return result.get_result()
           ^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.14t/site-packages/pluggy/_callers.py:38: in run_old_style_hookwrapper
    res = yield
          ^^^^^
.venv/lib/python3.14t/site-packages/_pytest/skipping.py:263: in pytest_runtest_call
    return (yield)
            ^^^^^
.venv/lib/python3.14t/site-packages/_pytest/unraisableexception.py:158: in pytest_runtest_call
    collect_unraisable(item.config)
.venv/lib/python3.14t/site-packages/_pytest/unraisableexception.py:79: in collect_unraisable
    raise errors[0]
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

config = <_pytest.config.Config object at 0x498bc589f10>

    def collect_unraisable(config: Config) -> None:
        pop_unraisable = config.stash[unraisable_exceptions].pop
        errors: list[pytest.PytestUnraisableExceptionWarning | RuntimeError] = []
        meta = None
        hook_error = None
        try:
            while True:
                try:
                    meta = pop_unraisable()
                except IndexError:
                    break
    
                if isinstance(meta, BaseException):
                    hook_error = RuntimeError("Failed to process unraisable exception")
                    hook_error.__cause__ = meta
                    errors.append(hook_error)
                    continue
    
                msg = meta.msg
                try:
>                   warnings.warn(pytest.PytestUnraisableExceptionWarning(msg))
E                   pytest.PytestUnraisableExceptionWarning: Exception ignored while finalizing file <_NamedTextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>: None

.venv/lib/python3.14t/site-packages/_pytest/unraisableexception.py:67: PytestUnraisableExceptionWarning
======================================== short test summary info =========================================
FAILED t.py::test_cmd[6801] - pytest.PytestUnraisableExceptionWarning: Exception ignored while finalizing file <_NamedTextIOWrapper...
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
===================================== 1 failed, 6801 passed in 6.13s =====================================

Environment:

  • Python version: 3.14.0b3t (reproduces with 3.13.5t too, and supposedly can also be triggered on a GIL-enabled interpreter with sys.setswitchinterval)
  • Click version: 8.2.1

Activity

  1. changed the title [-]BUG: a race condition in `click.testing.StreamMixer`'s finalization[/-] [+]a race condition in `click.testing.StreamMixer`'s finalization[/+] on Jul 4, 2025
  2. Rowlando13 commented on Jul 22, 2025

    @Rowlando13
    Member

    @neutrinoceros Can you add a changelog entry for this.

  3. added this to the 8.2.2 milestone on Jul 22, 2025
  4. neutrinoceros commented on Jul 22, 2025

    @neutrinoceros
    ContributorAuthor

    done in #3009

  5. Rowlando13 commented on Jul 23, 2025

    @Rowlando13
    Member

    Thanks!

  6. locked as resolved and limited conversation to collaborators on Aug 7, 2025
  7. added
    test runner
    on Feb 28, 2026
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

    test runner

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions