Repository navigation
Fetch Archive.org metadata concurrently for /api/volumes (#14593) - #14596
pranshup04 wants to merge 3 commits into
Conversation
…hive#14593) ReadProcessor.process called ia.get_metadata in a threadpool worker, fetching Archive.org metadata sequentially. Each uncached scan added up to a 3-second HTTP fetch in sequence. - Add memcache_memoize.call_many_async to batch memcache reads/writes via get_multi/set_multi in worker threads, bounding concurrency with a shared asyncio.Semaphore across foreground misses and background stale refreshes. - Support resilient error handling: read errors fall back to misses, set errors log warnings without raising, malformed JSON envelopes and invalid UTF-8 bytes are isolated per-key without failing the batch. - Fix cancellation safety: retain flag acquisition task during cancellation to verify flag acquisition status and ensure cleanup in finally. - Add ia.get_metadata_many_async and ia.get_api_response_async with default concurrency of 10. - Update ReadProcessor.process to await ia.get_metadata_many_async(iaids) and remove run_in_threadpool. - Add comprehensive test suites for cache resilience, cancellation cleanup, concurrency bounding, cache sharing, negative caching, and readlinks output parity.
for more information, see https://pre-commit.ci
|
Thanks for the PR, @pranshup04! @RayBB is assigned to this PR and currently has:
PR triage checklist (maintainers / Pierre)
Note This comment was automatically generated by Pierre, Open Library's PR first-touch assistant, on behalf of @mekarpeles. This is NOT a code review or sign-off. |
openlibrary-bot
left a comment
There was a problem hiding this comment.
This review is of 409e252. 2d7ad5c was pushed while it ran, so it neither approves nor blocks, and 2d7ad5c gets its own review.
1 finding · 2 suggestions on 409e252
Suggestions (won't block)
-
_background_tasks isn't scoped per event loop ·
openlibrary/core/cache.py:51
_background_tasksis a plain module-levelset, unlike_sf_local_locksa few lines below it in this same file, which is deliberately keyed per running loop because a task/lock created on one loop can't be safely awaited from another (see that function's own docstring). If a refresh task's loop ever closes before the task drains, it stays in_background_tasksindefinitely, and a laterwait_for_background_tasks()call from a different loop would raise instead of completing. Scoping it the same way_sf_local_locksis would avoid the inconsistency. -
No test for a mid-batch f_async failure in call_many_async ·
openlibrary/core/cache.py:172
compute(), which drives the cache-miss half ofcall_many_asyncviaasyncio.gather, has no per-item error handling, unlike_refresh_async.refresh_one, which catches and logs. Onef_asyncexception for any single miss aborts the whole batch, including values already computed for other keys in the same call. Worth a test, since the background-refresh path was deliberately made resilient to exactly this and the miss path wasn't.
Prompt for AI agents (3 open items)
Check if each issue is valid — if so, understand the root cause and fix it. If one isn't valid or won't be fixed in this PR, say why in its thread, or in a comment on the PR if it has none.
<file name="openlibrary/core/cache.py">
<item location="289">Batched memcache calls drop stats instrumentation: `_memcache_get_multi` and `_memcache_set_multi` call `self.memcache.get_multi`/`set_multi` directly with no `stats.begin`/`stats.end` around them, unlike every other memcache call in this file (`memcache_get`, `memcache_set`, and `MemcacheCache.get_multi`/`set_multi`, which wrap theirs). `/api/volumes`'s own debug trace (`options['stats']` in `readlinks.py`, which dumps `web.ctx.get('stats', [])`) used to show per-scan memcache timing via the old single-item calls; that visibility is now silently gone for every request through this batched path.</item>
<item location="51">_background_tasks isn't scoped per event loop: `_background_tasks` is a plain module-level `set`, unlike `_sf_local_locks` a few lines below it in this same file, which is deliberately keyed per running loop because a task/lock created on one loop can't be safely awaited from another (see that function's own docstring). If a refresh task's loop ever closes before the task drains, it stays in `_background_tasks` indefinitely, and a later `wait_for_background_tasks()` call from a different loop would raise instead of completing. Scoping it the same way `_sf_local_locks` is would avoid the inconsistency.</item>
<item location="172">No test for a mid-batch f_async failure in call_many_async: `compute()`, which drives the cache-miss half of `call_many_async` via `asyncio.gather`, has no per-item error handling, unlike `_refresh_async.refresh_one`, which catches and logs. One `f_async` exception for any single miss aborts the whole batch, including values already computed for other keys in the same call. Worth a test, since the background-refresh path was deliberately made resilient to exactly this and the miss path wasn't.</item>
</file>
🎫 Linked issues ✅: #14593 ✅
#14593 - Fully compliant
Compliant requirements:
- Async callers use an async archive.org metadata lookup; no run_in_threadpool around ia.get_metadata in readlinks.py
- Lookups within one request run concurrently
- The async and sync versions share the same memcache entries
- Sync callers of ia.get_metadata keep working unchanged
- Tests for the new async lookup
Please address the feedback above before a maintainer reviews this PR · How this bot works · Reviews new pushes after 10 minutes
openlibrary-bot
left a comment
There was a problem hiding this comment.
No issues found on e2e2063.
✅ Earlier findings: 1 addressed.
🎫 Linked issues ✅: #14593 ✅
#14593 - Fully compliant
Compliant requirements:
- Async callers use an async archive.org metadata lookup; no run_in_threadpool around ia.get_metadata in readlinks.py
- Lookups within one request run concurrently
- The async and sync versions share the same memcache entries
- Sync callers of ia.get_metadata keep working unchanged
- Tests for the new async lookup
A maintainer will review this PR next · How this bot works
Closes #14593. Follows up on #14585.
What does this PR achieve?
Refactor: replace sequential Archive.org metadata lookups in
/api/volumeswith asynchronous, bounded concurrent requests.The threadpool offload introduced in #14585 keeps the event loop responsive, but uncached scans are still fetched one after another. This change fetches them concurrently while preserving shared memcache entries, existing synchronous callers, and volume response behavior.
Technical
openlibrary/core/ia.py, reusingia.get_async_session(), the existing 3-second timeout, metadata normalization, andia-metadataServer-Timing metric.memcache_memoize.call_many_asyncto read and write the existing cache entries through worker-threadget_multi/set_multioperations. Preserve cache keys, JSON encoding, timestamps, cached empty results, and stale-while-revalidate behavior.addcan determine whether the refresh flag was acquired and clean it up.ReadProcessor.processto awaitia.get_metadata_many_async(iaids)and remove therun_in_threadpoolwrapper. Existing synchronousia.get_metadatacallers remain unchanged.Builds on @RayBB’s earlier async implementation in commit
6bbf98f533485941e682383c71a4f50ae4da152f.Testing
Validated in the Python 3.14 Docker environment:
83 passed, 1 warning.
Coverage includes:
show_all_items.All applicable repository pre-commit hooks passed across the seven changed files, including mypy, Ruff linting/formatting, and repository-specific checks.
The warning is a
StarletteDeprecationWarningconcerninghttpxuse by Starlette’sTestClient.Synthetic benchmarks, using simulated upstream responses with a default concurrency cap of 10:
{}Peak measured event-loop scheduling lag was 2.13 ms across the reported scenarios. These measurements demonstrate concurrency and loop responsiveness under simulated conditions; they are not production benchmarks or HTTP
/healthmeasurements.Screenshot
Not applicable; backend change with no UI changes.
Stakeholders
@RayBB