fix(history): make write() thread-safe

Guard DownloadHistory.write() with a threading.Lock so concurrent
worker threads do not corrupt or lose history entries during parallel
downloads. Lock wraps both _data mutation and disk flush; read-only
methods (is_downloaded, find) stay lock-free per CPython dict atomicity.

Closes #13
This commit is contained in:
AlexKucera committed 2026-06-03 17:15:57 +02:00
1 parent 2547bd1f22
commit a18232c063
5 files changed
+214 -3

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 --> <!-- write-log: session-log-index -->
| Date | Type | File | Summary | | Date | Type | File | Summary |
|------|------|------|---------| |------|------|------|---------|
| 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-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** | | 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** |
| 2026-06-03 | slice | [20260603-slice-6b-summary-exit-codes-and-integration-tests-issue9_log.md](docs/devlog/20260603-slice-6b-summary-exit-codes-and-integration-tests-issue9_log.md) | **Issue #9 Complete:** Enhanced summary (failed/skipped book details) + graceful Ctrl+C (exit 130) + 3 integration tests. **12 new tests, 168 total** · **15/15 AC** | | 2026-06-03 | slice | [20260603-slice-6b-summary-exit-codes-and-integration-tests-issue9_log.md](docs/devlog/20260603-slice-6b-summary-exit-codes-and-integration-tests-issue9_log.md) | **Issue #9 Complete:** Enhanced summary (failed/skipped book details) + graceful Ctrl+C (exit 130) + 3 integration tests. **12 new tests, 168 total** · **15/15 AC** |
+7
View File
@@ -14,6 +14,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
against implementation. Polished README with badges, features table, format against implementation. Polished README with badges, features table, format
comparison, and project comparison note. comparison, and project comparison note.
### Fixed
- **history:** Make `DownloadHistory.write()` thread-safe with
`threading.Lock` so concurrent worker threads don't corrupt or lose
history entries during parallel downloads. Lock guards both in-memory
mutation and disk flush. 5 new tests (184 total) (closes #13)
### Added ### Added
- **config:** Parallel download worker count: `workers` field on Config dataclass - **config:** Parallel download worker count: `workers` field on Config dataclass
(default 3), `InvalidWorkersError` validation for values < 1, YAML parsing (default 3), `InvalidWorkersError` validation for values < 1, YAML parsing
@@ -0,0 +1,57 @@
# Thread-Safe DownloadHistory.write() (Issue #13)
> **Date:** 2026-06-03
> **Type:** issue
> **Reference:** https://github.com/AlexKucera/librofm-downloader/issues/13
## Goal
Make `DownloadHistory.write()` safe for concurrent callers by adding a `threading.Lock`. Multiple worker threads call `history.write()` simultaneously when books finish downloading in parallel.
## What Was Done
- Added `import threading` and `self._lock = threading.Lock()` to `DownloadHistory.__init__()` (line 5, line 29 of `history.py`)
- Wrapped `write()` body with `with self._lock:` around both `_data` mutation and `_flush()` (lines 57-59)
- Left `is_downloaded()` and `find()` lock-free — CPython dict reads are atomic, and these are best-effort checks where stale reads are acceptable
- Added 5 new tests in `TestThreadSafety` class:
- `test_has_lock_attribute` — verifies `_lock` exists and is a `threading.Lock`
- `test_write_acquires_lock` — monkey-patches `_flush` to be slow; asserts lock is held during execution
- `test_concurrent_writes_no_lost_entries` — 20 threads writing simultaneously; all entries must be findable
- `test_concurrent_writes_produce_valid_json` — concurrent writes must produce parseable JSON with correct entry count
- `test_sequential_behavior_unchanged` — regression guard: sequential write/read/find still works
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Lock only in `write()`, not `is_downloaded()`/`find()` | Issue spec says stale reads are acceptable; CPython GIL makes single-key dict reads atomic anyway. Avoids unnecessary contention on read-hot paths. |
| `threading.Lock` (mutex) not `RLock` | `write()` never calls itself recursively, so reentrancy is unnecessary. Mutex is lighter. |
| Test lock-holding via slow-flush monkey-patch | Directly observable proof that the lock is acquired *during* execution, not just before/after. More robust than checking unlocked state on both sides. |
| 20 threads for concurrency tests | Enough to create real contention on a GIL-released I/O-bound path (`_flush` does disk write), but fast enough that tests complete in <0.1s. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| Test file corruption (duplicate lines) | Multiple `insert_after` edits on stale anchors caused content duplication | Used `replace_lines` with explicit start/end anchors to clean up the file |
| `TypeError: unexpected keyword argument 'author'` | `HistoryEntry` dataclass has no `author` field — only `isbn`, `title`, `format`, `path`, `downloaded_at` | Fixed test to use correct fields matching the actual dataclass definition |
| `TypeError: 'HistoryEntry' object is not subscriptable` | `find()` returns a `HistoryEntry` object, not a dict | Changed `found["title"]` to `found.title` attribute access |
| First version of `test_write_acquires_lock` was trivially passing | Only checked `locked() is False` before and after — true regardless of whether lock is used inside `write()` | Strengthened test to monkey-patch `_flush` with a slow version that checks `locked()` during execution |
## Files Changed
| File | Change Summary |
|------|---------------|
| `librofm_downloader/history.py` | Added `import threading`, `_lock` attribute in `__init__`, `with self._lock:` wrapper in `write()` |
| `tests/test_history.py` | Added `TestThreadSafety` class with 5 tests covering lock init, acquisition, concurrent integrity, JSON validity, regression |
## Open Items & Next Steps
- None — issue is complete. All 4 acceptance criteria met:
- ✅ `_lock` attribute initialized in `__init__`
- ✅ `write()` acquires lock before mutating + flushing
- ✅ 5 new concurrency tests (3–4 requested)
- ✅ **184/184 tests pass**, zero regressions
---
*Log written by write-log skill*
+6 -3
View File
@@ -2,6 +2,7 @@
import json import json
import logging import logging
import threading
from dataclasses import dataclass, asdict from dataclasses import dataclass, asdict
from pathlib import Path from pathlib import Path
@@ -25,6 +26,7 @@ class DownloadHistory:
def __init__(self, path: Path | str): def __init__(self, path: Path | str):
self._path = Path(path) self._path = Path(path)
self._data: dict[str, dict] = {} self._data: dict[str, dict] = {}
self._lock = threading.Lock()
self._load() self._load()
def _load(self) -> None: def _load(self) -> None:
@@ -51,9 +53,10 @@ class DownloadHistory:
return str(isbn) in self._data return str(isbn) in self._data
def write(self, entry: HistoryEntry) -> None: def write(self, entry: HistoryEntry) -> None:
"""Persist a history entry to disk.""" """Persist a history entry to disk. Thread-safe."""
self._data[entry.isbn] = asdict(entry) with self._lock:
self._flush() self._data[entry.isbn] = asdict(entry)
self._flush()
def _flush(self) -> None: def _flush(self) -> None:
"""Write current in-memory state to disk.""" """Write current in-memory state to disk."""
+143
View File
@@ -101,3 +101,146 @@ class TestCorruptRecovery:
history = DownloadHistory(history_path) history = DownloadHistory(history_path)
assert history.is_downloaded("978111") is False assert history.is_downloaded("978111") is False
class TestThreadSafety:
"""Issue #13: DownloadHistory.write() is safe for concurrent callers."""
def test_has_lock_attribute(self):
"""DownloadHistory initialises a _lock threading.Lock."""
import threading
with tempfile.TemporaryDirectory() as tmpdir:
history = DownloadHistory(Path(tmpdir) / "history.json")
assert hasattr(history, "_lock")
assert isinstance(history._lock, type(threading.Lock()))
def test_write_acquires_lock(self):
"""write() acquires _lock during execution and releases it after."""
import time
with tempfile.TemporaryDirectory() as tmpdir:
history = DownloadHistory(Path(tmpdir) / "history.json")
entry = HistoryEntry(
isbn="978000",
title="Test Book",
format="m4b",
path=str(Path(tmpdir) / "book.m4b"),
downloaded_at="2026-06-03T00:00:00Z",
)
lock_held_during_write = []
original_flush = history._flush
def slow_flush():
lock_held_during_write.append(history._lock.locked())
time.sleep(0.05)
original_flush()
history._flush = slow_flush
assert history._lock.locked() is False
history.write(entry)
assert history._lock.locked() is False # released after
assert lock_held_during_write == [True], "Lock must be held during _flush"
def test_concurrent_writes_no_lost_entries(self):
"""Multiple threads calling write() simultaneously don't lose entries."""
import threading
with tempfile.TemporaryDirectory() as tmpdir:
history = DownloadHistory(Path(tmpdir) / "history.json")
num_threads = 20
entries = [
HistoryEntry(
isbn=f"978{i:03d}",
title=f"Book {i}",
format="m4b",
path=str(Path(tmpdir) / f"book{i}.m4b"),
downloaded_at=f"2026-06-03T{i:02d}:00:00Z",
)
for i in range(num_threads)
]
threads = [
threading.Thread(target=history.write, args=(entries[i],))
for i in range(num_threads)
]
for t in threads:
t.start()
for t in threads:
t.join(timeout=5)
# All entries must be present — none lost to race conditions
for i in range(num_threads):
assert history.is_downloaded(f"978{i:03d}"), f"Entry 978{i:03d} was lost"
def test_concurrent_writes_produce_valid_json(self):
"""Concurrent writes don't corrupt the on-disk JSON file."""
import json
import threading
with tempfile.TemporaryDirectory() as tmpdir:
history = DownloadHistory(Path(tmpdir) / "history.json")
num_threads = 20
entries = [
HistoryEntry(
isbn=f"999{i:03d}",
title=f"Concurrent {i}",
format="mp3",
path=str(Path(tmpdir) / f"c{i}.mp3"),
downloaded_at=f"2026-06-04T{i:02d}:00:00Z",
)
for i in range(num_threads)
]
threads = [
threading.Thread(target=history.write, args=(entries[i],))
for i in range(num_threads)
]
for t in threads:
t.start()
for t in threads:
t.join(timeout=5)
# On-disk file must be valid JSON
raw = history._path.read_text()
data = json.loads(raw) # raises if corrupted
assert len(data) == num_threads
def test_sequential_behavior_unchanged(self):
"""Sequential writes still work exactly as before (regression)."""
with tempfile.TemporaryDirectory() as tmpdir:
history = DownloadHistory(Path(tmpdir) / "history.json")
entry1 = HistoryEntry(
isbn="111",
title="First",
format="m4b",
path=str(Path(tmpdir) / "first.m4b"),
downloaded_at="2026-01-01T00:00:00Z",
)
entry2 = HistoryEntry(
isbn="222",
title="Second",
format="mp3",
path=str(Path(tmpdir) / "second.mp3"),
downloaded_at="2026-02-01T00:00:00Z",
)
history.write(entry1)
history.write(entry2)
assert history.is_downloaded("111") is True
assert history.is_downloaded("222") is True
assert history.is_downloaded("999") is False
found = history.find("111")
assert found is not None
assert found.title == "First"