Skip to content

Commit 6a3d0f9

Browse files
committed
fix: batch Redis lookups and keep remote group ids in the remote-eval cache key
- redis_resolver sends every SMEMBERS in one redis-py pipeline instead of one round trip per key, as the Go SDK does. Clients now need pipeline(). - With cache_key_attributes set, the remote-eval cache key left out __gb_remoteGroupIds, so a user whose groups changed could get a cached response for the old groups. It's always included now, as in sdk-js. - add_remote_saved_groups docstring: it returns the context itself when there are no remote groups or the lookup fails.
1 parent bb942ca commit 6a3d0f9

4 files changed

Lines changed: 75 additions & 10 deletions

File tree

‎growthbook/growthbook.py‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,12 @@
6060
from urllib3.response import BaseHTTPResponse
6161

6262
from .core import _eval_feature_and_report, _getHashValue, run_experiment
63-
from .remote_saved_groups import RemoteSavedGroupsCache, is_missing_remote_group_ids, with_remote_group_ids
63+
from .remote_saved_groups import (
64+
REMOTE_GROUP_IDS_ATTRIBUTE,
65+
RemoteSavedGroupsCache,
66+
is_missing_remote_group_ids,
67+
with_remote_group_ids,
68+
)
6469

6570
logger = logging.getLogger("growthbook")
6671

