haystack icon indicating copy to clipboard operation
haystack copied to clipboard

feat: Add `run_async` to `MultiQueryEmbeddingRetriever`, `MultiQueryTextRetriever`, and `TextEmbeddingRetriever`

Open sachinn854 opened this issue 6 months ago • 3 comments

Is your feature request related to a problem? Please describe.

MultiQueryEmbeddingRetriever, MultiQueryTextRetriever, and TextEmbeddingRetriever do not implement run_async. When used in an AsyncPipeline, these components fall back to running in a thread executor instead of executing natively as coroutines:

# async_pipeline.py — what happens today for these three components:
outputs = await loop.run_in_executor(None, lambda: instance.run(**inputs))

This means:

  • The event loop is blocked during execution instead of yielding control
  • For MultiQueryEmbeddingRetriever and MultiQueryTextRetriever, an internal ThreadPoolExecutor is spawned inside an already-threaded executor call — resulting in nested threading overhead
  • The run_async methods of wrapped components (embedders, retrievers) are never called, even when they exist

Describe the solution you'd like

Add run_async to all three components, following the established pattern in similar retrievers (MultiRetriever, SentenceWindowRetriever, FilterRetriever, AutoMergingRetriever).

MultiQueryEmbeddingRetriever and MultiQueryTextRetriever

Replace the internal ThreadPoolExecutor with asyncio.gather to parallelize queries natively:

async def run_async(self, queries: list[str], ...) -> dict[str, list[Document]]:
    results = await asyncio.gather(*[self._run_one_async(q) for q in queries])
    docs = [doc for result in results for doc in (result or [])]
    docs = _deduplicate_documents(docs)
    docs.sort(key=lambda x: x.score or 0.0, reverse=True)
    return {"documents": docs}

Each _run_one_async should delegate to the wrapped retriever's run_async if available, falling back to run in an executor otherwise — exactly as MultiRetriever.run_async already does.

TextEmbeddingRetriever

Chain text_embedder.run_async and retriever.run_async sequentially (embedder output feeds retriever input, so parallelism is not possible here):

async def run_async(self, query: str, ...) -> dict[str, list[Document]]:
    if not self._is_warmed_up:
        self.warm_up()
    if hasattr(self.text_embedder, "run_async"):
        embedding_result = await self.text_embedder.run_async(text=query)
    else:
        embedding_result = self.text_embedder.run(text=query)
    if hasattr(self.retriever, "run_async"):
        result = await self.retriever.run_async(query_embedding=embedding_result["embedding"], ...)
    else:
        result = self.retriever.run(query_embedding=embedding_result["embedding"], ...)
    docs = result["documents"]
    docs.sort(key=lambda x: x.score or 0.0, reverse=True)
    return {"documents": docs}

Describe alternatives you've considered

The current thread executor fallback works correctly but is suboptimal:

  • It adds threading overhead inside an async pipeline
  • It never leverages run_async on the wrapped components, even when available
  • For the multi-query variants, it creates nested thread pools (run_in_executor → ThreadPoolExecutor)

Additional context

  • MultiRetriever was introduced in the same PR as TextEmbeddingRetriever (#10872) and already has run_async — the omission in TextEmbeddingRetriever appears to be an oversight.
  • MultiQueryEmbeddingRetriever and MultiQueryTextRetriever were migrated to the main Haystack package via issue #10086 (PR #10126) before async was being actively retrofitted.
  • Dedicated async test files exist for AutoMergingRetriever, FilterRetriever, and SentenceWindowRetriever, but not for these three components.
  • The @component decorator already fully supports optional run_async — no framework changes are needed.

Summary of what's missing

Component run run_async Async test file
InMemoryBM25Retriever ✅ ✅ —
InMemoryEmbeddingRetriever ✅ ✅ —
FilterRetriever ✅ ✅ ✅
AutoMergingRetriever ✅ ✅ ✅
SentenceWindowRetriever ✅ ✅ ✅
MultiRetriever ✅ ✅ —
TextEmbeddingRetriever ✅ ❌ ❌
MultiQueryEmbeddingRetriever ✅ ❌ ❌
MultiQueryTextRetriever ✅ ❌ ❌

sachinn854 avatar May 21 '26 07:05 sachinn854

@sachinn854 thanks for opening the issue! All for adding run_async methods to these components but I did want to push back on this point

The event loop is blocked during execution instead of yielding control

The event loop is not blocked, it offloads the sync call to a thread pool and returns an awaitable, so the event loop is still free to process other tasks while the thread runs. However, you are right that there is now additional (and perhaps unecessary overhead) by needing to spawn a thread pool.

sjrl avatar May 21 '26 07:05 sjrl

Thanks for the correction! You're right — run_in_executor offloads to a thread and returns an awaitable, so the event loop stays free. The real concern is the unnecessary thread pool overhead and that wrapped components' run_async never gets called even when available.

sachinn854 avatar May 21 '26 08:05 sachinn854

Happy to add run_async to these components if this looks good to you!

sachinn854 avatar May 21 '26 08:05 sachinn854