Libro.fm-downloader downloads audiobooks sequentially: one book must fully complete before the next begins. Audiobook files are large (200 MB – 1 GB each). A fresh sync run with many undownloaded books can take hours of wall-clock time, during which the user's available bandwidth is underutilized and a single hung CDN connection blocks every subsequent book.
Solution
Download multiple books simultaneously using ThreadPoolExecutor. The user controls concurrency via --workers N on the CLI or workers: in config.yaml (default: 3). Each book downloads independently with its own progress bar, error isolation, and history entry. One failure never blocks others.
User Stories
As a user with 20+ undownloaded books, I want books to download in parallel, so that my total sync time is reduced proportionally to my available bandwidth.
As a user running from an interactive terminal, I want one Rich progress bar per actively downloading book, so I can see each book's individual % complete, speed, and ETA at a glance.
As a user running from cron (non-TTY), I want download start/completion/failure log lines to interleave naturally as each book finishes, so my cron output remains readable without progress bar escape codes.
As a user who wants conservative behavior, I want --workers 1 to produce identical sequential behavior to the pre-parallelism version, so I can fall back if needed.
As a user who knows their connection can handle more, I want --workers 8 or higher for maximum throughput on fast connections.
As a user who doesn't want to think about it, I want a sensible default (3 workers) that works well for typical home broadband without angering Libro.fm's API.
As a user editing config.yaml, I want a persistent workers key so I don't have to pass --workers on every invocation.
As a user passing both --workers 5 and having workers: 2 in config.yaml, I want the CLI flag to win, so per-invocation overrides work naturally.
As a user whose download of Book C fails (CDN 502), I want Books A, B, D, E to continue downloading uninterrupted, so one flaky CDN doesn't waste my entire run.
As a user reviewing results after a mixed run, I want the summary grouped by status — succeeded books first, then failed, then skipped — each group in library order, so I can quickly scan what needs attention.
As a user hitting Ctrl+C mid-download, I want immediate feedback ("Aborting...") followed by a graceful drain of in-flight downloads, so I know the signal was received and partial files are in a resume-safe state.
As a user whose process is killed during graceful drain, I want any .partial files to be safely resumable on the next run via HTTP Range headers, just like sequential mode today.
As a user concerned about API rate limits, I want Libro.fm API calls (M4B URL fetch, manifest fetch, PDF URL fetch) capped at 3 concurrent regardless of worker count, so high worker counts don't hammer the API.
As a user with 8 workers, I want CDN file downloads (the actual multi-hundred-MB transfers) to NOT be limited by the API cap, since they go to CloudFront/AWS which handles high concurrency natively.
As a user reading the summary after a parallel run, I want downloaded/skipped/failed counts to be accurate even when multiple books completed within the same millisecond, so I can trust the numbers.
As a developer extending the tool, I want the parallel orchestration logic encapsulated in its own module with a clean interface, so I can test it without HTTP calls or filesystem side effects.
As a developer running the test suite, I want --workers 1 to be exercised alongside --workers 3+, so both sequential and parallel code paths stay green.
As a user with verbose mode enabled, I want per-book detail (URLs, paths, sizes) to still appear correctly when downloads overlap temporally, so verbose output remains useful for debugging.
As a user whose history file gets written to by 3 threads nearly simultaneously, I want the JSON file to never corrupt or lose entries, so my download tracking stays reliable.
As a user with a single new book to download, I want parallel mode to behave identically to sequential mode (one worker is sufficient), with no unnecessary thread overhead.
Implementation Decisions
Concurrency model
concurrent.futures.ThreadPoolExecutor. The codebase is entirely synchronous (httpx.Client, plain functions). Threads release the GIL during HTTP socket I/O (~99% of download time for large file transfers). No async refactor of any existing module.
Worker count configuration
Three-layer resolution: CLI flag > config.yaml key > hardcoded default (3). The Config dataclass gains a workers: int field (default 3, validated ≥ 1). The CLI argparse gains a --workers / -w argument (type int, metavar N, default 0 meaning "use config"). Resolution happens in run(): if CLI value > 0 use it; else use config.workers.
Parallel execution orchestrator (new deep module)
A new function/class encapsulating the ThreadPoolExecutor lifecycle. Interface: accepts a list of books + worker count + a download callback + reporter; returns a result object with counts and per-book outcomes grouped by status in library order. This keeps cli.py.run() at the same abstraction level — it swaps a for loop for orchestrator.run(). Testable without network or filesystem.
Progress reporting — TTY mode (Rich)
The ProgressReporter currently stores a singleton _current_task (one book at a time). This changes to a {task_id: book} mapping supporting N simultaneous tasks. Rich's Progress class already supports multiple concurrent tasks natively. On start_download(): create task, store mapping. On update(): look up current task by caller-provided identity. On complete()/fail(): look up by book, stop/remove task, print status line. When no active tasks remain, the progress display collapses cleanly.
Progress reporting — Plain text (cron)
PlainTextReporter gets the same singleton→dict fix but simpler: no bars to manage, just interleaved log lines. Thread-safe via the same dict lookup pattern.
Error policy
All futures submitted to the pool run to completion or exception individually. as_completed() yields results as each future finishes. Per-future exceptions are caught and recorded as failures; sibling futures continue unaffected. Identical semantics to the current sequential try/except-per-book.
Ctrl+C handling
Signal handler (or except KeyboardInterrupt around the executor block) prints "Aborting..." immediately, then calls executor.shutdown(wait=True) to let in-flight downloads finish. Exit code 130. Partial files remain resume-safe. If the user sends a second Ctrl+C, exit immediately (don't wait forever).
DownloadHistory thread-safety
threading.Lock instance on DownloadHistory. Acquired in write() around both the dict mutation and _flush(). is_downloaded() and find() only read _data (dict reads are atomic in CPython for single operations, and we don't need perfect consistency for a best-effort check). Lock is reentrant-safe for any future internal callers.
API rate limiting (new small module)
A threading.Semaphore(3) wrapping Libro.fm API calls. Applied to: fetch_m4b_url(), fetch_download_manifest(), fetch_pdf_extra_url(). Not applied to: CDN file downloads (download_m4b() streaming, ZIP part downloads). The semaphore lives either as a client wrapper or in the orchestrator layer — decided during implementation based on cleanest fit. Configurable constant, not user-facing.
Summary ordering
Results collected into three lists (downloaded, failed, skipped) as futures complete. Before calling reporter.summary(), each list is re-sorted to match the original fetch_library() order (stable sort by original index). Passed to reporter as ordered collections.
Config schema addition
The Config dataclass gains:
workers: int = 3
Validation: must be ≥ 1. Invalid values raise ConfigError (or a new InvalidWorkersError subclass).
Testing Decisions
Testing philosophy
Tests verify external behavior: correct number of parallel invocations, proper result grouping, lock prevents corruption, progress callbacks fire per-book, graceful drain completes. No testing of ThreadPoolExecutor internals or threading scheduling specifics.
Modules to test
Module
What to test
Estimated tests
Prior art
Config
workers field default (3), validation rejects 0 and negative, accepts from YAML
3–4
test_config.py existing field/validation tests
CLI / Orchestrator
Workers=1 matches sequential behavior; workers=3 submits N futures; one failure doesn't cancel siblings; results grouped by status + library order; Ctrl+C triggers drain; verbose mode works with overlap
Interleaved log lines from concurrent callers; summary aggregates correctly
2–3
test_progress.py TestPlainTextDownloading
ApiRateLimiter
Semaphore blocks at capacity; releases after call; multiple callers serialized correctly
3–4
New — model on test_client.py mock patterns
Downloader integration
download_book() called correctly from multiple threads simultaneously (same args, different books)
2–3
test_downloader.py TestDownloadBook
Total estimated: ~30–42 new tests (from current 3,592 to ~3,625–3,635).
Key test patterns from codebase
Client mocking: test_client.py uses httpx.MockTransport with route-based handlers — reuse this for API rate limiter tests
Downloader mocking: test_downloader.py builds mock LibroFmClient objects with canned return values — reuse for orchestrator tests
Progress assertions: test_progress.py captures reporter method calls and asserts call count/order — extend for multi-bar assertions
History file round-trip: test_history.py writes entries, reads back, asserts JSON structure — extend with threaded writer tests
CLI integration: test_cli.py has full end-to-end tests with mocked client/downloader — add parallel variants
Out of Scope
asyncio migration: Not converting any existing sync code to async. Threads are sufficient for I/O-bound downloads.
Per-book bandwidth limits: No per-download speed throttling. The OS and TCP congestion handle this.
Dynamic worker adjustment: No auto-scaling worker count based on measured bandwidth or latency. User sets it explicitly.
Priority/ordering control: No way to say "download this book first." Library order is preserved in summary but completion order is determined by CDN response times.
Retry with backoff: Failed books are reported in summary; re-running the tool retries them (via existing undownloaded filter). No automatic retry-within-run logic.
Download queue persistence: No saved queue across invocations. Each run re-evaluates from the library API.
Web UI / dashboard: No real-time web view of parallel progress.
Connection pooling sharing: Each thread currently creates its own httpx.Client per API call (existing behavior). Not changing to shared connection pools in this scope.
Domain glossary updated in CONTEXT.md: Sync Run now notes parallel capability; Workers term defined with config layering and API semaphore behavior.
Default of 3 workers is conservative for home broadband (typically 10–100 Mbps down). Users on fiber (500 Mbps–1 Gbps) should increase to 5–8. Users on slow connections (< 10 Mbps) may prefer 1–2.
The --workers flag intentionally uses -w as short flag (not -j like make/ninja) to avoid confusion with job-count conventions that imply CPU-bound parallelism.
## Problem Statement
Libro.fm-downloader downloads audiobooks sequentially: one book must fully complete before the next begins. Audiobook files are large (200 MB – 1 GB each). A fresh sync run with many undownloaded books can take hours of wall-clock time, during which the user's available bandwidth is underutilized and a single hung CDN connection blocks every subsequent book.
## Solution
Download multiple books simultaneously using `ThreadPoolExecutor`. The user controls concurrency via `--workers N` on the CLI or `workers:` in config.yaml (default: 3). Each book downloads independently with its own progress bar, error isolation, and history entry. One failure never blocks others.
## User Stories
1. As a user with 20+ undownloaded books, I want books to download in parallel, so that my total sync time is reduced proportionally to my available bandwidth.
2. As a user running from an interactive terminal, I want one Rich progress bar per actively downloading book, so I can see each book's individual % complete, speed, and ETA at a glance.
3. As a user running from cron (non-TTY), I want download start/completion/failure log lines to interleave naturally as each book finishes, so my cron output remains readable without progress bar escape codes.
4. As a user who wants conservative behavior, I want `--workers 1` to produce identical sequential behavior to the pre-parallelism version, so I can fall back if needed.
5. As a user who knows their connection can handle more, I want `--workers 8` or higher for maximum throughput on fast connections.
6. As a user who doesn't want to think about it, I want a sensible default (3 workers) that works well for typical home broadband without angering Libro.fm's API.
7. As a user editing config.yaml, I want a persistent `workers` key so I don't have to pass `--workers` on every invocation.
8. As a user passing both `--workers 5` and having `workers: 2` in config.yaml, I want the CLI flag to win, so per-invocation overrides work naturally.
9. As a user whose download of Book C fails (CDN 502), I want Books A, B, D, E to continue downloading uninterrupted, so one flaky CDN doesn't waste my entire run.
10. As a user reviewing results after a mixed run, I want the summary grouped by status — succeeded books first, then failed, then skipped — each group in library order, so I can quickly scan what needs attention.
11. As a user hitting Ctrl+C mid-download, I want immediate feedback ("Aborting...") followed by a graceful drain of in-flight downloads, so I know the signal was received and partial files are in a resume-safe state.
12. As a user whose process is killed during graceful drain, I want any `.partial` files to be safely resumable on the next run via HTTP Range headers, just like sequential mode today.
13. As a user concerned about API rate limits, I want Libro.fm API calls (M4B URL fetch, manifest fetch, PDF URL fetch) capped at 3 concurrent regardless of worker count, so high worker counts don't hammer the API.
14. As a user with 8 workers, I want CDN file downloads (the actual multi-hundred-MB transfers) to NOT be limited by the API cap, since they go to CloudFront/AWS which handles high concurrency natively.
15. As a user reading the summary after a parallel run, I want downloaded/skipped/failed counts to be accurate even when multiple books completed within the same millisecond, so I can trust the numbers.
16. As a developer extending the tool, I want the parallel orchestration logic encapsulated in its own module with a clean interface, so I can test it without HTTP calls or filesystem side effects.
17. As a developer running the test suite, I want `--workers 1` to be exercised alongside `--workers 3`+, so both sequential and parallel code paths stay green.
18. As a user with verbose mode enabled, I want per-book detail (URLs, paths, sizes) to still appear correctly when downloads overlap temporally, so verbose output remains useful for debugging.
19. As a user whose history file gets written to by 3 threads nearly simultaneously, I want the JSON file to never corrupt or lose entries, so my download tracking stays reliable.
20. As a user with a single new book to download, I want parallel mode to behave identically to sequential mode (one worker is sufficient), with no unnecessary thread overhead.
## Implementation Decisions
### Concurrency model
`concurrent.futures.ThreadPoolExecutor`. The codebase is entirely synchronous (`httpx.Client`, plain functions). Threads release the GIL during HTTP socket I/O (~99% of download time for large file transfers). No async refactor of any existing module.
### Worker count configuration
Three-layer resolution: CLI flag > config.yaml key > hardcoded default (3). The `Config` dataclass gains a `workers: int` field (default 3, validated ≥ 1). The CLI argparse gains a `--workers` / `-w` argument (type int, metavar N, default 0 meaning "use config"). Resolution happens in `run()`: if CLI value > 0 use it; else use `config.workers`.
### Parallel execution orchestrator (new deep module)
A new function/class encapsulating the ThreadPoolExecutor lifecycle. Interface: accepts a list of books + worker count + a download callback + reporter; returns a result object with counts and per-book outcomes grouped by status in library order. This keeps `cli.py.run()` at the same abstraction level — it swaps a `for` loop for `orchestrator.run()`. Testable without network or filesystem.
### Progress reporting — TTY mode (Rich)
The `ProgressReporter` currently stores a singleton `_current_task` (one book at a time). This changes to a `{task_id: book}` mapping supporting N simultaneous tasks. Rich's `Progress` class already supports multiple concurrent tasks natively. On `start_download()`: create task, store mapping. On `update()`: look up current task by caller-provided identity. On `complete()`/`fail()`: look up by book, stop/remove task, print status line. When no active tasks remain, the progress display collapses cleanly.
### Progress reporting — Plain text (cron)
`PlainTextReporter` gets the same singleton→dict fix but simpler: no bars to manage, just interleaved log lines. Thread-safe via the same dict lookup pattern.
### Error policy
All futures submitted to the pool run to completion or exception individually. `as_completed()` yields results as each future finishes. Per-future exceptions are caught and recorded as failures; sibling futures continue unaffected. Identical semantics to the current sequential try/except-per-book.
### Ctrl+C handling
Signal handler (or except KeyboardInterrupt around the executor block) prints "Aborting..." immediately, then calls `executor.shutdown(wait=True)` to let in-flight downloads finish. Exit code 130. Partial files remain resume-safe. If the user sends a second Ctrl+C, exit immediately (don't wait forever).
### DownloadHistory thread-safety
`threading.Lock` instance on `DownloadHistory`. Acquired in `write()` around both the dict mutation and `_flush()`. `is_downloaded()` and `find()` only read `_data` (dict reads are atomic in CPython for single operations, and we don't need perfect consistency for a best-effort check). Lock is reentrant-safe for any future internal callers.
### API rate limiting (new small module)
A `threading.Semaphore(3)` wrapping Libro.fm API calls. Applied to: `fetch_m4b_url()`, `fetch_download_manifest()`, `fetch_pdf_extra_url()`. Not applied to: CDN file downloads (`download_m4b()` streaming, ZIP part downloads). The semaphore lives either as a client wrapper or in the orchestrator layer — decided during implementation based on cleanest fit. Configurable constant, not user-facing.
### Summary ordering
Results collected into three lists (downloaded, failed, skipped) as futures complete. Before calling `reporter.summary()`, each list is re-sorted to match the original `fetch_library()` order (stable sort by original index). Passed to reporter as ordered collections.
### Config schema addition
The `Config` dataclass gains:
- `workers: int = 3`
Validation: must be ≥ 1. Invalid values raise `ConfigError` (or a new `InvalidWorkersError` subclass).
## Testing Decisions
### Testing philosophy
Tests verify external behavior: correct number of parallel invocations, proper result grouping, lock prevents corruption, progress callbacks fire per-book, graceful drain completes. No testing of ThreadPoolExecutor internals or threading scheduling specifics.
### Modules to test
| Module | What to test | Estimated tests | Prior art |
|---|---|---|---|
| **Config** | `workers` field default (3), validation rejects 0 and negative, accepts from YAML | 3–4 | `test_config.py` existing field/validation tests |
| **CLI / Orchestrator** | Workers=1 matches sequential behavior; workers=3 submits N futures; one failure doesn't cancel siblings; results grouped by status + library order; Ctrl+C triggers drain; verbose mode works with overlap | 10–15 | `test_cli.py` integration tests (TestIntegrationHappyPath, TestCLIDownloadOrchestration) |
| **History** | Concurrent writes don't corrupt JSON; no lost entries under contention; lock is acquired/released | 3–5 | `test_history.py` existing write/find/is_downloaded tests |
| **Progress (TTY)** | Multiple simultaneous bars update independently; complete removes correct bar; fail removes correct bar; summary fires after all done | 6–8 | `test_progress.py` TestProgressCallbackWiring, TestPlainTextDownloading |
| **Progress (plain)** | Interleaved log lines from concurrent callers; summary aggregates correctly | 2–3 | `test_progress.py` TestPlainTextDownloading |
| **ApiRateLimiter** | Semaphore blocks at capacity; releases after call; multiple callers serialized correctly | 3–4 | New — model on `test_client.py` mock patterns |
| **Downloader integration** | `download_book()` called correctly from multiple threads simultaneously (same args, different books) | 2–3 | `test_downloader.py` TestDownloadBook |
**Total estimated: ~30–42 new tests** (from current 3,592 to ~3,625–3,635).
### Key test patterns from codebase
- **Client mocking**: `test_client.py` uses `httpx.MockTransport` with route-based handlers — reuse this for API rate limiter tests
- **Downloader mocking**: `test_downloader.py` builds mock `LibroFmClient` objects with canned return values — reuse for orchestrator tests
- **Progress assertions**: `test_progress.py` captures reporter method calls and asserts call count/order — extend for multi-bar assertions
- **History file round-trip**: `test_history.py` writes entries, reads back, asserts JSON structure — extend with threaded writer tests
- **CLI integration**: `test_cli.py` has full end-to-end tests with mocked client/downloader — add parallel variants
## Out of Scope
- **asyncio migration**: Not converting any existing sync code to async. Threads are sufficient for I/O-bound downloads.
- **Per-book bandwidth limits**: No per-download speed throttling. The OS and TCP congestion handle this.
- **Dynamic worker adjustment**: No auto-scaling worker count based on measured bandwidth or latency. User sets it explicitly.
- **Priority/ordering control**: No way to say "download this book first." Library order is preserved in summary but completion order is determined by CDN response times.
- **Retry with backoff**: Failed books are reported in summary; re-running the tool retries them (via existing undownloaded filter). No automatic retry-within-run logic.
- **Download queue persistence**: No saved queue across invocations. Each run re-evaluates from the library API.
- **Web UI / dashboard**: No real-time web view of parallel progress.
- **Connection pooling sharing**: Each thread currently creates its own `httpx.Client` per API call (existing behavior). Not changing to shared connection pools in this scope.
## Further Notes
- Full architectural rationale documented in [`docs/adr/0001-parallel-downloads.md`](docs/adr/0001-parallel-downloads.md).
- Domain glossary updated in [`CONTEXT.md`](CONTEXT.md): **Sync Run** now notes parallel capability; **Workers** term defined with config layering and API semaphore behavior.
- Default of 3 workers is conservative for home broadband (typically 10–100 Mbps down). Users on fiber (500 Mbps–1 Gbps) should increase to 5–8. Users on slow connections (< 10 Mbps) may prefer 1–2.
- The `--workers` flag intentionally uses `-w` as short flag (not `-j` like make/ninja) to avoid confusion with job-count conventions that imply CPU-bound parallelism.
Slices 1–4 are independent and can be worked in parallel. Slice 5 joins them into the orchestrator. Slice 6 wires it all into the CLI. Slice 7 updates docs once the feature is complete.
## Execution Plan — Vertical Slices
All slices are **AFK** (no human interaction required).
| Slice | Issue | Title | Blocked By | Est. Tests |
|-------|-------|-------|------------|-----------|
| 1 | #12 | Config `workers` field + CLI `--workers` flag | — | 3–4 |
| 2 | #13 | DownloadHistory thread-safety | — | 3–5 |
| 3 | #14 | ProgressReporter multi-bar support | — | 6–8 |
| 4 | #15 | API rate limiter (Semaphore) | — | 3–4 |
| 5 | #16 | Parallel orchestrator module | #12, #13, #14, #15 | 12–15 |
| 6 | #17 | CLI integration + Ctrl+C drain | #16 | 10–12 |
| 7 | **#18** | **Update documentation** | **#17** | — |
**Slices 1–4 are independent** and can be worked in parallel. **Slice 5** joins them into the orchestrator. **Slice 6** wires it all into the CLI. **Slice 7** updates docs once the feature is complete.
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.
Problem Statement
Libro.fm-downloader downloads audiobooks sequentially: one book must fully complete before the next begins. Audiobook files are large (200 MB – 1 GB each). A fresh sync run with many undownloaded books can take hours of wall-clock time, during which the user's available bandwidth is underutilized and a single hung CDN connection blocks every subsequent book.
Solution
Download multiple books simultaneously using
ThreadPoolExecutor. The user controls concurrency via--workers Non the CLI orworkers:in config.yaml (default: 3). Each book downloads independently with its own progress bar, error isolation, and history entry. One failure never blocks others.User Stories
--workers 1to produce identical sequential behavior to the pre-parallelism version, so I can fall back if needed.--workers 8or higher for maximum throughput on fast connections.workerskey so I don't have to pass--workerson every invocation.--workers 5and havingworkers: 2in config.yaml, I want the CLI flag to win, so per-invocation overrides work naturally..partialfiles to be safely resumable on the next run via HTTP Range headers, just like sequential mode today.--workers 1to be exercised alongside--workers 3+, so both sequential and parallel code paths stay green.Implementation Decisions
Concurrency model
concurrent.futures.ThreadPoolExecutor. The codebase is entirely synchronous (httpx.Client, plain functions). Threads release the GIL during HTTP socket I/O (~99% of download time for large file transfers). No async refactor of any existing module.Worker count configuration
Three-layer resolution: CLI flag > config.yaml key > hardcoded default (3). The
Configdataclass gains aworkers: intfield (default 3, validated ≥ 1). The CLI argparse gains a--workers/-wargument (type int, metavar N, default 0 meaning "use config"). Resolution happens inrun(): if CLI value > 0 use it; else useconfig.workers.Parallel execution orchestrator (new deep module)
A new function/class encapsulating the ThreadPoolExecutor lifecycle. Interface: accepts a list of books + worker count + a download callback + reporter; returns a result object with counts and per-book outcomes grouped by status in library order. This keeps
cli.py.run()at the same abstraction level — it swaps aforloop fororchestrator.run(). Testable without network or filesystem.Progress reporting — TTY mode (Rich)
The
ProgressReportercurrently stores a singleton_current_task(one book at a time). This changes to a{task_id: book}mapping supporting N simultaneous tasks. Rich'sProgressclass already supports multiple concurrent tasks natively. Onstart_download(): create task, store mapping. Onupdate(): look up current task by caller-provided identity. Oncomplete()/fail(): look up by book, stop/remove task, print status line. When no active tasks remain, the progress display collapses cleanly.Progress reporting — Plain text (cron)
PlainTextReportergets the same singleton→dict fix but simpler: no bars to manage, just interleaved log lines. Thread-safe via the same dict lookup pattern.Error policy
All futures submitted to the pool run to completion or exception individually.
as_completed()yields results as each future finishes. Per-future exceptions are caught and recorded as failures; sibling futures continue unaffected. Identical semantics to the current sequential try/except-per-book.Ctrl+C handling
Signal handler (or except KeyboardInterrupt around the executor block) prints "Aborting..." immediately, then calls
executor.shutdown(wait=True)to let in-flight downloads finish. Exit code 130. Partial files remain resume-safe. If the user sends a second Ctrl+C, exit immediately (don't wait forever).DownloadHistory thread-safety
threading.Lockinstance onDownloadHistory. Acquired inwrite()around both the dict mutation and_flush().is_downloaded()andfind()only read_data(dict reads are atomic in CPython for single operations, and we don't need perfect consistency for a best-effort check). Lock is reentrant-safe for any future internal callers.API rate limiting (new small module)
A
threading.Semaphore(3)wrapping Libro.fm API calls. Applied to:fetch_m4b_url(),fetch_download_manifest(),fetch_pdf_extra_url(). Not applied to: CDN file downloads (download_m4b()streaming, ZIP part downloads). The semaphore lives either as a client wrapper or in the orchestrator layer — decided during implementation based on cleanest fit. Configurable constant, not user-facing.Summary ordering
Results collected into three lists (downloaded, failed, skipped) as futures complete. Before calling
reporter.summary(), each list is re-sorted to match the originalfetch_library()order (stable sort by original index). Passed to reporter as ordered collections.Config schema addition
The
Configdataclass gains:workers: int = 3Validation: must be ≥ 1. Invalid values raise
ConfigError(or a newInvalidWorkersErrorsubclass).Testing Decisions
Testing philosophy
Tests verify external behavior: correct number of parallel invocations, proper result grouping, lock prevents corruption, progress callbacks fire per-book, graceful drain completes. No testing of ThreadPoolExecutor internals or threading scheduling specifics.
Modules to test
workersfield default (3), validation rejects 0 and negative, accepts from YAMLtest_config.pyexisting field/validation teststest_cli.pyintegration tests (TestIntegrationHappyPath, TestCLIDownloadOrchestration)test_history.pyexisting write/find/is_downloaded teststest_progress.pyTestProgressCallbackWiring, TestPlainTextDownloadingtest_progress.pyTestPlainTextDownloadingtest_client.pymock patternsdownload_book()called correctly from multiple threads simultaneously (same args, different books)test_downloader.pyTestDownloadBookTotal estimated: ~30–42 new tests (from current 3,592 to ~3,625–3,635).
Key test patterns from codebase
test_client.pyuseshttpx.MockTransportwith route-based handlers — reuse this for API rate limiter teststest_downloader.pybuilds mockLibroFmClientobjects with canned return values — reuse for orchestrator teststest_progress.pycaptures reporter method calls and asserts call count/order — extend for multi-bar assertionstest_history.pywrites entries, reads back, asserts JSON structure — extend with threaded writer teststest_cli.pyhas full end-to-end tests with mocked client/downloader — add parallel variantsOut of Scope
httpx.Clientper API call (existing behavior). Not changing to shared connection pools in this scope.Further Notes
docs/adr/0001-parallel-downloads.md.CONTEXT.md: Sync Run now notes parallel capability; Workers term defined with config layering and API semaphore behavior.--workersflag intentionally uses-was short flag (not-jlike make/ninja) to avoid confusion with job-count conventions that imply CPU-bound parallelism.Execution Plan — Vertical Slices
All slices are AFK (no human interaction required).
workersfield + CLI--workersflagSlices 1–4 are independent and can be worked in parallel. Slice 5 joins them into the orchestrator. Slice 6 wires it all into the CLI. Slice 7 updates docs once the feature is complete.