@@ -877,7 +882,12 @@ def _compute_cache_key(
877882
return base
878883
attrs = payload.get("attributes") or {}
879884
if cache_key_attributes is not None:
880-
attrs = {k: attrs[k] for k in cache_key_attributes if k in attrs}
885+
filtered = {k: attrs[k] for k in cache_key_attributes if k in attrs}
886+
# The response depends on the user's remote groups even when the
887+
# app's list leaves them out, as in the JS SDK
888+
if REMOTE_GROUP_IDS_ATTRIBUTE in attrs:
889+
filtered[REMOTE_GROUP_IDS_ATTRIBUTE] = attrs[REMOTE_GROUP_IDS_ATTRIBUTE]
890+
attrs = filtered
881891
# forcedFeatures is intentionally excluded from the cache key.
882892
# Matches the JS SDK: the proxy does not filter on forced features, so
883893
# responses are identical across forced-feature values. See

‎growthbook/growthbook_client.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1286,7 +1286,8 @@ async def add_remote_saved_groups(
12861286
self, user_context: UserContext, resolver: SavedGroupResolver,
12871287
) -> UserContext:
12881288
"""A copy of `user_context`, taken when called, with the user's remote saved groups from
1289-
`resolver`, or `user_context` unchanged if the resolver fails.
1289+
`resolver`. Returns `user_context` itself when the payload has no remote
1290+
groups or the lookup fails.
12901291
12911292
Requires a saved group references v2 payload for group metadata. With
12921293
inline/v1 payloads, resolve membership in the app and set

‎growthbook/remote_saved_groups.py‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -104,9 +104,11 @@ async def resolve_remote_group_ids(
104104

105105

106106
def redis_resolver(redis: Any) -> SavedGroupResolver:
107-
"""A resolver for remote groups loaded into Redis by GrowthBook's loader: one
108-
``SMEMBERS gb:member:<attribute>:<value>`` per attribute value. Takes an
109-
async client with ``smembers``, such as ``redis.asyncio.Redis``.
107+
"""A resolver for remote groups loaded into Redis by GrowthBook's loader:
108+
``SMEMBERS gb:member:<attribute>:<value>`` for each attribute value, sent in
109+
one pipeline. Takes an async redis-py client, such as ``redis.asyncio.Redis``
110+
or ``redis.asyncio.RedisCluster``. A failed lookup raises, so remote rules
111+
fail closed.
110112
111113
A derived group checks its own attribute's value in its source group's
112114
sets: `grp_vip:parent_id` looks up `gb:member:<grp_vip's attribute>:<parent_id>`
@@ -124,7 +126,14 @@ async def resolve(attributes: Dict[str, Any], groups: List[RemoteSavedGroup]) ->
124126
for value in _to_lookup_values(attributes.get(group["attributeKey"])):
125127
checks.append((group["id"], f"gb:member:{source['attributeKey']}:{value}", source["id"]))
126128
keys = _unique([key for _, key, _ in checks])
127-
members = {key: {_decode(m) for m in await redis.smembers(key)} for key in keys}
129+
if not keys:
130+
return []
131+
# One round trip for all keys, not one per key
132+
async with redis.pipeline(transaction=False) as pipe:
133+
for key in keys:
134+
pipe.smembers(key)
135+
results = await pipe.execute()
136+
members = {key: {_decode(m) for m in result} for key, result in zip(keys, results)}
128137
# Checking for the expected id, not any id in the set, also keeps keys
129138
# that collide when attributes or values contain ":" (`a:b` + `c` and
130139
# `a` + `b:c`) from mixing up groups.

‎tests/test_remote_saved_groups.py‎

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -216,13 +216,38 @@ async def resolver(attributes, groups):
216216

217217

218218
class FakeRedis:
219+
"""The part of redis.asyncio.Redis that redis_resolver uses: a pipeline of
220+
SMEMBERS calls."""
221+
219222
def __init__(self, sets):
220223
self.sets = sets
221224
self.keys = []
225+
self.round_trips = 0
226+
227+
def pipeline(self, transaction=True):
228+
assert transaction is False
229+
return FakePipeline(self)
230+
231+
232+
class FakePipeline:
233+
def __init__(self, redis):
234+
self.redis = redis
235+
self.queued = []
236+
237+
async def __aenter__(self):
238+
return self
239+
240+
async def __aexit__(self, *exc):
241+
return False
222242

223-
async def smembers(self, key):
224-
self.keys.append(key)
225-
return self.sets.get(key, set())
243+
def smembers(self, key):
244+
self.queued.append(key)
245+
return self
246+
247+
async def execute(self):
248+
self.redis.round_trips += 1
249+
self.redis.keys.extend(self.queued)
250+
return [self.redis.sets.get(key, set()) for key in self.queued]
226251

227252

228253
@pytest.mark.asyncio
@@ -242,9 +267,15 @@ async def test_redis_resolver():
242267
resolve = redis_resolver(redis)
243268

244269
assert await resolve({"account_id": "a1", "parent_id": "p9", "a:b": "c"}, groups) == ["grp_vip", "grp_vip:parent_id"]
270+
# Every key goes in one pipeline
271+
assert redis.round_trips == 1
272+
assert len(redis.keys) == 3
245273
# Arrays are looked up item by item; numbers as JS String(value)
246274
assert await resolve({"account_id": ["x", 2.0]}, groups) == ["grp_vip"]
247275
assert "gb:member:account_id:2" in redis.keys
276+
# Nothing to look up: no round trip
277+
assert await resolve({}, groups) == []
278+
assert redis.round_trips == 2
248279

249280

250281
@pytest.mark.asyncio
@@ -346,3 +377,17 @@ def counting(saved_groups):
346377
# A new payload is scanned again
347378
assert first.has_remote_groups(dict(local_only)) is False
348379
assert len(scans) == 3
380+
381+
382+
def test_remote_eval_cache_key_keeps_remote_group_ids_with_cache_key_attributes():
383+
from growthbook.growthbook import FeatureRepository
384+
385+
def key(ids):
386+
payload = {"attributes": {"id": "u1", "plan": "pro", REMOTE_GROUP_IDS_ATTRIBUTE: ids}}
387+
return FeatureRepository._compute_cache_key("https://h", "k", True, payload, ["id"])
388+
389+
# A user's resolved groups change the response, so they change the key
390+
assert key([]) != key(["grp_vip"])
391+
without_ids = FeatureRepository._compute_cache_key(
392+
"https://h", "k", True, {"attributes": {"id": "u1"}}, ["id"])
393+
assert without_ids != key([])

0 commit comments

Comments
 (0)