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

+17 -2
View File
@@ -1,6 +1,8 @@
"""CLI entry point — wire config → auth → fetch library → download → history."""
import os
import sys
import threading
from pathlib import Path
from rich.console import Console
@@ -139,6 +141,7 @@ def run(
# 5. Download loop with TTY-aware reporting
reporter = DownloadReporter()
cancel_event = threading.Event()
console.print(f"\n[bold]{len(new_books)} book(s) to download:[/bold]\n")
# --- Download loop (parallel via orchestrator — Issue #16) ---
@@ -154,6 +157,7 @@ def run(
format_strategy=config.format,
config=config,
progress=reporter.update,
cancel_event=cancel_event,
)
return _download_fn
@@ -162,6 +166,7 @@ def run(
workers=resolved_workers,
download_fn=_make_download_fn(),
reporter=reporter,
cancel_event=cancel_event,
)
downloaded = result.downloaded_count
@@ -178,6 +183,9 @@ def run(
skipped_books=skipped_books,
)
if result.interrupted:
return 130
if verbose:
console.print("[dim]── done ────────────────────────────────────────[/dim]")
@@ -214,14 +222,21 @@ def main() -> None:
)
args = parser.parse_args()
sys.exit(run(
exit_code = run(
config_path=args.config,
secrets_path=args.secrets,
history_path=args.history,
verbose=args.verbose,
limit=args.limit,
workers=args.workers,
))
)
if exit_code == 130:
try:
sys.stdout.flush()
sys.stderr.flush()
finally:
os._exit(130)
sys.exit(exit_code)
if __name__ == "__main__":
+79 -53
View File
@@ -4,6 +4,17 @@ Pure logic module — no I/O, no network. All deterministic string manipulation.
"""
import logging
import threading
class InterruptedDownload(Exception):
"""Raised when a download is cancelled mid-stream via cancel_event.
Signals that the user pressed Ctrl+C and the download loop detected
the cancellation signal between chunks. Distinct from KeyboardInterrupt so
callers can distinguish "user hit Ctrl+C" from "download was cancelled
cooperatively during drain."
"""
import re
from dataclasses import dataclass
from pathlib import Path
@@ -185,6 +196,7 @@ def download_zip_part(
output_dir: Path | str,
transport: httpx.BaseTransport | None = None,
progress: "Callable[[int], None] | None" = None,
cancel_event: threading.Event | None = None,
) -> list[Path]:
"""Download a single ZIP part and extract its contents.
@@ -223,38 +235,44 @@ def download_zip_part(
client = httpx.Client(transport=transport, follow_redirects=True)
mode = "ab" if resume_from > 0 else "wb"
with client.stream("GET", url, headers=headers) as resp:
resp.raise_for_status()
with open(partial_path, mode) as f:
downloaded = resume_from
content_length: int | None = None
for chunk in resp.iter_bytes(chunk_size=CHUNK_SIZE):
f.write(chunk)
downloaded += len(chunk)
if progress:
if content_length is None:
cl_header = resp.headers.get("content-length")
if cl_header:
content_length = int(cl_header)
progress(downloaded, total=content_length)
else:
progress(downloaded)
try:
with client.stream("GET", url, headers=headers) as resp:
resp.raise_for_status()
with open(partial_path, mode) as f:
downloaded = resume_from
content_length: int | None = None
for chunk in resp.iter_bytes(chunk_size=CHUNK_SIZE):
if cancel_event is not None and cancel_event.is_set():
raise InterruptedDownload("Download cancelled by user")
f.write(chunk)
downloaded += len(chunk)
if progress:
if content_length is None:
cl_header = resp.headers.get("content-length")
if cl_header:
content_length = int(cl_header)
progress(downloaded, total=content_length)
else:
progress(downloaded)
# Atomic rename from .partial to .zip
partial_path.rename(zip_path)
# Atomic rename from .partial to .zip
partial_path.rename(zip_path)
# Extract all files from ZIP into output_dir
extracted: list[Path] = []
with _zipfile.ZipFile(zip_path, "r") as zf:
zf.extractall(output_dir)
for name in zf.namelist():
extracted.append(output_dir / name)
# Extract all files from ZIP into output_dir
extracted: list[Path] = []
with _zipfile.ZipFile(zip_path, "r") as zf:
zf.extractall(output_dir)
for name in zf.namelist():
extracted.append(output_dir / name)
# Clean up ZIP file after extraction
zip_path.unlink(missing_ok=True)
# Clean up ZIP file after extraction
zip_path.unlink(missing_ok=True)
logger.info("Downloaded & extracted %s → %d file(s) in %s", url, len(extracted), output_dir)
return extracted
logger.info("Downloaded & extracted %s → %d file(s) in %s", url, len(extracted), output_dir)
return extracted
except InterruptedDownload:
# Skip post-processing on cancellation — partial file stays as .partial
raise
# ---------------------------------------------------------------------------
@@ -267,6 +285,7 @@ def download_m4b(
output_path: Path | str,
transport: httpx.BaseTransport | None = None,
progress: "Callable[[int], None] | None" = None,
cancel_event: threading.Event | None = None,
) -> Path:
"""Download an M4B file via streaming chunks.
@@ -301,29 +320,34 @@ def download_m4b(
mode = "ab" if resume_from > 0 else "wb"
with client.stream("GET", url, headers=headers) as resp:
resp.raise_for_status()
try:
with client.stream("GET", url, headers=headers) as resp:
resp.raise_for_status()
with open(partial_path, mode) as f:
downloaded = resume_from
content_length: int | None = None
for chunk in resp.iter_bytes(chunk_size=CHUNK_SIZE):
f.write(chunk)
downloaded += len(chunk)
if progress:
if content_length is None:
cl_header = resp.headers.get("content-length")
if cl_header:
content_length = int(cl_header)
progress(downloaded, total=content_length)
else:
progress(downloaded)
with open(partial_path, mode) as f:
downloaded = resume_from
content_length: int | None = None
for chunk in resp.iter_bytes(chunk_size=CHUNK_SIZE):
if cancel_event is not None and cancel_event.is_set():
raise InterruptedDownload("Download cancelled by user")
f.write(chunk)
downloaded += len(chunk)
if progress:
if content_length is None:
cl_header = resp.headers.get("content-length")
if cl_header:
content_length = int(cl_header)
progress(downloaded, total=content_length)
else:
progress(downloaded)
# Atomic rename from .partial to final filename
partial_path.rename(output_path)
# Atomic rename from .partial to final filename
partial_path.rename(output_path)
logger.info("Downloaded %s → %s", url, output_path)
return output_path
logger.info("Downloaded %s → %s", url, output_path)
return output_path
except InterruptedDownload:
raise
def _resolve_output_dir(
@@ -364,6 +388,7 @@ def download_book(
config: "Config | None" = None,
transport: httpx.BaseTransport | None = None,
progress: "Callable[[int], None] | None" = None,
cancel_event: threading.Event | None = None,
) -> Path | None:
"""Orchestrate a single book download with format strategy.
@@ -391,7 +416,7 @@ def download_book(
m4b_url = client.fetch_m4b_url(book.isbn, transport=transport)
title_sanitized = sanitize(book.title)
m4b_path = output_dir / f"{title_sanitized}.m4b"
result = download_m4b(m4b_url, m4b_path, transport=transport, progress=progress)
result = download_m4b(m4b_url, m4b_path, transport=transport, progress=progress, cancel_event=cancel_event)
_write_history(history, book, "m4b", str(result))
if config:
download_accompanying_files(book, output_dir, config, client=client, transport=transport)
@@ -400,14 +425,14 @@ def download_book(
logger.info("M4B not available for %s (%s), falling back to MP3", book.title, book.isbn)
# Fall back to MP3
result = _download_mp3(book, client, output_dir, history, transport)
result = _download_mp3(book, client, output_dir, history, transport, progress=progress, cancel_event=cancel_event)
if result and config:
download_accompanying_files(book, output_dir, config, client=client, transport=transport)
return result
# --- mp3_only: skip M4B entirely ---
if format_strategy == "mp3_only":
result = _download_mp3(book, client, output_dir, history, transport)
result = _download_mp3(book, client, output_dir, history, transport, progress=progress, cancel_event=cancel_event)
if result and config:
download_accompanying_files(book, output_dir, config, client=client, transport=transport)
return result
@@ -418,7 +443,7 @@ def download_book(
m4b_url = client.fetch_m4b_url(book.isbn, transport=transport)
title_sanitized = sanitize(book.title)
m4b_path = output_dir / f"{title_sanitized}.m4b"
result = download_m4b(m4b_url, m4b_path, transport=transport, progress=progress)
result = download_m4b(m4b_url, m4b_path, transport=transport, progress=progress, cancel_event=cancel_event)
_write_history(history, book, "m4b", str(result))
if config:
download_accompanying_files(book, output_dir, config, client=client, transport=transport)
@@ -437,6 +462,7 @@ def _download_mp3(
history: "DownloadHistory",
transport: httpx.BaseTransport | None = None,
progress: "Callable[[int], None] | None" = None,
cancel_event: threading.Event | None = None,
) -> Path | None:
"""Fetch MP3 manifest and download all ZIP parts."""
try:
@@ -453,7 +479,7 @@ def _download_mp3(
all_extracted: list[Path] = []
for part in parts:
part_url = part["url"]
extracted = download_zip_part(part_url, output_dir, transport=transport, progress=progress)
extracted = download_zip_part(part_url, output_dir, transport=transport, progress=progress, cancel_event=cancel_event)
all_extracted.extend(extracted)
# Record first extracted file as representative path
+110 -9
View File
@@ -8,7 +8,11 @@ All coordination logic lives here; cli.py stays a thin wiring layer.
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor, as_completed
import os
import sys
import threading
import time
from concurrent.futures import CancelledError, ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
from typing import Any, Callable
@@ -17,6 +21,19 @@ from rich.console import Console
from librofm_downloader.downloader import Book
def _hard_exit(code: int) -> None:
"""Exit immediately without Python thread-pool cleanup.
ThreadPoolExecutor workers may be blocked in HTTP reads and cannot be
killed from Python. `sys.exit()` runs interpreter shutdown hooks that join
those workers, causing Ctrl+C tracebacks. For user interrupts, flush output
then bypass cleanup.
"""
try:
sys.stdout.flush()
sys.stderr.flush()
finally:
os._exit(code)
@dataclass(frozen=True)
class OrchestratorResult:
"""Structured result from a parallel download batch.
@@ -34,6 +51,7 @@ class OrchestratorResult:
failed_count: int = 0
failed_books: list[tuple[Book, str]] = field(default_factory=list)
skipped_books: list[Book] = field(default_factory=list)
interrupted: bool = False
def _raw_to_book(raw: dict) -> Book:
@@ -63,6 +81,7 @@ def _download_one(
book: Book,
download_fn: Callable[[Book], Any],
reporter: Any,
cancel_event: threading.Event | None = None,
) -> tuple[Book, Any, str | None, bool]:
"""Execute one book's download pipeline and return (book, result, error, was_skipped).
@@ -80,7 +99,7 @@ def _download_one(
return book, None, None, True
reporter.complete(book)
return book, result, None, False
except Exception as exc:
except BaseException as exc:
reporter.fail(book, reason=str(exc))
return book, None, str(exc), False
@@ -91,6 +110,8 @@ def download_all_books(
workers: int,
download_fn: Callable[[Book], Any],
reporter: Any,
cancel_event: threading.Event | None = None,
hard_exit: Callable[[int], Any] = _hard_exit,
) -> OrchestratorResult:
"""Run downloads for all books using a thread pool.
@@ -122,9 +143,11 @@ def download_all_books(
executor = ThreadPoolExecutor(max_workers=workers)
executor_shutdown = False
processed_futures: set[Any] = set()
try:
futures = {
executor.submit(_download_one, book, download_fn, reporter): idx
executor.submit(_download_one, book, download_fn, reporter, cancel_event): idx
for idx, book in books_with_index
}
@@ -132,6 +155,7 @@ def download_all_books(
for future in as_completed(futures):
original_idx = futures[future]
book, result, error, was_skipped = future.result()
processed_futures.add(future)
if error:
failed_count += 1
@@ -142,17 +166,94 @@ def download_all_books(
else:
downloaded_count += 1
except KeyboardInterrupt:
# (Console imported at module level)
Console().print("\n[yellow]Aborting...[/yellow] (draining in-flight downloads)")
# --- Cooperative cancellation ---
# 1. Signal download loops to check between chunks and exit
if cancel_event is not None:
cancel_event.set()
# 2. Stop progress display BEFORE printing (prevents Rich corruption)
reporter.stop()
Console().print("\n[yellow]Aborting...[/yellow] (cancelling downloads)")
# 3. Cancel all pending futures (ones not yet started by workers)
for f in futures:
f.cancel()
# 4. Wait briefly for running tasks to notice cancel_event.
# Each download loop checks between 8 MB chunks, so worst case
# is ~1-2 seconds per task at slow connection speeds.
try:
executor.shutdown(wait=True)
deadline = time.monotonic() + 2.0
for f in list(futures):
remaining = deadline - time.monotonic()
if remaining <= 0:
break
try:
f.result(timeout=min(remaining, 0.5))
except Exception:
pass # cancelled/failed/interrupted — collect below
except KeyboardInterrupt:
# Double Ctrl+C → user wants out NOW. Do not rely on Python
# shutdown; worker threads may be blocked in HTTP reads.
Console().print("\n[red]Force quit — partial downloads may be incomplete.[/red]")
executor.shutdown(wait=False, cancel_futures=True)
raise # re-raise immediately for fast exit
raise # re-raise single KeyboardInterrupt for cli.py to handle exit code 130
executor_shutdown = True
hard_exit(130)
# Do not wait for running worker threads here. A worker may be
# blocked in network I/O and Python cannot kill it. Mark every
# unfinished future as aborted, return a partial result, and let
# the CLI hard-exit after printing the summary.
# 5. Collect whatever results we have and mark unfinished work aborted.
for future in list(futures):
if future in processed_futures:
continue
idx = futures.get(future)
if idx is None:
continue
book = books_with_index[idx][1]
if not future.done():
failed_count += 1
failed_books.append((idx, book, "Download cancelled by user"))
continue
try:
_, result, error, was_skipped = future.result()
if error:
failed_count += 1
failed_books.append((idx, book, error or "Download cancelled by user"))
elif was_skipped:
skipped_count += 1
skipped_books.append((idx, book))
else:
downloaded_count += 1
except Exception as exc:
failed_count += 1
failed_books.append((idx, book, "cancelled" if isinstance(exc, CancelledError) else (str(exc) or "Download cancelled by user")))
# 6. Return partial result (no re-raise — CLI will hard-exit)
executor.shutdown(wait=False, cancel_futures=True)
executor_shutdown = True
failed_books.sort(key=lambda x: x[0])
skipped_books.sort(key=lambda x: x[0])
return OrchestratorResult(
downloaded_count=downloaded_count,
skipped_count=skipped_count,
failed_count=failed_count,
failed_books=[(b, r) for (_, b, r) in failed_books],
skipped_books=[b for (_, b) in skipped_books],
interrupted=True,
)
finally:
executor.shutdown(wait=False) # safety: only effective if not already shut down
if not executor_shutdown:
try:
executor.shutdown(wait=True, cancel_futures=True)
except KeyboardInterrupt:
Console().print("\n[red]Force quit — partial downloads may be incomplete.[/red]")
hard_exit(130)
# Stable sort by original index to preserve library order
failed_books.sort(key=lambda x: x[0])
+12
View File
@@ -37,6 +37,9 @@ class PlainTextReporter:
detail = f" ({reason})" if reason else ""
self._print(f"Failed: {authors} - {book.title} [{book.isbn}]{detail}")
def stop(self) -> None:
"""No-op for plain text mode — nothing to stop."""
def update(self, completed: int, *, total: int | None = None) -> None:
"""No-op progress update — plain text mode has no progress bar."""
@@ -148,6 +151,15 @@ class ProgressReporter:
kwargs["total"] = total
self._progress.update(task_id, **kwargs)
def stop(self) -> None:
"""Stop the live progress display.
Must be called before printing any output outside the progress system,
e.g. in KeyboardInterrupt/exception handlers, to prevent display corruption.
"""
if self._progress is not None:
self._progress.stop()
def complete(self, book) -> None:
"""Mark this book's progress bar as complete and remove it."""
task_id = self._book_ids.pop(id(book), None)