fix(progress): wire task_id through parallel progress callback

In parallel download mode, all progress updates went to the same
(most recently started) bar because task_id was never threaded from
start_download() to the update callback. Create per-book closure in
orchestrator that binds task_id, pass through cli._download_fn as
optional kwarg. 3 new regression tests. 259 total.
This commit is contained in:
AlexKucera committed 2026-06-04 13:26:38 +02:00
1 parent 83254750e6
commit 75a6eb61ea
7 files changed
+301 -25

No files matched your search

+21 -21
View File
@@ -71,7 +71,7 @@ class TestSequentialParity:
"""One book, workers=1 → downloaded_count=1, no failures."""
results: list[Path | None] = []
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
results.append(Path(f"/fake/{book.isbn}.m4b"))
return results[-1]
@@ -93,7 +93,7 @@ class TestSequentialParity:
"""Three books, workers=1 → all 3 downloaded, counts correct."""
results: list[Path | None] = []
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
p = Path(f"/fake/{book.isbn}.m4b")
results.append(p)
return p
@@ -127,7 +127,7 @@ class TestSkippedBooks:
def test_skipped_book_returned_in_result(self):
"""download_fn returning None → skipped_count=1, book in skipped_books."""
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
return None # no format available
raw_books = [_make_raw_book(isbn="978111", title="Skip Me")]
@@ -148,7 +148,7 @@ class TestSkippedBooks:
def test_mixed_download_and_skip(self):
"""2 succeed, 1 skipped → correct counts and lists."""
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
if book.isbn == "978222":
return None # skip this one
return Path(f"/fake/{book.isbn}.m4b")
@@ -183,7 +183,7 @@ class TestFailedBooks:
def test_failed_book_with_reason_tuple(self):
"""Exception → failed_count=1, (book, reason_string) in failed_books."""
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
raise ConnectionError("CDN unreachable")
raw_books = [_make_raw_book(isbn="978111", title="Fail Book")]
@@ -206,7 +206,7 @@ class TestFailedBooks:
def test_mixed_success_skip_fail(self):
"""1 downloads, 1 skips, 1 fails → all three buckets populated."""
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
if book.isbn == "978222":
return None
if book.isbn == "978333":
@@ -247,7 +247,7 @@ class TestStableOrdering:
# Book at index 0 takes longer to fail than book at index 1
# This proves stable sort, not completion-order sort
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
if book.isbn == "978111":
time.sleep(0.05) # index 0 is slower
raise RuntimeError(f"fail {book.isbn}")
@@ -271,7 +271,7 @@ class TestStableOrdering:
def test_skipped_books_sorted_by_original_order(self):
"""Skipped books maintain original library order."""
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
return None
raw_books = [
@@ -308,7 +308,7 @@ class TestConcurrency:
start_times: list[float] = []
lock = threading.Lock()
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
with lock:
start_times.append(time.monotonic())
time.sleep(0.05) # simulate work
@@ -347,7 +347,7 @@ class TestFailureIsolation:
"""2nd book fails; 1st and 3rd still succeed."""
results: list[str] = []
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
if book.isbn == "978222":
raise RuntimeError("boom")
results.append(book.isbn)
@@ -376,7 +376,7 @@ class TestFailureIsolation:
completed_isbns: list[str] = []
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
if book.isbn == "978111":
raise RuntimeError("instant fail")
time.sleep(0.03) # other books take time
@@ -413,7 +413,7 @@ class TestCallbackWiring:
"""Each book triggers exactly one download_fn call."""
calls: list[Book] = []
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
calls.append(book)
return Path(f"/fake/{book.isbn}.m4b")
@@ -439,7 +439,7 @@ class TestCallbackWiring:
"""The Book passed to download_fn has all fields from raw dict."""
captured_book: Book | None = None
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
nonlocal captured_book
captured_book = book
return Path("/fake/book.m4b")
@@ -481,7 +481,7 @@ class TestReporterCallbacks:
"""Download success → start_download + complete (no fail)."""
reporter = FakeReporter()
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
return Path(f"/fake/{book.isbn}.m4b")
raw_books = [_make_raw_book(isbn="978111", title="OK")]
@@ -501,7 +501,7 @@ class TestReporterCallbacks:
"""Skipped book (None return) → start + complete, not fail."""
reporter = FakeReporter()
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
return None
raw_books = [_make_raw_book(isbn="978111", title="Skip")]
@@ -521,7 +521,7 @@ class TestReporterCallbacks:
"""Exception → start + fail (no complete)."""
reporter = FakeReporter()
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
raise ConnectionError("network error")
raw_books = [_make_raw_book(isbn="978111", title="Fail")]
@@ -542,7 +542,7 @@ class TestReporterCallbacks:
"""2 ok, 1 skip, 1 fail → correct callback counts."""
reporter = FakeReporter()
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
if book.isbn == "978222":
return None
if book.isbn == "978333":
@@ -578,7 +578,7 @@ class TestEdgeCases:
def test_empty_book_list_returns_zero_result(self):
"""No books → OrchestratorResult with all zeros and empty lists."""
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
raise AssertionError("should never be called") # noqa: TRY003
result = download_all_books(
@@ -597,7 +597,7 @@ class TestEdgeCases:
def test_all_books_fail(self):
"""Every book raises → failed_count=N, others zero."""
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
raise RuntimeError(f"fail {book.isbn}")
raw_books = [
@@ -622,7 +622,7 @@ class TestEdgeCases:
def test_all_books_skipped(self):
"""Every book returns None → skipped_count=N."""
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
return None
raw_books = [
@@ -666,7 +666,7 @@ class TestCtrlCDrain:
cancel_event = threading.Event()
def download_fn(book: Book) -> Path | None:
def download_fn(book: Book, **_kwargs) -> Path | None:
if book.isbn == "978111":
raise RuntimeError("Simulated download failure")
return Path(f"/fake/{book.isbn}.m4b")
+203
View File
@@ -1047,6 +1047,209 @@ class TestMultiBarProgress:
assert len(reporter._tasks) == 0
class TestMultiBookPlainText:
"""Plain-text reporter with multiple books."""
def test_multiple_complete_and_fail(self):
from io import StringIO
out = StringIO()
reporter = PlainTextReporter(stdout=out)
book_a = Book(title="Alpha", authors=["A"], narrators=["N"], isbn="111")
book_b = Book(title="Beta", authors=["B"], narrators=["N"], isbn="222")
reporter.start_download(book_a)
reporter.start_download(book_b)
reporter.complete(book_a)
reporter.fail(book_b, reason="network error")
output = out.getvalue()
assert "Completed: A - Alpha" in output
assert "Failed: B - Beta [222] (network error)" in output
class TestParallelProgressCallbackWiring:
"""Regression test: progress callback must carry task_id to update correct bar.
Bug: when cli.py passes ``progress=reporter.update`` as the callback,
the downloader calls ``progress(downloaded)`` with no task_id.
ProgressReporter.update() falls back to ``next(reversed(self._tasks))``,
so ALL parallel download threads update the same (most recently started) bar.
"""
def test_update_without_task_id_always_hits_most_recent_bar(self):
"""Demonstrates the bug: untargeted updates all go to the last-started bar."""
from unittest.mock import MagicMock
mock_tty = MagicMock()
mock_tty.isatty.return_value = True
reporter = ProgressReporter(stdout=mock_tty)
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
book_c = Book(title="Book C", authors=["Author C"], narrators=["N"], isbn="9783333333333")
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
task_id_b = reporter.start_download(book_b, total_bytes=100_000_000)
task_id_c = reporter.start_download(book_c, total_bytes=100_000_000)
# Simulate what happens in production: each download thread calls
# reporter.update(completed) WITHOUT passing task_id — because
# cli.py wires ``progress=reporter.update`` which loses the identity.
# Thread A reports 50% progress
reporter.update(50_000_000)
# Thread B reports 30% progress
reporter.update(30_000_000)
# Thread C reports 80% progress
reporter.update(80_000_000)
# BUG: all updates went to the most recently started bar (book_c)
# because task_id was None every time, triggering the fallback.
task_a = reporter._progress.tasks[task_id_a]
task_b = reporter._progress.tasks[task_id_b]
task_c = reporter._progress.tasks[task_id_c]
# All three bars show the LAST value written (80M), not their own value
assert task_c.completed == 80_000_000 # last-started bar got ALL updates
assert task_a.completed == 0 # book A never got an update ← THE BUG
assert task_b.completed == 0 # book B never got an update ← THE BUG
def make_progress_callback(self, reporter, task_id):
"""Factory: returns a progress closure bound to a specific task_id.
This is what cli.py SHOULD do instead of passing ``reporter.update`` directly.
"""
def _progress(completed, *, total=None):
reporter.update(completed, total=total, task_id=task_id)
return _progress
def test_bound_callback_updates_correct_bar(self):
"""When each thread gets a task_id-bound callback, bars update independently."""
from unittest.mock import MagicMock
mock_tty = MagicMock()
mock_tty.isatty.return_value = True
reporter = ProgressReporter(stdout=mock_tty)
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
book_c = Book(title="Book C", authors=["Author C"], narrators=["N"], isbn="9783333333333")
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
task_id_b = reporter.start_download(book_b, total_bytes=100_000_1000)
task_id_c = reporter.start_download(book_c, total_bytes=100_000_000)
# Each download thread gets its OWN callback, pre-bound to its task_id
progress_a = self.make_progress_callback(reporter, task_id_a)
progress_b = self.make_progress_callback(reporter, task_id_b)
progress_c = self.make_progress_callback(reporter, task_id_c)
# Each thread reports its own progress
progress_a(50_000_000)
progress_b(30_000_000)
progress_c(80_000_000)
task_a = reporter._progress.tasks[task_id_a]
task_b = reporter._progress.tasks[task_id_b]
task_c = reporter._progress.tasks[task_id_c]
# Each bar shows ITS OWN progress — this is the fixed behavior
assert task_a.completed == 50_000_000
assert task_b.completed == 30_000_000
assert task_c.completed == 80_000_000
class TestParallelProgressCallbackWiring:
"""Regression test: progress callback must carry task_id to update correct bar.
Bug: when cli.py passes ``progress=reporter.update`` as the callback,
the downloader calls ``progress(downloaded)`` with no task_id.
ProgressReporter.update() falls back to ``next(reversed(self._tasks))``,
so ALL parallel download threads update the same (most recently started) bar.
"""
def test_update_without_task_id_always_hits_most_recent_bar(self):
"""Demonstrates the bug: untargeted updates all go to the last-started bar."""
from unittest.mock import MagicMock
mock_tty = MagicMock()
mock_tty.isatty.return_value = True
reporter = ProgressReporter(stdout=mock_tty)
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
book_c = Book(title="Book C", authors=["Author C"], narrators=["N"], isbn="9783333333333")
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
task_id_b = reporter.start_download(book_b, total_bytes=100_000_000)
task_id_c = reporter.start_download(book_c, total_bytes=100_000_000)
# Simulate what happens in production: each download thread calls
# reporter.update(completed) WITHOUT passing task_id — because
# cli.py wires ``progress=reporter.update`` which loses the identity.
# Thread A reports 50% progress
reporter.update(50_000_000)
# Thread B reports 30% progress
reporter.update(30_000_000)
# Thread C reports 80% progress
reporter.update(80_000_000)
# BUG: all updates went to the most recently started bar (book_c)
# because task_id was None every time, triggering the fallback.
task_a = reporter._progress.tasks[task_id_a]
task_b = reporter._progress.tasks[task_id_b]
task_c = reporter._progress.tasks[task_id_c]
# All three bars show the LAST value written (80M), not their own value
assert task_c.completed == 80_000_000 # last-started bar got ALL updates
assert task_a.completed == 0 # book A never got an update ← THE BUG
assert task_b.completed == 0 # book B never got an update ← THE BUG
def make_progress_callback(self, reporter, task_id):
"""Factory: returns a progress closure bound to a specific task_id.
This is what cli.py SHOULD do instead of passing ``reporter.update`` directly.
"""
def _progress(completed, *, total=None):
reporter.update(completed, total=total, task_id=task_id)
return _progress
def test_bound_callback_updates_correct_bar(self):
"""When each thread gets a task_id-bound callback, bars update independently."""
from unittest.mock import MagicMock
mock_tty = MagicMock()
mock_tty.isatty.return_value = True
reporter = ProgressReporter(stdout=mock_tty)
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
book_c = Book(title="Book C", authors=["Author C"], narrators=["N"], isbn="9783333333333")
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
task_id_b = reporter.start_download(book_b, total_bytes=100_000_000)
task_id_c = reporter.start_download(book_c, total_bytes=100_000_000)
# Each download thread gets its OWN callback, pre-bound to its task_id
progress_a = self.make_progress_callback(reporter, task_id_a)
progress_b = self.make_progress_callback(reporter, task_id_b)
progress_c = self.make_progress_callback(reporter, task_id_c)
# Each thread reports its own progress
progress_a(50_000_000)
progress_b(30_000_000)
progress_c(80_000_000)
task_a = reporter._progress.tasks[task_id_a]
task_b = reporter._progress.tasks[task_id_b]
task_c = reporter._progress.tasks[task_id_c]
# Each bar shows ITS OWN progress — this is the fixed behavior
assert task_a.completed == 50_000_000
assert task_b.completed == 30_000_000
assert task_c.completed == 80_000_000
"""PlainTextReporter handles multiple concurrent books correctly."""
def test_interleaved_start_complete_fail_lines(self):