You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
CliRunner.invoke raises a "ValueError: I/O operation on closed file" #3110
Hi,
I am a maintainer of subliminal that uses click for its CLI. Some tests for the CLI are failing since the upgrade to click 8.3.0.
I tracked the failures to a regression in click 8.3.0 due to #2991. Reverting this commit makes my tests pass with click 8.3.0.
The failing pytest tests are of the following form:
def test_cli_download(tmp_path: os.PathLike[str]) -> None:
runner = CliRunner()
result = runner.invoke(subliminal_cli, ['download', '-l', 'en', '-p', 'podnapisi', 'video.mkv'])
# Curiously this test is not failing, subtitle is even downloaded
assert result.exit_code == 0
# The following two asserts are failing because `result.output` show a long error message.
assert result.output.startswith('Collecting videos')
assert result.output.endswith('Downloaded 1 subtitle\n')
When I only run this test function with pytest, all the assertions pass, but when I run the whole file that has plenty of test functions with the same structure, all the functions fail at the result.output assert (although not consistently...)
The error message in result.output is like this:
--- Logging error ---
Traceback (most recent call last):
File "/usr/lib/python3.13/logging/__init__.py", line 1154, in emit
stream.write(msg + self.terminator)
~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
ValueError: I/O operation on closed file.
[...]
File "src/subliminal/score.py", line 157, in compute_score
logger.debug('Found matches %r', matches)
Message: 'Found matches %r'
Arguments: ({'country', 'episode', 'season', 'series', 'year'},)
It seems the logging files are closed after one CliRunner.invoke call and its giving rise to failures in the other tests.
Reacted by Edgar Ramírez Mondragón and Ben Chopson
I'm seeing similar output in some projects. I think that ironically #2991 introduced a different race condition, because the stream is closed by the time logging tries to write a message to it.
Thanks for the ping. I'm not an expert here, so please take everything I say with a grain of salt, but I do notice there was a test that needed updating for click's own CI to survive my patch. Could you try using the CliRunner.isolation context manager in your tests, see if it resolves the new race ?
I've been looking at the code in testing.py, instead of overloading StreamMixer.__del__, it would be cleaner to modify BytesIOCopy to handle properly the fact that the copy_to stream can be closed or dereferenced.
Edit: maybe allowing copy_to to be None and checking for that possibility in the methods would be enough.
@neutrinoceros I tried your reproducer from #2993 with Python 3.14 (via uv) on click 8.2.1 and after a dozen runs I still haven't been able to hit the exception. Or do you mean you run that ~9 second reproducer 10 000 times, so it takes upwards of 25 hours of constant hammering to reproduce the problem once?
@neutrinoceros I tried your reproducer from #2993 with Python 3.14 (via uv) on click 8.2.1 and after a dozen runs I still haven't been able to hit the exception. Or do you mean you run that ~9 second reproducer 10 000 times, so it takes upwards of 25 hours of constant hammering to reproduce the problem once?
No, I can reliably reproduce it under 10min. It is much easier to hit with a free-threaded interpreter. Is that what you did ?
@getzze since __del__() doesn't give many guarantees, my goal was to make things deterministic so everybody runs close at the same time.
After having looked closer at this, one problem is that the two _NamedTextIOWrapper are taking ownership of StreamMixer.stdout and StreamMixer.stderr, and the _NamedTextIOWrapper calling close() on those buffers during its destruction. I created #3139 to prevent _NamedTextIOWrapper from closing StreamMixer's buffers.
No, I can reliably reproduce it under 10min. It is much easier to hit with a free-threaded interpreter. Is that what you did ?
I had missed the free-threaded part, if I remove your __del__ implementation I can trigger the problem in 1.7s on latest stable with the free-threaded interpreter. Thank you for taking the time to explain what the issue you had filed actually said and for testing my attempt to make things deterministic.
Hi! I tried reproducing this on the current main branch using Python 3.13 on Windows by adding tests around CliRunner.invoke with stdout/stderr writes and exceptions, but I wasn’t able to trigger the ValueError: I/O operation on closed file.
This might be version- or environment-specific (e.g., older Click or Python versions). I’m happy to try reproducing it on a specific version if you have one in mind.
A fix is available in #3139 and that PR is ready to be merged upstream. Can you check that your cases are fixed by that PR? And the test suite covers it?
Activity
edgarrmondragon commentedon Oct 16, 2025
I'm seeing similar output in some projects. I think that ironically #2991 introduced a different race condition, because the stream is closed by the time
loggingtries to write a message to it.cc @neutrinoceros
neutrinoceros commentedon Oct 16, 2025
Thanks for the ping. I'm not an expert here, so please take everything I say with a grain of salt, but I do notice there was a test that needed updating for click's own CI to survive my patch. Could you try using the
CliRunner.isolationcontext manager in your tests, see if it resolves the new race ?getzze commentedon Oct 16, 2025
I didn't try but the docs say that the
invokemethod uses theisolationcontext, so there would be nested contexts, not sure it would help.getzze commentedon Oct 16, 2025
I was thinking, would it solve your problem if your patch would delete the
BytesIOattributes instead of calling theirclosemethod?neutrinoceros commentedon Oct 17, 2025
I checked, and I can confirm that it wouldn't.
neutrinoceros commentedon Oct 17, 2025
Indeed, but to be clear, I'm suggesting to replace
runner.invokewith arunner.isolationcontext. See for instanceclick/tests/test_testing.py
Lines 443 to 451 in 309ce91
getzze commentedon Oct 17, 2025
I've been looking at the code in
testing.py, instead of overloadingStreamMixer.__del__, it would be cleaner to modifyBytesIOCopyto handle properly the fact that thecopy_tostream can be closed or dereferenced.Edit: maybe allowing
copy_toto be None and checking for that possibility in the methods would be enough.dev-python/click: add 8.3.1
pjonsson commentedon Nov 12, 2025
@neutrinoceros I tried your reproducer from #2993 with Python 3.14 (via uv) on click 8.2.1 and after a dozen runs I still haven't been able to hit the exception. Or do you mean you run that ~9 second reproducer 10 000 times, so it takes upwards of 25 hours of constant hammering to reproduce the problem once?
Even Python's own documentation seem pretty keen on not using
__del__(): https://docs.python.org/3.14/reference/datamodel.html#object.__del__If it takes you 9 seconds to reproduce the problem, could you please see if the following also avoids the problem you were fixing?
neutrinoceros commentedon Nov 12, 2025
No, I can reliably reproduce it under 10min. It is much easier to hit with a free-threaded interpreter. Is that what you did ?
neutrinoceros commentedon Nov 12, 2025
I'll try this in a couple minutes, thanks !
neutrinoceros commentedon Nov 12, 2025
Warmup: I could still reliably reproduce this race (got 6 hits in 70s of crunching) with Python 3.14.0t + click 8.2.0
Pièce de résistance: I just tried your patch. Happy to report I didn't hit the race a single time with an equal amount of effort1
Footnotes
just for
securityfun, I also tried 10x harder, and ... 🥁 ... still no hit 🎉 ↩getzze commentedon Nov 12, 2025
@pjonsson thanks for the patch, but it is still giving an error with
subliminal.Removing the call to
BytesIO.close()fixes it though:@neutrinoceros, does it also fix the race condition in your case?
neutrinoceros commentedon Nov 12, 2025
yes !
pjonsson commentedon Nov 12, 2025
@getzze since
__del__()doesn't give many guarantees, my goal was to make things deterministic so everybody runs close at the same time.After having looked closer at this, one problem is that the two
_NamedTextIOWrapperare taking ownership ofStreamMixer.stdoutandStreamMixer.stderr, and the_NamedTextIOWrappercallingclose()on those buffers during its destruction. I created #3139 to prevent_NamedTextIOWrapperfrom closingStreamMixer's buffers.pjonsson commentedon Nov 12, 2025
I had missed the free-threaded part, if I remove your
__del__implementation I can trigger the problem in 1.7s on latest stable with the free-threaded interpreter. Thank you for taking the time to explain what the issue you had filed actually said and for testing my attempt to make things deterministic.getzze commentedon Nov 12, 2025
I wrote a PR that fixes to errors with
subliminaltests.@neutrinoceros can you confirm it also fixes your bug ?
Thanks!
Priya-Yanamandra commentedon Jan 4, 2026
Priya-Yanamandra commentedon Jan 4, 2026
Hi! I tried reproducing this on the current main branch using Python 3.13 on Windows by adding tests around CliRunner.invoke with stdout/stderr writes and exceptions, but I wasn’t able to trigger the
ValueError: I/O operation on closed file.This might be version- or environment-specific (e.g., older Click or Python versions). I’m happy to try reproducing it on a specific version if you have one in mind.
Add regular and stress tests for ``CliRunner`` stream lifecycle and o…
kdeldycke commentedon Feb 28, 2026
A fix is available in #3139 and that PR is ready to be merged upstream. Can you check that your cases are fixed by that PR? And the test suite covers it?
kdeldycke commentedon Mar 1, 2026
Fix has been merged in
stablebranch. It will be available as part of the v8.3.2 release.