Skip to content

Commit 1ecf363

Browse files
DevChiniwalacodex
andauthored
fix: preserve remote-eval requests across cache invalidation (#158)
* fix: preserve remote-eval requests across cache invalidation Only the future that still owns an in-flight entry may remove it or populate the cache. An older request completing after SSE invalidation must not remove a newer request for the same key. Cover success, empty responses, errors and cancellation in both completion orders through the public asynchronous client. Co-authored-by: Codex <noreply@openai.com> * test: bound remote-eval race regression completion Fail promptly if an in-flight future becomes stranded and cancel pending callers before cleanup. Address the asynchronous-test review finding. Co-authored-by: Codex <noreply@openai.com> * refactor: centralize remote-eval in-flight ownership Address review feedback by sharing the identity-checked release helper and documenting cache flush generations consistently. Co-authored-by: Codex <noreply@openai.com> --------- Co-authored-by: Codex <noreply@openai.com>
1 parent cb3746b commit 1ecf363

2 files changed

Lines changed: 122 additions & 20 deletions

File tree

‎growthbook/growthbook_client.py‎

Lines changed: 25 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -191,9 +191,9 @@ def __init__(self,
191191
# already atomic from asyncio's perspective.
192192
self._remote_eval_cache: "OrderedDict[str, tuple[Dict[str, Any], float]]" = OrderedDict()
193193
self._remote_eval_cache_max = remote_eval_cache_size
194-
# Inflight coalescing AND SWR-dedup: a key in this dict means a POST
195-
# for that cache key is already in flight, so concurrent foreground
196-
# callers and background-SWR refresh tasks both observe and skip.
194+
# Current-generation POSTs for foreground coalescing and SWR dedup.
195+
# A flush clears this map without cancelling older POSTs or waiters,
196+
# allowing a new request for the same cache key in the next generation.
197197
self._remote_eval_inflight: Dict[str, "asyncio.Future[Optional[Dict[str, Any]]]"] = {}
198198
# Fire-and-forget SWR refresh tasks. Tracked so `stop_refresh()` can
199199
# cancel them on shutdown — otherwise they may try to write to a
@@ -222,7 +222,7 @@ async def fetch_remote_eval(
222222
until cache_ttl and then refetched synchronously.
223223
224224
Concurrent foreground callers AND background SWR refreshes coalesce
225-
on a single inflight POST per cache key.
225+
on a single inflight POST per cache key in the current generation.
226226
"""
227227
cache_key = self._compute_cache_key(api_host, client_key, True, payload, cache_key_attributes)
228228
effective_stale_ttl = stale_ttl if stale_ttl is not None else cache_ttl
@@ -261,6 +261,15 @@ async def fetch_remote_eval(
261261
api_host, client_key, payload, cache_key, effective_stale_ttl
262262
)
263263

264+
def _release_inflight(
265+
self, cache_key: str, inflight: "asyncio.Future[Optional[Dict[str, Any]]]"
266+
) -> bool:
267+
"""Remove the entry only if this future still owns it and return ownership."""
268+
if self._remote_eval_inflight.get(cache_key) is inflight:
269+
del self._remote_eval_inflight[cache_key]
270+
return True
271+
return False
272+
264273
async def _post_and_cache(
265274
self,
266275
api_host: str,
@@ -270,8 +279,8 @@ async def _post_and_cache(
270279
effective_stale_ttl: int,
271280
) -> Optional[Dict[str, Any]]:
272281
"""POST + cache-write helper shared by foreground misses and background
273-
SWR refreshes. Registers `cache_key` in the inflight map for the POST's
274-
duration so duplicate POSTs are coalesced. Bumps `stale_at` on every
282+
SWR refreshes. Registers `cache_key` in the inflight map until the POST
283+
completes or a cache flush starts a new generation. Bumps `stale_at` on every
275284
successful write — even an unchanged payload refreshes freshness
276285
(matches JS SDK)."""
277286
# Re-check inflight: a concurrent caller might have raced us.
@@ -288,7 +297,7 @@ async def _post_and_cache(
288297
# derives it from BaseException). Without cleanup on cancellation
289298
# the inflight map leaks the cache_key forever and any waiters
290299
# blocked on `await existing` hang indefinitely.
291-
self._remote_eval_inflight.pop(cache_key, None)
300+
self._release_inflight(cache_key, inflight)
292301
if not inflight.done():
293302
if isinstance(e, asyncio.CancelledError):
294303
# Cancel the inflight Future instead of `set_exception(e)`.
@@ -302,15 +311,11 @@ async def _post_and_cache(
302311
inflight.set_exception(e)
303312
raise
304313

305-
# If `flush_remote_eval_cache()` ran while we were awaiting the POST,
306-
# the cache_key is no longer in `_remote_eval_inflight` — the response
307-
# we just got is from BEFORE the invalidation signal, so writing it to
308-
# the cache would silently re-populate stale data the proxy just told
309-
# us to drop. Still resolve waiters with the response (they observed
310-
# the pre-flush request and have a right to its answer), but skip the
311-
# cache write so future eval calls trigger a fresh POST.
312-
was_flushed = self._remote_eval_inflight.pop(cache_key, None) is None
313-
if response is not None and not was_flushed:
314+
# A flush may have replaced this entry with a newer request for the
315+
# same key. Only the request that still owns the entry may remove it
316+
# and populate the cache. Pre-flush waiters still receive their answer.
317+
owns_entry = self._release_inflight(cache_key, inflight)
318+
if response is not None and owns_entry:
314319
stale_at = time.monotonic() + effective_stale_ttl
315320
self._remote_eval_cache[cache_key] = (response, stale_at)
316321
self._remote_eval_cache.move_to_end(cache_key)
@@ -328,10 +333,10 @@ def flush_remote_eval_cache(self) -> None:
328333
"""Drop all cached remote-eval responses. Called when the proxy
329334
emits a features-updated SSE event.
330335
331-
Also clears the inflight map so any POSTs in flight at this moment
332-
know (via the `was_flushed` check in `_post_and_cache`) that their
333-
result predates the proxy's invalidation signal and must NOT be
334-
written back to the cache."""
336+
Also clears the inflight map so new calls can start a new generation.
337+
Older POSTs still resolve their existing waiters, but no longer own an
338+
entry. `_post_and_cache` checks ownership before removing an entry or
339+
caching a response."""
335340
self._remote_eval_cache.clear()
336341
self._remote_eval_inflight.clear()
337342

‎tests/test_remote_eval.py‎

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1425,3 +1425,100 @@ async def cdn_fetch(api_host, client_key, decryption_key=""):
14251425
client._features_repository.cache.cache.clear() if hasattr(client._features_repository.cache, "cache") else None
14261426
assert await client.initialize() is True
14271427
assert await client.get_feature_value("flag1", "fallback", UserContext(attributes={"id": "u1"})) == "cdn-value"
1428+
1429+
1430+
@pytest.mark.asyncio
1431+
@pytest.mark.parametrize("old_outcome", ["success", "none", "error", "cancel"])
1432+
@pytest.mark.parametrize("old_finishes_first", [True, False])
1433+
async def test_async_inflight_generation_survives_old_request_completion(
1434+
old_outcome, old_finishes_first
1435+
):
1436+
entered = [asyncio.Event(), asyncio.Event()]
1437+
release = [asyncio.Event(), asyncio.Event()]
1438+
calls = 0
1439+
old_response = {"features": {"f": {"defaultValue": "old"}}, "savedGroups": {}}
1440+
fresh_response = {"features": {"f": {"defaultValue": "fresh"}}, "savedGroups": {}}
1441+
1442+
async def post_handler(*args, **kwargs):
1443+
nonlocal calls
1444+
index = calls
1445+
calls += 1
1446+
assert index < 2, "A request in the new generation was not coalesced"
1447+
entered[index].set()
1448+
await release[index].wait()
1449+
if index == 1:
1450+
return fresh_response
1451+
if old_outcome == "error":
1452+
raise RuntimeError("Old request failed")
1453+
return None if old_outcome == "none" else old_response
1454+
1455+
client = await _make_async_client(post_handler)
1456+
user = UserContext(attributes={"id": "generation-user"})
1457+
repository = client._features_repository
1458+
tasks = []
1459+
1460+
async def evaluate():
1461+
return await client.get_feature_value("f", "fallback", user)
1462+
1463+
async def finish_old():
1464+
if old_outcome == "cancel":
1465+
old.cancel()
1466+
else:
1467+
release[0].set()
1468+
results = await asyncio.wait_for(
1469+
asyncio.gather(old, old_waiter, return_exceptions=True), timeout=5
1470+
)
1471+
if old_outcome == "cancel":
1472+
assert all(isinstance(result, asyncio.CancelledError) for result in results)
1473+
elif old_outcome == "error":
1474+
assert all(isinstance(result, RuntimeError) for result in results)
1475+
else:
1476+
expected = "fallback" if old_outcome == "none" else "old"
1477+
assert results == [expected, expected]
1478+
1479+
try:
1480+
old = asyncio.create_task(evaluate())
1481+
tasks.append(old)
1482+
await asyncio.wait_for(entered[0].wait(), timeout=5)
1483+
old_waiter = asyncio.create_task(evaluate())
1484+
tasks.append(old_waiter)
1485+
await asyncio.sleep(0)
1486+
1487+
# An SSE invalidation permits a new request for the same user before
1488+
# the previous generation completes.
1489+
await repository._handle_sse_event({"type": "features-updated"})
1490+
fresh = asyncio.create_task(evaluate())
1491+
tasks.append(fresh)
1492+
await asyncio.wait_for(entered[1].wait(), timeout=5)
1493+
new_key, new_inflight = next(iter(repository._remote_eval_inflight.items()))
1494+
1495+
if old_finishes_first:
1496+
await finish_old()
1497+
assert repository._remote_eval_inflight.get(new_key) is new_inflight
1498+
assert not repository._remote_eval_cache, "Old data repopulated the cache"
1499+
fresh_waiter = asyncio.create_task(evaluate())
1500+
tasks.append(fresh_waiter)
1501+
await asyncio.sleep(0)
1502+
assert calls == 2
1503+
release[1].set()
1504+
assert await asyncio.wait_for(fresh_waiter, timeout=5) == "fresh"
1505+
assert await asyncio.wait_for(fresh, timeout=5) == "fresh"
1506+
else:
1507+
release[1].set()
1508+
assert await asyncio.wait_for(fresh, timeout=5) == "fresh"
1509+
await finish_old()
1510+
1511+
assert await asyncio.wait_for(evaluate(), timeout=5) == "fresh"
1512+
assert calls == 2
1513+
assert not repository._remote_eval_inflight
1514+
assert next(iter(repository._remote_eval_cache.values()))[0] == fresh_response
1515+
finally:
1516+
for gate in release:
1517+
gate.set()
1518+
for task in tasks:
1519+
if not task.done():
1520+
task.cancel()
1521+
await asyncio.wait_for(
1522+
asyncio.gather(*tasks, return_exceptions=True), timeout=5
1523+
)
1524+
await asyncio.wait_for(client.close(), timeout=5)

0 commit comments

Comments
 (0)