diff --git a/README.md b/README.md index 78bbac5..12fcbb6 100644 --- a/README.md +++ b/README.md @@ -528,6 +528,52 @@ 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. + +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. 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 +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: @@ -555,6 +601,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 e98e740..d00c459 100644 --- a/growthbook/growthbook.py +++ b/growthbook/growthbook.py @@ -1021,6 +1021,16 @@ 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() + # 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() @@ -1377,6 +1387,11 @@ def destroy(self, timeout: float = 10) -> None: try: 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() self._assigned.clear() @@ -1392,6 +1407,63 @@ 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. + + 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. + + 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 + 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 user tracking callback, or None. + + 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 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. @@ -1508,7 +1580,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, @@ -1548,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]]: @@ -1604,10 +1677,23 @@ 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): + 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: + 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 21f4fc6..6809eb8 100644 --- a/growthbook/plugins/growthbook_tracking.py +++ b/growthbook/plugins/growthbook_tracking.py @@ -164,7 +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.""" + """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: @@ -176,23 +182,21 @@ def cleanup(self) -> None: # Experiment / feature auto-tracking (legacy hooks) # ------------------------------------------------------------------ - 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) - - if hasattr(gb_instance, "_trackingCallback"): - original = gb_instance._trackingCallback + 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 legacy_wrapper(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) + def _setup_experiment_tracking(self, gb_instance: Any) -> None: + tracking_wrapper = self._on_experiment_viewed - gb_instance._trackingCallback = legacy_wrapper + 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. + # 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" @@ -209,7 +213,7 @@ def async_wrapper(experiment: Any, result: Any, user_context: Any) -> None: else: self.logger.warning( - "_trackingCallback 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 74b0265..d139d45 100644 --- a/tests/test_growthbook.py +++ b/tests/test_growthbook.py @@ -2109,6 +2109,314 @@ def test_stale_while_revalidate_cleanup(mocker): 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(caplog): + 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) + + 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() + + +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_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_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() + + +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() + + +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()