Skip to content

Parallel web_search calls hang in Amplifier's async tool executor #219

Open

Description

@Joi

Summary

When the LLM fires multiple web_search tool calls in parallel (e.g., 9-10 simultaneous searches), all searches hang indefinitely — no results return, no timeout fires, and the session dies. This is reproducible on resume.

Affected module: microsoft/amplifier-module-tool-web

Environment

  • macOS (Apple Silicon)
  • Python 3.11
  • ddgs 9.10.0 + primp 1.0.0
  • Amplifier CLI latest (as of 2026-02-15)

Root Cause Analysis

The WebSearchTool._real_search() method at __init__.py:103-123 has three issues:

  1. No concurrency limit: Each search creates a new DDGS() instance (which internally creates a primp Rust HTTP client) and dispatches it to the default ThreadPoolExecutor via run_in_executor(None, ...). When 9-10 run simultaneously, they appear to deadlock — likely due to thread pool starvation or contention in primp's Rust runtime.

  2. No timeout: If run_in_executor hangs, it hangs forever. There's no asyncio.wait_for() wrapper, so the session becomes permanently stuck.

  3. Deprecated API: Uses asyncio.get_event_loop() instead of asyncio.get_running_loop().

Reproduction

  • Have an LLM session make 9+ parallel web_search tool calls (e.g., looking up phone numbers for multiple businesses)
  • The tool:pre events fire but zero tool:post events are recorded
  • Session becomes unresponsive

Note: The same 9 parallel searches work fine in a standalone asyncio.run() test script. The hang is specific to Amplifier's runtime event loop / thread pool context.

Suggested Fix

class WebSearchTool:
    _search_semaphore: asyncio.Semaphore | None = None
    _SEARCH_TIMEOUT = 30
    _MAX_CONCURRENT = 3

    def __init__(self, config):
        ...
        if WebSearchTool._search_semaphore is None:
            WebSearchTool._search_semaphore = asyncio.Semaphore(self._MAX_CONCURRENT)

    async def _real_search(self, query):
        try:
            def search_sync():
                ddgs = DDGS()
                return [...]

            async with self._search_semaphore:
                loop = asyncio.get_running_loop()
                results = await asyncio.wait_for(
                    loop.run_in_executor(None, search_sync),
                    timeout=self._SEARCH_TIMEOUT,
                )
            return results

        except TimeoutError:
            logger.warning(f"DuckDuckGo search timed out after {self._SEARCH_TIMEOUT}s: {query}")
            return await self._mock_search(query)
        except Exception as e:
            logger.warning(f"DuckDuckGo search failed: {e}, falling back to mock")
            return await self._mock_search(query)

Key changes:

  • Semaphore (max 3 concurrent) prevents thread pool starvation
  • asyncio.wait_for() with 30s timeout prevents infinite hangs, falls back to mock
  • asyncio.get_running_loop() replaces deprecated get_event_loop()

Additional Note: primp/ddgs version mismatch

There's also a cosmetic issue: ddgs 9.10.0 requests browser impersonation profiles (e.g., chrome_126) that primp 1.0.0 doesn't recognize, producing Impersonate 'chrome_126' does not exist, using 'random' warnings. The random fallback works fine — this is noisy but not the cause of the hang. The uv.lock pins ddgs==9.9.2 + primp==0.15.0 (compatible pair) but the installed versions have drifted.


🤖 Generated with Amplifier

Activity

  1. PhilflowIO commented on Apr 18, 2026

    @PhilflowIO

    Cross-reference — the underlying root cause of this hang is very likely not thread-pool starvation but an init-time deadlock inside primp.Client, and it has been diagnosed + fixed upstream in deedy5/ddgs#452.

    Short version: when several threads construct primp.Client(impersonate="random", ...) concurrently, an ordering deadlock can occur between Python's logging._lock (one thread holds it entering the ctor) and an internal Rust mutex (another thread holds it on primp's lazy-init path of the browser-fingerprint data, then tries to acquire logging._lock). After that, no timeout can free the thread — requests/primp timeouts are inter-byte only, and asyncio.to_thread / run_in_executor can't cancel OS threads. That matches your observation exactly: tool:pre fires, no tool:post, session dies, but the same code works fine in a plain asyncio.run() test where the race happens not to hit.

    faulthandler fingerprint to confirm (run faulthandler.dump_traceback_later(30) before the parallel calls):

    • N worker threads stuck in ddgs/http_client.py:53 → primp.Client(...)
    • one thread stuck in logging/__init__.py → getLogger → _lock

    Workarounds until the PR lands upstream:

    1. Minimal one-liner: add a sequential warmup call at startup before any parallel search:

      from ddgs import DDGS
      DDGS(timeout=5).text("warmup", max_results=1)   # blocks once, ~1.5 s

      This pre-initializes primp's Rust statics on a single thread, and the race is gone on every subsequent concurrent call. No code-path changes needed.

    2. Defense-in-depth (keep alongside (1)): wrap the executor call with asyncio.wait_for(..., timeout=N) as you already proposed. Your Semaphore(3) is also a good idea for general rate-limiting against DuckDuckGo, but the hang itself does not actually require >3 concurrent calls — it can fire at 2.

    Once the patched ddgs version is released, both workarounds become optional. The PR description has the full reproducer and a 17/17-green test run.

    (I have no affiliation with either project — just landed this fix in our own stack and figured the signal would help you unblock this one.)

  2. PhilflowIO commented on Apr 18, 2026

    @PhilflowIO

    Upstream root-cause fix now proposed at deedy5/primp#141. It diagnoses the deadlock to Client::new() running the reqwest builder under the GIL, which triggers re-entrant logging.getLogger calls via pyo3-log; releasing the GIL with py.detach around the build eliminates the race at the source. An isolated reproducer (8 threads × primp.Client(impersonate="random"), no ddgs) reliably shows the hang before and ~10 ms completion after. Consumer-side workarounds (the asyncio.wait_for wrap + Semaphore) still make sense as defense-in-depth, but once a patched primp is released you won't actually need them.

  3. deedy5 commented on May 4, 2026

    @deedy5

    ddgs parallel initialization deadlock is fixed in v9.14.1 (deedy5/primp#142)

  4. Joi commented on Jul 5, 2026

    @Joi
    Author

    Root cause is now settled upstream: a parallel primp.Client initialization deadlock, fixed in deedy5/primp#142 (merged 2026-04-20, b63c41da6e2eba0f116aa2874e1fb085d86dc837) and released in primp v1.2.3; ddgs 9.14.1 requires primp>=1.2.3. amplifier-module-tool-web cannot receive that fix: pyproject.toml:15 pins primp>=0.15.0,<1.0.0 (added in 4ed3af01 on 2026-02-15 for an unrelated impersonation breakage), which caps the resolver below the fixed release. The module is unchanged since 26b6d903 (2026-02-17): _real_search still constructs DDGS() per call (amplifier_module_tool_web/__init__.py:114), uses deprecated asyncio.get_event_loop() (:127), and runs run_in_executor with no timeout or concurrency limit (:128), so one hung thread still hangs the session indefinitely. The fix is now small: bump pins to ddgs>=9.14.1 and primp>=1.2.3, and add an asyncio.wait_for timeout as defense in depth.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions