diff --git a/openbb_platform/providers/government_us/openbb_government_us/congress/utils/bulk.py b/openbb_platform/providers/government_us/openbb_government_us/congress/utils/bulk.py index 1880ae9cabf..b5908ac2322 100644 --- a/openbb_platform/providers/government_us/openbb_government_us/congress/utils/bulk.py +++ b/openbb_platform/providers/government_us/openbb_government_us/congress/utils/bulk.py @@ -526,7 +526,10 @@ def _amendment_record(am) -> dict: } -_LOAD_LOCKS: dict[str, asyncio.Lock] = {} +# The loads in flight, keyed by (running loop, key): an asyncio.Lock belongs to +# the loop that first waits on it, and the commands can run on more than one +# loop. An entry lasts only as long as its load, so no closed loop is kept. +_LOAD_LOCKS: dict[tuple, asyncio.Lock] = {} async def _memoized(key: str, loader: Callable[[], Awaitable]): @@ -536,14 +539,20 @@ async def _memoized(key: str, loader: Callable[[], Awaitable]): if cached is not None: return cached - lock = _LOAD_LOCKS.setdefault(key, asyncio.Lock()) - async with lock: - cached = state.bulk.get(key) - if cached is not None: - return cached - records = await loader() - state.bulk[key] = records - return records + lock_key = (asyncio.get_running_loop(), key) + lock = _LOAD_LOCKS.setdefault(lock_key, asyncio.Lock()) + try: + async with lock: + cached = state.bulk.get(key) + if cached is not None: + return cached + records = await loader() + state.bulk[key] = records + return records + finally: + # Waiters hold the lock itself and read the cache once they have it. + if _LOAD_LOCKS.get(lock_key) is lock: + del _LOAD_LOCKS[lock_key] def _legislation_rows_from_records( diff --git a/openbb_platform/providers/government_us/tests/test_congress_bulk.py b/openbb_platform/providers/government_us/tests/test_congress_bulk.py index 6e967a68c52..c0d4bed0726 100644 --- a/openbb_platform/providers/government_us/tests/test_congress_bulk.py +++ b/openbb_platform/providers/government_us/tests/test_congress_bulk.py @@ -1364,6 +1364,45 @@ def test_memoized_dedupes_concurrent_loads(monkeypatch, tmp_path): assert store.bills_loaded(119, "hr") +def test_memoized_load_lock_is_per_event_loop(): + """A load on a second event loop does not reuse the first loop's lock.""" + import threading + + key = "TEST_LOAD_LOCK_ACROSS_LOOPS" + holding, release, outcome = threading.Event(), threading.Event(), {} + + async def _slow(): + holding.set() + while not release.is_set(): + await asyncio.sleep(0.01) + return ["first"] + + async def _contend(): + # The second waiter is what binds an asyncio.Lock to its loop. + return await asyncio.gather( + bulk._memoized(key, _slow), bulk._memoized(key, _slow) + ) + + thread = threading.Thread( + target=lambda: outcome.update(first=asyncio.run(_contend())) + ) + thread.start() + try: + assert holding.wait(5) + + async def _other(): + return ["second"] + + # One lock per key raised "is bound to a different event loop" here. + assert asyncio.run(bulk._memoized(key, _other)) == ["second"] + finally: + release.set() + thread.join(5) + assert len(outcome["first"]) == 2 + # No lock, and so no event loop, outlives its load. + assert not any(k[1] == key for k in bulk._LOAD_LOCKS) + + def test_ensure_billstatus_in_memory_short_circuit(monkeypatch): """A warmed key returns instantly without any download.""" BillsState().bulk.clear()