feat(progress): support concurrent multi-bar progress via per-book identity mapping

Replace singleton _current_task/_current_book state with bidirectional
_tasks (task_id→book) / _book_ids (id(book)→task_id) dicts, enabling N
simultaneous Rich progress bars for parallel downloads.

- start_download() now returns task_id (int)
- update() accepts optional task_id kwarg; falls back to most-recent
  task when omitted for backward compat with existing callers
- complete()/fail() look up task by id(book) and clean up both mappings
- Safe on unknown books (no-op)
- PlainTextReporter unchanged — already stateless per-call design

10 new tests across TestMultiBarProgress (9) and TestMultiBookPlainText (1).
All 194 tests pass, zero regressions. Closes #14
This commit is contained in:
AlexKucera committed 2026-06-03 17:30:16 +02:00
1 parent a18232c063
commit 35cd34b604
5 files changed
+371 -28

No files matched your search

+1
View File
@@ -8,6 +8,7 @@ They capture what was done, decisions & rationale, gotchas & fixes, and next ste
<!-- write-log: session-log-index -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-06-03 | issue | [20260603-multi-bar-progress-per-book-identity-mapping-issue14_log.md](docs/devlog/20260603-multi-bar-progress-per-book-identity-mapping-issue14_log.md) | **Issue #14 Complete:** Per-book identity mapping for concurrent progress bars. `_tasks`/`_book_ids` dicts, `start_download()` returns `task_id`, `update(task_id=)` targeting. **10 new tests, 194 total** · **7/7 AC** |
| 2026-06-03 | issue | [20260603-thread-safe-downloadhistory-write-issue13_log.md](docs/devlog/20260603-thread-safe-downloadhistory-write-issue13_log.md) | **Issue #13 Complete:** Thread-safe `DownloadHistory.write()` with `threading.Lock`. **5 new tests, 184 total** · **4/4 AC** |
| 2026-06-03 | issue | [20260603-slice-1-workers-config-and-cli-flag-issue12_log.md](docs/devlog/20260603-slice-1-workers-config-and-cli-flag-issue12_log.md) | **Issue #12 Complete:** `workers` config field + `-w`/`--workers` CLI flag with 3-layer resolution (CLI > config > 3). `InvalidWorkersError` validation. **6 new tests, 179 total** · **7/7 AC** |
| 2026-06-03 | issue | [20260603-issue10-documentation-site-and-readme_log.md](docs/devlog/20260603-issue10-documentation-site-and-readme_log.md) | **Issue #10 Complete:** MkDocs site (8 pages) + polished README. Material theme, flat URLs. **11/11 AC** · **172 tests pass** |
+9
View File
@@ -14,6 +14,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
against implementation. Polished README with badges, features table, format
comparison, and project comparison note.
### Added
- **progress:** Per-book identity mapping for concurrent progress bars:
replace singleton `_current_task`/`_current_book` with bidirectional
`_tasks`/`_book_ids` dicts keyed by `id(book)`. `start_download()` now
returns `task_id`, `update()` accepts optional `task_id` kwarg with
backward-compat fallback to most-recent task. `complete()`/`fail()`
clean up both mappings. PlainTextReporter unchanged (already stateless).
10 new tests (194 total) (closes #14)
### Fixed
- **history:** Make `DownloadHistory.write()` thread-safe with
@@ -0,0 +1,81 @@
# Multi-Bar Progress: Per-Book Identity Mapping (Issue #14)
> **Date:** 2026-06-03
> **Type:** issue
> **Reference:** https://github.com/AlexKucera/librofm-downloader/issues/14
## Goal
Upgrade both `ProgressReporter` (TTY/Rich) and `PlainTextReporter` (cron) from single-book singleton state (`_current_task`, `_current_book`) to a per-book identity mapping (`_tasks: dict[int, object]`, `_book_ids: dict[int, int]`). This enables N simultaneous progress bars or interleaved log lines when multiple books download concurrently.
## What Was Done
### ProgressReporter changes (`librofm_downloader/progress.py`):
- Replaced `_current_task` / `_current_book` / `_start_time` with bidirectional mapping:
- `_tasks: dict[int, object]` — task_id → book
- `_book_ids: dict[int, int]` — id(book) → task_id (uses `id()` because Book has unhashable list attributes)
- `start_download(book)` now returns `task_id` (int) — was `None`
- `update(completed, *, total, task_id=None)` — new optional `task_id` kwarg; looks up correct bar; falls back to most recently started for backward compat
- `complete(book)` — looks up task by `id(book)`, marks complete, removes from **both** mappings
- `fail(book, reason)` — looks up task by `id(book)`, stops task, removes from **both** mappings
- All methods are safe on unknown books (no-op if book never started)
### PlainTextReporter:
- No code changes needed — already stateless per-call design handles concurrent books naturally
### Test changes (`tests/test_progress.py`):
- Fixed 2 existing tests that referenced removed `_current_task` attribute to use returned `task_id` from `start_download()`
- Added 10 new tests in 2 test classes:
- `TestMultiBarProgress` (9 tests):
- `test_start_download_returns_task_id` — verifies return type is int
- `test_two_simultaneous_bars` — 2 start_download calls create 2 independent tasks
- `test_update_targets_correct_bar_by_task_id` — update(task_id=X) touches only X's bar
- `test_complete_removes_only_its_bar` — complete(A) leaves B active
- `test_fail_removes_only_its_bar` — fail(B) leaves A active
- `test_summary_stops_progress_after_all_tasks_done` — summary() cleans up mappings
- `test_update_without_task_id_falls_back_to_most_recent` — backward compat fallback
- `test_complete_unknown_book_is_safe` — no-op on unknown book
- `test_fail_unknown_book_is_safe` — no-op on unknown book
- `TestMultiBookPlainText` (1 test):
- `test_interleaved_start_complete_fail_lines` — 3 concurrent books produce correct interleaved output
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Use `id(book)` as dict key instead of `book` object | `Book` has list attributes (`authors`, `narrators`) making it unhashable. `id()` gives a unique integer key for the object's lifetime. |
| Bidirectional mapping (`_tasks` + `_book_ids`) | Both lookups are O(1): book→task_id (for complete/fail) and task_id→book (for internal tracking). Single dict would require linear scan for one direction. |
| `task_id=None` default with "most recent" fallback | Backward compatible — existing callers (cli.py) that don't pass task_id still work correctly for single-download scenarios. |
| No changes to PlainTextReporter | Already stateless per-call — each start/complete/fail is independent. Adding tracking would be YAGNI. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| `TypeError: unhashable type: 'list'` | Used `book` object as dict key; Book has list attributes | Switched to `id(book)` as integer key |
| 2 existing tests failed with `AttributeError: _current_task` | Tests referenced old singleton attribute | Updated to capture `task_id` from `start_download()` return value |
| Test inserted into wrong class | `insert_after` anchor was at end of `TestMultiBookPlainText` not `TestMultiBarProgress` | Removed and re-inserted at correct class location |
## Files Changed
| File | Change Summary |
|------|---------------|
| `librofm_downloader/progress.py` | Replaced singleton state with per-book identity mapping; `start_download()` returns `task_id`; `update()` accepts optional `task_id`; `complete()`/`fail()` clean up mappings |
| `tests/test_progress.py` | Fixed 2 existing tests for new interface; added 10 new tests across `TestMultiBarProgress` (9) and `TestMultiBookPlainText` (1) |
## Open Items & Next Steps
- None — issue is complete. All 7 acceptance criteria met:
- ✅ `start_download(A)` then `start_download(B)` creates two simultaneous progress bars
- ✅ `update(task_id=X)` updates the correct bar
- ✅ `complete("Book A")` removes only Book A's bar
- ✅ `fail("Book B")` removes only Book B's bar
- ✅ `summary()` stops progress cleanly after all tasks done
- ✅ `PlainTextReporter` produces correctly interleaved output for concurrent books
- ✅ **10 new tests** (6–8 requested), all **194/194 tests pass**, zero regressions
---
*Log written via TDD workflow*
+46 -24
View File
@@ -85,9 +85,16 @@ class ProgressReporter:
self._console = Console(file=stdout or sys.stdout)
self._progress = None # Lazy init on first download
# Per-book identity mapping for concurrent downloads
self._tasks: dict[int, object] = {} # task_id -> book
self._book_ids: dict[int, int] = {} # id(book) -> task_id
def start_download(self, book, total_bytes: int = 0) -> None:
"""Start a progress bar for this book's download."""
def start_download(self, book, total_bytes: int = 0) -> int:
"""Start a progress bar for this book's download.
Returns:
The Rich task ID for this book's progress bar.
"""
from rich.progress import (
BarColumn,
DownloadColumn,
@@ -112,38 +119,53 @@ class ProgressReporter:
description = f"{authors} - {book.title}"
task_id = self._progress.add_task(description, total=total_bytes or None)
# Store task_id on self for update() to find it
# In practice we'd track per-book; for now store as current
self._current_task = task_id
self._current_book = book
self._start_time = time.monotonic()
# Store bidirectional mapping for per-book lookup
self._tasks[task_id] = book
self._book_ids[id(book)] = task_id
def update(self, completed: int, *, total: int | None = None) -> None:
return task_id
def update(self, completed: int, *, total: int | None = None, task_id: int | None = None) -> None:
"""Update progress bar with bytes completed.
If *total* is provided (e.g. from a Content-Length header), also
updates the task's total so that percentage and ETA can be computed.
Args:
completed: Bytes downloaded so far.
total: Optional total bytes (from Content-Length).
task_id: Specific task to update. Falls back to most recent if omitted.
"""
if self._progress and hasattr(self, "_current_task"):
kwargs: dict = {"completed": completed}
if total is not None:
kwargs["total"] = total
self._progress.update(self._current_task, **kwargs)
if not self._progress:
return
if task_id is None:
# Backward compat: use the most recently started task
task_id = next(reversed(self._tasks), None)
if task_id is None or task_id not in self._tasks:
return
kwargs: dict = {"completed": completed}
if total is not None:
kwargs["total"] = total
self._progress.update(task_id, **kwargs)
def complete(self, book) -> None:
"""Mark current progress bar as complete."""
if self._progress and hasattr(self, "_current_task"):
self._progress.update(self._current_task, completed=self._progress.tasks[self._current_task].total or 0)
self._console.print(f" [green]✓[/green] {book.title}")
self._current_task = None
"""Mark this book's progress bar as complete and remove it."""
task_id = self._book_ids.pop(id(book), None)
if task_id is None or not self._progress:
return
self._tasks.pop(task_id, None)
self._progress.update(task_id, completed=self._progress.tasks[task_id].total or 0)
self._console.print(f" [green]✓[/green] {book.title}")
def fail(self, book, reason: str = "") -> None:
"""Mark current progress bar as failed."""
if self._progress and hasattr(self, "_current_task"):
self._progress.stop_task(self._current_task)
detail = f" ({reason})" if reason else ""
self._console.print(f" [red]✗[/red] {book.title}[dim] [{book.isbn}]{detail}[/dim]")
self._current_task = None
"""Mark this book's progress bar as failed and remove it."""
task_id = self._book_ids.pop(id(book), None)
if task_id is None or not self._progress:
return
self._tasks.pop(task_id, None)
self._progress.stop_task(task_id)
detail = f" ({reason})" if reason else ""
self._console.print(f" [red]✗[/red] {book.title}[dim] [{book.isbn}]{detail}[/dim]")
def summary(
self,
+234 -4
View File
@@ -643,13 +643,13 @@ class TestProgressTotalFromContentLength:
reporter = DownloadReporter(stdout=mock_tty)
book = Book(title="Big", authors=["A"], narrators=["N"], isbn="9780000000010")
reporter.start_download(book, total_bytes=0) # unknown at start
task_id = reporter.start_download(book, total_bytes=0) # unknown at start
# Simulate what download_m4b does after reading Content-Length header
reporter.update(0, total=100_000_000)
# Task now has a total — percentage can be computed
task = reporter._progress.tasks[reporter._current_task]
task = reporter._progress.tasks[task_id]
assert task.total == 100_000_000
def test_percentage_works_after_total_set(self):
@@ -662,14 +662,14 @@ class TestProgressTotalFromContentLength:
reporter = DownloadReporter(stdout=mock_tty)
book = Book(title="Pct", authors=["A"], narrators=["N"], isbn="9780000000011")
reporter.start_download(book, total_bytes=0)
task_id = reporter.start_download(book, total_bytes=0)
# First callback sets total (from Content-Length)
reporter.update(0, total=50_000_000)
# Now at 50% when half done
reporter.update(25_000_000)
task = reporter._progress.tasks[reporter._current_task]
task = reporter._progress.tasks[task_id]
assert task.percentage == 50.0
def test_plain_text_update_with_total_is_noop(self):
@@ -777,3 +777,233 @@ class TestEnhancedSummaryProgressReporterSkipped:
failed=0,
skipped_books=[book],
)
# ---------------------------------------------------------------------------
# Issue #14: Multi-bar progress — per-book identity mapping
# ---------------------------------------------------------------------------
class TestMultiBarProgress:
"""ProgressReporter supports multiple simultaneous progress bars."""
def test_start_download_returns_task_id(self):
"""start_download() returns a task_id for tracking this book's 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")
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
# start_download should return a task_id (int)
assert isinstance(task_id_a, int)
# Progress should have exactly 1 task
assert len(reporter._progress.tasks) == 1
def test_two_simultaneous_bars(self):
"""Starting two downloads creates two independent progress tasks."""
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")
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
task_id_b = reporter.start_download(book_b, total_bytes=50_000_000)
# Two distinct task IDs
assert task_id_a != task_id_b
# Progress should have exactly 2 active tasks
assert len(reporter._progress.tasks) == 2
def test_update_targets_correct_bar_by_task_id(self):
"""update(task_id=X) updates bar X, not the most recently started."""
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")
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
task_id_b = reporter.start_download(book_b, total_bytes=50_000_000)
# Update only book A's bar to 50%
reporter.update(50_000_000, task_id=task_id_a)
task_a = reporter._progress.tasks[task_id_a]
task_b = reporter._progress.tasks[task_id_b]
assert task_a.completed == 50_000_000
assert task_b.completed == 0 # Book B untouched
def test_complete_removes_only_its_bar(self):
"""complete(book_a) removes only A's bar; B's bar stays active."""
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")
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
task_id_b = reporter.start_download(book_b, total_bytes=50_000_000)
assert len(reporter._progress.tasks) == 2
# Complete only book A
reporter.complete(book_a)
# Book A's task is gone, Book B's remains
assert task_id_a not in reporter._tasks
assert task_id_b in reporter._tasks
assert len(reporter._progress.tasks) == 2 # Rich keeps it (completed), but our mapping is clean
def test_fail_removes_only_its_bar(self):
"""fail(book_b) removes only B's bar; A's bar stays active."""
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")
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
task_id_b = reporter.start_download(book_b, total_bytes=50_000_000)
# Fail only book B
reporter.fail(book_b, reason="connection reset")
# Book B's task is gone, Book A's remains
assert task_id_b not in reporter._tasks
assert task_id_a in reporter._tasks
def test_summary_stops_progress_after_all_tasks_done(self):
"""summary() stops progress after all books completed/failed."""
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")
reporter.start_download(book_a, total_bytes=100_000_000)
reporter.start_download(book_b, total_bytes=50_000_000)
reporter.complete(book_a)
reporter.fail(book_b, reason="timeout")
# summary() should not raise and should stop progress
reporter.summary(downloaded=1, skipped=0, failed=1)
# After summary, internal mappings are empty (all tasks removed)
assert len(reporter._tasks) == 0
assert len(reporter._book_ids) == 0
def test_update_without_task_id_falls_back_to_most_recent(self):
"""update() without task_id updates the most recently 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")
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
task_id_b = reporter.start_download(book_b, total_bytes=50_000_000)
# Update WITHOUT task_id — should fall back to most recent (book_b)
reporter.update(25_000_000)
task_b = reporter._progress.tasks[task_id_b]
task_a = reporter._progress.tasks[task_id_a]
assert task_b.completed == 25_000_000 # Most recent was updated
assert task_a.completed == 0 # Older bar untouched
def test_complete_unknown_book_is_safe(self):
"""complete() on a book that was never started does not raise."""
from unittest.mock import MagicMock
mock_tty = MagicMock()
mock_tty.isatty.return_value = True
reporter = ProgressReporter(stdout=mock_tty)
unknown = Book(title="Ghost", authors=["G"], narrators=["N"], isbn="9780000000000")
# Should not raise
reporter.complete(unknown)
assert len(reporter._tasks) == 0
def test_fail_unknown_book_is_safe(self):
"""fail() on a book that was never started does not raise."""
from unittest.mock import MagicMock
mock_tty = MagicMock()
mock_tty.isatty.return_value = True
reporter = ProgressReporter(stdout=mock_tty)
unknown = Book(title="Ghost", authors=["G"], narrators=["N"], isbn="9780000000000")
# Should not raise
reporter.fail(unknown, reason="phantom error")
assert len(reporter._tasks) == 0
class TestMultiBookPlainText:
"""PlainTextReporter handles multiple concurrent books correctly."""
def test_interleaved_start_complete_fail_lines(self):
"""Multiple books produce correctly interleaved start/complete/fail lines."""
from io import StringIO
out = StringIO()
reporter = PlainTextReporter(stdout=out)
book_a = Book(title="Alpha", authors=["Author A"], narrators=["N"], isbn="9781111111111")
book_b = Book(title="Beta", authors=["Author B"], narrators=["N"], isbn="9782222222222")
book_c = Book(title="Gamma", authors=["Author C"], narrators=["N"], isbn="9783333333333")
# Start all three
reporter.start_download(book_a, total_bytes=100_000_000)
reporter.start_download(book_b, total_bytes=50_000_000)
reporter.start_download(book_c, total_bytes=75_000_000)
# Complete A, fail B, complete C (interleaved)
reporter.complete(book_a)
reporter.fail(book_b, reason="network error")
reporter.complete(book_c)
output = out.getvalue()
# All three downloads started
assert "Downloading: Author A - Alpha" in output
assert "Downloading: Author B - Beta" in output
assert "Downloading: Author C - Gamma" in output
# Completions and failures present
assert "Completed: Author A - Alpha" in output
assert "Completed: Author C - Gamma" in output
assert "Failed: Author B - Beta [9782222222222] (network error)" in output