Slice 2: DownloadHistory thread-safety #13

Closed
opened 2026-06-03 16:46:30 +02:00 by AlexKucera · 1 comment
AlexKucera commented 2026-06-03 16:46:30 +02:00 (Migrated from github.com)

Parent

#11

What to build

Make DownloadHistory.write() safe for concurrent callers by adding a threading.Lock. Multiple worker threads will call history.write() simultaneously when books finish downloading in parallel.

Changes to history.py:

  • Add import threading and a _lock = threading.Lock() instance attribute on DownloadHistory.__init__()
  • Acquire self._lock in write() around both self._data[entry.isbn] = asdict(entry) and self._flush()
  • Leave is_downloaded() and find() lock-free — CPython dict reads for single keys are atomic, and these are best-effort checks where stale reads are acceptable
  • Lock is reentrant-safe (Python threading.Lock is a mutex, not a reentrant lock, but write() never calls itself recursively so this is fine)

Acceptance criteria

  • DownloadHistory has a _lock attribute initialized in __init__
  • write() acquires the lock before mutating _data and calling _flush()
  • 3–4 new tests: concurrent writes via threading.Thread do not corrupt JSON; no lost entries under contention; lock is acquired/released; sequential behavior unchanged
  • Existing history tests still pass (no regression)

Blocked by

None - can start immediately

## Parent #11 ## What to build Make `DownloadHistory.write()` safe for concurrent callers by adding a `threading.Lock`. Multiple worker threads will call `history.write()` simultaneously when books finish downloading in parallel. **Changes to `history.py`:** - Add `import threading` and a `_lock = threading.Lock()` instance attribute on `DownloadHistory.__init__()` - Acquire `self._lock` in `write()` around both `self._data[entry.isbn] = asdict(entry)` and `self._flush()` - Leave `is_downloaded()` and `find()` lock-free — CPython dict reads for single keys are atomic, and these are best-effort checks where stale reads are acceptable - Lock is reentrant-safe (Python `threading.Lock` is a mutex, not a reentrant lock, but `write()` never calls itself recursively so this is fine) ## Acceptance criteria - [ ] `DownloadHistory` has a `_lock` attribute initialized in `__init__` - [ ] `write()` acquires the lock before mutating `_data` and calling `_flush()` - [ ] 3–4 new tests: concurrent writes via `threading.Thread` do not corrupt JSON; no lost entries under contention; lock is acquired/released; sequential behavior unchanged - [ ] Existing history tests still pass (no regression) ## Blocked by None - can start immediately
AlexKucera commented 2026-06-03 17:16:07 +02:00 (Migrated from github.com)

Closed via commit a18232c — thread-safe DownloadHistory.write() with threading.Lock. 5 new tests, 184 total passing.

Closed via commit a18232c — thread-safe DownloadHistory.write() with threading.Lock. 5 new tests, 184 total passing.
Sign in to join this conversation.