Fix output capturing in ConcurrentWrapper for concurrent processes #261
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.
Refactored ConcurrentWrapper to ensure proper closure of file descriptors and restoration of standard output/error streams using context managers, enhancing resource management and reliability.
Description
In the original implementation, file descriptors for
stdout
andstderr
were opened but not explicitly closed. This could potentially lead to resource leaks, especially if the wrapper is used to spawn many instances. In this version, thewith
statement ensures that the file descriptors are properly closed once the block is exited, even if exceptions occur.Additionally the standard output (
sys.stdout
) and error (sys.stderr
) were redirected to the files but were not restored to their original state after the runnable function finished executing. This means that any subsequent prints or error messages in the same process (or thread, depending on the execution environment) would continue to be redirected to the last files opened, which is likely unintended behavior. This MR addresses this by storing the originalsys.stdout
andsys.stderr
, then restoring them after executing the runnable function, ensuring that the redirection is temporary and scoped only to the execution of runnable.I found these problems when I identified an issue where the last line of output was sometimes not captured. This should be due to to the standard output and error buffers not being explicitly flushed.
Related Issue (if any)
n/a
Motivation and Context
The current version sometimes fails to capture all output of a runnable. The added tests show which problems may occur.
How Has This Been Tested?
I added a few tests to
tests/test_concurrent_wrapper.py
. I test if delayed output is captured, the descriptors are closed and that thestdout
is restored.If anything is missing or unclear, please let me know.