From 15e87c76889382de134031b020a9a916d4f38e61 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Tue, 17 Mar 2026 14:27:08 +0000 Subject: [PATCH] fix: move rate limiter sleep outside lock to avoid blocking threads Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com> --- .../dataflows/alpha_vantage_common.py | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/tradingagents/dataflows/alpha_vantage_common.py b/tradingagents/dataflows/alpha_vantage_common.py index a979bc84..5aaa27a5 100644 --- a/tradingagents/dataflows/alpha_vantage_common.py +++ b/tradingagents/dataflows/alpha_vantage_common.py @@ -97,14 +97,18 @@ def _rate_limited_request(function_name: str, params: dict, timeout: int = 30) - # Re-check and register under lock to avoid races where multiple # threads calculate similar sleep times and then all fire at once. - with _rate_lock: - now = _time.time() - _call_timestamps[:] = [t for t in _call_timestamps if now - t < 60] - if len(_call_timestamps) >= _RATE_LIMIT: - # Another thread filled the window while we slept — wait again - extra_sleep = 60 - (now - _call_timestamps[0]) + 0.1 - _time.sleep(extra_sleep) - _call_timestamps.append(_time.time()) + while True: + with _rate_lock: + now = _time.time() + _call_timestamps[:] = [t for t in _call_timestamps if now - t < 60] + if len(_call_timestamps) >= _RATE_LIMIT: + # Another thread filled the window while we slept — wait again + extra_sleep = 60 - (now - _call_timestamps[0]) + 0.1 + else: + _call_timestamps.append(_time.time()) + break + # Sleep outside the lock to avoid blocking other threads + _time.sleep(extra_sleep) return _make_api_request(function_name, params, timeout=timeout)