Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,38 @@ When loading a payload yourself, use `gb.set_payload(payload)` or
Receiving v2 payloads requires a registered SDK version with this capability
and **All Saved Groups** under the SDK Connection's **Pass Saved Groups by reference**.

### Remote saved groups

A **remote** saved group keeps its members outside the payload, for lists too
large to ship (millions of ids). The payload only says which attribute the
group is about, `{"type": "remote", "attributeKey": "account_id"}`, so the SDK
needs the ids of the groups the user is in. Conditions read them as the
`__gb_remoteGroupIds` attribute, and remote evaluation sends them too.

With `GrowthBookClient`, resolve them per user. `redis_resolver` reads the sets
GrowthBook's loader writes to Redis (`SMEMBERS gb:member:<attribute>:<value>`);
any async callable `(attributes, groups) -> ids` works as a resolver:

```python
import redis.asyncio as redis
from growthbook.remote_saved_groups import redis_resolver

resolver = redis_resolver(redis.Redis())
user = await client.add_remote_saved_groups(UserContext(attributes={"account_id": "a1"}), resolver)
result = await client.eval_feature("my-feature", user)
```

Or set them directly: `UserContext(remote_group_ids=["grp_vip"])` for
`GrowthBookClient`, `GrowthBook(remote_group_ids=[...])` or
`gb.set_remote_group_ids([...])` for `GrowthBook`. Setting them wins over an
attribute of that name, which also works on its own.

Leave them unset (`None`) while they are unresolved: rules that use remote
groups then fail, including "not in group" rules, and one warning is logged.
An empty list means the user is in no group, which is what lets "not in group"
rules match. If the resolver raises, `add_remote_saved_groups` logs it and
returns the context unchanged.

## GrowthBook class

The GrowthBook constructor has the following parameters:
Expand Down
12 changes: 12 additions & 0 deletions growthbook/common_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,11 @@ class UserContext:
overrides: Dict[str, Any] = field(default_factory=dict)
sticky_bucket_assignment_docs: Dict[str, Any] = field(default_factory=dict)
skip_all_experiments: bool = False
# The remote saved groups the user is in, resolved by the app. None means
# unresolved, which is not the same as no groups: rules using remote groups
# then fail, "not in group" included. Evaluation reads them as the
# __gb_remoteGroupIds attribute, over any value the attributes set for it.
remote_group_ids: Optional[List[str]] = None


class TrackingCallback(Protocol):
Expand Down Expand Up @@ -630,6 +635,12 @@ def copy_value(value: Any) -> Any:
return {k: copy_value(v) for k, v in attributes.items()}


def _copy_remote_group_ids(user: Any) -> Optional[List[str]]:
# getattr: duck-typed user contexts predate the field
ids = getattr(user, "remote_group_ids", None)
return list(ids) if ids is not None else None


