Skip to content

Commit cb57085

Browse files
committed
run(fix): Reap children after callback failure
why: A progress callback exception leaves a native command running although the caller has already abandoned the operation. what: Terminate and reap the immediate child when waiting or its callback raises, then propagate the original exception. Verify RuntimeError and KeyboardInterrupt with a pipe-blocked child.
1 parent f99014f commit cb57085

2 files changed

Lines changed: 67 additions & 7 deletions

File tree

‎src/libvcs/_internal/run.py‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -275,13 +275,22 @@ def progress_cb(output: t.AnyStr, timestamp: datetime.datetime) -> None:
275275

276276
callback = progress_cb
277277

278-
code, timeout_stdout, timeout_stderr = _wait_with_deadline(
279-
proc,
280-
deadline=time.monotonic() + timeout if timeout is not None else None,
281-
timeout=timeout,
282-
callback=callback,
283-
cmd=_stringify_command(normalized_args),
284-
)
278+
try:
279+
code, timeout_stdout, timeout_stderr = _wait_with_deadline(
280+
proc,
281+
deadline=time.monotonic() + timeout if timeout is not None else None,
282+
timeout=timeout,
283+
callback=callback,
284+
cmd=_stringify_command(normalized_args),
285+
)
286+
except BaseException:
287+
try:
288+
_terminate_process(proc, _stringify_command(normalized_args))
289+
finally:
290+
for stream in (proc.stdin, proc.stdout, proc.stderr):
291+
if stream is not None:
292+
stream.close()
293+
raise
285294
if callback and callable(callback):
286295
callback(output="\r", timestamp=datetime.datetime.now(tz=datetime.UTC))
287296

‎tests/_internal/test_run.py‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,57 @@ def test_run_without_timeout_completes_successfully() -> None:
131131
assert "ok" in output
132132

133133

134+
@pytest.mark.parametrize("error_type", [RuntimeError, KeyboardInterrupt])
135+
def test_run_callback_failure_reaps_child(
136+
monkeypatch: pytest.MonkeyPatch, error_type: type[BaseException]
137+
) -> None:
138+
"""An exception from streamed output stops the child before propagating."""
139+
processes: list[subprocess.Popen[bytes]] = []
140+
original_popen = subprocess.Popen
141+
142+
def capture(*args: t.Any, **kwargs: t.Any) -> subprocess.Popen[bytes]:
143+
process = original_popen(*args, **kwargs)
144+
processes.append(process)
145+
return process
146+
147+
# Capture the owned child so the assertion distinguishes cleanup from leakage.
148+
monkeypatch.setattr(subprocess, "Popen", capture)
149+
expected = error_type("callback stopped")
150+
151+
def fail(output: str, timestamp: t.Any) -> None:
152+
raise expected
153+
154+
try:
155+
with pytest.raises(error_type) as caught:
156+
run(
157+
[
158+
sys.executable,
159+
"-c",
160+
(
161+
"import sys; print('ready', file=sys.stderr, flush=True); "
162+
"sys.stdin.buffer.read()"
163+
),
164+
],
165+
stdin=subprocess.PIPE,
166+
callback=fail,
167+
timeout=1,
168+
)
169+
assert caught.value is expected
170+
assert processes[0].returncode is not None
171+
assert all(
172+
stream is None or stream.closed
173+
for stream in (processes[0].stdin, processes[0].stdout, processes[0].stderr)
174+
)
175+
finally:
176+
for process in processes:
177+
if process.poll() is None:
178+
process.kill()
179+
process.wait(timeout=1)
180+
for stream in (process.stdin, process.stdout, process.stderr):
181+
if stream is not None:
182+
stream.close()
183+
184+
134185
def test_run_timeout_none_is_the_default() -> None:
135186
"""Omitting ``timeout`` is equivalent to ``timeout=None``."""
136187
output = run([sys.executable, "-c", "print('default')"], timeout=None)

0 commit comments

Comments
 (0)