GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Fix CliRunner error with logging message by getzze · Pull Request #3140 · pallets/click

Conversation

@getzze

@getzze getzze commented Nov 12, 2025

Copy link
Copy Markdown

Tests using CliRunner run in parallel (with pytest-xdist) sometimes raise an error due to logging messages not being processed correctly because a buffer has been closed. This bug is a due to a regression after #2991.

fixes #3110

Difficult to write a test for it...

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@getzze
fix CliRunner error with logging message
6d8dac7
@getzze getzze mentioned this pull request Nov 12, 2025
CliRunner.invoke raises a "ValueError: I/O operation on closed file" #3110
Closed
@neutrinoceros

neutrinoceros commented Nov 13, 2025

Copy link
Copy Markdown
Contributor

I confirm that this approach does not regress on #2993

getzze reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

neutrinoceros
neutrinoceros reviewed Nov 13, 2025
View reviewed changes

@neutrinoceros neutrinoceros left a comment •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

I think you need to update the docstring for __del__ if del is the agreed upon solution: it's not about closing bytesIO instances in a deterministic order any more

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@getzze

getzze commented Nov 13, 2025

Copy link
Copy Markdown
Author

You're right thanks, I'll change it.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@pjonsson

pjonsson commented Nov 13, 2025

Copy link
Copy Markdown
Contributor

Running uv run --python 3.14t pytest t.py -x where t.py contains the test case for #2993 on this branch gives me:

________________________________ test_cmd[598] _________________________________

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

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

src/click/testing.py:80: 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 0x349b37bda40>
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/_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 0x349ae58a090>

    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[598] - pytest.PytestUnraisableExceptionWarning: Exception ignored while finalizing...
!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!
======================== 1 failed, 598 passed in 0.89s =========================
All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@neutrinoceros

neutrinoceros commented Nov 13, 2025

Copy link
Copy Markdown
Contributor

Interesting, so there is a regression after all ? to be complete, I used a slightly different command to check this earlier. Here it is:

uv run --no-dev -p 3.14t -w typer -w pytest pytest t.py -x

Also note that I multiplied the number of tests by 10, as compared to my reprod in #2993

I also re-ran this just now, and still didn't hit the race. Maybe it's platform specific now ? I'm running macOS 15 on a 10-cores M2 arch for what it's worth (but I originally discovered this race in GHA).

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@pjonsson

pjonsson commented Nov 13, 2025

Copy link
Copy Markdown
Contributor

I'm running inside a Ubuntu 24.04-based docker container (GDAL 3.10.3) on a 16-core Ryzen 9950X3D running Ubuntu 24.04.

I don't know anything about the race conditions, but I still believe the root cause is multiple objects believing they have ownership over these buffers.

neutrinoceros reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

getzze added 2 commits November 13, 2025 13:27
@getzze
deal with copy_to stream being closed
d71fa41
@getzze
add description in CHANGES.rst
59ed117
neutrinoceros
neutrinoceros reviewed Nov 13, 2025
View reviewed changes
Comment thread src/click/testing.py
Comment on lines +82 to +83
if not self.copy_to.closed:
self.copy_to.flush()

@neutrinoceros neutrinoceros Nov 13, 2025

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

unfortunately this LBYL (Look Before You Leap) approach is infamously inappropriate to guard against races; in a concurrent execution model, self.copy_to.closed could change between the moment the guard clause (if ...) is evaluated, and the rest of the block is, and then you're back to square one, but the code is more complex and the race is potentially harder to reproduce (which isn't necessarily a good thing when you're try to debug it).

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@neutrinoceros

neutrinoceros commented Nov 13, 2025

Copy link
Copy Markdown
Contributor

I still believe the root cause is multiple objects believing they have ownership over these buffers.

I agree. That seems like an accurate description of the problem.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@kdeldycke kdeldycke added this to the 8.3.2 milestone Nov 18, 2025
@kdeldycke kdeldycke mentioned this pull request Nov 19, 2025
Randomized and parallel tests #3151
Merged
@kdeldycke

kdeldycke commented Nov 19, 2025

Copy link
Copy Markdown
Collaborator

I am in favor of introducing pytest-xdist to Click. Even better: activate the pytest-randomly plugin.

I am testing the effects of these two in: #3151

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@kdeldycke

kdeldycke commented Nov 19, 2025

Copy link
Copy Markdown
Collaborator

FYI, these changes does not fix the issues uncovered from #3151. It doesn't mean that this PR is not fixing something else! 😅

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@kdeldycke kdeldycke mentioned this pull request Feb 28, 2026
NamedTextIOWrapper: stop closing buffer #3139
Merged
@kdeldycke

kdeldycke commented Feb 28, 2026

Copy link
Copy Markdown
Collaborator

FYI, these changes does not fix the issues uncovered from #3151. It doesn't mean that this PR is not fixing something else! 😅

OK this PR, as well as #3139, have nothing to do with #3151.

The real fix is in #3139. See my comment at: #3139 (comment)

This PR is superseded by #3139.

neutrinoceros and getzze reacted with heart emoji
All reactions
  • ❤️ 2 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

kdeldycke added a commit to pjonsson/click that referenced this pull request Feb 28, 2026
@kdeldycke
Add regular and stress tests for CliRunner stream lifecycle and o…
777a89e
…wnership

Closes: pallets#824, pallets#3110
Reverts: pallets#2991
Reproduces pallets#2993
Supersed: pallets#3140
@kdeldycke kdeldycke added bug test runner CliRunner and Click's test utilities feature labels Feb 28, 2026
@getzze

getzze commented Feb 28, 2026

Copy link
Copy Markdown
Author

Great, thanks! I'll close this PR then

kdeldycke reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@getzze getzze closed this Feb 28, 2026
@getzze
getzze deleted the fix-testing branch February 28, 2026 10:54
@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Mar 15, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Reviewers

1 more reviewer
@neutrinoceros neutrinoceros neutrinoceros left review comments
Reviewers whose approvals may not affect merge requirements

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

test runner CliRunner and Click's test utilities feature

Projects

None yet

Milestone

8.3.2

Development

Successfully merging this pull request may close these issues.

CliRunner.invoke raises a "ValueError: I/O operation on closed file"

Uh oh!

There was an error while loading. Please reload this page.

4 participants

@getzze @neutrinoceros @pjonsson @kdeldycke
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.