def snapshot_user_context(user: "UserContext") -> "UserContext":
"""Call-time snapshot of every mutable evaluation input on a UserContext.

Expand All @@ -646,6 +657,7 @@ def snapshot_user_context(user: "UserContext") -> "UserContext":
forced_variations=snapshot_attributes(user.forced_variations),
forced_features=snapshot_attributes(user.forced_features),
overrides=snapshot_attributes(user.overrides),
remote_group_ids=_copy_remote_group_ids(user),
)


Expand Down
15 changes: 15 additions & 0 deletions growthbook/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
UserContext,
VariationMeta,
)
from .remote_saved_groups import REMOTE_GROUP_IDS_ATTRIBUTE


logger = logging.getLogger("growthbook.core")
Expand Down Expand Up @@ -124,6 +125,20 @@ def _eval_saved_group(
if prune is not None:
return prune(attributes, condition, saved_groups, next_visited)
return _eval_condition(attributes, condition, saved_groups, next_visited)
if entry.get("type") == "remote":
# The ids live outside the payload: the user's groups arrive resolved,
# in REMOTE_GROUP_IDS_ATTRIBUTE. A resolver can't look up an entry
# without an attribute, so its absence from the ids means nothing:
# undecided, so it fails under $not too.
if not isinstance(entry.get("attributeKey"), str):
return None
# Another attribute needs a derived group, which isn't supported yet
if "attributeKey" in reference and reference["attributeKey"] != entry.get("attributeKey"):
return False
if prune is not None and not _is_known(attributes, REMOTE_GROUP_IDS_ATTRIBUTE):
return None
group_ids = getPath(attributes, REMOTE_GROUP_IDS_ATTRIBUTE)
return isinstance(group_ids, list) and group_id in group_ids
# A group type added after this SDK was built. The client SDK may support it.
return None

Expand Down
47 changes: 45 additions & 2 deletions growthbook/growthbook.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
from urllib3.response import BaseHTTPResponse

from .core import _eval_feature_and_report, _getHashValue, run_experiment
from .remote_saved_groups import RemoteSavedGroupsCache, is_missing_remote_group_ids, with_remote_group_ids

logger = logging.getLogger("growthbook")

Expand Down Expand Up @@ -941,8 +942,14 @@ def __init__(
# a client SDK (see get_deferred_tracking_calls). Independent of
# on_experiment_viewed.
defer_tracking: bool = False,
# After defer_tracking so every earlier positional index is preserved.
# The remote saved groups the user is in, resolved by the app (see
# set_remote_group_ids).
remote_group_ids: Optional[List[str]] = None,
remoteGroupIds: Optional[List[str]] = None,
) -> None:
remote_eval = remote_eval or remoteEval
self._remote_group_ids = remote_group_ids if remote_group_ids is not None else remoteGroupIds
saved_groups = saved_groups if saved_groups is not None else savedGroups
contextual_bandits = contextual_bandits if contextual_bandits is not None else contextualBandits
cache_key_attributes = cache_key_attributes if cache_key_attributes is not None else cacheKeyAttributes
Expand All @@ -968,6 +975,8 @@ def __init__(
self._url = url
self._features: Dict[str, Feature] = {}
self._saved_groups = saved_groups if saved_groups is not None else {}
self._warned_missing_remote_group_ids = False
self._remote_saved_groups_cache = RemoteSavedGroupsCache()
self._contextual_bandits = contextual_bandits if contextual_bandits is not None else {}
self._api_host = api_host
self._client_key = client_key
Expand Down Expand Up @@ -1077,7 +1086,7 @@ def __init__(

def _remote_eval_payload(self) -> Dict[str, Any]:
return build_remote_eval_payload(
self._attributes, self._forcedVariations, self._url,
with_remote_group_ids(self._attributes, self._remote_group_ids), self._forcedVariations, self._url,
forced_features=self._forcedFeatures,
)

Expand Down Expand Up @@ -1299,6 +1308,23 @@ def set_url(self, url: str) -> None:
if self._remoteEval and self._client_key:
self.load_features()

def set_remote_group_ids(self, remote_group_ids: Optional[List[str]]) -> None:
"""Set the remote saved groups the user is in. A remote saved group keeps
its members outside the payload, so the app resolves the user's groups
and passes their ids here. Conditions read them as the
`__gb_remoteGroupIds` attribute, over any value the attributes set for
it, and remote evaluation sends them too.

Pass None while the groups are unresolved: rules that use remote groups
then fail, including "not in group". Don't pass [] for that — it means
"in no group", so "not in group" rules match."""
self._remote_group_ids = list(remote_group_ids) if remote_group_ids is not None else None
if self._remoteEval and self._client_key:
self.load_features()

def get_remote_group_ids(self) -> Optional[List[str]]:
return self._remote_group_ids

@deprecated("getAttributes is deprecated, use get_attributes instead")
def getAttributes(self) -> Dict[str, Any]:
return self.get_attributes()
Expand Down Expand Up @@ -1441,7 +1467,8 @@ def _sync_user_ctx_from_instance(self) -> None:
the user_context the callback sees in a stale, inconsistent state.

"""
self._user_ctx.attributes = self._attributes
self._user_ctx.attributes = with_remote_group_ids(self._attributes, self._remote_group_ids)
self._user_ctx.remote_group_ids = self._remote_group_ids
self._user_ctx.url = self._url
self._user_ctx.overrides = self._overrides
self._user_ctx.forced_variations = self._forcedVariations
Expand All @@ -1461,6 +1488,7 @@ def _build_eval_context(self) -> EvaluationContext:
"""
# Centralized sync (see _sync_user_ctx_from_instance for rationale).
self._sync_user_ctx_from_instance()
self._warn_if_remote_group_ids_missing()
# global_ctx.options.url is not part of _user_ctx; still needs updating.
self._global_ctx.options.url = self._url
return EvaluationContext(
Expand All @@ -1476,6 +1504,21 @@ def _build_eval_context(self) -> EvaluationContext:
tracking_buffer = self._deferred_buffer,
)

def _warn_if_remote_group_ids_missing(self) -> None:
"""Logs once when the payload has remote saved groups but the user has no
remote group ids, since every rule using them will then fail. Logs no
attribute values."""
if self._warned_missing_remote_group_ids:
return
if is_missing_remote_group_ids(
self._attributes, self._remote_group_ids, self._saved_groups, self._remote_saved_groups_cache,
):
self._warned_missing_remote_group_ids = True
logger.warning(
"The payload has remote saved groups, but the user has no remote group ids. "
"Rules using them won't match. See set_remote_group_ids."
)

def _get_eval_context(self) -> EvaluationContext:
# Lazy refresh: ensure features are fresh before evaluation, then build
# the (side-effect-free) context.
Expand Down
78 changes: 76 additions & 2 deletions growthbook/growthbook_client.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env python
import inspect
import json
from dataclasses import dataclass, field
from dataclasses import dataclass, field, replace
import random
import logging
from types import TracebackType
Expand All @@ -20,6 +20,14 @@
from contextlib import asynccontextmanager

from .core import _eval_feature_and_report, _hash_string, _is_hashable, reduce_payload, run_experiment
from .remote_saved_groups import (
RemoteSavedGroupsCache,
SavedGroupResolver,
get_remote_saved_groups,
is_missing_remote_group_ids,
resolve_remote_group_ids,
with_remote_group_ids,
)
from .common_types import (
T,
AsyncEventLogger,
Expand Down Expand Up @@ -48,6 +56,10 @@

logger = logging.getLogger("growthbook.growthbook_client")

# How many times add_remote_saved_groups looks the groups up while payload
# refreshes keep replacing them, before it leaves them unresolved
_REMOTE_GROUP_LOOKUP_ATTEMPTS = 3

class SingletonMeta(type):
"""One instance per (class, api_host, client_key). Two GrowthBookClients
talking to different proxies — or one CDN-mode and one remote-eval-mode
Expand Down Expand Up @@ -710,6 +722,8 @@ def __init__(
)

