Skip to content

feat(expander): add expand_async for use from async event loops#8

Merged
silversurfer562 merged 1 commit into
mainfrom
perf/expander-async-variant
May 8, 2026
Merged

feat(expander): add expand_async for use from async event loops#8
silversurfer562 merged 1 commit into
mainfrom
perf/expander-async-variant

Conversation

@silversurfer562
Copy link
Copy Markdown
Member

Code-review finding (expander.py:64). Sync messages.create blocked the event loop in attune-gui's RAG routes — every async caller sat for the full Anthropic round-trip.

Adds expand_async that wraps the existing sync expand in asyncio.to_thread. Cache is shared so a hit on either path serves the other. Sync API preserved for non-async callers.

3 new tests. 303 passed.

🤖 Generated with Claude Code

Code-review 2026-05-07 flagged ``QueryExpander.expand`` as a sync
``messages.create`` on the hot path of attune-gui's async route
handlers — sitting on the event loop for the full Anthropic round-
trip (typically 1-3 seconds) blocks every other request behind it.

Add ``async def expand_async(query)`` that:
- Hits the same in-memory cache first; cache hit returns synchronously
  without dispatching to a thread.
- On miss, wraps the existing sync ``expand`` in
  ``asyncio.to_thread`` so the Anthropic call runs off the event loop.

The sync ``expand`` stays — non-async callers (CLI, scripts, tests)
keep their existing API. Cache is shared across both paths.

Implementation note: assigned ``asyncio.to_thread`` to a module-level
``_ASYNCIO_TO_THREAD`` so the import survives auto-format passes that
otherwise prune ``import asyncio`` as unused (the editor's formatter
strips imports it can't see being referenced at the same edit step).

Three new tests cover: parity with sync expand, cache short-circuit
without thread dispatch, and verification that the API call runs on
a different thread than the event loop.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
@silversurfer562 silversurfer562 merged commit 135d202 into main May 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant