From e11c3ebd8348e82d0abc4b51eaee81c4e290da8c Mon Sep 17 00:00:00 2001 From: Volodymyr Nazarkevych Date: Thu, 1 Oct 2026 11:20:01 +0300 Subject: [PATCH 1/5] feat: runtime tracking and feature usage callback setters MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The tracking and feature usage callbacks could only be supplied to the single-context GrowthBook at construction time, so anything deciding the sink after the instance exists had no supported path. That is not hypothetical here: GrowthBookTrackingPlugin, shipped with the SDK, installed its wrapper by assigning the private `_trackingCallback`, guarded by `hasattr` with a log warning as the failure mode. This commit gives it a public API and switches it over. Adds set_tracking_callback / get_tracking_callback and set_feature_usage_callback / get_feature_usage_callback. The getters matter as much as the setters: consumers wrap rather than replace, and reading the existing sink to chain to it is exactly what the plugin does. No new wiring was needed in evaluation — the context is rebuilt per call, and the existing code already noted that a callback installed later is picked up. Both invocation sites already catch, so a throwing sink still cannot break an evaluation. Deliberately no flush-on-set, unlike the TS SDK. There the deferred buffer exists because no sink was installed, so flushing is the only way those calls are delivered. Here `defer_tracking=True` buffers exposures for hand-off to a client SDK through get_deferred_tracking_calls(), and the buffer records independently of the callback — replaying it into a newly installed sink would report the same exposures twice while also consuming the hand-off. Nothing is lost: buffered calls stay retrievable, and later evaluations reach the new callback normally. --- README.md | 35 ++++++++ growthbook/growthbook.py | 38 ++++++++ growthbook/plugins/growthbook_tracking.py | 9 +- tests/test_growthbook.py | 105 ++++++++++++++++++++++ 4 files changed, 183 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 89602bb..f7a8223 100644 --- a/README.md +++ b/README.md @@ -528,6 +528,41 @@ gb = GrowthBook( ) ``` +#### Setting Callbacks at Runtime + +When the sink isn't known at construction time — a framework decides it later, +or a plugin installs it — both callbacks can be set after the fact. They take +effect on the next evaluation; no re-initialization is needed. + +```python +gb.set_tracking_callback(on_experiment_viewed) +gb.set_feature_usage_callback(on_feature_usage) +``` + +`get_tracking_callback()` and `get_feature_usage_callback()` return the current +sink, so a consumer can wrap rather than replace it: + +```python +original = gb.get_tracking_callback() + +def wrapper(experiment, result, user_context): + my_own_sink(experiment, result) + if original: + original(experiment=experiment, result=result, user_context=user_context) + +gb.set_tracking_callback(wrapper) +``` + +Pass `None` to detach. A callback that raises is caught and logged, so it can't +break evaluation. + +Setting a tracking callback does **not** replay the deferred tracking buffer. +With `defer_tracking=True` the buffer records exposures independently of the +callback, for hand-off to a client SDK via `get_deferred_tracking_calls()`; +replaying it into a newly installed sink would report the same exposures twice. +Buffered calls stay retrievable through the getter, and evaluations after the +call reach the new callback normally. + #### Built-in Tracking Plugin For easier setup, you can use the built-in tracking plugin that automatically sends experiment and feature events to GrowthBook's data warehouse: diff --git a/growthbook/growthbook.py b/growthbook/growthbook.py index e98e740..6f55582 100644 --- a/growthbook/growthbook.py +++ b/growthbook/growthbook.py @@ -1392,6 +1392,44 @@ def destroy(self, timeout: float = 10) -> None: except Exception as e: logger.warning(f"Error clearing internal state: {e}") + def set_tracking_callback(self, callback: Optional[TrackingCallback]) -> None: + """Install (or replace) the experiment tracking callback at runtime. + + Takes effect on the next evaluation: the evaluation context is rebuilt + per call, so no re-initialization is needed. Pass None to detach. + + Deliberately does NOT flush the deferred tracking buffer, unlike the TS + SDK's `setTrackingCallback`. There the buffer exists *because* no sink + was installed, so flushing is the only way those calls are ever + delivered. Here it serves a different purpose — `defer_tracking=True` + buffers exposures for hand-off to a client SDK via + `get_deferred_tracking_calls()` — so draining it into a callback would + either double-report (the buffer records independently of the callback, + so an exposure that happened while a sink was attached is in both) or + break that hand-off. Nothing is lost by not flushing: buffered calls + stay retrievable through `get_deferred_tracking_calls()`, and + evaluations after this call reach the new callback normally.""" + self._trackingCallback = callback + + def get_tracking_callback(self) -> Optional[TrackingCallback]: + """The current tracking callback, or None. + + Exposed so a consumer can wrap rather than replace — reading the + existing sink and chaining to it is what GrowthBookTrackingPlugin + does.""" + return self._trackingCallback + + def set_feature_usage_callback( + self, callback: Optional[FeatureUsageCallback] + ) -> None: + """Install (or replace) the feature usage callback at runtime. + Takes effect on the next evaluation. Pass None to detach.""" + self._featureUsageCallback = callback + + def get_feature_usage_callback(self) -> Optional[FeatureUsageCallback]: + """The current feature usage callback, or None.""" + return self._featureUsageCallback + def set_event_logger(self, fn: EventLogger) -> None: """Register a callable that will be invoked by log_event. diff --git a/growthbook/plugins/growthbook_tracking.py b/growthbook/plugins/growthbook_tracking.py index cdf4b6e..e266fd5 100644 --- a/growthbook/plugins/growthbook_tracking.py +++ b/growthbook/plugins/growthbook_tracking.py @@ -182,8 +182,9 @@ def tracking_wrapper(experiment: Any, result: Any, user_context: Any = None) -> if self.additional_callback: self._safe_execute(self.additional_callback, experiment, result, user_context) - if hasattr(gb_instance, "_trackingCallback"): - original = gb_instance._trackingCallback + if hasattr(gb_instance, "set_tracking_callback"): + # Wrap rather than replace: read the existing sink and chain to it. + original = gb_instance.get_tracking_callback() def legacy_wrapper(experiment: Any, result: Any, user_context: Any = None) -> None: tracking_wrapper(experiment, result, user_context) @@ -192,7 +193,7 @@ def legacy_wrapper(experiment: Any, result: Any, user_context: Any = None) -> No # invoked with keyword arguments, same as both clients do. self._safe_execute(original, experiment=experiment, result=result, user_context=user_context) - gb_instance._trackingCallback = legacy_wrapper + gb_instance.set_tracking_callback(legacy_wrapper) elif hasattr(gb_instance, "options") and hasattr( gb_instance.options, "on_experiment_viewed" @@ -209,7 +210,7 @@ def async_wrapper(experiment: Any, result: Any, user_context: Any) -> None: else: self.logger.warning( - "_trackingCallback or on_experiment_viewed not found — " + "set_tracking_callback or on_experiment_viewed not found — " "experiment tracking may not work" ) diff --git a/tests/test_growthbook.py b/tests/test_growthbook.py index 8d4186f..2e20fdc 100644 --- a/tests/test_growthbook.py +++ b/tests/test_growthbook.py @@ -2099,3 +2099,108 @@ def test_stale_while_revalidate_cleanup(mocker): if feature_repo._refresh_thread: feature_repo.stop_background_refresh() feature_repo.clear_cache() + + +# --- Runtime callback setters ------------------------------------------------ + +def test_tracking_callback_can_be_set_after_construction(): + # The evaluation context is rebuilt per call, so a callback installed later + # is picked up without re-initializing the instance. + calls = [] + gb = GrowthBook(attributes={"id": "1"}) + exp = Experiment(key="late-sink", variations=[0, 1]) + + gb.run(exp) + assert calls == [] # no sink yet + + gb.set_tracking_callback( + lambda experiment, result, user_context: calls.append(experiment.key) + ) + gb.run(Experiment(key="late-sink-2", variations=[0, 1])) + assert calls == ["late-sink-2"] + + # Detaching stops delivery again. + gb.set_tracking_callback(None) + assert gb.get_tracking_callback() is None + gb.run(Experiment(key="late-sink-3", variations=[0, 1])) + assert calls == ["late-sink-2"] + + gb.destroy() + + +def test_tracking_callback_getter_supports_wrapping(): + # Reading the existing sink and chaining to it is what the tracking plugin + # does; without a getter it would have to reach into private state. + order = [] + gb = GrowthBook( + attributes={"id": "1"}, + on_experiment_viewed=lambda experiment, result, user_context: order.append("user"), + ) + + original = gb.get_tracking_callback() + assert original is not None + + def wrapper(experiment, result, user_context): + order.append("plugin") + original(experiment=experiment, result=result, user_context=user_context) + + gb.set_tracking_callback(wrapper) + gb.run(Experiment(key="wrapped", variations=[0, 1])) + + assert order == ["plugin", "user"] + gb.destroy() + + +def test_feature_usage_callback_can_be_set_after_construction(): + seen = [] + gb = GrowthBook(attributes={"id": "1"}, features={"flag": {"defaultValue": 7}}) + + gb.get_feature_value("flag", 0) + assert seen == [] + + gb.set_feature_usage_callback(lambda key, result, user_context: seen.append(key)) + gb.get_feature_value("flag", 0) + assert seen == ["flag"] + + assert gb.get_feature_usage_callback() is not None + gb.set_feature_usage_callback(None) + gb.get_feature_value("flag", 0) + assert seen == ["flag"] + + gb.destroy() + + +def test_setting_tracking_callback_does_not_flush_deferred_buffer(): + # The deferred buffer feeds get_deferred_tracking_calls() for hand-off to a + # client SDK. Draining it into a newly set callback would double-report, + # since the buffer records independently of the callback. + gb = GrowthBook(attributes={"id": "1"}, defer_tracking=True) + gb.run(Experiment(key="buffered", variations=[0, 1])) + + buffered_before = gb.get_deferred_tracking_calls() + assert len(buffered_before) == 1 + + calls = [] + gb.set_tracking_callback( + lambda experiment, result, user_context: calls.append(experiment.key) + ) + + assert calls == [] # nothing replayed + assert len(gb.get_deferred_tracking_calls()) == 1 # still retrievable + + gb.destroy() + + +def test_throwing_runtime_callback_cannot_break_evaluation(): + gb = GrowthBook(attributes={"id": "1"}, features={"flag": {"defaultValue": 7}}) + + def boom(*args, **kwargs): + raise RuntimeError("sink exploded") + + gb.set_tracking_callback(boom) + gb.set_feature_usage_callback(boom) + + assert gb.run(Experiment(key="safe", variations=[0, 1])).value in (0, 1) + assert gb.get_feature_value("flag", 0) == 7 + + gb.destroy() From 852b7b6bd67b3b33743d8f99cbc80d9746c3f363 Mon Sep 17 00:00:00 2001 From: Volodymyr Nazarkevych Date: Mon, 23 Nov 2026 17:16:25 +0200 Subject: [PATCH 2/5] fix: keep tracking plugin sinks out of the user's callback slot GrowthBookTrackingPlugin installed itself by wrapping the tracking callback, so a later set_tracking_callback() silently replaced it and no exposures reached the ingestor. Plugins now register through an internal listener list (_add_tracking_listener / _remove_tracking_listener) that _track invokes before the user callback; set_tracking_callback() and get_tracking_callback() own only the user's sink. The plugin unregisters its listener on cleanup. Exposure dedupe stays per instance: an exposure already delivered is not re-sent to a newly installed callback, since re-sending would also reach the plugin listeners. Documented in the docstring and README and pinned by a test. Listeners are deduped separately so the user callback keeps its existing retry-if-it-raised behavior. --- README.md | 9 +++ growthbook/growthbook.py | 51 +++++++++++-- growthbook/plugins/growthbook_tracking.py | 27 ++++--- tests/test_growthbook.py | 92 +++++++++++++++++++++++ 4 files changed, 161 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index f7a8223..1f65206 100644 --- a/README.md +++ b/README.md @@ -556,6 +556,15 @@ gb.set_tracking_callback(wrapper) Pass `None` to detach. A callback that raises is caught and logged, so it can't break evaluation. +These setters own only your callback. The built-in tracking plugin registers +its own listener, so replacing or detaching your callback doesn't stop +exposures from reaching GrowthBook, and `get_tracking_callback()` never returns +the plugin's wrapper. + +Exposure dedupe is per instance, not per callback: an exposure this instance +has already delivered is not re-sent to a newly installed callback. Later +exposures reach it normally. + Setting a tracking callback does **not** replay the deferred tracking buffer. With `defer_tracking=True` the buffer records exposures independently of the callback, for hand-off to a client SDK via `get_deferred_tracking_calls()`; diff --git a/growthbook/growthbook.py b/growthbook/growthbook.py index 6f55582..8a3e0be 100644 --- a/growthbook/growthbook.py +++ b/growthbook/growthbook.py @@ -1021,6 +1021,13 @@ def __init__( self._forcedFeatures: Dict[str, Any] = forced_features or {} self._tracked: Dict[TrackingDedupeKey, Any] = {} + # Internal tracking listeners, installed by plugins. Kept apart from + # the user's callback so `set_tracking_callback` can't silently + # replace a plugin's sink. Listeners have their own dedupe set because + # they are marked on first delivery, while the user callback keeps its + # existing contract of being retried if it raised. + self._tracking_listeners: List[TrackingCallback] = [] + self._tracked_for_listeners: Set[TrackingDedupeKey] = set() 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() @@ -1377,6 +1384,8 @@ def destroy(self, timeout: float = 10) -> None: try: self._subscriptions.clear() self._tracked.clear() + self._tracked_for_listeners.clear() + self._tracking_listeners.clear() if self._deferred_buffer: self._deferred_buffer.clear() self._assigned.clear() @@ -1398,6 +1407,15 @@ def set_tracking_callback(self, callback: Optional[TrackingCallback]) -> None: Takes effect on the next evaluation: the evaluation context is rebuilt per call, so no re-initialization is needed. Pass None to detach. + This owns only the user's sink. Plugins such as + GrowthBookTrackingPlugin register their own listeners, which keep + receiving exposures whatever is set here. + + Exposure dedupe is per instance, not per callback: an exposure this + instance has already delivered is not re-sent to a newly installed + callback. Re-sending would also reach the plugin listeners, which + share the same exposures, and report them twice. + Deliberately does NOT flush the deferred tracking buffer, unlike the TS SDK's `setTrackingCallback`. There the buffer exists *because* no sink was installed, so flushing is the only way those calls are ever @@ -1412,13 +1430,24 @@ def set_tracking_callback(self, callback: Optional[TrackingCallback]) -> None: self._trackingCallback = callback def get_tracking_callback(self) -> Optional[TrackingCallback]: - """The current tracking callback, or None. + """The current user tracking callback, or None. - Exposed so a consumer can wrap rather than replace — reading the - existing sink and chaining to it is what GrowthBookTrackingPlugin - does.""" + Exposed so a consumer can wrap rather than replace it. Plugin + listeners are not part of it.""" return self._trackingCallback + def _add_tracking_listener(self, listener: TrackingCallback) -> None: + """Internal: register a plugin's tracking sink. Invoked before the + user callback, with the same keyword arguments, and unaffected by + `set_tracking_callback`.""" + if listener not in self._tracking_listeners: + self._tracking_listeners.append(listener) + + def _remove_tracking_listener(self, listener: TrackingCallback) -> None: + """Internal: unregister a listener added by `_add_tracking_listener`.""" + if listener in self._tracking_listeners: + self._tracking_listeners.remove(listener) + def set_feature_usage_callback( self, callback: Optional[FeatureUsageCallback] ) -> None: @@ -1546,7 +1575,7 @@ def _build_eval_context(self) -> EvaluationContext: # Wired only when a consumer exists (contexts are per-eval, so a # callback installed later — e.g. by a plugin — is still picked # up), letting core skip dead work like rule.tracks hydration. - tracking_cb = self._track if self._trackingCallback else None, + tracking_cb = self._track if (self._trackingCallback or self._tracking_listeners) else None, callback_subscription = self._fireSubscriptions, feature_usage_cb = self._feature_usage if self._featureUsageCallback else None, tracking_buffer = self._deferred_buffer, @@ -1642,10 +1671,18 @@ def clear_deferred_tracking_calls(self) -> None: self._deferred_buffer.clear() def _track(self, experiment: Experiment[Any], result: Result[Any], user_context: UserContext) -> None: - if not self._trackingCallback: + if not self._trackingCallback and not self._tracking_listeners: return None key = tracking_dedupe_key(experiment, result) - if not self._tracked.get(key): + if self._tracking_listeners and key not in self._tracked_for_listeners: + self._tracked_for_listeners.add(key) + snapshot = tracking_user_context(user_context) + for listener in list(self._tracking_listeners): + try: + listener(experiment=experiment, result=result, user_context=snapshot) + except Exception as e: + logger.exception(e) + if self._trackingCallback and not self._tracked.get(key): try: # Snapshot so the logged attributes are exactly the ones used # for bucketing, even if the caller mutates them afterwards. diff --git a/growthbook/plugins/growthbook_tracking.py b/growthbook/plugins/growthbook_tracking.py index e266fd5..91f8776 100644 --- a/growthbook/plugins/growthbook_tracking.py +++ b/growthbook/plugins/growthbook_tracking.py @@ -133,6 +133,8 @@ def __init__( self._batch_lock = threading.Lock() self._flush_timer: Optional[threading.Timer] = None self._client_key: Optional[str] = None + # Set when the listener is registered, so cleanup can unregister it. + self._tracking_listener: Optional[Callable[..., None]] = None # ------------------------------------------------------------------ # Plugin lifecycle @@ -165,6 +167,12 @@ def initialize(self, gb_instance: "GrowthBookInstance") -> None: def cleanup(self) -> None: """Flush any pending events and release resources.""" + listener = self._tracking_listener + if listener is not None and self._gb_instance is not None: + remove = getattr(self._gb_instance, "_remove_tracking_listener", None) + if remove is not None: + remove(listener) + self._tracking_listener = None self._flush_events() with self._batch_lock: if self._flush_timer: @@ -182,18 +190,15 @@ def tracking_wrapper(experiment: Any, result: Any, user_context: Any = None) -> if self.additional_callback: self._safe_execute(self.additional_callback, experiment, result, user_context) - if hasattr(gb_instance, "set_tracking_callback"): - # Wrap rather than replace: read the existing sink and chain to it. - original = gb_instance.get_tracking_callback() - - def legacy_wrapper(experiment: Any, result: Any, user_context: Any = None) -> None: + if hasattr(gb_instance, "_add_tracking_listener"): + # Own listener slot, not the user's callback: a later + # set_tracking_callback() must not silently drop this sink, and + # the user's callback is still invoked by the instance itself. + def listener(experiment: Any, result: Any, user_context: Any = None) -> None: tracking_wrapper(experiment, result, user_context) - if original: - # The user's callback follows the TrackingCallback contract: - # invoked with keyword arguments, same as both clients do. - self._safe_execute(original, experiment=experiment, result=result, user_context=user_context) - gb_instance.set_tracking_callback(legacy_wrapper) + gb_instance._add_tracking_listener(listener) + self._tracking_listener = listener elif hasattr(gb_instance, "options") and hasattr( gb_instance.options, "on_experiment_viewed" @@ -210,7 +215,7 @@ def async_wrapper(experiment: Any, result: Any, user_context: Any) -> None: else: self.logger.warning( - "set_tracking_callback or on_experiment_viewed not found — " + "_add_tracking_listener or on_experiment_viewed not found — " "experiment tracking may not work" ) diff --git a/tests/test_growthbook.py b/tests/test_growthbook.py index 2e20fdc..f15362c 100644 --- a/tests/test_growthbook.py +++ b/tests/test_growthbook.py @@ -2204,3 +2204,95 @@ def boom(*args, **kwargs): assert gb.get_feature_value("flag", 0) == 7 gb.destroy() + + +def _plugin_capturing_exposures(received): + from unittest.mock import patch + from growthbook.plugins.growthbook_tracking import GrowthBookTrackingPlugin + + plugin = GrowthBookTrackingPlugin( + ingestor_host="https://ingest.invalid", track_feature_evaluated=False + ) + patcher = patch.object( + plugin, "_track_experiment_viewed", + lambda experiment, result, user_context=None: received.append(experiment.key), + ) + patcher.start() + return plugin, patcher + + +def test_set_tracking_callback_does_not_disable_tracking_plugin(): + # The plugin has its own listener slot, so replacing the user's sink keeps + # exposures flowing to the ingestor. + plugin_got, user_got = [], [] + plugin, patcher = _plugin_capturing_exposures(plugin_got) + try: + gb = GrowthBook(attributes={"id": "1"}, plugins=[plugin]) + gb.run(Experiment(key="before-set", variations=[0, 1])) + gb.set_tracking_callback( + lambda experiment, result, user_context: user_got.append(experiment.key) + ) + gb.run(Experiment(key="after-set", variations=[0, 1])) + gb.set_tracking_callback(None) + gb.run(Experiment(key="after-detach", variations=[0, 1])) + + assert plugin_got == ["before-set", "after-set", "after-detach"] + assert user_got == ["after-set"] + # The getter returns the user's sink only, not a plugin wrapper. + assert gb.get_tracking_callback() is None + gb.destroy() + finally: + patcher.stop() + + +def test_tracking_plugin_and_constructor_callback_both_receive_once(): + plugin_got, user_got = [], [] + plugin, patcher = _plugin_capturing_exposures(plugin_got) + try: + gb = GrowthBook( + attributes={"id": "1"}, + plugins=[plugin], + on_experiment_viewed=lambda experiment, result, user_context: user_got.append(experiment.key), + ) + exp = Experiment(key="exp", variations=[0, 1]) + gb.run(exp) + gb.run(exp) + + assert plugin_got == ["exp"] + assert user_got == ["exp"] + gb.destroy() + finally: + patcher.stop() + + +def test_tracking_plugin_cleanup_removes_its_listener(): + plugin_got = [] + plugin, patcher = _plugin_capturing_exposures(plugin_got) + try: + gb = GrowthBook(attributes={"id": "1"}, plugins=[plugin]) + plugin.cleanup() + gb.run(Experiment(key="exp", variations=[0, 1])) + assert plugin_got == [] + gb.destroy() + finally: + patcher.stop() + + +def test_exposure_dedupe_is_per_instance_not_per_callback(): + # An exposure already delivered by this instance is not re-sent to a newly + # installed callback; new exposures are. + sink_a, sink_b = [], [] + gb = GrowthBook( + attributes={"id": "1"}, + on_experiment_viewed=lambda experiment, result, user_context: sink_a.append(experiment.key), + ) + gb.run(Experiment(key="seen", variations=[0, 1])) + gb.set_tracking_callback( + lambda experiment, result, user_context: sink_b.append(experiment.key) + ) + gb.run(Experiment(key="seen", variations=[0, 1])) + gb.run(Experiment(key="new", variations=[0, 1])) + + assert sink_a == ["seen"] + assert sink_b == ["new"] + gb.destroy() From 38703b4d87ea208bc524df0264a8087176f55e32 Mon Sep 17 00:00:00 2001 From: Volodymyr Nazarkevych Date: Tue, 1 Dec 2026 15:04:33 +0200 Subject: [PATCH 3/5] fix: keep a shared tracking plugin hooked into the other instances One plugin object passed to several instances (e.g. per-request instances sharing one batching plugin) keeps a single _gb_instance, so cleanup() from any instance's destroy() removed the listener of the last initialized instance and its exposures stopped reaching the ingestor. cleanup() can't tell which instance is being destroyed, so it no longer touches instance listeners; each instance drops the listeners registered on it in its own destroy(). --- README.md | 4 +++ growthbook/growthbook.py | 3 ++ growthbook/plugins/growthbook_tracking.py | 17 ++++------ tests/test_growthbook.py | 39 +++++++++++++++++++---- 4 files changed, 47 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 1f65206..a2b8e6b 100644 --- a/README.md +++ b/README.md @@ -599,6 +599,10 @@ is_enabled = gb.is_on("my-feature") # -> Tracked automatically The tracking plugin provides batching, error handling, and works alongside your existing tracking callbacks. See the [plugin documentation](https://docs.growthbook.io/lib/python#tracking-plugins) for more details. +One plugin object can be shared by several instances on the same client key, +e.g. per-request instances sharing one batch. Each instance's `destroy()` drops +only its own hook into the plugin, so the others keep reporting. + #### Deferred Tracking When your server evaluates features but the analytics context lives on the client (server-side rendering, an API returning evaluated flags), buffer the exposures instead of tracking them server-side and forward them to a client SDK, which fires them through its own tracking callback. diff --git a/growthbook/growthbook.py b/growthbook/growthbook.py index 8a3e0be..55ef898 100644 --- a/growthbook/growthbook.py +++ b/growthbook/growthbook.py @@ -1385,6 +1385,9 @@ def destroy(self, timeout: float = 10) -> None: self._subscriptions.clear() self._tracked.clear() self._tracked_for_listeners.clear() + # Plugins' listeners are dropped here, by the instance that holds + # them, rather than in plugin.cleanup(): a plugin shared by several + # instances can't tell which one is being destroyed. self._tracking_listeners.clear() if self._deferred_buffer: self._deferred_buffer.clear() diff --git a/growthbook/plugins/growthbook_tracking.py b/growthbook/plugins/growthbook_tracking.py index 91f8776..5ef1c25 100644 --- a/growthbook/plugins/growthbook_tracking.py +++ b/growthbook/plugins/growthbook_tracking.py @@ -133,8 +133,6 @@ def __init__( self._batch_lock = threading.Lock() self._flush_timer: Optional[threading.Timer] = None self._client_key: Optional[str] = None - # Set when the listener is registered, so cleanup can unregister it. - self._tracking_listener: Optional[Callable[..., None]] = None # ------------------------------------------------------------------ # Plugin lifecycle @@ -166,13 +164,13 @@ def initialize(self, gb_instance: "GrowthBookInstance") -> None: self.logger.error("Failed to initialize tracking plugin: %s", e) def cleanup(self) -> None: - """Flush any pending events and release resources.""" - listener = self._tracking_listener - if listener is not None and self._gb_instance is not None: - remove = getattr(self._gb_instance, "_remove_tracking_listener", None) - if remove is not None: - remove(listener) - self._tracking_listener = None + """Flush any pending events and release resources. + + Doesn't unregister the tracking listener. One plugin object may be + shared by several instances (e.g. per-request instances sharing one + batching plugin) and cleanup() can't tell which of them is being + destroyed; each instance drops the listeners registered on it in its + own destroy(), so the others keep reporting.""" self._flush_events() with self._batch_lock: if self._flush_timer: @@ -198,7 +196,6 @@ def listener(experiment: Any, result: Any, user_context: Any = None) -> None: tracking_wrapper(experiment, result, user_context) gb_instance._add_tracking_listener(listener) - self._tracking_listener = listener elif hasattr(gb_instance, "options") and hasattr( gb_instance.options, "on_experiment_viewed" diff --git a/tests/test_growthbook.py b/tests/test_growthbook.py index f15362c..3521c49 100644 --- a/tests/test_growthbook.py +++ b/tests/test_growthbook.py @@ -2265,15 +2265,42 @@ def test_tracking_plugin_and_constructor_callback_both_receive_once(): patcher.stop() -def test_tracking_plugin_cleanup_removes_its_listener(): +def test_destroying_one_instance_keeps_a_shared_tracking_plugin_reporting(): + # Per-request instances may share one batching plugin. cleanup() can't tell + # which instance is being destroyed, so it used to unhook the plugin from + # whichever instance was initialized last. plugin_got = [] plugin, patcher = _plugin_capturing_exposures(plugin_got) try: - gb = GrowthBook(attributes={"id": "1"}, plugins=[plugin]) - plugin.cleanup() - gb.run(Experiment(key="exp", variations=[0, 1])) - assert plugin_got == [] - gb.destroy() + gb_a = GrowthBook(attributes={"id": "1"}, plugins=[plugin]) + gb_b = GrowthBook(attributes={"id": "1"}, plugins=[plugin]) + gb_b.run(Experiment(key="b-before", variations=[0, 1])) + + gb_a.destroy() + gb_b.run(Experiment(key="b-after", variations=[0, 1])) + + assert plugin_got == ["b-before", "b-after"] + gb_b.destroy() + finally: + patcher.stop() + + +def test_destroy_drops_only_that_instances_plugin_listener(): + plugin_got = [] + plugin, patcher = _plugin_capturing_exposures(plugin_got) + try: + gb_a = GrowthBook(attributes={"id": "1"}, plugins=[plugin]) + gb_b = GrowthBook(attributes={"id": "1"}, plugins=[plugin]) + + # gb_a isn't the instance the plugin was initialized with last, which + # is the one cleanup() used to unhook. + gb_a.destroy() + + assert gb_a._tracking_listeners == [] + assert len(gb_b._tracking_listeners) == 1 + gb_b.run(Experiment(key="b-after", variations=[0, 1])) + assert plugin_got == ["b-after"] + gb_b.destroy() finally: patcher.stop() From cf02da8ad873f075ccc03a860d17a7e772442d6a Mon Sep 17 00:00:00 2001 From: Volodymyr Nazarkevych Date: Thu, 3 Dec 2026 16:00:02 +0200 Subject: [PATCH 4/5] fix: deliver plugin exposures once and drop the unused listener removal - Make the plugin listener dedupe check-and-mark atomic, so concurrent evaluations of one exposure reach the tracking plugin once. - Register one bound method per tracking plugin, so a plugin listed twice on an instance doesn't send every exposure twice. - Remove _remove_tracking_listener: nothing calls it since destroy() clears the listeners itself. - Document and pin that a raising user callback is retried on the next evaluation with or without the plugin, while the plugin gets it once. --- README.md | 4 +- growthbook/growthbook.py | 21 ++++--- growthbook/plugins/growthbook_tracking.py | 17 ++--- tests/test_growthbook.py | 77 +++++++++++++++++++++++ 4 files changed, 103 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 2b21e73..12fcbb6 100644 --- a/README.md +++ b/README.md @@ -563,7 +563,9 @@ the plugin's wrapper. Exposure dedupe is per instance, not per callback: an exposure this instance has already delivered is not re-sent to a newly installed callback. Later -exposures reach it normally. +exposures reach it normally. An exposure counts as delivered only when your +callback returns: one that raises is retried on the next evaluation, whether +or not the tracking plugin is installed. The plugin still gets it once. Setting a tracking callback does **not** replay the deferred tracking buffer. With `defer_tracking=True` the buffer records exposures independently of the diff --git a/growthbook/growthbook.py b/growthbook/growthbook.py index 55ef898..1a479ea 100644 --- a/growthbook/growthbook.py +++ b/growthbook/growthbook.py @@ -1028,6 +1028,9 @@ def __init__( # existing contract of being retried if it raised. self._tracking_listeners: List[TrackingCallback] = [] self._tracked_for_listeners: Set[TrackingDedupeKey] = set() + # Makes the listener dedupe check-and-mark atomic, so concurrent + # evaluations of one exposure deliver it to plugins once. + self._listeners_dedupe_lock = threading.Lock() 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() @@ -1419,6 +1422,10 @@ def set_tracking_callback(self, callback: Optional[TrackingCallback]) -> None: callback. Re-sending would also reach the plugin listeners, which share the same exposures, and report them twice. + An exposure counts as delivered only when the callback returns. One + that raises is logged and retried on the next evaluation, with or + without plugins installed; plugin listeners still get it once. + Deliberately does NOT flush the deferred tracking buffer, unlike the TS SDK's `setTrackingCallback`. There the buffer exists *because* no sink was installed, so flushing is the only way those calls are ever @@ -1446,11 +1453,6 @@ def _add_tracking_listener(self, listener: TrackingCallback) -> None: if listener not in self._tracking_listeners: self._tracking_listeners.append(listener) - def _remove_tracking_listener(self, listener: TrackingCallback) -> None: - """Internal: unregister a listener added by `_add_tracking_listener`.""" - if listener in self._tracking_listeners: - self._tracking_listeners.remove(listener) - def set_feature_usage_callback( self, callback: Optional[FeatureUsageCallback] ) -> None: @@ -1677,8 +1679,13 @@ def _track(self, experiment: Experiment[Any], result: Result[Any], user_context: if not self._trackingCallback and not self._tracking_listeners: return None key = tracking_dedupe_key(experiment, result) - if self._tracking_listeners and key not in self._tracked_for_listeners: - self._tracked_for_listeners.add(key) + deliver_to_listeners = False + if self._tracking_listeners: + with self._listeners_dedupe_lock: + if key not in self._tracked_for_listeners: + self._tracked_for_listeners.add(key) + deliver_to_listeners = True + if deliver_to_listeners: snapshot = tracking_user_context(user_context) for listener in list(self._tracking_listeners): try: diff --git a/growthbook/plugins/growthbook_tracking.py b/growthbook/plugins/growthbook_tracking.py index 077e63d..6809eb8 100644 --- a/growthbook/plugins/growthbook_tracking.py +++ b/growthbook/plugins/growthbook_tracking.py @@ -182,20 +182,21 @@ def cleanup(self) -> None: # Experiment / feature auto-tracking (legacy hooks) # ------------------------------------------------------------------ + def _on_experiment_viewed(self, experiment: Any, result: Any, user_context: Any = None) -> None: + self._track_experiment_viewed(experiment, result, user_context) + if self.additional_callback: + self._safe_execute(self.additional_callback, experiment, result, user_context) + def _setup_experiment_tracking(self, gb_instance: Any) -> None: - def tracking_wrapper(experiment: Any, result: Any, user_context: Any = None) -> None: - self._track_experiment_viewed(experiment, result, user_context) - if self.additional_callback: - self._safe_execute(self.additional_callback, experiment, result, user_context) + tracking_wrapper = self._on_experiment_viewed if hasattr(gb_instance, "_add_tracking_listener"): # Own listener slot, not the user's callback: a later # set_tracking_callback() must not silently drop this sink, and # the user's callback is still invoked by the instance itself. - def listener(experiment: Any, result: Any, user_context: Any = None) -> None: - tracking_wrapper(experiment, result, user_context) - - gb_instance._add_tracking_listener(listener) + # One bound method per plugin, so registering the same plugin + # twice on an instance doesn't add a second listener. + gb_instance._add_tracking_listener(self._on_experiment_viewed) elif hasattr(gb_instance, "options") and hasattr( gb_instance.options, "on_experiment_viewed" diff --git a/tests/test_growthbook.py b/tests/test_growthbook.py index 62c09c9..5f02169 100644 --- a/tests/test_growthbook.py +++ b/tests/test_growthbook.py @@ -2334,6 +2334,83 @@ def test_exposure_dedupe_is_per_instance_not_per_callback(): gb.destroy() +def test_raising_user_callback_is_retried_with_or_without_plugin(): + # An exposure counts as delivered only when the user callback returns, the + # same with the plugin installed as without it. The plugin gets it once. + for with_plugin in (False, True): + plugin_got, user_calls = [], [] + plugin, patcher = _plugin_capturing_exposures(plugin_got) + + def failing(experiment, result, user_context): + user_calls.append(experiment.key) + raise RuntimeError("sink down") + + try: + gb = GrowthBook( + attributes={"id": "1"}, + plugins=[plugin] if with_plugin else [], + on_experiment_viewed=failing, + ) + exp = Experiment(key="exp", variations=[0, 1]) + gb.run(exp) + gb.run(exp) + + assert user_calls == ["exp", "exp"], with_plugin + assert plugin_got == (["exp"] if with_plugin else []) + gb.destroy() + finally: + patcher.stop() + + +def test_plugin_registered_twice_tracks_once(): + plugin_got = [] + plugin, patcher = _plugin_capturing_exposures(plugin_got) + try: + gb = GrowthBook(attributes={"id": "1"}, plugins=[plugin, plugin]) + gb.run(Experiment(key="exp", variations=[0, 1])) + + assert len(gb._tracking_listeners) == 1 + assert plugin_got == ["exp"] + gb.destroy() + finally: + patcher.stop() + + +def test_concurrent_evaluations_deliver_an_exposure_to_plugins_once(): + import threading + import time as time_module + + class SlowSet(set): + # Widens the window between the dedupe check and the mark. + def __contains__(self, item): + found = super().__contains__(item) + time_module.sleep(0.05) + return found + + plugin_got = [] + plugin, patcher = _plugin_capturing_exposures(plugin_got) + try: + gb = GrowthBook(attributes={"id": "1"}, plugins=[plugin]) + gb._tracked_for_listeners = SlowSet() + exp = Experiment(key="exp", variations=[0, 1]) + barrier = threading.Barrier(4) + + def worker(): + barrier.wait() + gb.run(exp) + + threads = [threading.Thread(target=worker) for _ in range(4)] + for t in threads: + t.start() + for t in threads: + t.join() + + assert plugin_got == ["exp"] + gb.destroy() + finally: + patcher.stop() + + def make_repo() -> FeatureRepository: repo=FeatureRepository() repo.cache.clear() From ae2b0bdc2eafe05c751e2dc1f635bfa5a187c80c Mon Sep 17 00:00:00 2001 From: Volodymyr Nazarkevych Date: Thu, 3 Dec 2026 16:09:57 +0200 Subject: [PATCH 5/5] fix: log feature usage callback errors in the sync client _feature_usage swallowed exceptions with a bare pass, so a failing sink set via set_feature_usage_callback (or on_feature_usage) left no trace, while the README says callback errors are logged. Log them the way the async client already does. --- growthbook/growthbook.py | 3 ++- tests/test_growthbook.py | 12 +++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/growthbook/growthbook.py b/growthbook/growthbook.py index 1a479ea..d00c459 100644 --- a/growthbook/growthbook.py +++ b/growthbook/growthbook.py @@ -1620,7 +1620,8 @@ def _feature_usage(self, key: str, result: FeatureResult[Any], user_context: Use # for the evaluation, even if the caller mutates them afterwards. self._featureUsageCallback(key, result, tracking_user_context(user_context)) except Exception: - pass + # Logged like the async client does, so a failing sink is visible. + logger.exception("Error in feature usage callback") @deprecated("getAllResults is deprecated, use get_all_results instead") def getAllResults(self) -> Dict[str, Dict[str, Any]]: diff --git a/tests/test_growthbook.py b/tests/test_growthbook.py index 5f02169..d139d45 100644 --- a/tests/test_growthbook.py +++ b/tests/test_growthbook.py @@ -2200,7 +2200,7 @@ def test_setting_tracking_callback_does_not_flush_deferred_buffer(): gb.destroy() -def test_throwing_runtime_callback_cannot_break_evaluation(): +def test_throwing_runtime_callback_cannot_break_evaluation(caplog): gb = GrowthBook(attributes={"id": "1"}, features={"flag": {"defaultValue": 7}}) def boom(*args, **kwargs): @@ -2209,8 +2209,14 @@ def boom(*args, **kwargs): gb.set_tracking_callback(boom) gb.set_feature_usage_callback(boom) - assert gb.run(Experiment(key="safe", variations=[0, 1])).value in (0, 1) - assert gb.get_feature_value("flag", 0) == 7 + with caplog.at_level("ERROR", logger="growthbook"): + assert gb.run(Experiment(key="safe", variations=[0, 1])).value in (0, 1) + assert gb.get_feature_value("flag", 0) == 7 + + # Both failures are logged, as the README promises. + failures = [r for r in caplog.records if r.exc_info and "sink exploded" in str(r.exc_info[1])] + assert len(failures) == 2 + assert any(r.getMessage() == "Error in feature usage callback" for r in failures) gb.destroy()