Skip to content

Fetch Archive.org metadata concurrently for /api/volumes (#14593) - #14596

Open
pranshup04 wants to merge 3 commits into
internetarchive:masterfrom
pranshup04:14593/fetch-ia-metadata-async
Open

pranshup04 wants to merge 3 commits into
internetarchive:masterfrom
pranshup04:14593/fetch-ia-metadata-async

Conversation

@pranshup04

Copy link
Copy Markdown
Contributor

Closes #14593. Follows up on #14585.

What does this PR achieve?

Refactor: replace sequential Archive.org metadata lookups in /api/volumes with 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

  • Add async HTTP and metadata helpers in openlibrary/core/ia.py, reusing ia.get_async_session(), the existing 3-second timeout, metadata normalization, and ia-metadata Server-Timing metric.
  • Add memcache_memoize.call_many_async to read and write the existing cache entries through worker-thread get_multi/set_multi operations. Preserve cache keys, JSON encoding, timestamps, cached empty results, and stale-while-revalidate behavior.
  • Default to 10 concurrent lookups per batch, with the same semaphore used for that batch’s stale refreshes. Deduplicate item IDs before fetching. This is a per-batch limit, not a global rate limit.
  • Treat cache read failures as misses, return fetched metadata when cache writes fail, and isolate malformed JSON or invalid UTF-8 entries without failing the batch.
  • Retain shielded flag-acquisition tasks so cancellation during memcache add can determine whether the refresh flag was acquired and clean it up.
  • Update ReadProcessor.process to await ia.get_metadata_many_async(iaids) and remove the run_in_threadpool wrapper. Existing synchronous ia.get_metadata callers remain unchanged.
  • Keep strong references to background refresh tasks and provide deterministic test synchronization. Application shutdown integration and the remaining synchronous Infobase lookups are outside this change.

Builds on @RayBB’s earlier async implementation in commit 6bbf98f533485941e682383c71a4f50ae4da152f.

Testing

Validated in the Python 3.14 Docker environment:

pytest \
  openlibrary/tests/core/test_cache.py \
  openlibrary/tests/core/test_ia.py \
  openlibrary/plugins/books/tests/test_readlinks.py \
  openlibrary/tests/fastapi/test_books.py

83 passed, 1 warning.

Coverage includes:

  • Concurrent execution and concurrency-limit enforcement.
  • Sync-to-async and async-to-sync cache interoperability.
  • Fresh, stale, missing, and cached empty metadata.
  • Refresh flag contention and cancellation during flag acquisition.
  • Cache failures, malformed entries, and invalid UTF-8.
  • Upstream timeouts and HTTP errors without discarding successful results.
  • Readlinks output parity for full-access, lendable, checked-out, restricted, and missing items, with and without 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 StarletteDeprecationWarning concerning httpx use by Starlette’s TestClient.

Synthetic benchmarks, using simulated upstream responses with a default concurrency cap of 10:

Scenario Result
Cold cache: 50 items, 50 ms upstream delay 0.265 s versus approximately 2.50 s sequential; peak concurrency 10
Warm cache: 50 items 1.75 ms; no upstream requests
Stale cache: 50 items Caller returns in 1.93 ms; refresh peak concurrency 10
Mixed failures: 10 successes, 5 HTTP 503s, 5 timeouts Successful metadata retained; failed lookups return {}

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 /health measurements.

Screenshot

Not applicable; backend change with no UI changes.

Stakeholders

@RayBB

…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.
@openlibrary-bot
openlibrary-bot requested a review from a team November 19, 2026 14:24
@github-project-automation github-project-automation Bot moved this to Waiting Review/Merge from Staff in Ray's Project Nov 19, 2026
@openlibrary-bot

Copy link
Copy Markdown
Collaborator

Thanks for the PR, @pranshup04!

@RayBB is assigned to this PR and currently has:

  • 26 open PR(s) of equal or higher priority to review first.
PR triage checklist (maintainers / Pierre)
  • PR description — not empty; explains what the change does and how to verify it
  • References an issue — PR body contains a #NNN reference
    • Linked issue is triaged — has a Priority: * label (not just Needs: Triage)
    • Linked issue is assigned — has at least one assignee
  • Commit history clean — no WIP/fixup/conflict noise; commit messages are meaningful
  • CI passing — no failing check-runs
  • Test cases present — if the change touches substantive logic, test coverage exists or is explained
  • Proof of testing — PR body includes a description of what was tested, a screenshot, or a video

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 openlibrary-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_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.

  • 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 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.

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

Comment thread openlibrary/core/cache.py Resolved
@openlibrary-bot
openlibrary-bot requested a review from a team November 19, 2026 15:05

@openlibrary-bot openlibrary-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@pranshup04

Copy link
Copy Markdown
Contributor Author

Hi @RayBB, following up on this implementation of #14593. Would you prefer the current scope, or would separating the cache changes from the async metadata integration make review easier? I’ll hold off on restructuring until I hear your preference. Thanks!

@github-actions github-actions Bot added the Needs: Response Issues which require feedback from lead label Dec 6, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Needs: Response Issues which require feedback from lead

Projects

Status: Waiting Review/Merge from Staff

Development

Successfully merging this pull request may close these issues.

Make the archive.org metadata lookup async for /api/volumes

3 participants