self._global_context: Optional[GlobalContext] = None
self._warned_missing_remote_group_ids = False
self._remote_saved_groups_cache = RemoteSavedGroupsCache()
# The decrypted payload as received, for reduce_payload. Swapped
# together with _global_context.
self._payload: Dict[str, Any] = {}
Expand Down Expand Up @@ -1151,7 +1165,7 @@ async def initialize(self) -> bool:

def _remote_eval_payload(self, user_context: UserContext) -> Dict[str, Any]:
return build_remote_eval_payload(
user_context.attributes,
with_remote_group_ids(user_context.attributes, getattr(user_context, "remote_group_ids", None)),
user_context.forced_variations,
user_context.url,
forced_features=user_context.forced_features,
Expand Down Expand Up @@ -1268,6 +1282,57 @@ def _context_callbacks(self, tracking_buffer: Optional[TrackingBuffer]) -> Dict[
"tracking_buffer": tracking_buffer,
}

async def add_remote_saved_groups(
self, user_context: UserContext, resolver: SavedGroupResolver,
) -> UserContext:
"""A copy of `user_context` with the user's remote saved groups from
`resolver`, or `user_context` unchanged if the resolver fails.

Requires a saved group references v2 payload for group metadata. With
inline/v1 payloads, resolve membership in the app and set
`remote_group_ids` on the UserContext directly instead."""
try:
# A refresh during a lookup can add groups the result doesn't cover,
# and a missing group would pass "not in group" rules. So the result
# only counts if the payload is still the one it was looked up for.
for _ in range(_REMOTE_GROUP_LOOKUP_ATTEMPTS):
saved_groups = self._global_context.saved_groups if self._global_context else None
# No remote entries doesn't mean no remote rules: payloads for
# SDKs without remote support check __gb_remoteGroupIds directly.
# Leaving it unset makes those rules fail closed; [] would let
# every "not in group" rule match.
if not get_remote_saved_groups(saved_groups):
return user_context
remote_group_ids = await resolve_remote_group_ids(user_context.attributes, saved_groups, resolver)
current = self._global_context.saved_groups if self._global_context else None
if current is saved_groups:
return replace(user_context, remote_group_ids=remote_group_ids)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
# Still changing: leave the groups unresolved, so their rules fail
# closed, rather than return ids that miss the newest groups
logger.warning("Saved groups kept changing during the remote group lookup; leaving them unresolved")
return user_context
except Exception:
logger.exception("Could not resolve remote saved groups")
return user_context

def _warn_if_remote_group_ids_missing(
self, user_context: UserContext, saved_groups: Optional[Dict[str, Any]],
) -> None:
"""Logs once when the payload has remote saved groups but the user has no
remote group ids, since every rule using them will then fail. Logs no
attribute values."""
if self._warned_missing_remote_group_ids:
return
remote_group_ids = getattr(user_context, "remote_group_ids", None)
if is_missing_remote_group_ids(
user_context.attributes, remote_group_ids, saved_groups, self._remote_saved_groups_cache,
):
self._warned_missing_remote_group_ids = True
logger.warning(
"The payload has remote saved groups, but the user has no remote group ids. "
"Rules using them won't match. See add_remote_saved_groups."
)

async def create_evaluation_context(
self,
user_context: UserContext,
Expand All @@ -1292,6 +1357,15 @@ async def create_evaluation_context(
caller_context = user_context
if self.options.remote_eval or self.options.sticky_bucket_service is not None:
user_context = snapshot_user_context(user_context)
self._warn_if_remote_group_ids_missing(user_context, global_context.saved_groups)
# getattr: duck-typed user contexts predate the field
remote_group_ids = getattr(user_context, "remote_group_ids", None)
if remote_group_ids is not None:
# Conditions read the ids as the __gb_remoteGroupIds attribute. A copy,
# so the caller's attributes are left as they were.
user_context = replace(
user_context, attributes=with_remote_group_ids(user_context.attributes, remote_group_ids),
)

if self.options.remote_eval and self._features_repository:
# Per-user POST + cache: features come from the proxy filtered for
Expand Down
Loading