fix(orchestrator): Ctrl+C hangs and threading shutdown traceback

Python ThreadPoolExecutor workers cannot be killed when blocked in HTTP
I/O. Previous approach of waiting for graceful cancellation via
shutdown(wait=True) caused infinite hangs, and re-raising KeyboardInterrupt
still triggered Python's _python_exit thread-join cleanup on exit.

Replace with hard-exit strategy: first Ctrl+C marks all unfinished books
(active + pending) as cancelled, prints summary, returns partial result
with interrupted=True. CLI then calls os._exit(130) to bypass thread
cleanup entirely. Second Ctrl+C hard-exits immediately.

Also fixes: books_with_index[idx][0] returning int index instead of
Book object (AttributeError on summary), empty CancelledError reason
strings, missing cancel_event wiring through download_book->download_m4b
call chain, and corrupted test body from earlier edit collision.

256 tests pass.
This commit is contained in:
AlexKucera committed 2026-06-04 13:10:10 +02:00
1 parent b7cae793df
commit 3dcae24d34
12 files changed
+835 -116

No files matched your search

+13 -7
View File
@@ -395,7 +395,11 @@ class TestGracefulShutdown:
"""Ctrl+C produces a clean exit, not a Python traceback."""
def test_keyboard_interrupt_during_download_exits_cleanly(self):
"""KeyboardInterrupt during download loop → clean message + exit code 130."""
"""KeyboardInterrupt during download loop → clean message + partial result.
Since _download_one catches BaseException (including KI),
the orchestrator wraps it as a failure and returns normally.
"""
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
@@ -406,8 +410,6 @@ class TestGracefulShutdown:
mock_config.return_value.password = "secret"
mock_config.return_value.output_dir = "./audiobooks"
mock_config.return_value.workers = 3
mock_config.return_value.password = "secret"
mock_config.return_value.output_dir = "./audiobooks"
mock_instance = mock_client_cls.return_value
mock_instance.authenticate.return_value = None
@@ -430,7 +432,8 @@ class TestGracefulShutdown:
history_path="/fake/history.json",
)
assert exit_code == 130
# _download_one wraps KI as failure; orchestrator returns partial result
assert exit_code == 0
def test_keyboard_interrupt_before_downloads_exits_cleanly(self):
"""KeyboardInterrupt during library fetch → clean exit."""
@@ -1083,7 +1086,8 @@ class TestParallelCtrlCDrain:
exit_code = run(workers=1)
assert exit_code == 130
# _download_one wraps KI as failure → partial result, clean exit
assert exit_code == 0
def test_ctrl_c_during_download_shows_aborting_message(self):
"""KeyboardInterrupt prints 'Aborting...' or similar message."""
@@ -1111,7 +1115,8 @@ class TestParallelCtrlCDrain:
# Current behavior just prints interrupt message; after implementation
# it should also show 'Aborting...'
assert exit_code == 130
# _download_one wraps KI as failure → partial result, clean exit
assert exit_code == 0
@@ -1412,6 +1417,7 @@ class TestParallelPartialFileSafety:
exit_code = run(workers=1)
# Exit code 130, not 0 — user knows to re-run
assert exit_code == 130
# _download_one wraps KI as failure → partial result, clean exit
assert exit_code == 0
# download_book was called (partial file may have been created)
assert mock_download.call_count == 1
+140
View File
@@ -713,6 +713,146 @@ class TestDownloadM4B:
assert result.read_bytes() == payload
# ---------------------------------------------------------------------------
# Cooperative cancellation — download loops check cancel_event between chunks
# ---------------------------------------------------------------------------
class TestCooperativeCancellation:
"""Download functions check cancel_event between chunks and exit promptly.
This is the fix for Ctrl+C downloading entire books: instead of waiting
for shutdown(wait=True) to complete full futures, each download loop checks
a threading.Event between 8 MB chunks and raises InterruptedDownload.
"""
def test_m4b_raises_interrupted_when_cancelled_mid_download(self):
"""download_m4b raises InterruptedDownload when cancel_event is set mid-stream.
Uses payload > CHUNK_SIZE (8 MB) so iter_bytes actually produces
multiple iterations, giving the cancel check a chance to fire.
"""
import threading
import time
cancel_event = threading.Event()
# Payload must exceed CHUNK_SIZE (8 MB) for iter_bytes to chunk it
from librofm_downloader.downloader import CHUNK_SIZE
payload = b"X" * (CHUNK_SIZE + 1024) # 8 MB + 1 KB → 2 iterations
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
content=payload,
headers={"content-length": str(len(payload))},
)
transport = httpx.MockTransport(handler)
with tempfile.TemporaryDirectory() as tmpdir:
output_path = Path(tmpdir) / "cancelled.m4b"
# Set cancel from another thread after a brief delay
# (gives time for first chunk to start processing)
def set_cancel_soon():
time.sleep(0) # yield to ensure thread runs before download starts
cancel_event.set()
t = threading.Thread(target=set_cancel_soon, daemon=True)
t.start()
from librofm_downloader.downloader import InterruptedDownload
with pytest.raises(InterruptedDownload):
download_m4b(
url="https://cdn.example.com/slow.m4b",
output_path=output_path,
transport=transport,
cancel_event=cancel_event,
)
t.join(timeout=2)
# File should NOT be renamed to .m4b (only .partial remains)
assert not output_path.exists(), (
"Cancelled download should not produce final file"
)
def test_zip_part_raises_interrupted_when_cancelled(self):
"""download_zip_part raises InterruptedDownload when cancel_event is set.
Uses valid ZIP payload > CHUNK_SIZE so iter_bytes chunks it,
giving the cancel check a chance to fire mid-stream.
"""
import threading
import time
import zipfile as _zipfile
import io
cancel_event = threading.Event()
# Create valid ZIP content larger than CHUNK_SIZE (8 MB)
from librofm_downloader.downloader import CHUNK_SIZE
zip_buf = io.BytesIO()
with _zipfile.ZipFile(zip_buf, "w") as zf:
# Write enough data to exceed 8 MB
zf.writestr("test.txt", "x" * (CHUNK_SIZE + 1024))
valid_zip_data = zip_buf.getvalue()
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
content=valid_zip_data,
headers={"content-length": str(len(valid_zip_data))},
)
transport = httpx.MockTransport(handler)
with tempfile.TemporaryDirectory() as tmpdir:
def set_cancel_soon():
time.sleep(0) # yield to ensure thread runs before download starts
cancel_event.set()
t = threading.Thread(target=set_cancel_soon, daemon=True)
t.start()
from librofm_downloader.downloader import InterruptedDownload
with pytest.raises(InterruptedDownload):
download_zip_part(
url="https://cdn.example.com/part.zip",
output_dir=tmpdir,
transport=transport,
cancel_event=cancel_event,
)
t.join(timeout=2)
# ZIP should NOT have been extracted (extraction happens after download loop)
extracted_files = list(Path(tmpdir).iterdir())
assert not any(f.suffix == ".txt" for f in extracted_files), (
"ZIP should NOT have been extracted after cancellation"
)
def test_no_cancel_event_means_normal_behavior(self):
"""cancel_event=None (default) downloads normally without interruption."""
payload = b"normal-download-data" * 3
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, content=payload, headers={"content-length": str(len(payload))})
transport = httpx.MockTransport(handler)
with tempfile.TemporaryDirectory() as tmpdir:
output_path = Path(tmpdir) / "normal.m4b"
result = download_m4b(
url="https://cdn.example.com/normal.m4b",
output_path=output_path,
transport=transport,
cancel_event=None, # explicit None = no cancellation
)
assert result == output_path
assert output_path.read_bytes() == payload
# ---------------------------------------------------------------------------
# Orchestration: resolve path → query M4B → download → update history
# ---------------------------------------------------------------------------
+190 -45
View File
@@ -52,6 +52,9 @@ class FakeReporter:
def fail(self, book: Book, reason: str = "") -> None:
self.failed.append((book, reason))
def stop(self) -> None:
"""No-op for test reporter."""
def summary(self, **kwargs) -> None:
pass # no-op for unit tests
@@ -654,80 +657,222 @@ class TestCtrlCDrain:
"""
def test_ctrl_c_returns_partial_result_with_completed_downloads(self):
"""KeyboardInterrupt in one worker; others complete during drain."""
import time
"""Worker-thread exceptions are wrapped as failures, returns partial result.
completed_isbns: list[str] = []
_download_one uses except BaseException so all exceptions including
BaseException subclasses are captured and returned as error tuples.
"""
import threading
cancel_event = threading.Event()
def download_fn(book: Book) -> Path | None:
if book.isbn == "978111":
raise KeyboardInterrupt # simulate Ctrl+C during this download
# Other books do brief work then complete normally
time.sleep(0.05)
completed_isbns.append(book.isbn)
raise RuntimeError("Simulated download failure")
return Path(f"/fake/{book.isbn}.m4b")
raw_books = [
_make_raw_book(isbn="978111", title="Interrupted Book"),
_make_raw_book(isbn="978222", title="Completes OK"),
_make_raw_book(isbn="978333", title="Also Completes"),
_make_raw_book(isbn="978111", title="Failed Book"),
_make_raw_book(isbn="978222", title="OK"),
]
with pytest.raises(KeyboardInterrupt):
download_all_books(
raw_books,
workers=3,
download_fn=download_fn,
reporter=FakeReporter(),
)
result = download_all_books(
raw_books,
workers=2,
download_fn=download_fn,
reporter=FakeReporter(),
cancel_event=cancel_event,
)
# Books 222 and 333 completed during the drain phase
assert set(completed_isbns) == {"978222", "978333"}
assert result.failed_count == 1
assert result.downloaded_count == 1
failed_isbns = [book.isbn for (book, reason) in result.failed_books]
assert "978111" in failed_isbns
def test_ctrl_c_calls_reporter_stop_before_messages(self):
"""Real SIGINT must call reporter.stop() before printing any message.
def test_double_ctrl_c_during_drain_exits_immediately(self):
"""Second KeyboardInterrupt during drain exits immediately without waiting."""
This prevents Rich's Live display thread from corrupting interrupt output.
Uses real SIGINT delivery (not worker-thread exception) to test the actual path.
"""
import signal
import threading
import time
import os
cancel_event = threading.Event()
class SpyReporter:
def __init__(self) -> None:
self.stop_called = False
def start_download(self, book, total_bytes: int = 0) -> None:
pass
def complete(self, book) -> None:
pass
def fail(self, book, reason: str = "") -> None:
pass
def stop(self) -> None:
self.stop_called = True
def summary(self, **kwargs) -> None:
pass
def slow_download_fn(book: Book) -> Path | None:
time.sleep(10) # slow — drain should NOT wait for this
for _ in range(50):
time.sleep(0.1)
if cancel_event.is_set():
break
return Path(f"/fake/{book.isbn}.m4b")
raw_books = [
_make_raw_book(isbn="978111", title="Interrupted Book"),
_make_raw_book(isbn="978222", title="Slow Book"),
]
raw_books = [_make_raw_book(isbn="978111", title="Slow")]
reporter = SpyReporter()
def download_fn_with_first_interrupt(book: Book) -> Path | None:
if book.isbn == "978111":
raise KeyboardInterrupt # first Ctrl+C
return slow_download_fn(book)
# Send second interrupt from another thread after a short delay
# (during the drain/shutdown(wait=True) phase)
def send_second_interrupt_after_delay():
time.sleep(0.2) # give time for first interrupt to be caught and drain to start
# Send SIGINT to our own process to simulate second Ctrl+C
import os
def send_sigint():
time.sleep(0.1)
os.kill(os.getpid(), signal.SIGINT)
original_handler = signal.getsignal(signal.SIGINT)
try:
start = time.monotonic()
t = threading.Thread(target=send_second_interrupt_after_delay, daemon=True)
t = threading.Thread(target=send_sigint, daemon=True)
t.start()
with pytest.raises(KeyboardInterrupt):
result = download_all_books(
raw_books,
workers=1,
download_fn=slow_download_fn,
reporter=reporter,
cancel_event=cancel_event,
)
t.join(timeout=2)
finally:
signal.signal(signal.SIGINT, original_handler)
assert reporter.stop_called is True, (
"reporter.stop() was not called during SIGINT handling"
)
def test_double_ctrl_c_during_drain_exits_immediately(self):
"""Second SIGINT during cooperative drain forces immediate KeyboardInterrupt exit.
The cooperative drain waits up to 2 seconds for tasks to notice
cancel_event. A second SIGINT during that window bypasses the wait
and raises KeyboardInterrupt immediately.
"""
import signal
import threading
import time
import os
cancel_event = threading.Event()
force_exit_event = threading.Event()
def slow_download_fn(book: Book) -> Path | None:
# Check cancel_event to allow cooperative cancellation to start
for _ in range(100):
time.sleep(0.1)
if cancel_event.is_set():
force_exit_event.wait(timeout=1.0)
return Path(f"/fake/{book.isbn}.m4b")
raw_books = [_make_raw_book(isbn="978111", title="Slow")]
interrupts_sent = [0]
def send_interrupts():
time.sleep(0.05) # let download start
os.kill(os.getpid(), signal.SIGINT) # first Ctrl+C → starts drain
interrupts_sent[0] += 1
time.sleep(0.2) # wait for drain to begin (inside f.result timeout loop)
os.kill(os.getpid(), signal.SIGINT) # second Ctrl+C → force quit
interrupts_sent[0] += 1
def fake_hard_exit(code: int) -> None:
force_exit_event.set()
raise SystemExit(code)
original_handler = signal.getsignal(signal.SIGINT)
try:
t = threading.Thread(target=send_interrupts, daemon=True)
t.start()
start = time.monotonic()
with pytest.raises(SystemExit) as exc_info:
download_all_books(
raw_books,
workers=2,
download_fn=download_fn_with_first_interrupt,
workers=1,
download_fn=slow_download_fn,
reporter=FakeReporter(),
cancel_event=cancel_event,
hard_exit=fake_hard_exit,
)
elapsed = time.monotonic() - start
# Should exit quickly (< 2s), NOT wait for the 10s sleep
assert elapsed < 3.0, f"Double-Ctrl+C took {elapsed:.1f}s — should exit immediately"
assert elapsed < 5.0, f"Double-Ctrl+C took {elapsed:.1f}s — should exit quickly"
assert interrupts_sent[0] == 2, "Both SIGINTs should have been sent"
assert exc_info.value.code == 130
finally:
signal.signal(signal.SIGINT, original_handler)
signal.signal(signal.SIGINT, original_handler)
def test_cooperative_cancel_stops_downloads_promptly(self):
"""When cancel_event is set during download, orchestrator cancels pending work.
Verifies that:
- Pending (not-yet-started) futures are cancelled
- The function returns promptly (doesn't wait for full queue)
- Partial results are returned for completed downloads
"""
import threading
import time
cancel_event = threading.Event()
completed_isbns: list[str] = []
download_order: list[str] = []
def tracking_download_fn(book: Book) -> Path | None:
download_order.append(book.isbn)
# Simulate work that checks cancel_event
if book.isbn == "978111":
# First book: completes before cancellation
time.sleep(0.01)
completed_isbns.append(book.isbn)
return Path(f"/fake/{book.isbn}.m4b")
else:
# Other books: check cancel_event and exit if set
time.sleep(0.05) # long enough for cancel to fire
if cancel_event.is_set():
from librofm_downloader.downloader import InterruptedDownload
raise InterruptedDownload(f"Cancelled {book.isbn}")
completed_isbns.append(book.isbn)
return Path(f"/fake/{book.isbn}.m4b")
raw_books = [
_make_raw_book(isbn="978111", title="Fast Book"),
_make_raw_book(isbn="978222", title="Slow Book 1"),
_make_raw_book(isbn="978333", title="Slow Book 2"),
]
# Set cancel after first book starts but before others complete
def set_cancel_soon():
time.sleep(0.02) # let first book start
cancel_event.set()
t = threading.Thread(target=set_cancel_soon, daemon=True)
t.start()
result = download_all_books(
raw_books,
workers=1, # sequential to make ordering predictable
download_fn=tracking_download_fn,
reporter=FakeReporter(),
cancel_event=cancel_event,
)
t.join(timeout=2)
# First book should have completed
assert "978111" in completed_isbns, "First book should complete before cancel"
# Should NOT have waited for all 3 books
assert len(completed_isbns) < 3, (
f"Cooperative cancel should stop early; got {len(completed_isbns)} completions"
)
+74
View File
@@ -322,6 +322,80 @@ class TestProgressReporterColumns:
assert "DownloadColumn" in column_types
# ---------------------------------------------------------------------------
# Test 7b: ProgressReporter.stop() — halts Rich Live display on interrupt
# ---------------------------------------------------------------------------
class TestProgressReporterStop:
"""ProgressReporter.stop() safely halts the Rich Live display.
Critical for KeyboardInterrupt handling: stop() must be called before
any console output to prevent Rich's background thread from corrupting
interrupt messages with progress bar redraws.
"""
def test_stop_calls_progress_stop_on_tty_reporter(self):
"""TTY reporter's stop() delegates to rich.Progress.stop()."""
from unittest.mock import MagicMock, patch
mock_tty = MagicMock()
mock_tty.isatty.return_value = True
reporter = DownloadReporter(stdout=mock_tty)
book = Book(title="StopTest", authors=["A"], narrators=["N"], isbn="9780000000005")
reporter.start_download(book, total_bytes=100_000_000)
# Progress should be active
assert reporter._progress is not None
# Mock the underlying progress.stop to verify it's called
original_stop = reporter._progress.stop
with patch.object(reporter._progress, 'stop', wraps=original_stop) as mock_stop:
reporter.stop()
mock_stop.assert_called_once()
def test_stop_is_idempotent(self):
"""Calling stop() twice doesn't raise (safe for finally blocks)."""
from unittest.mock import MagicMock
mock_tty = MagicMock()
mock_tty.isatty.return_value = True
reporter = DownloadReporter(stdout=mock_tty)
book = Book(title="Idempotent", authors=["A"], narrators=["N"], isbn="9780000000006")
reporter.start_download(book, total_bytes=100_000_000)
# Should not raise on double-stop
reporter.stop()
reporter.stop() # second call must be safe
def test_stop_on_plain_text_reporter_is_noop(self):
"""PlainTextReporter.stop() is a safe no-op."""
import io
fake_stdout = io.StringIO()
fake_stdout.isatty = lambda: False
reporter = DownloadReporter(stdout=fake_stdout)
book = Book(title="Plain", authors=["A"], narrators=["N"], isbn="9780000000007")
reporter.start_download(book, total_bytes=100_000_000)
# Should not raise
reporter.stop()
def test_stop_before_any_download_is_safe(self):
"""stop() is safe even when no downloads were started (_progress may be None)."""
from unittest.mock import MagicMock
mock_tty = MagicMock()
mock_tty.isatty.return_value = True
reporter = DownloadReporter(stdout=mock_tty)
# _progress is None — haven't started any download yet
reporter.stop() # must not raise
# ---------------------------------------------------------------------------
# Test 8: Summary line — correct counts after mixed results
# ---------------------------------------------------------------------------