Skip to content

Commit 6d8aef0

Browse files
committed
feat: feature refresh listeners on both clients
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.
1 parent 962ca8f commit 6d8aef0

5 files changed

Lines changed: 474 additions & 5 deletions

File tree

‎README.md‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,41 @@ client = GrowthBookClient(
289289
)
290290
```
291291

292+
### Feature Refresh Listeners
293+
294+
Both clients can notify your application whenever a new feature payload is
295+
applied, so you can react to updates instead of polling:
296+
297+
```python
298+
def on_refresh(payload):
299+
log.info("features updated: %d flags", len(payload.get("features", {})))
300+
301+
unsubscribe = gb.add_feature_refresh_listener(on_refresh)
302+
# ...later
303+
unsubscribe()
304+
```
305+
306+
The listener receives the raw payload dict (`features`, `savedGroups`, …) and
307+
runs *after* it has been applied, so evaluating a feature from inside the
308+
listener already sees the new definitions. It fires once per refresh — not once
309+
per evaluation — covering HTTP loads, the stale-while-revalidate background
310+
worker and streaming (SSE) updates. A listener that raises is logged and
311+
skipped; it cannot break a refresh.
312+
313+
On the async client the listener may be a plain function or a coroutine
314+
function:
315+
316+
```python
317+
async def on_refresh(payload):
318+
await cache.invalidate()
319+
320+
unsubscribe = gb_client.add_feature_refresh_listener(on_refresh)
321+
```
322+
323+
Remote-eval mode emits no events on the async client: payloads there are
324+
per-user, so there is no client-wide "definitions changed" moment to report.
325+
The sync client, which is already per-user, does fire them.
326+
292327
### Concurrency and Thread Safety
293328

294329
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:

‎growthbook/growthbook.py‎

Lines changed: 85 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1005,6 +1005,12 @@ def __init__(
10051005
self._deferred_buffer: Optional[TrackingBuffer] = TrackingBuffer() if defer_tracking else None
10061006
self._assigned: Dict[str, Any] = {}
10071007
self._subscriptions: Set[Callable[[Experiment[Any], Result[Any]], None]] = set()
1008+
self._feature_refresh_listeners: List[Callable[[Dict[str, Any]], None]] = []
1009+
# Identity of the last payload dispatched to listeners. The cache hands
1010+
# back the same object on every hit, and evaluation calls load_features()
1011+
# constantly, so an identity check is what keeps listeners firing once
1012+
# per actual refresh instead of once per evaluation.
1013+
self._last_refresh_payload: Optional[Dict[str, Any]] = None
10081014
self._is_updating_features = False
10091015
# Serializes payload writers (set_features/set_payload/refreshes).
10101016
# Re-entrant because _ingest_payload calls set_features while holding
@@ -1083,8 +1089,7 @@ def _remote_eval_payload(self) -> Dict[str, Any]:
10831089

10841090
def _on_feature_update(self, features_data: Dict[str, Any]) -> None:
10851091
"""Callback to handle automatic feature updates from FeatureRepository"""
1086-
if features_data:
1087-
self._ingest_payload(features_data)
1092+
self._apply_and_notify(features_data if features_data else None)
10881093

10891094
def _ingest_payload(self, data: Dict[str, Any]) -> None:
10901095
"""Apply the sections present in a (decrypted) SDK payload.
@@ -1150,7 +1155,12 @@ def load_features(self, force_refresh: bool = False) -> None:
11501155
force_refresh=force_refresh,
11511156
)
11521157
if response is not None:
1153-
self._ingest_payload(response)
1158+
# In CDN mode the repository already dispatched this exact object
1159+
# via _on_feature_update; the identity check there makes the notify
1160+
# a no-op. It matters in remote-eval mode, where the repository
1161+
# deliberately skips its global callbacks and this is the only
1162+
# dispatch point.
1163+
self._apply_and_notify(response)
11541164

11551165
async def load_features_async(self, force_refresh: bool = False) -> None:
11561166
if not self._client_key:
@@ -1169,7 +1179,7 @@ async def load_features_async(self, force_refresh: bool = False) -> None:
11691179
)
11701180

11711181
if features is not None:
1172-
self._ingest_payload(features)
1182+
self._apply_and_notify(features)
11731183

11741184
def _features_event_handler(self, features: str) -> None:
11751185
decoded = json.loads(features)
@@ -1180,7 +1190,10 @@ def _features_event_handler(self, features: str) -> None:
11801190
key = self._api_host + "::" + self._client_key
11811191

11821192
if data is not None:
1183-
self._ingest_payload(data)
1193+
# The streaming path applies the payload itself and never goes
1194+
# through the repository's callbacks, so without this listeners
1195+
# would miss exactly the updates they exist to observe.
1196+
self._apply_and_notify(data)
11841197
feature_repo.save_in_cache(key, data, self._cache_ttl)
11851198

11861199
def _dispatch_sse_event(self, event_data: Dict[str, Any]) -> None:
@@ -1255,6 +1268,72 @@ def set_features(self, features: Dict[str, Any]) -> None:
12551268
finally:
12561269
self._is_updating_features = False
12571270

1271+
def add_feature_refresh_listener(
1272+
self, listener: Callable[[Dict[str, Any]], None]
1273+
) -> Callable[[], None]:
1274+
"""Register a callable invoked whenever a new feature payload is applied
1275+
to this instance, so an app can react to updates without polling.
1276+
1277+
The listener receives the raw payload dict (``features``, ``savedGroups``,
1278+
…). It runs *after* the payload has been applied, so evaluating a feature
1279+
from inside the listener already sees the new definitions.
1280+
1281+
Fires once per refresh — not once per evaluation — for HTTP loads, the
1282+
stale-while-revalidate background worker and streaming (SSE) updates.
1283+
A listener that raises is logged and skipped; it can't break a refresh.
1284+
1285+
Returns a callable that unregisters the listener."""
1286+
if listener not in self._feature_refresh_listeners:
1287+
self._feature_refresh_listeners.append(listener)
1288+
1289+
def unsubscribe() -> None:
1290+
self.remove_feature_refresh_listener(listener)
1291+
1292+
return unsubscribe
1293+
1294+
def remove_feature_refresh_listener(
1295+
self, listener: Callable[[Dict[str, Any]], None]
1296+
) -> None:
1297+
if listener in self._feature_refresh_listeners:
1298+
self._feature_refresh_listeners.remove(listener)
1299+
1300+
def _apply_and_notify(self, payload: Optional[Dict[str, Any]]) -> None:
1301+
"""Apply a payload and dispatch it to the refresh listeners as one
1302+
unit, under the payload-writer lock.
1303+
1304+
Notifying outside the lock would let two refresh sources reorder:
1305+
one applies A, the other applies and notifies B, then the first
1306+
notifies A — so listeners see an older payload last, and a listener
1307+
that evaluates sees state that doesn't match the payload it was
1308+
handed. The lock is reentrant, and evaluation never takes it (reads
1309+
go through the published snapshot), so a listener is free to
1310+
evaluate."""
1311+
with self._payload_lock:
1312+
if payload is not None:
1313+
self._ingest_payload(payload)
1314+
self._notify_feature_refresh(payload)
1315+
1316+
def _notify_feature_refresh(self, payload: Optional[Dict[str, Any]]) -> None:
1317+
"""Dispatch a payload to the refresh listeners, once per distinct
1318+
payload object. Call this only after the payload has been applied."""
1319+
if payload is None:
1320+
# A failed refresh applied nothing, so the payload listeners last
1321+
# saw is unchanged. Clearing the marker here would make the next
1322+
# cache hit — which returns that same previously-notified object —
1323+
# look like a fresh payload and fire listeners a second time.
1324+
return
1325+
if payload is self._last_refresh_payload:
1326+
return
1327+
self._last_refresh_payload = payload
1328+
if not self._feature_refresh_listeners:
1329+
return
1330+
1331+
for listener in list(self._feature_refresh_listeners):
1332+
try:
1333+
listener(payload)
1334+
except Exception:
1335+
logger.exception("Error in feature refresh listener")
1336+
12581337
@deprecated("getFeatures is deprecated, use get_features instead")
12591338
def getFeatures(self) -> Dict[str, Feature]:
12601339
return self.get_features()
@@ -1340,6 +1419,7 @@ def destroy(self, timeout: float = 10) -> None:
13401419
# Clear all internal state
13411420
try:
13421421
self._subscriptions.clear()
1422+
self._feature_refresh_listeners.clear()
13431423
self._tracked.clear()
13441424
if self._deferred_buffer:
13451425
self._deferred_buffer.clear()

‎growthbook/growthbook_client.py‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -657,6 +657,13 @@ def __init__(
657657
self._subscriptions: Set[Callable[[Experiment[Any], Result[Any]], Union[None, Awaitable[None]]]] = set()
658658
self._subscriptions_lock = threading.Lock()
659659

660+
# Feature refresh listeners (sync or async callables)
661+
self._feature_refresh_listeners: List[Callable[[Dict[str, Any]], Any]] = []
662+
self._feature_refresh_lock = threading.Lock()
663+
# Serializes apply-then-notify so concurrent refreshes can't reorder
664+
# listener events; see _feature_update_callback.
665+
self._refresh_order_lock = asyncio.Lock()
666+
660667
# Per-attributes-key inflight sticky bucket fetches. Concurrent evals
661668
# with identical attributes coalesce onto one service fetch; distinct
662669
# attributes fetch in parallel. No cross-eval result cache by default
@@ -810,6 +817,54 @@ def unsubscribe() -> None:
810817
self._subscriptions.discard(callback)
811818
return unsubscribe
812819

820+
def add_feature_refresh_listener(
821+
self, listener: Callable[[Dict[str, Any]], Any]
822+
) -> Callable[[], None]:
823+
"""Register a callable invoked whenever a new feature payload is applied
824+
to this client, so an app can react to updates without polling.
825+
826+
The listener receives the raw payload dict (``features``, ``savedGroups``,
827+
…) and may be a plain function or a coroutine function; coroutines are
828+
awaited. It runs *after* the payload has been applied to the global
829+
context, so evaluating a feature from inside the listener already sees
830+
the new definitions. A listener that raises is logged and skipped.
831+
832+
Fires on the initial load and on every refresh, whether driven by
833+
streaming (SSE) or HTTP polling. Remote-eval mode emits no events:
834+
payloads there are per-user, so there is no client-wide "definitions
835+
changed" moment to report.
836+
837+
Returns a callable that unregisters the listener."""
838+
with self._feature_refresh_lock:
839+
if listener not in self._feature_refresh_listeners:
840+
self._feature_refresh_listeners.append(listener)
841+
842+
def unsubscribe() -> None:
843+
self.remove_feature_refresh_listener(listener)
844+
845+
return unsubscribe
846+
847+
def remove_feature_refresh_listener(
848+
self, listener: Callable[[Dict[str, Any]], Any]
849+
) -> None:
850+
with self._feature_refresh_lock:
851+
if listener in self._feature_refresh_listeners:
852+
self._feature_refresh_listeners.remove(listener)
853+
854+
async def _notify_feature_refresh(self, payload: Dict[str, Any]) -> None:
855+
"""Dispatch a payload to the refresh listeners. Call only after the
856+
payload has been applied to the global context."""
857+
with self._feature_refresh_lock:
858+
listeners = list(self._feature_refresh_listeners)
859+
860+
for listener in listeners:
861+
try:
862+
result = listener(payload)
863+
if asyncio.iscoroutine(result):
864+
await result
865+
except Exception:
866+
logger.exception("Error in feature refresh listener")
867+
813868
def _fire_subscriptions(self, experiment: Experiment[Any], result: Result[Any]) -> None:
814869
"""Thread-safe subscription notifications"""
815870
with self._subscriptions_lock:
@@ -1185,6 +1240,18 @@ async def _feature_update_callback(self, features_data: Dict[str, Any]) -> None:
11851240
logger.warning("Warning: Received empty features data")
11861241
return
11871242

1243+
# Apply and notify as one unit. The ordering lock is distinct from the
1244+
# context lock on purpose: evaluation takes that one, so notifying
1245+
# under it would deadlock any listener that evaluates. Evaluation
1246+
# never takes this one, so holding it across the pair is safe — and it
1247+
# is what keeps two overlapping refreshes from notifying out of
1248+
# application order (apply A, apply+notify B, notify A).
1249+
async with self._refresh_order_lock:
1250+
await self._apply_payload(features_data)
1251+
# Outside the context lock, which _apply_payload has released.
1252+
await self._notify_feature_refresh(features_data)
1253+
1254+
async def _apply_payload(self, features_data: Dict[str, Any]) -> None:
11881255
async with self._context_lock: # serializes concurrent updaters only
11891256
prev = self._global_context
11901257
# Mirror JS setPayload: sections absent from the update carry
@@ -1443,6 +1510,11 @@ async def close(self) -> None:
14431510
self._tracked.clear()
14441511
with self._subscriptions_lock:
14451512
self._subscriptions.clear()
1513+
# Listener closures capture application objects; a closed client that
1514+
# kept them would hold those alive and, if reinitialized, fire
1515+
# callbacks registered in its previous lifecycle.
1516+
with self._feature_refresh_lock:
1517+
self._feature_refresh_listeners.clear()
14461518
# Clear context
14471519
async with self._context_lock:
14481520
self._global_context = None

0 commit comments

Comments
 (0)