Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

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:
Expand Down Expand Up @@ -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.
Expand Down
91 changes: 88 additions & 3 deletions growthbook/growthbook.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand All @@ -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.

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -1604,10 +1676,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.
Expand Down
38 changes: 21 additions & 17 deletions growthbook/plugins/growthbook_tracking.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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"
Expand All @@ -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"
)

Expand Down
Loading
Loading