diff --git a/deeptutor/services/singleflight_cache.py b/deeptutor/services/singleflight_cache.py index a78ca0296..5927ab536 100644 --- a/deeptutor/services/singleflight_cache.py +++ b/deeptutor/services/singleflight_cache.py @@ -61,8 +61,15 @@ class AsyncSingleFlightTTLCache(Generic[K, V]): return cached pending = self.inflight.get(key) - if pending is None or pending.done(): - pending = asyncio.ensure_future(factory()) + if pending is None: + + async def produce() -> V: + value = await factory() + if cache_when(value): + self.remember(key, value) + return value + + pending = asyncio.create_task(produce()) self.inflight[key] = pending def producer_done(completed: asyncio.Future[V]) -> None: @@ -75,11 +82,7 @@ class AsyncSingleFlightTTLCache(Generic[K, V]): completed.exception() pending.add_done_callback(producer_done) - value = await asyncio.shield(pending) - - if cache_when(value): - self.remember(key, value) - return value + return await asyncio.shield(pending) __all__ = ["AsyncSingleFlightTTLCache"] diff --git a/tests/services/test_singleflight_cache.py b/tests/services/test_singleflight_cache.py index d8d1b5057..2539dd494 100644 --- a/tests/services/test_singleflight_cache.py +++ b/tests/services/test_singleflight_cache.py @@ -150,3 +150,30 @@ async def test_abandoned_producer_failure_is_cleaned_up_and_can_be_retried() -> assert not unhandled finally: loop.set_exception_handler(previous_handler) + + +@pytest.mark.asyncio +async def test_completed_hint_is_cached_after_the_original_waiter_leaves() -> None: + subject = cache([1.0]) + started = asyncio.Event() + release = asyncio.Event() + calls = 0 + + async def produce() -> Value: + nonlocal calls + calls += 1 + started.set() + await release.wait() + return Value("generated hint", 1.0) + + first = asyncio.create_task(subject.get_or_create("key", produce)) + await started.wait() + pending = subject.inflight["key"] + first.cancel() + with pytest.raises(asyncio.CancelledError): + await first + + release.set() + await pending + assert await subject.get_or_create("key", produce) == Value("generated hint", 1.0) + assert calls == 1