From 6d8aef0e9ec53e319cfb031d51e3756d1284c107 Mon Sep 17 00:00:00 2001 From: Volodymyr Nazarkevych Date: Wed, 9 Sep 2026 02:38:00 +0300 Subject: [PATCH 1/5] feat: feature refresh listeners on both clients MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Applications had no supported way to react to a feature payload being applied. The plumbing existed but wasn't reachable: the sync path exposed it only on the module-level feature_repo singleton, and the async path only through client._features_repository, a private attribute, with an async-only callback. Adds add_feature_refresh_listener / remove_feature_refresh_listener to both GrowthBook and GrowthBookClient. The add method returns a callable that unregisters the listener. Listeners receive the raw payload dict and run after it has been applied, so evaluating from inside a listener already sees the new definitions. A listener that raises is logged and skipped. The async client accepts plain functions and coroutine functions alike. Also fixes a gap on the way: the sync streaming path applied payloads and wrote the cache without notifying anything, so in SSE mode — the case this feature exists for — nothing observed the update. Three ordering and lifecycle details, each with a regression test: Dispatch is keyed on payload identity, so listeners fire once per refresh rather than once per evaluation (evaluation calls load_features() constantly and usually gets a cache hit, which returns the same object). A failed refresh no longer clears that identity marker. It applies nothing, so the payload listeners last saw is unchanged; clearing it made the next cache hit — which returns that same previously-notified object — look fresh and fire listeners a second time. Apply and notify happen as one unit. In the sync client that is the reentrant payload-writer lock, which evaluation never takes. In the async client it is a separate ordering lock, since evaluation takes the context lock and notifying under that one deadlocks any listener that evaluates. Without this, two overlapping refreshes could apply A, apply and notify B, then notify A — handing listeners an older payload last and letting a listener see state that doesn't match the payload it was given. GrowthBookClient.close() clears the listener list, matching subscriptions and the sync client. Listener closures capture application objects, and a reinitialized client would otherwise fire callbacks from its previous lifecycle. --- README.md | 35 +++++++ growthbook/growthbook.py | 90 +++++++++++++++++- growthbook/growthbook_client.py | 72 +++++++++++++++ tests/test_growthbook.py | 125 +++++++++++++++++++++++++ tests/test_growthbook_client.py | 157 ++++++++++++++++++++++++++++++++ 5 files changed, 474 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 411b098..992c26f 100644 --- a/README.md +++ b/README.md @@ -289,6 +289,41 @@ client = GrowthBookClient( ) ``` +### Feature Refresh Listeners + +Both clients can notify your application whenever a new feature payload is +applied, so you can react to updates instead of polling: + +```python +def on_refresh(payload): + log.info("features updated: %d flags", len(payload.get("features", {}))) + +unsubscribe = gb.add_feature_refresh_listener(on_refresh) +# ...later +unsubscribe() +``` + +The listener receives the raw payload dict (`features`, `savedGroups`, …) and +runs *after* it has been applied, so evaluating a feature from inside the +listener already sees the new definitions. It fires once per refresh — not once +per evaluation — covering HTTP loads, the stale-while-revalidate background +worker and streaming (SSE) updates. A listener that raises is logged and +skipped; it cannot break a refresh. + +On the async client the listener may be a plain function or a coroutine +function: + +```python +async def on_refresh(payload): + await cache.invalidate() + +unsubscribe = gb_client.add_feature_refresh_listener(on_refresh) +``` + +Remote-eval mode emits no events on the async client: payloads there are +per-user, so there is no client-wide "definitions changed" moment to report. +The sync client, which is already per-user, does fire them. + ### Concurrency and Thread Safety The async client is designed to be thread-safe and handle concurrent requests efficiently. You can safely use a single client instance across multiple coroutines. For web applications, you can create a single client instance at startup and share it across requests. Here's an example: diff --git a/growthbook/growthbook.py b/growthbook/growthbook.py index ded32bc..571cc5d 100644 --- a/growthbook/growthbook.py +++ b/growthbook/growthbook.py @@ -1005,6 +1005,12 @@ def __init__( self._deferred_buffer: Optional[TrackingBuffer] = TrackingBuffer() if defer_tracking else None self._assigned: Dict[str, Any] = {} self._subscriptions: Set[Callable[[Experiment[Any], Result[Any]], None]] = set() + self._feature_refresh_listeners: List[Callable[[Dict[str, Any]], None]] = [] + # Identity of the last payload dispatched to listeners. The cache hands + # back the same object on every hit, and evaluation calls load_features() + # constantly, so an identity check is what keeps listeners firing once + # per actual refresh instead of once per evaluation. + self._last_refresh_payload: Optional[Dict[str, Any]] = None self._is_updating_features = False # Serializes payload writers (set_features/set_payload/refreshes). # Re-entrant because _ingest_payload calls set_features while holding @@ -1083,8 +1089,7 @@ def _remote_eval_payload(self) -> Dict[str, Any]: def _on_feature_update(self, features_data: Dict[str, Any]) -> None: """Callback to handle automatic feature updates from FeatureRepository""" - if features_data: - self._ingest_payload(features_data) + self._apply_and_notify(features_data if features_data else None) def _ingest_payload(self, data: Dict[str, Any]) -> None: """Apply the sections present in a (decrypted) SDK payload. @@ -1150,7 +1155,12 @@ def load_features(self, force_refresh: bool = False) -> None: force_refresh=force_refresh, ) if response is not None: - self._ingest_payload(response) + # In CDN mode the repository already dispatched this exact object + # via _on_feature_update; the identity check there makes the notify + # a no-op. It matters in remote-eval mode, where the repository + # deliberately skips its global callbacks and this is the only + # dispatch point. + self._apply_and_notify(response) async def load_features_async(self, force_refresh: bool = False) -> None: if not self._client_key: @@ -1169,7 +1179,7 @@ async def load_features_async(self, force_refresh: bool = False) -> None: ) if features is not None: - self._ingest_payload(features) + self._apply_and_notify(features) def _features_event_handler(self, features: str) -> None: decoded = json.loads(features) @@ -1180,7 +1190,10 @@ def _features_event_handler(self, features: str) -> None: key = self._api_host + "::" + self._client_key if data is not None: - self._ingest_payload(data) + # The streaming path applies the payload itself and never goes + # through the repository's callbacks, so without this listeners + # would miss exactly the updates they exist to observe. + self._apply_and_notify(data) feature_repo.save_in_cache(key, data, self._cache_ttl) def _dispatch_sse_event(self, event_data: Dict[str, Any]) -> None: @@ -1255,6 +1268,72 @@ def set_features(self, features: Dict[str, Any]) -> None: finally: self._is_updating_features = False + def add_feature_refresh_listener( + self, listener: Callable[[Dict[str, Any]], None] + ) -> Callable[[], None]: + """Register a callable invoked whenever a new feature payload is applied + to this instance, so an app can react to updates without polling. + + The listener receives the raw payload dict (``features``, ``savedGroups``, + …). It runs *after* the payload has been applied, so evaluating a feature + from inside the listener already sees the new definitions. + + Fires once per refresh — not once per evaluation — for HTTP loads, the + stale-while-revalidate background worker and streaming (SSE) updates. + A listener that raises is logged and skipped; it can't break a refresh. + + Returns a callable that unregisters the listener.""" + if listener not in self._feature_refresh_listeners: + self._feature_refresh_listeners.append(listener) + + def unsubscribe() -> None: + self.remove_feature_refresh_listener(listener) + + return unsubscribe + + def remove_feature_refresh_listener( + self, listener: Callable[[Dict[str, Any]], None] + ) -> None: + if listener in self._feature_refresh_listeners: + self._feature_refresh_listeners.remove(listener) + + def _apply_and_notify(self, payload: Optional[Dict[str, Any]]) -> None: + """Apply a payload and dispatch it to the refresh listeners as one + unit, under the payload-writer lock. + + Notifying outside the lock would let two refresh sources reorder: + one applies A, the other applies and notifies B, then the first + notifies A — so listeners see an older payload last, and a listener + that evaluates sees state that doesn't match the payload it was + handed. The lock is reentrant, and evaluation never takes it (reads + go through the published snapshot), so a listener is free to + evaluate.""" + with self._payload_lock: + if payload is not None: + self._ingest_payload(payload) + self._notify_feature_refresh(payload) + + def _notify_feature_refresh(self, payload: Optional[Dict[str, Any]]) -> None: + """Dispatch a payload to the refresh listeners, once per distinct + payload object. Call this only after the payload has been applied.""" + if payload is None: + # A failed refresh applied nothing, so the payload listeners last + # saw is unchanged. Clearing the marker here would make the next + # cache hit — which returns that same previously-notified object — + # look like a fresh payload and fire listeners a second time. + return + if payload is self._last_refresh_payload: + return + self._last_refresh_payload = payload + if not self._feature_refresh_listeners: + return + + for listener in list(self._feature_refresh_listeners): + try: + listener(payload) + except Exception: + logger.exception("Error in feature refresh listener") + @deprecated("getFeatures is deprecated, use get_features instead") def getFeatures(self) -> Dict[str, Feature]: return self.get_features() @@ -1340,6 +1419,7 @@ def destroy(self, timeout: float = 10) -> None: # Clear all internal state try: self._subscriptions.clear() + self._feature_refresh_listeners.clear() self._tracked.clear() if self._deferred_buffer: self._deferred_buffer.clear() diff --git a/growthbook/growthbook_client.py b/growthbook/growthbook_client.py index b8678eb..fdf7fae 100644 --- a/growthbook/growthbook_client.py +++ b/growthbook/growthbook_client.py @@ -657,6 +657,13 @@ def __init__( self._subscriptions: Set[Callable[[Experiment[Any], Result[Any]], Union[None, Awaitable[None]]]] = set() self._subscriptions_lock = threading.Lock() + # Feature refresh listeners (sync or async callables) + self._feature_refresh_listeners: List[Callable[[Dict[str, Any]], Any]] = [] + self._feature_refresh_lock = threading.Lock() + # Serializes apply-then-notify so concurrent refreshes can't reorder + # listener events; see _feature_update_callback. + self._refresh_order_lock = asyncio.Lock() + # Per-attributes-key inflight sticky bucket fetches. Concurrent evals # with identical attributes coalesce onto one service fetch; distinct # attributes fetch in parallel. No cross-eval result cache by default @@ -810,6 +817,54 @@ def unsubscribe() -> None: self._subscriptions.discard(callback) return unsubscribe + def add_feature_refresh_listener( + self, listener: Callable[[Dict[str, Any]], Any] + ) -> Callable[[], None]: + """Register a callable invoked whenever a new feature payload is applied + to this client, so an app can react to updates without polling. + + The listener receives the raw payload dict (``features``, ``savedGroups``, + …) and may be a plain function or a coroutine function; coroutines are + awaited. It runs *after* the payload has been applied to the global + context, so evaluating a feature from inside the listener already sees + the new definitions. A listener that raises is logged and skipped. + + Fires on the initial load and on every refresh, whether driven by + streaming (SSE) or HTTP polling. Remote-eval mode emits no events: + payloads there are per-user, so there is no client-wide "definitions + changed" moment to report. + + Returns a callable that unregisters the listener.""" + with self._feature_refresh_lock: + if listener not in self._feature_refresh_listeners: + self._feature_refresh_listeners.append(listener) + + def unsubscribe() -> None: + self.remove_feature_refresh_listener(listener) + + return unsubscribe + + def remove_feature_refresh_listener( + self, listener: Callable[[Dict[str, Any]], Any] + ) -> None: + with self._feature_refresh_lock: + if listener in self._feature_refresh_listeners: + self._feature_refresh_listeners.remove(listener) + + async def _notify_feature_refresh(self, payload: Dict[str, Any]) -> None: + """Dispatch a payload to the refresh listeners. Call only after the + payload has been applied to the global context.""" + with self._feature_refresh_lock: + listeners = list(self._feature_refresh_listeners) + + for listener in listeners: + try: + result = listener(payload) + if asyncio.iscoroutine(result): + await result + except Exception: + logger.exception("Error in feature refresh listener") + def _fire_subscriptions(self, experiment: Experiment[Any], result: Result[Any]) -> None: """Thread-safe subscription notifications""" with self._subscriptions_lock: @@ -1185,6 +1240,18 @@ async def _feature_update_callback(self, features_data: Dict[str, Any]) -> None: logger.warning("Warning: Received empty features data") return + # Apply and notify as one unit. The ordering lock is distinct from the + # context lock on purpose: evaluation takes that one, so notifying + # under it would deadlock any listener that evaluates. Evaluation + # never takes this one, so holding it across the pair is safe — and it + # is what keeps two overlapping refreshes from notifying out of + # application order (apply A, apply+notify B, notify A). + async with self._refresh_order_lock: + await self._apply_payload(features_data) + # Outside the context lock, which _apply_payload has released. + await self._notify_feature_refresh(features_data) + + async def _apply_payload(self, features_data: Dict[str, Any]) -> None: async with self._context_lock: # serializes concurrent updaters only prev = self._global_context # Mirror JS setPayload: sections absent from the update carry @@ -1443,6 +1510,11 @@ async def close(self) -> None: self._tracked.clear() with self._subscriptions_lock: self._subscriptions.clear() + # Listener closures capture application objects; a closed client that + # kept them would hold those alive and, if reinitialized, fire + # callbacks registered in its previous lifecycle. + with self._feature_refresh_lock: + self._feature_refresh_listeners.clear() # Clear context async with self._context_lock: self._global_context = None diff --git a/tests/test_growthbook.py b/tests/test_growthbook.py index 7f40f92..b7c3845 100644 --- a/tests/test_growthbook.py +++ b/tests/test_growthbook.py @@ -1984,3 +1984,128 @@ def test_stale_while_revalidate_cleanup(mocker): if feature_repo._refresh_thread: feature_repo.stop_background_refresh() feature_repo.clear_cache() + + +# --- Feature refresh listeners ---------------------------------------------- + +def test_feature_refresh_listener_fires_once_per_refresh(mocker): + m = mocker.patch.object(feature_repo, "_get") + m.return_value = MockHttpResp(200, json.dumps({"features": {"flag": {"defaultValue": 1}}})) + + seen = [] + gb = GrowthBook(api_host="https://cdn.growthbook.io", client_key="sdk-abc123") + gb.add_feature_refresh_listener(lambda payload: seen.append(payload["features"])) + + gb.load_features() + assert len(seen) == 1 + + # Evaluation refreshes from cache on every call; that must not re-fire. + gb.get_feature_value("flag", 0) + gb.get_feature_value("flag", 0) + assert len(seen) == 1 + + m.return_value = MockHttpResp(200, json.dumps({"features": {"flag": {"defaultValue": 2}}})) + gb.load_features(force_refresh=True) + assert len(seen) == 2 + assert seen[1]["flag"]["defaultValue"] == 2 + + gb.destroy() + feature_repo.clear_cache() + + +def test_feature_refresh_listener_fires_on_sse_payload(mocker): + # The streaming path applies features without going through the + # repository's callbacks — the case listeners exist for. + mocker.patch.object( + feature_repo, "_get", + return_value=MockHttpResp(200, json.dumps({"features": {}})), + ) + mocker.patch.object(feature_repo, "startAutoRefresh") + + seen = [] + gb = GrowthBook( + api_host="https://cdn.growthbook.io", client_key="sdk-abc123", streaming=True + ) + gb.add_feature_refresh_listener(seen.append) + + gb._dispatch_sse_event({ + "type": "features", + "data": json.dumps({"features": {"flag": {"defaultValue": "live"}}}), + }) + + assert len(seen) == 1 + assert gb.get_feature_value("flag", "none") == "live" + + gb.destroy() + feature_repo.clear_cache() + + +def test_feature_refresh_listener_sees_applied_payload(mocker): + # Evaluating from inside the listener must already see the new definitions. + m = mocker.patch.object(feature_repo, "_get") + m.return_value = MockHttpResp(200, json.dumps({"features": {"flag": {"defaultValue": "new"}}})) + + observed = [] + gb = GrowthBook(api_host="https://cdn.growthbook.io", client_key="sdk-abc123") + gb.add_feature_refresh_listener( + lambda payload: observed.append(gb.get_feature_value("flag", "old")) + ) + + gb.load_features() + assert observed == ["new"] + + gb.destroy() + feature_repo.clear_cache() + + +def test_feature_refresh_listener_unsubscribe_and_error_isolation(mocker): + m = mocker.patch.object(feature_repo, "_get") + m.return_value = MockHttpResp(200, json.dumps({"features": {"flag": {"defaultValue": 1}}})) + + calls = [] + + def boom(payload): + raise RuntimeError("listener exploded") + + gb = GrowthBook(api_host="https://cdn.growthbook.io", client_key="sdk-abc123") + gb.add_feature_refresh_listener(boom) + unsubscribe = gb.add_feature_refresh_listener(lambda payload: calls.append(payload)) + + # A raising listener is logged, not propagated, and doesn't stop the others. + gb.load_features() + assert len(calls) == 1 + + unsubscribe() + m.return_value = MockHttpResp(200, json.dumps({"features": {"flag": {"defaultValue": 2}}})) + gb.load_features(force_refresh=True) + assert len(calls) == 1 + + gb.destroy() + feature_repo.clear_cache() + + +def test_failed_refresh_does_not_replay_the_previous_payload(mocker): + # A failed refresh applies nothing, so it must not clear the marker of the + # payload listeners last saw: the next cache hit returns that same object, + # which would then look fresh and fire listeners a second time. + m = mocker.patch.object(feature_repo, "_get") + m.return_value = MockHttpResp(200, json.dumps({"features": {"flag": {"defaultValue": 1}}})) + + seen = [] + gb = GrowthBook(api_host="https://cdn.growthbook.io", client_key="replay-key") + gb.add_feature_refresh_listener(seen.append) + + gb.load_features() + assert len(seen) == 1 + + # Forced refresh fails; the repository keeps the previously cached payload. + m.return_value = MockHttpResp(500, "") + gb.load_features(force_refresh=True) + assert len(seen) == 1 + + # The next evaluation reads that same cached object — not a new payload. + gb.get_feature_value("flag", 0) + assert len(seen) == 1 + + gb.destroy() + feature_repo.clear_cache() diff --git a/tests/test_growthbook_client.py b/tests/test_growthbook_client.py index b0c7595..98f4345 100644 --- a/tests/test_growthbook_client.py +++ b/tests/test_growthbook_client.py @@ -1780,3 +1780,160 @@ async def test_reduce_payload_keeps_zero_coverage(): assert reduced["features"][key]["rules"] == [{"force": True, "coverage": 0, "hashVersion": 1}] finally: await client.close() + + +# --- Feature refresh listeners ---------------------------------------------- + +@pytest.mark.asyncio +async def test_client_feature_refresh_listener_sync_and_async(mock_options): + """Both plain and coroutine listeners fire, on the initial load and on + every subsequent refresh.""" + payload = {"features": {"flag": {"defaultValue": 1}}, "savedGroups": {}} + sync_seen, async_seen = [], [] + + async def async_listener(data): + async_seen.append(data["features"]) + + with patch('growthbook.FeatureRepository.load_features_async', + new_callable=AsyncMock, return_value=payload), \ + patch('growthbook.growthbook_client.EnhancedFeatureRepository.start_feature_refresh', + new_callable=AsyncMock), \ + patch('growthbook.growthbook_client.EnhancedFeatureRepository.stop_refresh', + new_callable=AsyncMock): + + client = GrowthBookClient(mock_options) + client.add_feature_refresh_listener(lambda data: sync_seen.append(data["features"])) + client.add_feature_refresh_listener(async_listener) + try: + await client.initialize() + assert len(sync_seen) == 1 and len(async_seen) == 1 + + # A later refresh (e.g. from SSE) goes through the same callback. + await client._feature_update_callback( + {"features": {"flag": {"defaultValue": 2}}, "savedGroups": {}} + ) + assert len(sync_seen) == 2 and len(async_seen) == 2 + assert sync_seen[1]["flag"]["defaultValue"] == 2 + finally: + await client.close() + + +@pytest.mark.asyncio +async def test_client_feature_refresh_listener_can_evaluate(mock_options): + """A listener that evaluates a feature must see the new payload and must + not deadlock: evaluation takes the same context lock the update holds.""" + payload = {"features": {"flag": {"defaultValue": "new"}}, "savedGroups": {}} + observed = [] + + with patch('growthbook.FeatureRepository.load_features_async', + new_callable=AsyncMock, return_value=payload), \ + patch('growthbook.growthbook_client.EnhancedFeatureRepository.start_feature_refresh', + new_callable=AsyncMock), \ + patch('growthbook.growthbook_client.EnhancedFeatureRepository.stop_refresh', + new_callable=AsyncMock): + + client = GrowthBookClient(mock_options) + + async def listener(data): + value = await client.get_feature_value("flag", "old", UserContext(attributes={"id": "1"})) + observed.append(value) + + client.add_feature_refresh_listener(listener) + try: + await asyncio.wait_for(client.initialize(), timeout=5) + assert observed == ["new"] + finally: + await client.close() + + +@pytest.mark.asyncio +async def test_client_feature_refresh_listener_unsubscribe_and_errors(mock_options): + payload = {"features": {"flag": {"defaultValue": 1}}, "savedGroups": {}} + calls = [] + + def boom(data): + raise RuntimeError("listener exploded") + + with patch('growthbook.FeatureRepository.load_features_async', + new_callable=AsyncMock, return_value=payload), \ + patch('growthbook.growthbook_client.EnhancedFeatureRepository.start_feature_refresh', + new_callable=AsyncMock), \ + patch('growthbook.growthbook_client.EnhancedFeatureRepository.stop_refresh', + new_callable=AsyncMock): + + client = GrowthBookClient(mock_options) + client.add_feature_refresh_listener(boom) + unsubscribe = client.add_feature_refresh_listener(lambda data: calls.append(data)) + try: + await client.initialize() + assert len(calls) == 1 + + unsubscribe() + await client._feature_update_callback(payload) + assert len(calls) == 1 + finally: + await client.close() + + +@pytest.mark.asyncio +async def test_close_clears_feature_refresh_listeners(mock_options): + """Listener closures capture application objects; a closed client that + kept them would hold those alive and, if reinitialized, fire callbacks + registered in its previous lifecycle.""" + payload = {"features": {"flag": {"defaultValue": 1}}, "savedGroups": {}} + seen = [] + + with patch('growthbook.FeatureRepository.load_features_async', + new_callable=AsyncMock, return_value=payload), \ + patch('growthbook.growthbook_client.EnhancedFeatureRepository.start_feature_refresh', + new_callable=AsyncMock), \ + patch('growthbook.growthbook_client.EnhancedFeatureRepository.stop_refresh', + new_callable=AsyncMock): + + client = GrowthBookClient(mock_options) + client.add_feature_refresh_listener(seen.append) + await client.initialize() + assert len(seen) == 1 + + await client.close() + assert client._feature_refresh_listeners == [] + + # A later update from the previous lifecycle reaches nobody. + await client._feature_update_callback(payload) + assert len(seen) == 1 + + +@pytest.mark.asyncio +async def test_concurrent_refreshes_notify_in_application_order(mock_options): + """Two overlapping refreshes must not reorder: apply A, apply+notify B, + notify A would hand listeners an older payload last, and a listener that + evaluates would see state that doesn't match the payload it was given.""" + with patch('growthbook.growthbook_client.EnhancedFeatureRepository.stop_refresh', + new_callable=AsyncMock): + client = GrowthBookClient(mock_options) + observed = [] + + async def listener(data): + # Yield inside the callback to widen the interleaving window. + await asyncio.sleep(0) + value = data["features"]["flag"]["defaultValue"] + ctx_value = client._global_context.features["flag"].defaultValue + observed.append((value, ctx_value)) + + client.add_feature_refresh_listener(listener) + try: + await asyncio.gather(*[ + client._feature_update_callback( + {"features": {"flag": {"defaultValue": i}}, "savedGroups": {}} + ) + for i in range(6) + ]) + + delivered = [v for v, _ in observed] + assert len(delivered) == 6 + # Each listener call sees the context matching its own payload. + assert all(v == ctx for v, ctx in observed), observed + # And the last one delivered is the last one applied. + assert delivered[-1] == client._global_context.features["flag"].defaultValue + finally: + await client.close() From f412be94cfd5a088cce9729187b7ba1100049c70 Mon Sep 17 00:00:00 2001 From: Volodymyr Nazarkevych Date: Mon, 16 Nov 2026 14:01:29 +0200 Subject: [PATCH 2/5] fix: handle refreshes started from a feature refresh listener A listener that updated features re-entered the dispatch: - Async client: _feature_update_callback waited for the ordering lock that its own dispatch held, so a listener calling set_payload, set_features or initialize hung the client. - Sync client: the reentrant payload lock let the nested refresh deliver the newer payload to every listener before the outer loop resumed, so the remaining listeners got the older payload last, while evaluation already used the newer one. A refresh started from a listener now only applies its payload. The running dispatch delivers it: the remaining listeners get only the newer payload, and delivery starts over with it. The sync client recognises re-entry by a flag held under its payload lock. The async client uses a context variable carrying the running dispatch's token, so a task the listener awaits counts as re-entry too, while a concurrent refresh still waits for the lock. Regression tests cover both clients; each fails without the fix (the async ones by timeout). --- README.md | 8 +++++ growthbook/growthbook.py | 33 +++++++++++++++---- growthbook/growthbook_client.py | 57 +++++++++++++++++++++++++++++++-- tests/test_growthbook.py | 36 +++++++++++++++++++++ tests/test_growthbook_client.py | 44 +++++++++++++++++++++++++ 5 files changed, 170 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 992c26f..dc56ea2 100644 --- a/README.md +++ b/README.md @@ -310,6 +310,14 @@ per evaluation — covering HTTP loads, the stale-while-revalidate background worker and streaming (SSE) updates. A listener that raises is logged and skipped; it cannot break a refresh. +Listeners run one after another, in registration order, and payloads are +delivered in the order they were applied. A listener may update features +itself (`set_payload`, `load_features`, …). The newer payload is then applied +immediately, the remaining listeners receive only the newer one, and delivery +starts over with it, so no listener is handed a payload older than the applied +state. Keep listeners quick: a slow one delays the next refresh, so move heavy +work to a task. + On the async client the listener may be a plain function or a coroutine function: diff --git a/growthbook/growthbook.py b/growthbook/growthbook.py index 571cc5d..746fede 100644 --- a/growthbook/growthbook.py +++ b/growthbook/growthbook.py @@ -1011,6 +1011,9 @@ def __init__( # constantly, so an identity check is what keeps listeners firing once # per actual refresh instead of once per evaluation. self._last_refresh_payload: Optional[Dict[str, Any]] = None + # True while listeners run; a refresh started from inside a listener + # only applies its payload and leaves the delivery to the running loop. + self._dispatching_refresh = False self._is_updating_features = False # Serializes payload writers (set_features/set_payload/refreshes). # Re-entrant because _ingest_payload calls set_features while holding @@ -1281,6 +1284,8 @@ def add_feature_refresh_listener( Fires once per refresh — not once per evaluation — for HTTP loads, the stale-while-revalidate background worker and streaming (SSE) updates. A listener that raises is logged and skipped; it can't break a refresh. + A listener may trigger a refresh itself: the remaining listeners then + get only the newer payload, never the one it superseded. Returns a callable that unregisters the listener.""" if listener not in self._feature_refresh_listeners: @@ -1325,14 +1330,30 @@ def _notify_feature_refresh(self, payload: Optional[Dict[str, Any]]) -> None: if payload is self._last_refresh_payload: return self._last_refresh_payload = payload - if not self._feature_refresh_listeners: + if self._dispatching_refresh: + # A listener started this refresh, on this thread (we hold the + # payload lock). Delivering here would finish the newer payload + # before the outer loop resumes with the older one, so the running + # loop picks it up instead. return - for listener in list(self._feature_refresh_listeners): - try: - listener(payload) - except Exception: - logger.exception("Error in feature refresh listener") + self._dispatching_refresh = True + try: + while True: + current = self._last_refresh_payload + for listener in list(self._feature_refresh_listeners): + if self._last_refresh_payload is not current: + # Superseded by a refresh from a listener: the rest + # get only the newer payload, never the older one. + break + try: + listener(current) + except Exception: + logger.exception("Error in feature refresh listener") + if self._last_refresh_payload is current: + return + finally: + self._dispatching_refresh = False @deprecated("getFeatures is deprecated, use get_features instead") def getFeatures(self) -> Dict[str, Feature]: diff --git a/growthbook/growthbook_client.py b/growthbook/growthbook_client.py index fdf7fae..8ae4086 100644 --- a/growthbook/growthbook_client.py +++ b/growthbook/growthbook_client.py @@ -11,6 +11,7 @@ if TYPE_CHECKING: from .plugins.base import PluginLike import asyncio +import contextvars import threading import time import traceback @@ -48,6 +49,13 @@ logger = logging.getLogger("growthbook.growthbook_client") +# Tokens of the refresh-listener dispatches the current code runs inside. A +# listener (and any task it creates) inherits this context, which is how a +# refresh started from a listener is told apart from a concurrent one. +_active_refresh_dispatches: "contextvars.ContextVar[Tuple[object, ...]]" = contextvars.ContextVar( + "growthbook_active_refresh_dispatches", default=() +) + class SingletonMeta(type): """One instance per (class, api_host, client_key). Two GrowthBookClients talking to different proxies — or one CDN-mode and one remote-eval-mode @@ -663,6 +671,10 @@ def __init__( # Serializes apply-then-notify so concurrent refreshes can't reorder # listener events; see _feature_update_callback. self._refresh_order_lock = asyncio.Lock() + # The latest applied payload, and the token of the dispatch currently + # delivering it; see _feature_update_callback. + self._latest_refresh_payload: Optional[Dict[str, Any]] = None + self._refresh_dispatch_token: Optional[object] = None # Per-attributes-key inflight sticky bucket fetches. Concurrent evals # with identical attributes coalesce onto one service fetch; distinct @@ -828,6 +840,9 @@ def add_feature_refresh_listener( awaited. It runs *after* the payload has been applied to the global context, so evaluating a feature from inside the listener already sees the new definitions. A listener that raises is logged and skipped. + A listener may update the payload itself (``set_payload`` and so on): + the remaining listeners then get only the newer payload, never the one + it superseded. Fires on the initial load and on every refresh, whether driven by streaming (SSE) or HTTP polling. Remote-eval mode emits no events: @@ -853,11 +868,14 @@ def remove_feature_refresh_listener( async def _notify_feature_refresh(self, payload: Dict[str, Any]) -> None: """Dispatch a payload to the refresh listeners. Call only after the - payload has been applied to the global context.""" + payload has been applied to the global context. Stops once a newer + payload has been applied.""" with self._feature_refresh_lock: listeners = list(self._feature_refresh_listeners) for listener in listeners: + if self._latest_refresh_payload is not payload: + return try: result = listener(payload) if asyncio.iscoroutine(result): @@ -1246,10 +1264,44 @@ async def _feature_update_callback(self, features_data: Dict[str, Any]) -> None: # never takes this one, so holding it across the pair is safe — and it # is what keeps two overlapping refreshes from notifying out of # application order (apply A, apply+notify B, notify A). + token = self._refresh_dispatch_token + if token is not None and token in _active_refresh_dispatches.get(): + # Started from a listener of the running dispatch, which holds the + # ordering lock: waiting for it would deadlock. Apply only; the + # running loop delivers this payload once the listener returns, + # so it can't be finished before the older one it interrupted. + await self._apply_payload(features_data) + self._latest_refresh_payload = features_data + return + async with self._refresh_order_lock: await self._apply_payload(features_data) + self._latest_refresh_payload = features_data # Outside the context lock, which _apply_payload has released. - await self._notify_feature_refresh(features_data) + await self._dispatch_feature_refresh() + + async def _dispatch_feature_refresh(self) -> None: + """Deliver the latest applied payload to the refresh listeners. Call + with the ordering lock held. + + If a listener applies a newer payload, the remaining listeners get + only the newer one, then delivery starts over with it, so no listener + receives a payload older than one it has already seen or than the + applied state.""" + token = object() + self._refresh_dispatch_token = token + reset = _active_refresh_dispatches.set(_active_refresh_dispatches.get() + (token,)) + try: + while True: + current = self._latest_refresh_payload + if current is None: + return + await self._notify_feature_refresh(current) + if self._latest_refresh_payload is current: + return + finally: + _active_refresh_dispatches.reset(reset) + self._refresh_dispatch_token = None async def _apply_payload(self, features_data: Dict[str, Any]) -> None: async with self._context_lock: # serializes concurrent updaters only @@ -1515,6 +1567,7 @@ async def close(self) -> None: # callbacks registered in its previous lifecycle. with self._feature_refresh_lock: self._feature_refresh_listeners.clear() + self._latest_refresh_payload = None # Clear context async with self._context_lock: self._global_context = None diff --git a/tests/test_growthbook.py b/tests/test_growthbook.py index b7c3845..95df719 100644 --- a/tests/test_growthbook.py +++ b/tests/test_growthbook.py @@ -2109,3 +2109,39 @@ def test_failed_refresh_does_not_replay_the_previous_payload(mocker): gb.destroy() feature_repo.clear_cache() + + +def test_refresh_from_a_listener_never_delivers_an_older_payload_last(mocker): + # A listener that triggers a refresh applies a newer payload while the + # outer dispatch is still running. The listeners after it must not then + # receive the older payload, which no longer matches the applied state. + old = {"features": {"flag": {"defaultValue": "old"}}} + new = {"features": {"flag": {"defaultValue": "new"}}} + cache = {"payload": old} # like the real cache: hands back the latest object + mocker.patch.object(feature_repo, "load_features", side_effect=lambda *a, **k: cache["payload"]) + + gb = GrowthBook(api_host="https://cdn.growthbook.io", client_key="nested-key") + first, second = [], [] + + def refreshing_listener(payload): + first.append((payload["features"]["flag"]["defaultValue"], gb.get_feature_value("flag", None))) + if payload is old: + cache["payload"] = new + gb.load_features() + + def observing_listener(payload): + second.append((payload["features"]["flag"]["defaultValue"], gb.get_feature_value("flag", None))) + + gb.add_feature_refresh_listener(refreshing_listener) + gb.add_feature_refresh_listener(observing_listener) + try: + gb.load_features() + + # Each delivery matches the state applied at that moment... + assert all(value == state for value, state in first + second), (first, second) + # ...the superseded payload isn't handed to the remaining listener... + assert second == [("new", "new")] + # ...and every listener ends on the payload that is actually applied. + assert first == [("old", "old"), ("new", "new")] + finally: + gb.destroy() diff --git a/tests/test_growthbook_client.py b/tests/test_growthbook_client.py index 98f4345..2db8f40 100644 --- a/tests/test_growthbook_client.py +++ b/tests/test_growthbook_client.py @@ -1937,3 +1937,47 @@ async def listener(data): assert delivered[-1] == client._global_context.features["flag"].defaultValue finally: await client.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("via_task", [False, True], ids=["awaited", "awaited_task"]) +async def test_refresh_from_a_listener_does_not_deadlock_or_reorder(mock_options, via_task): + """A listener that updates the payload re-enters _feature_update_callback + while the outer dispatch holds the ordering lock. That must neither hang + nor hand the remaining listeners the superseded payload.""" + with patch('growthbook.growthbook_client.EnhancedFeatureRepository.stop_refresh', + new_callable=AsyncMock): + client = GrowthBookClient(mock_options) + old = {"features": {"flag": {"defaultValue": "old"}}, "savedGroups": {}} + new = {"features": {"flag": {"defaultValue": "new"}}, "savedGroups": {}} + first, second = [], [] + + def state(): + return client._global_context.features["flag"].defaultValue + + async def refreshing_listener(data): + first.append((data["features"]["flag"]["defaultValue"], state())) + if data is old: + if via_task: + await asyncio.create_task(client.set_payload(new)) + else: + await client.set_payload(new) + + async def observing_listener(data): + second.append((data["features"]["flag"]["defaultValue"], state())) + + client.add_feature_refresh_listener(refreshing_listener) + client.add_feature_refresh_listener(observing_listener) + try: + await asyncio.wait_for(client.set_payload(old), timeout=5) + + assert all(value == ctx for value, ctx in first + second), (first, second) + assert second == [("new", "new")] + assert first == [("old", "old"), ("new", "new")] + + # The ordering lock is free again: a later refresh still dispatches. + later = {"features": {"flag": {"defaultValue": "later"}}, "savedGroups": {}} + await asyncio.wait_for(client.set_payload(later), timeout=5) + assert second[-1] == ("later", "later") + finally: + await client.close() From d0e82cfd00dee52e0163413aa5788e46b2619ed1 Mon Sep 17 00:00:00 2001 From: Volodymyr Nazarkevych Date: Mon, 16 Nov 2026 14:24:45 +0200 Subject: [PATCH 3/5] fix: deliver a payload applied after its listener dispatch ended A task that a listener starts without awaiting inherits the dispatch context, so its set_payload() takes the re-entry path and skips the ordering lock. If the dispatch finished while the task was still applying, the payload was applied but never delivered to listeners. After a re-entrant apply, if no dispatch is running any more, the task now takes the ordering lock and dispatches the payload itself, unless a newer payload has replaced it or another dispatch already delivered it. --- growthbook/growthbook_client.py | 14 +++++++++++ tests/test_growthbook_client.py | 43 +++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/growthbook/growthbook_client.py b/growthbook/growthbook_client.py index 8ae4086..a59730c 100644 --- a/growthbook/growthbook_client.py +++ b/growthbook/growthbook_client.py @@ -674,6 +674,7 @@ def __init__( # The latest applied payload, and the token of the dispatch currently # delivering it; see _feature_update_callback. self._latest_refresh_payload: Optional[Dict[str, Any]] = None + self._delivered_refresh_payload: Optional[Dict[str, Any]] = None self._refresh_dispatch_token: Optional[object] = None # Per-attributes-key inflight sticky bucket fetches. Concurrent evals @@ -1272,6 +1273,17 @@ async def _feature_update_callback(self, features_data: Dict[str, Any]) -> None: # so it can't be finished before the older one it interrupted. await self._apply_payload(features_data) self._latest_refresh_payload = features_data + if self._refresh_dispatch_token is not None: + # A dispatch is still running; its loop rechecks the latest + # payload after every listener, so it will deliver this one. + return + # The dispatch ended while we were applying (a task the listener + # didn't await). Deliver it ourselves, unless a newer payload has + # replaced it or another dispatch already delivered it. + async with self._refresh_order_lock: + if (self._latest_refresh_payload is features_data + and self._delivered_refresh_payload is not features_data): + await self._dispatch_feature_refresh() return async with self._refresh_order_lock: @@ -1298,6 +1310,7 @@ async def _dispatch_feature_refresh(self) -> None: return await self._notify_feature_refresh(current) if self._latest_refresh_payload is current: + self._delivered_refresh_payload = current return finally: _active_refresh_dispatches.reset(reset) @@ -1568,6 +1581,7 @@ async def close(self) -> None: with self._feature_refresh_lock: self._feature_refresh_listeners.clear() self._latest_refresh_payload = None + self._delivered_refresh_payload = None # Clear context async with self._context_lock: self._global_context = None diff --git a/tests/test_growthbook_client.py b/tests/test_growthbook_client.py index 2db8f40..4a31eeb 100644 --- a/tests/test_growthbook_client.py +++ b/tests/test_growthbook_client.py @@ -1981,3 +1981,46 @@ async def observing_listener(data): assert second[-1] == ("later", "later") finally: await client.close() + + +@pytest.mark.asyncio +async def test_fire_and_forget_refresh_from_a_listener_is_still_delivered(mock_options): + """A task a listener starts without awaiting inherits the dispatch context. + If that dispatch ends while the task is still applying its payload, the + task must deliver the payload itself instead of leaving it unannounced.""" + with patch('growthbook.growthbook_client.EnhancedFeatureRepository.stop_refresh', + new_callable=AsyncMock): + client = GrowthBookClient(mock_options) + old = {"features": {"flag": {"defaultValue": "old"}}, "savedGroups": {}} + new = {"features": {"flag": {"defaultValue": "new"}}, "savedGroups": {}} + seen = [] + tasks = [] + delivered_new = asyncio.Event() + + real_apply = client._apply_payload + + async def slow_apply(data): + if data is new: + # Let the dispatch that started this task finish first. + await asyncio.sleep(0.05) + await real_apply(data) + + async def listener(data): + seen.append((data["features"]["flag"]["defaultValue"], + client._global_context.features["flag"].defaultValue)) + if data is old: + tasks.append(asyncio.create_task(client.set_payload(new))) + await asyncio.sleep(0) # the task starts inside this dispatch + else: + delivered_new.set() + + client.add_feature_refresh_listener(listener) + try: + with patch.object(client, "_apply_payload", side_effect=slow_apply): + await asyncio.wait_for(client.set_payload(old), timeout=5) + await asyncio.wait_for(asyncio.gather(*tasks), timeout=5) + await asyncio.wait_for(delivered_new.wait(), timeout=5) + + assert seen == [("old", "old"), ("new", "new")] + finally: + await client.close() From 05a5a3e1355258ebe8132494308c72e7c222f408 Mon Sep 17 00:00:00 2001 From: Volodymyr Nazarkevych Date: Mon, 23 Nov 2026 15:23:17 +0200 Subject: [PATCH 4/5] fix: settle refresh listeners with copying caches and SSE reloads _notify_feature_refresh skipped a payload only when it was the same object as the last one dispatched. A cache that decodes on every hit, like the README's Redis cache, returns a new dict each time, so every load_features() fired the listeners again, and a listener that loads features itself kept the delivery loop from ever finishing. Also skip a payload equal to the last one. The SSE handler applied and dispatched the streamed payload before caching it. A listener calling load_features() then got the previous payload from the cache and reapplied it over the update. Cache the payload first. --- growthbook/growthbook.py | 20 ++++++--- tests/test_growthbook.py | 91 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+), 6 deletions(-) diff --git a/growthbook/growthbook.py b/growthbook/growthbook.py index e70bc30..8782f2e 100644 --- a/growthbook/growthbook.py +++ b/growthbook/growthbook.py @@ -1025,10 +1025,11 @@ def __init__( self._assigned: Dict[str, Any] = {} self._subscriptions: Set[Callable[[Experiment[Any], Result[Any]], None]] = set() self._feature_refresh_listeners: List[Callable[[Dict[str, Any]], None]] = [] - # Identity of the last payload dispatched to listeners. The cache hands - # back the same object on every hit, and evaluation calls load_features() - # constantly, so an identity check is what keeps listeners firing once - # per actual refresh instead of once per evaluation. + # The last payload dispatched to listeners. load_features() returns the + # cached payload on every hit, so a hit must not count as a refresh: + # _notify_feature_refresh compares against this by identity (the + # in-memory cache returns the same object) and then by content (custom + # caches, e.g. Redis, decode a new dict on every hit). self._last_refresh_payload: Optional[Dict[str, Any]] = None # True while listeners run; a refresh started from inside a listener # only applies its payload and leaves the delivery to the running loop. @@ -1212,11 +1213,14 @@ def _features_event_handler(self, features: str) -> None: key = self._api_host + "::" + self._client_key if data is not None: + # Cache first: a listener may call load_features(), which must get + # this payload from the cache, not the previous one it would then + # reapply over the update. + feature_repo.save_in_cache(key, data, self._cache_ttl) # The streaming path applies the payload itself and never goes # through the repository's callbacks, so without this listeners # would miss exactly the updates they exist to observe. self._apply_and_notify(data) - feature_repo.save_in_cache(key, data, self._cache_ttl) def _dispatch_sse_event(self, event_data: Dict[str, Any]) -> None: event_type = event_data.get('type') @@ -1346,7 +1350,11 @@ def _notify_feature_refresh(self, payload: Optional[Dict[str, Any]]) -> None: # cache hit — which returns that same previously-notified object — # look like a fresh payload and fire listeners a second time. return - if payload is self._last_refresh_payload: + if payload is self._last_refresh_payload or payload == self._last_refresh_payload: + # Same object, or a copy of it from a cache that decodes on every + # hit. Treating a copy as new would fire listeners on every + # load_features(), and a listener that loads features itself would + # keep the delivery loop below from ever finishing. return self._last_refresh_payload = payload if self._dispatching_refresh: diff --git a/tests/test_growthbook.py b/tests/test_growthbook.py index 2923490..5880b8a 100644 --- a/tests/test_growthbook.py +++ b/tests/test_growthbook.py @@ -2218,6 +2218,97 @@ def test_failed_refresh_does_not_replay_the_previous_payload(mocker): feature_repo.clear_cache() +class _JsonRoundTripCache: + """Like the README's Redis cache: every hit decodes a new dict.""" + + def __init__(self): + self.store = {} + + def get(self, key): + data = self.store.get(key) + return None if data is None else json.loads(data) + + def set(self, key, value, ttl): + self.store[key] = json.dumps(value) + + def clear(self): + self.store.clear() + + +def test_refresh_listener_with_a_cache_that_returns_copies(mocker): + # A cache that decodes on every hit never returns the same object twice, + # so an identity check would treat every hit as a new payload: listeners + # would fire on every load_features(), and a listener that loads features + # itself would keep the delivery loop going forever. + from growthbook.growthbook import AbstractFeatureCache, InMemoryFeatureCache + + class Cache(_JsonRoundTripCache, AbstractFeatureCache): + pass + + m = mocker.patch.object(feature_repo, "_get") + m.return_value = MockHttpResp(200, json.dumps({"features": {"flag": {"defaultValue": 1}}})) + feature_repo.set_cache(Cache()) + + gb = GrowthBook(api_host="https://cdn.growthbook.io", client_key="copies-key") + seen = [] + + def reloading_listener(payload): + seen.append(payload["features"]["flag"]["defaultValue"]) + if len(seen) > 5: + raise AssertionError("delivery loop did not settle") + gb.load_features() + + gb.add_feature_refresh_listener(reloading_listener) + try: + gb.load_features() + assert seen == [1] + + # Later cache hits with the same content are not new payloads. + gb.load_features() + gb.load_features() + assert seen == [1] + + m.return_value = MockHttpResp(200, json.dumps({"features": {"flag": {"defaultValue": 2}}})) + gb.load_features(force_refresh=True) + assert seen == [1, 2] + finally: + gb.destroy() + feature_repo.set_cache(InMemoryFeatureCache()) + + +def test_sse_payload_is_cached_before_listeners_run(mocker): + # A listener that loads features during an SSE update must get the + # streamed payload from the cache, not the previous one, or it would + # reapply the old definitions over the update. + mocker.patch.object( + feature_repo, "_get", + return_value=MockHttpResp(200, json.dumps({"features": {"flag": {"defaultValue": "old"}}})), + ) + mocker.patch.object(feature_repo, "startAutoRefresh") + + gb = GrowthBook( + api_host="https://cdn.growthbook.io", client_key="sse-order-key", streaming=True + ) + seen = [] + + def reloading_listener(payload): + gb.load_features() + seen.append((payload["features"]["flag"]["defaultValue"], gb.get_feature_value("flag", None))) + + gb.add_feature_refresh_listener(reloading_listener) + try: + gb._dispatch_sse_event({ + "type": "features", + "data": json.dumps({"features": {"flag": {"defaultValue": "live"}}}), + }) + + assert seen == [("live", "live")] + assert gb.get_feature_value("flag", None) == "live" + finally: + gb.destroy() + feature_repo.clear_cache() + + def test_refresh_from_a_listener_never_delivers_an_older_payload_last(mocker): # A listener that triggers a refresh applies a newer payload while the # outer dispatch is still running. The listeners after it must not then From 1cd4d2fee652ec52e2372bf1c6f2b15cb1598b5e Mon Sep 17 00:00:00 2001 From: Volodymyr Nazarkevych Date: Mon, 23 Nov 2026 15:29:17 +0200 Subject: [PATCH 5/5] fix: tell JSON types apart in refresh dedup and keep SSE updates on cache errors The content check that skips repeated payloads used ==, which treats True == 1, False == 0 and 1 == 1.0 as equal. A setting changing between those values was applied but never reached the refresh listeners. Compare payloads structurally with types kept apart instead. The SSE handler now caches before applying, so a failing custom cache (e.g. a Redis outage) raised before the update was applied, and the stream does not retry the event. Log the failed write and apply the payload anyway. --- growthbook/growthbook.py | 32 ++++++++++++++++++++++---- tests/test_growthbook.py | 49 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 5 deletions(-) diff --git a/growthbook/growthbook.py b/growthbook/growthbook.py index 8782f2e..4879f9a 100644 --- a/growthbook/growthbook.py +++ b/growthbook/growthbook.py @@ -86,6 +86,23 @@ def decrypt(encrypted_str: str, key_str: str) -> str: return bytestring.decode("utf-8") + +def _same_payload(a: Any, b: Any) -> bool: + """Structural equality that, unlike ==, keeps JSON values of different + types apart: True == 1, False == 0 and 1 == 1.0 in Python, but they are + different settings. Values of different types are never the same, so an + unexpected type at worst fires listeners for an unchanged payload.""" + if a is b: + return True + if type(a) is not type(b): + return False + if isinstance(a, dict): + return a.keys() == b.keys() and all(_same_payload(v, b[k]) for k, v in a.items()) + if isinstance(a, (list, tuple)): + return len(a) == len(b) and all(_same_payload(x, y) for x, y in zip(a, b)) + return bool(a == b) + + class AbstractFeatureCache(ABC): @abstractmethod def get(self, key: str) -> Optional[Dict[str, Any]]: @@ -1028,8 +1045,8 @@ def __init__( # The last payload dispatched to listeners. load_features() returns the # cached payload on every hit, so a hit must not count as a refresh: # _notify_feature_refresh compares against this by identity (the - # in-memory cache returns the same object) and then by content (custom - # caches, e.g. Redis, decode a new dict on every hit). + # in-memory cache returns the same object) and then by type-strict + # content (custom caches, e.g. Redis, decode a new dict on every hit). self._last_refresh_payload: Optional[Dict[str, Any]] = None # True while listeners run; a refresh started from inside a listener # only applies its payload and leaves the delivery to the running loop. @@ -1215,8 +1232,13 @@ def _features_event_handler(self, features: str) -> None: if data is not None: # Cache first: a listener may call load_features(), which must get # this payload from the cache, not the previous one it would then - # reapply over the update. - feature_repo.save_in_cache(key, data, self._cache_ttl) + # reapply over the update. A failed write (e.g. a custom cache that + # is down) must not cost us the update: the stream doesn't retry + # the event, so apply it anyway. + try: + feature_repo.save_in_cache(key, data, self._cache_ttl) + except Exception: + logger.exception("Could not cache the streamed payload; applying it anyway") # The streaming path applies the payload itself and never goes # through the repository's callbacks, so without this listeners # would miss exactly the updates they exist to observe. @@ -1350,7 +1372,7 @@ def _notify_feature_refresh(self, payload: Optional[Dict[str, Any]]) -> None: # cache hit — which returns that same previously-notified object — # look like a fresh payload and fire listeners a second time. return - if payload is self._last_refresh_payload or payload == self._last_refresh_payload: + if _same_payload(payload, self._last_refresh_payload): # Same object, or a copy of it from a cache that decodes on every # hit. Treating a copy as new would fire listeners on every # load_features(), and a listener that loads features itself would diff --git a/tests/test_growthbook.py b/tests/test_growthbook.py index 5880b8a..b49de66 100644 --- a/tests/test_growthbook.py +++ b/tests/test_growthbook.py @@ -2309,6 +2309,55 @@ def reloading_listener(payload): feature_repo.clear_cache() +@pytest.mark.parametrize("before, after", [ + (True, 1), + (False, 0), + (1, 1.0), + ([True], [1]), +]) +def test_refresh_listener_tells_booleans_from_numbers(before, after): + # Python's == treats True == 1, False == 0 and 1 == 1.0, but those are + # different JSON values: a listener must see the change. + gb = GrowthBook() + seen = [] + gb.add_feature_refresh_listener(lambda payload: seen.append(payload["features"]["flag"]["defaultValue"])) + try: + gb.set_payload({"features": {"flag": {"defaultValue": before}}}) + gb.set_payload({"features": {"flag": {"defaultValue": after}}}) + assert len(seen) == 2 + assert type(seen[1]) is type(after) + finally: + gb.destroy() + + +def test_sse_payload_is_applied_when_the_cache_write_fails(mocker): + # The cache is written before listeners run, but a failing cache (e.g. a + # Redis outage) must not cost the client the streamed update. + mocker.patch.object( + feature_repo, "_get", + return_value=MockHttpResp(200, json.dumps({"features": {"flag": {"defaultValue": "old"}}})), + ) + mocker.patch.object(feature_repo, "startAutoRefresh") + + gb = GrowthBook( + api_host="https://cdn.growthbook.io", client_key="sse-cache-fail-key", streaming=True + ) + seen = [] + gb.add_feature_refresh_listener(lambda payload: seen.append(payload["features"]["flag"]["defaultValue"])) + mocker.patch.object(feature_repo, "save_in_cache", side_effect=ConnectionError("cache down")) + try: + gb._dispatch_sse_event({ + "type": "features", + "data": json.dumps({"features": {"flag": {"defaultValue": "live"}}}), + }) + + assert gb.get_feature_value("flag", None) == "live" + assert seen[-1] == "live" + finally: + gb.destroy() + feature_repo.clear_cache() + + def test_refresh_from_a_listener_never_delivers_an_older_payload_last(mocker): # A listener that triggers a refresh applies a newer payload while the # outer dispatch is still running. The listeners after it must not then