Skip to content

Commit e249b55

Browse files
committed
run(fix): Drain pipes without a timeout
why: Waiting for process exit before reading stdout deadlocks when Git fills its pipe. Streaming stderr alone cannot unblock that child. what: - Drain both pipes with the existing selector path for every command - Wait for exit without polling once both pipes reach EOF - Bound native regression children and verify both callback modes
1 parent 6441de4 commit e249b55

2 files changed

Lines changed: 42 additions & 51 deletions

File tree

‎src/libvcs/_internal/run.py‎

Lines changed: 21 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -267,8 +267,6 @@ def progress_cb(output, timestamp):
267267
)
268268

269269
all_output: str = ""
270-
code = None
271-
line = None
272270
if log_in_real_time and callback is None:
273271

274272
def progress_cb(output: t.AnyStr, timestamp: datetime.datetime) -> None:
@@ -277,34 +275,13 @@ def progress_cb(output: t.AnyStr, timestamp: datetime.datetime) -> None:
277275

278276
callback = progress_cb
279277

280-
# Note: When git detects that stderr is not a TTY (e.g., when piped),
281-
# it outputs progress with newlines instead of carriage returns.
282-
# This causes each progress update to appear on a new line.
283-
# To get proper single-line progress updates, git would need to be
284-
# connected to a pseudo-TTY, which would require significant changes
285-
# to how subprocess execution is handled.
286-
287-
timeout_stdout: bytes | None = None
288-
timeout_stderr: bytes | None = None
289-
if timeout is None:
290-
while code is None:
291-
code = proc.poll()
292-
293-
if callback and callable(callback) and proc.stderr is not None:
294-
line = console_to_str(proc.stderr.read(128))
295-
if line:
296-
callback(
297-
output=line,
298-
timestamp=datetime.datetime.now(tz=datetime.UTC),
299-
)
300-
else:
301-
code, timeout_stdout, timeout_stderr = _wait_with_deadline(
302-
proc,
303-
deadline=time.monotonic() + timeout,
304-
timeout=timeout,
305-
callback=callback,
306-
cmd=_stringify_command(normalized_args),
307-
)
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+
)
308285
if callback and callable(callback):
309286
callback(output="\r", timestamp=datetime.datetime.now(tz=datetime.UTC))
310287

@@ -348,12 +325,12 @@ def progress_cb(output: t.AnyStr, timestamp: datetime.datetime) -> None:
348325
def _wait_with_deadline(
349326
proc: subprocess.Popen[bytes],
350327
*,
351-
deadline: float,
352-
timeout: float,
328+
deadline: float | None,
329+
timeout: float | None,
353330
callback: ProgressCallbackProtocol | None,
354331
cmd: str | list[str],
355332
) -> tuple[int, bytes | None, bytes | None]:
356-
"""Wait for ``proc`` to exit, enforcing a wall-clock deadline.
333+
"""Drain child pipes while waiting, enforcing an optional wall-clock deadline.
357334
358335
Drains both ``stdout`` and ``stderr`` concurrently so a child that fills
359336
either kernel pipe buffer (~64 KiB on Linux) cannot deadlock waiting for
@@ -427,8 +404,8 @@ def _wait_with_deadline(
427404
)
428405
break
429406

430-
remaining = deadline - time.monotonic()
431-
if remaining <= 0:
407+
remaining = deadline - time.monotonic() if deadline is not None else None
408+
if remaining is not None and remaining <= 0:
432409
# ``vcs_exit_code`` deliberately omitted here: ``proc.returncode``
433410
# is still ``None`` because the child has not been signalled yet,
434411
# and CLAUDE.md treats ``vcs_exit_code`` as a scalar ``int``.
@@ -452,12 +429,16 @@ def _wait_with_deadline(
452429
timeout=timeout,
453430
)
454431

455-
wait = min(_TIMEOUT_POLL_INTERVAL_SECONDS, remaining)
432+
wait = (
433+
min(_TIMEOUT_POLL_INTERVAL_SECONDS, remaining)
434+
if remaining is not None
435+
else _TIMEOUT_POLL_INTERVAL_SECONDS
436+
)
456437
if not registered:
457-
# No streams to select on (e.g. ``os.set_blocking`` failed on
458-
# Windows pipes). Yield the CPU explicitly instead of busy-
459-
# looping until the deadline or process exit.
460-
time.sleep(wait)
438+
try:
439+
proc.wait(timeout=remaining)
440+
except subprocess.TimeoutExpired:
441+
continue
461442
continue
462443

463444
events = sel.select(timeout=wait)

‎tests/_internal/test_run.py‎

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from __future__ import annotations
44

55
import logging
6+
import os
67
import pathlib
78
import subprocess
89
import sys
@@ -176,19 +177,28 @@ def test_run_timeout_message_includes_duration(
176177
assert "0.3" in rendered
177178

178179

179-
def test_run_timeout_does_not_deadlock_on_chatty_stdout() -> None:
180-
"""A child filling its stdout pipe must not deadlock the deadline loop.
181-
182-
The OS pipe buffer is typically 64 KiB on Linux. The child below writes
183-
well past that before exiting; if the parent only drained ``stderr``, the
184-
child would block on ``write()`` and only ``terminate()`` would unwedge
185-
it, losing all the legitimate output.
186-
"""
187-
script = "import sys; sys.stdout.write('x' * 200000); sys.stdout.flush()"
180+
@pytest.mark.skipif(os.name != "posix", reason="uses a child alarm to bound deadlocks")
181+
@pytest.mark.parametrize("timeout", [None, 15.0])
182+
@pytest.mark.parametrize("streaming", [False, True])
183+
def test_run_drains_both_pipes(timeout: float | None, streaming: bool) -> None:
184+
"""Both pipes drain with or without a deadline and progress callback."""
185+
script = (
186+
"import os, signal; signal.setitimer(signal.ITIMER_REAL, 0.5); "
187+
"os.write(1, b'x' * 200000); os.write(2, b'y' * 200000)"
188+
)
189+
progress = []
188190

189-
output = run([sys.executable, "-c", script], timeout=15.0)
191+
def callback(output: str, timestamp: t.Any) -> None:
192+
progress.append(output)
190193

191-
assert len(output) >= 200000
194+
output = run(
195+
[sys.executable, "-c", script],
196+
timeout=timeout,
197+
callback=callback if streaming else None,
198+
)
199+
assert output == "x" * 200000
200+
if streaming:
201+
assert "".join(progress).rstrip("\r") == "y" * 200000
192202

193203

194204
def test_run_timeout_preserves_stdout_after_exit() -> None:

0 commit comments

Comments
 (0)