fix(hints): cache completed results after waiters cancel (#2781)

This commit is contained in:
Rudy Mizrahi Celekli
2026-12-02 02:28:22 -06:00
committed by GitHub
parent 8b565918ce
commit 19348d46eb
2 changed files with 37 additions and 7 deletions

View File

@@ -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"]

View File

@@ -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