diff --git a/README.md b/README.md index 78bbac5..e7898b9 100644 --- a/README.md +++ b/README.md @@ -289,6 +289,63 @@ client = GrowthBookClient( ) ``` +### Polling + +`polling_interval` (seconds) makes the async client refresh features on a fixed +schedule: + +```python +client = GrowthBookClient(Options( + api_host="https://cdn.growthbook.io", + client_key="sdk-abc123", + polling_interval=60, +)) +``` + +Three things worth knowing: + +**It runs alongside SSE, not instead of it.** Combine it with +`refresh_strategy=SERVER_SENT_EVENTS` and you get both. That is the point: a +stream blocked by a proxy or firewall looks exactly like a stream with no events +yet, so polling is what keeps such an app refreshing. + +**The configured interval is the interval used.** Polling bypasses the feature +cache. Without `polling_interval` set, the built-in refresh goes through the +cache, so an interval shorter than `cache_ttl` issues no requests at all. + +**Failures back off.** After a failed refresh the wait doubles from the +interval, up to five minutes or the interval itself, whichever is longer. +Jitter then stretches each wait by up to 2x, so the longest wait is ten minutes +(or twice the interval). It returns to the interval on the next success and +never retries faster than the configured interval. + +Out-of-range values (non-positive, non-numeric, or longer than a day) are +rejected with a warning rather than clamped — a negative interval is a typo, +and reinterpreting it as "as fast as possible" turns a config slip into a +request flood. The client then refreshes as if `polling_interval` were unset: +the stream only with SSE, the default cache-bound 60s polling otherwise. + +Remote-eval mode ignores it: payloads there are per-user, so there is no global +payload to poll for. + +For the sync `GrowthBook` class the equivalent is +`stale_while_revalidate=True` with `stale_ttl` as the interval; it already +fetches directly rather than through the cache. `stale_ttl` is validated the +same way: an out-of-range value logs a warning and leaves the poller off. +That includes values over a day, which used to poll at that interval. + +Instances on the same `api_host` and `client_key` share one poller. `destroy()` +releases the instance's share, and the poller stops when the last instance +using it is destroyed, so a per-request instance can be destroyed without +stopping refreshes for a long-lived one on the same key. +`feature_repo.stop_background_refresh()` is still a hard stop for everyone. + +The first instance on a key sets the poller's interval, `cache_ttl` and +decryption key; a later instance asking for a different interval gets a warning +and the running poller. The async client works the same way: one feature +repository per key, so a second `GrowthBookClient` with its own +`polling_interval` is warned and keeps the first one's polling. + ### Concurrency and Thread Safety The async client is designed to be thread-safe and handle concurrent requests efficiently. You can safely use a single client instance across multiple coroutines. For web applications, you can create a single client instance at startup and share it across requests. Here's an example: diff --git a/growthbook/common_types.py b/growthbook/common_types.py index 9824764..71e9e7b 100644 --- a/growthbook/common_types.py +++ b/growthbook/common_types.py @@ -2,6 +2,7 @@ import json import logging +import math import threading from copy import deepcopy from dataclasses import dataclass, field, replace @@ -799,6 +800,12 @@ class Options: # sticky_bucket_cache_size. Non-positive values disable caching. sticky_bucket_cache_ttl: float = 0 sticky_bucket_cache_size: int = 1000 + # Seconds between background feature refreshes. None keeps the historical + # behavior: polling only when refresh_strategy is STALE_WHILE_REVALIDATE, + # at a fixed 60s. Set it and polling runs at exactly this interval, + # bypassing the cache — and it runs alongside SSE rather than instead of + # it, so a stream blocked by a proxy still leaves the app refreshing. + polling_interval: Optional[float] = None @dataclass @@ -902,6 +909,44 @@ def build_remote_eval_payload( } +MAX_POLLING_INTERVAL_SECONDS = 60 * 60 * 24 # a day; longer is a unit mix-up + + +def validate_polling_interval( + interval: Optional[float], name: str = "polling_interval" +) -> Optional[float]: + """Return the interval to poll at, or None to leave polling off. + + Out-of-range values are rejected with a warning rather than clamped: a + negative interval is a typo, and silently reinterpreting it as "poll as + fast as possible" is how a config slip turns into a request flood + (`Event.wait()` and `asyncio.sleep()` both return immediately on a negative + delay). Reporting it and leaving polling off is the safer failure.""" + if interval is None: + return None + if not isinstance(interval, (int, float)) or isinstance(interval, bool): + logger.warning("Ignoring non-numeric %s: %r", name, interval) + return None + if not math.isfinite(interval): + # NaN slips past both range checks (every comparison is False), and + # Event.wait(nan) doesn't wait, so it would be a request flood too. + logger.warning("Ignoring non-finite %s: %r", name, interval) + return None + if interval <= 0: + logger.warning("Ignoring non-positive %s: %r", name, interval) + return None + if interval > MAX_POLLING_INTERVAL_SECONDS: + logger.warning( + "Ignoring %s of %r seconds: longer than the %d second maximum " + "(the value is in seconds, not milliseconds)", + name, + interval, + MAX_POLLING_INTERVAL_SECONDS, + ) + return None + return float(interval) + + def is_cloud_host(api_host: Optional[str]) -> bool: """True if api_host points at GrowthBook Cloud (which doesn't expose /api/eval). Handles schemeless inputs like "cdn.growthbook.io" — naive diff --git a/growthbook/growthbook.py b/growthbook/growthbook.py index e98e740..2ec9b2a 100644 --- a/growthbook/growthbook.py +++ b/growthbook/growthbook.py @@ -6,6 +6,7 @@ """ import atexit import json +import random import threading import logging import warnings @@ -42,6 +43,7 @@ features_from_dict, tracking_dedupe_key, tracking_user_context, + validate_polling_interval, validate_remote_eval_options, ) @@ -86,6 +88,33 @@ def decrypt(encrypted_str: str, key_str: str) -> str: return bytestring.decode("utf-8") +# Ceiling for background-refresh backoff. Matches the reference SDK: long +# enough that a dead CDN stops costing traffic, short enough that recovery is +# noticed within a few minutes. +MAX_REFRESH_BACKOFF_SECONDS = 300 + + +def backoff_delay(base: float, attempt: int, cap: float = MAX_REFRESH_BACKOFF_SECONDS) -> float: + """Exponential backoff with proportional jitter. + + `attempt` is the number of consecutive failures so far (1 for the first). + The base delay doubles per attempt up to `max(cap, base)`; jitter then + scales it by 1-2x, so the wait is between that value and twice it. Jitter + is proportional rather than a flat window so that many clients retrying the + same host spread out instead of re-colliding on the next tick. + """ + # Never below the configured interval: with an interval above the cap, + # clipping to the cap would retry a failing host more often than a healthy + # one is polled. + cap = max(cap, base) + # Bound the exponent: failures keep counting through a long outage, and + # base * 2**n raises OverflowError once 2**n no longer fits in a float + # (n >= 1024). 2**64 already exceeds any cap for a positive base. + exponent = min(max(attempt - 1, 0), 64) + delay = min(base * (2 ** exponent), cap) + return float(delay * (1 + random.random())) + + class AbstractFeatureCache(ABC): @abstractmethod def get(self, key: str) -> Optional[Dict[str, Any]]: @@ -384,11 +413,34 @@ def __init__(self) -> None: self.http_connect_timeout: Optional[int] = None self.http_read_timeout: Optional[int] = None self.sse_client: Optional[SSEClient] = None - self._feature_update_callbacks: List[Callable[[Dict[str, Any]], None]] = [] + # (callback, connection) pairs. The list is shared by every SDK + # connection in the process, and each key's poller delivers its own + # payload, so a keyed callback only hears from its own connection; a + # None connection hears all of them. Kept as pairs rather than a dict + # so callbacks don't have to be hashable. + self._feature_update_callbacks: List[ + Tuple[Callable[[Dict[str, Any]], None], Optional[Tuple[str, str]]] + ] = [] + # add/remove find an entry and then change it by index; without the + # lock, instances destroyed from two threads could shift the list in + # between and drop a live client's callback. + self._callbacks_lock = threading.Lock() # Background refresh support - self._refresh_thread: Optional[threading.Thread] = None - self._refresh_stop_event = threading.Event() + # One poller per (api_host, client_key). A single shared thread meant + # the second SDK connection in a process silently got no refreshes at + # all: start_background_refresh() returned early because *a* thread was + # already running, regardless of which key it was polling for. + self._refresh_threads: Dict[Tuple[str, str], threading.Thread] = {} + self._refresh_stop_events: Dict[Tuple[str, str], threading.Event] = {} + # Every instance on a key shares its poller, so the poller counts its + # owners and stops when the last one releases it. Without the count, + # destroying a short-lived instance (one per request is the documented + # pattern) stopped refreshes for a long-lived instance on the same key. + self._refresh_owners: Dict[Tuple[str, str], int] = {} + # Interval each poller runs at, so a caller joining with a different + # one can be warned that the first caller's settings win. + self._refresh_intervals: Dict[Tuple[str, str], float] = {} self._refresh_lock = threading.Lock() # ETag cache for bandwidth optimization @@ -406,19 +458,51 @@ def clear_cache(self) -> None: def save_in_cache(self, key: str, res: Dict[str, Any], ttl: int = 600) -> None: self.cache.set(key, res, ttl) - def add_feature_update_callback(self, callback: Callable[[Dict[str, Any]], None]) -> None: - """Add a callback to be notified when features are updated due to cache expiry""" - if callback not in self._feature_update_callbacks: - self._feature_update_callbacks.append(callback) + def add_feature_update_callback( + self, + callback: Callable[[Dict[str, Any]], None], + api_host: Optional[str] = None, + client_key: Optional[str] = None, + ) -> None: + """Add a callback to be notified when features are updated due to cache expiry. + + Pass api_host/client_key to receive only that connection's updates; + without them the callback hears every connection, as before.""" + connection = (api_host, client_key) if api_host is not None and client_key is not None else None + with self._callbacks_lock: + for i, (existing, _) in enumerate(self._feature_update_callbacks): + # Same identity-then-equality match as the `in` check this replaced. + if existing is callback or existing == callback: + self._feature_update_callbacks[i] = (existing, connection) + return + self._feature_update_callbacks.append((callback, connection)) def remove_feature_update_callback(self, callback: Callable[[Dict[str, Any]], None]) -> None: """Remove a feature update callback""" - if callback in self._feature_update_callbacks: - self._feature_update_callbacks.remove(callback) + with self._callbacks_lock: + for i, (existing, _) in enumerate(self._feature_update_callbacks): + if existing is callback or existing == callback: + del self._feature_update_callbacks[i] + return - def _notify_feature_update_callbacks(self, features_data: Dict[str, Any]) -> None: - """Notify all registered callbacks about feature updates""" - for callback in self._feature_update_callbacks: + def _notify_feature_update_callbacks( + self, + features_data: Dict[str, Any], + api_host: Optional[str] = None, + client_key: Optional[str] = None, + ) -> None: + """Notify registered callbacks about feature updates. + + With api_host/client_key, callbacks registered for another connection + are skipped; unkeyed callbacks always hear the update.""" + source = (api_host, client_key) if api_host is not None and client_key is not None else None + # Snapshot under the lock, call outside it: a callback may add or + # remove callbacks itself. + with self._callbacks_lock: + callbacks = list(self._feature_update_callbacks) + for callback, target in callbacks: + if source is not None and target is not None and target != source: + continue try: callback(features_data) except Exception as e: @@ -461,7 +545,7 @@ def load_features( # per-instance/per-user, so broadcasting would cross-pollute # other GrowthBook instances sharing this singleton repo. if not remote_eval: - self._notify_feature_update_callbacks(res) + self._notify_feature_update_callbacks(res, api_host, client_key) return res return cached @@ -492,7 +576,7 @@ async def load_features_async( self.cache.set(key, res, ttl) logger.debug("Fetched features from API, stored in cache") if not remote_eval: - self._notify_feature_update_callbacks(res) + self._notify_feature_update_callbacks(res, api_host, client_key) return res return cached @@ -809,55 +893,154 @@ def stopAutoRefresh(self, timeout: float = 10) -> None: self.sse_client.disconnect(timeout=timeout) self.sse_client = None - def start_background_refresh(self, api_host: str, client_key: str, decryption_key: str, ttl: int = 600, refresh_interval: int = 300) -> None: + def start_background_refresh(self, api_host: str, client_key: str, decryption_key: str, ttl: int = 600, refresh_interval: float = 300) -> None: """Start periodic background refresh task""" + self._acquire_background_refresh(api_host, client_key, decryption_key, ttl, refresh_interval) + def _acquire_background_refresh( + self, + api_host: str, + client_key: str, + decryption_key: str, + ttl: int, + refresh_interval: float, + ) -> Optional[threading.Event]: + """Start the poller for this key, or join the one already running. + + Returns a lease for `_release_background_refresh`, or None when no + poller was started because the interval is invalid. The lease is the + poller's stop event, so a lease taken on a poller that has since been + stopped (and maybe replaced) can't release the replacement.""" if not client_key: raise ValueError("Must specify `client_key` to refresh features") + # Event.wait() returns immediately on a non-positive delay, so an + # unchecked interval of 0 or below is a tight request loop. + interval = validate_polling_interval(refresh_interval, "refresh_interval") + if interval is None: + return None + + poller_key = (api_host, client_key) + with self._refresh_lock: - if self._refresh_thread is not None: - return # Already running - - self._refresh_stop_event.clear() - self._refresh_thread = threading.Thread( + stop_event = self._refresh_stop_events.get(poller_key) + if stop_event is not None: + # Already polling for this key: the running poller's interval, + # ttl and decryption key stay in effect. + running = self._refresh_intervals.get(poller_key) + if running is not None and running != interval: + logger.warning( + "Background refresh for %s already runs every %ss; " + "ignoring the requested %ss (the first instance's " + "settings apply to every instance on this key)", + client_key, running, interval, + ) + self._refresh_owners[poller_key] = self._refresh_owners.get(poller_key, 0) + 1 + return stop_event + + stop_event = threading.Event() + self._refresh_stop_events[poller_key] = stop_event + self._refresh_owners[poller_key] = 1 + self._refresh_intervals[poller_key] = interval + thread = threading.Thread( target=self._background_refresh_worker, - args=(api_host, client_key, decryption_key, ttl, refresh_interval), + args=(api_host, client_key, decryption_key, ttl, interval, stop_event), daemon=True ) - self._refresh_thread.start() - logger.debug("Started background refresh task") + self._refresh_threads[poller_key] = thread + thread.start() + logger.debug("Started background refresh task for %s", client_key) + return stop_event + + def _release_background_refresh( + self, api_host: str, client_key: str, lease: threading.Event + ) -> None: + """Drop one owner of the poller; stop it when no owners are left.""" + poller_key = (api_host, client_key) + with self._refresh_lock: + if self._refresh_stop_events.get(poller_key) is not lease: + return # That poller was already stopped explicitly + owners = self._refresh_owners.get(poller_key, 1) - 1 + if owners > 0: + self._refresh_owners[poller_key] = owners + return + thread = self._pop_poller(poller_key) + self._join_poller(poller_key, thread) + + def _pop_poller(self, poller_key: Tuple[str, str]) -> Optional[threading.Thread]: + # Caller holds _refresh_lock. + self._refresh_owners.pop(poller_key, None) + self._refresh_intervals.pop(poller_key, None) + event = self._refresh_stop_events.pop(poller_key, None) + if event is not None: + event.set() + return self._refresh_threads.pop(poller_key, None) + + @staticmethod + def _join_poller(poller_key: Tuple[str, str], thread: Optional[threading.Thread]) -> None: + # Outside the lock, so a stop doesn't block other keys for up to a second. + if thread is not None: + thread.join(timeout=1.0) # Wait up to 1 second + logger.debug("Stopped background refresh task for %s", poller_key[1]) - def _background_refresh_worker(self, api_host: str, client_key: str, decryption_key: str, ttl: int, refresh_interval: int) -> None: + def _background_refresh_worker( + self, + api_host: str, + client_key: str, + decryption_key: str, + ttl: int, + refresh_interval: float, + stop_event: threading.Event, + ) -> None: """Worker method for periodic background refresh""" - while not self._refresh_stop_event.is_set(): + failures = 0 + while not stop_event.is_set(): try: - # Wait for the refresh interval or stop event - if self._refresh_stop_event.wait(refresh_interval): + # Wait for the refresh interval or stop event. After a failure + # wait out the backoff instead, so an unreachable CDN isn't + # hammered at the configured interval indefinitely. + delay = refresh_interval if not failures else backoff_delay(refresh_interval, failures) + if stop_event.wait(delay): break # Stop event was set - + logger.debug("Background refresh for Features - started") res = self._fetch_features(api_host, client_key, decryption_key) if res is not None: + failures = 0 cache_key = api_host + "::" + client_key self.cache.set(cache_key, res, ttl) logger.debug("Background refresh completed") - # Notify callbacks about fresh features - self._notify_feature_update_callbacks(res) + # Notify this connection's callbacks about fresh features + self._notify_feature_update_callbacks(res, api_host, client_key) else: - logger.warning("Background refresh failed") + # _fetch_features swallows HTTP/parse errors and returns + # None, so this is the ordinary failure path, not just the + # exceptional one below. + failures += 1 + logger.warning("Background refresh failed (attempt %d)", failures) except Exception as e: + failures += 1 logger.warning(f"Background refresh error: {e}") - def stop_background_refresh(self) -> None: - """Stop background refresh task""" - self._refresh_stop_event.set() - + def stop_background_refresh( + self, api_host: Optional[str] = None, client_key: Optional[str] = None + ) -> None: + """Stop background refresh, whoever else is using it. + + With no arguments every poller is stopped (the historical behavior). + Pass api_host/client_key to stop only that connection's poller, leaving + other SDK connections in the same process running. This is a hard stop: + `GrowthBook.destroy()` doesn't call it, it releases its share of the + poller instead, so other instances on the same key keep refreshing.""" with self._refresh_lock: - if self._refresh_thread is not None: - self._refresh_thread.join(timeout=1.0) # Wait up to 1 second - self._refresh_thread = None - logger.debug("Stopped background refresh task") + if api_host is not None and client_key is not None: + keys = [(api_host, client_key)] + else: + keys = list(self._refresh_threads) + stopped = [(key, self._pop_poller(key)) for key in keys] + + for key, thread in stopped: + self._join_poller(key, thread) @staticmethod def _get_features_url(api_host: str, client_key: str) -> str: @@ -1012,6 +1195,8 @@ def __init__( self._streaming_timeout = streaming_connection_timeout self._stale_while_revalidate = stale_while_revalidate self._stale_ttl = stale_ttl + # This instance's share of the key's background poller, if it holds one. + self._refresh_lease: Optional[threading.Event] = None # Deprecated args self._user = user if user is not None else {} @@ -1071,7 +1256,9 @@ def __init__( # callback would cross-pollute other GrowthBook instances sharing the # singleton FeatureRepository. if self._client_key and not self._remoteEval: - feature_repo.add_feature_update_callback(self._on_feature_update) + feature_repo.add_feature_update_callback( + self._on_feature_update, self._api_host, self._client_key + ) self._initialize_plugins() @@ -1081,10 +1268,13 @@ def __init__( elif self._stale_while_revalidate: # Start background refresh task for stale-while-revalidate self.load_features() # Initial load - feature_repo.start_background_refresh( - self._api_host, self._client_key, self._decryption_key, - self._cache_ttl, self._stale_ttl - ) + # stale_ttl is the poll interval here; an invalid one is reported + # and leaves the poller off rather than spinning on Event.wait(<=0). + if validate_polling_interval(self._stale_ttl, "stale_ttl") is not None: + self._refresh_lease = feature_repo._acquire_background_refresh( + self._api_host, self._client_key, self._decryption_key, + self._cache_ttl, self._stale_ttl + ) elif self._remoteEval: # Initial POST to /api/eval/{client_key} so features are populated # before the first eval. Matches the JS SDK init() behavior. @@ -1360,9 +1550,12 @@ def destroy(self, timeout: float = 10) -> None: logger.warning(f"Error stopping auto refresh during destroy: {e}") try: - # Stop background refresh operations - if self._stale_while_revalidate and self._client_key: - feature_repo.stop_background_refresh() + # Release this instance's share of the key's poller. It only stops + # once no other instance on the same key still uses it, and taking + # the lease first makes a second destroy() a no-op. + lease, self._refresh_lease = self._refresh_lease, None + if lease is not None: + feature_repo._release_background_refresh(self._api_host, self._client_key, lease) except Exception as e: logger.warning(f"Error stopping background refresh during destroy: {e}") diff --git a/growthbook/growthbook_client.py b/growthbook/growthbook_client.py index aff2fb1..ca45025 100644 --- a/growthbook/growthbook_client.py +++ b/growthbook/growthbook_client.py @@ -17,6 +17,7 @@ from collections import OrderedDict from datetime import datetime from growthbook import FeatureRepository, feature_repo +from .growthbook import backoff_delay from contextlib import asynccontextmanager from .core import _eval_feature_and_report, _hash_string, _is_hashable, reduce_payload, run_experiment @@ -51,6 +52,7 @@ TrackingDedupeKey, tracking_dedupe_key, tracking_user_context, + validate_polling_interval, validate_remote_eval_options, ) @@ -179,11 +181,21 @@ def __init__(self, # down the CDN path on a fresh client. self._remote_eval = remote_eval self._refresh_lock = threading.Lock() + # SSE lifecycle task. Polling gets its own task so the two can run + # side by side (see `start_feature_refresh`). self._refresh_task: Optional[asyncio.Task[None]] = None + self._poll_task: Optional[asyncio.Task[None]] = None + # Interval the running poll task uses, and whether it bypasses the + # cache (i.e. came from an explicit polling_interval). + self._poll_config: Optional[Tuple[float, bool]] = None self._stop_event = asyncio.Event() self._backoff = BackoffStrategy() self._feature_cache = FeatureCache() self._callbacks: List[Callable[[Dict[str, Any]], Awaitable[None]]] = [] + # Bumped on every applied update. A poll compares it before and after + # its fetch: if SSE applied a payload meanwhile, the poll's response + # may be older and is dropped instead of overwriting newer flags. + self._update_seq = 0 self._last_successful_refresh: Optional[datetime] = None self._refresh_in_progress = asyncio.Lock() self.http_connect_timeout = http_connect_timeout @@ -376,6 +388,7 @@ async def refresh_operation(self) -> AsyncIterator[bool]: async def _handle_feature_update(self, data: Dict[str, Any]) -> None: """Update features with memory optimization""" + self._update_seq += 1 # Directly update with new features # Sections absent from the payload are passed as None so the cache # preserves their current values (see FeatureCache.update). @@ -512,42 +525,74 @@ async def _maintain_sse_connection() -> None: # Start a task that owns the SSE lifecycle and cleanup. self._refresh_task = asyncio.create_task(_maintain_sse_connection()) - async def _start_http_refresh(self, interval: int = 60) -> None: - """Enhanced HTTP polling with backoff""" - if self._refresh_task: + async def _start_http_refresh( + self, interval: float = 60, bypass_cache: bool = False + ) -> None: + """Enhanced HTTP polling with backoff. + + `bypass_cache` makes the configured interval the interval actually + used. Without it the loop goes through the feature cache, so any + interval shorter than `cache_ttl` issues no request at all — it just + re-reads the cached payload and sleeps again. + + A failed fetch usually surfaces as `None` rather than an exception, so + both count as failures: the wait grows from `interval` via + `backoff_delay` and returns to `interval` on the next success.""" + if self._poll_task: + # One repository (and poll task) per (api_host, client_key): a + # later client asking for its own polling_interval doesn't get it. + if bypass_cache and self._poll_config != (interval, True): + logger.warning( + "Polling for %s is already running (%s); ignoring " + "polling_interval=%ss from another client on the same key", + self._client_key, + f"every {self._poll_config[0]}s" if self._poll_config else "default", + interval, + ) return async def refresh_loop() -> None: + failures = 0 try: while not self._stop_event.is_set(): async with self.refresh_operation() as should_refresh: if should_refresh: + seq_before_fetch = self._update_seq try: response = await self.load_features_async( api_host=self._api_host, client_key=self._client_key, decryption_key=self._decryption_key, - ttl=self._cache_ttl + ttl=self._cache_ttl, + force_refresh=bypass_cache, ) - if response is not None: - await self._handle_feature_update(response) - # On success, reset backoff and use normal interval - self._backoff.reset() - try: - await asyncio.sleep(interval) - except asyncio.CancelledError: - # Allow cancellation during sleep - raise except Exception as e: - # On failure, use backoff delay - delay = self._backoff.next_delay() - logger.error(f"Refresh failed, next attempt in {delay:.2f}s: {str(e)}") + response = None + logger.error(f"Refresh failed: {str(e)}") traceback.print_exc() - try: - await asyncio.sleep(delay) - except asyncio.CancelledError: - # Allow cancellation during sleep - raise + if response is None: + failures += 1 + else: + # The fetch succeeded, so the CDN is reachable: + # an error in update handling is logged but + # doesn't back off the next poll. + failures = 0 + if self._update_seq != seq_before_fetch: + # Another path (an SSE event) applied an + # update while this fetch was in flight; + # applying this response could roll it back. + logger.debug("Dropping polled payload superseded during fetch") + else: + try: + await self._handle_feature_update(response) + except Exception: + logger.exception("Error handling polled feature update") + delay = backoff_delay(interval, failures) if failures else interval + if failures: + logger.warning( + f"Refresh failed {failures} time(s) in a row, next attempt in {delay:.2f}s" + ) + await asyncio.sleep(delay) except asyncio.CancelledError: # Clean exit on cancellation raise @@ -555,14 +600,30 @@ async def refresh_loop() -> None: # Ensure we're marked as stopped self._stop_event.set() - self._refresh_task = asyncio.create_task(refresh_loop()) + self._poll_config = (interval, bypass_cache) + self._poll_task = asyncio.create_task(refresh_loop()) + + async def start_feature_refresh( + self, + strategy: FeatureRefreshStrategy, + callback: Optional[Callable[..., Any]] = None, + polling_interval: Optional[float] = None, + ) -> None: + """Initialize feature refresh based on strategy. - async def start_feature_refresh(self, strategy: FeatureRefreshStrategy, callback: Optional[Callable[..., Any]] = None) -> None: - """Initialize feature refresh based on strategy""" + `polling_interval` is orthogonal to the strategy rather than another + strategy value: with SSE it runs alongside the stream, which is the + point — a stream blocked by a proxy is exactly when an app still needs + refreshes, and the streaming path cannot tell the difference between + "no events yet" and "never connected".""" self._refresh_callback = callback - + if strategy == FeatureRefreshStrategy.SERVER_SENT_EVENTS: await self._start_sse_refresh() + if polling_interval is not None: + await self._start_http_refresh(polling_interval, bypass_cache=True) + elif polling_interval is not None: + await self._start_http_refresh(polling_interval, bypass_cache=True) else: await self._start_http_refresh() @@ -591,19 +652,23 @@ async def stop_refresh(self) -> None: except Exception: logger.exception("Error draining SWR background tasks") self._swr_tasks.clear() - if self._refresh_task: - # Cancel the task - self._refresh_task.cancel() + # Cancel and await both the SSE lifecycle task and the polling task; + # with SSE + polling_interval both are running. + for refresh_task in (self._refresh_task, self._poll_task): + if refresh_task is None: + continue + refresh_task.cancel() try: # Wait for it to actually finish - await self._refresh_task + await refresh_task except asyncio.CancelledError: pass except Exception as e: logger.error(f"Error during refresh task cleanup: {e}") - finally: - self._refresh_task = None - self._backoff.reset() + self._refresh_task = None + self._poll_task = None + self._poll_config = None + self._backoff.reset() self._stop_event.clear() async def __aenter__(self) -> "EnhancedFeatureRepository": @@ -1134,6 +1199,12 @@ async def initialize(self) -> bool: # Only SSE is meaningful in remote-eval mode (the validation # guard already rejects STALE_WHILE_REVALIDATE). None means # "no background refresh; rely on cache TTL". + if self.options.polling_interval is not None: + logger.warning( + "polling_interval is ignored in remote-eval mode: payloads are " + "per-user, so there is no global payload to poll for. SSE " + "invalidation flushes the per-user cache instead." + ) if self.options.refresh_strategy == FeatureRefreshStrategy.SERVER_SENT_EVENTS: await self._features_repository.start_feature_refresh( self.options.refresh_strategy, @@ -1160,7 +1231,10 @@ async def initialize(self) -> bool: # Start feature refresh refresh_strategy = self.options.refresh_strategy or FeatureRefreshStrategy.STALE_WHILE_REVALIDATE - await self._features_repository.start_feature_refresh(refresh_strategy) + await self._features_repository.start_feature_refresh( + refresh_strategy, + polling_interval=validate_polling_interval(self.options.polling_interval), + ) return True except Exception as e: diff --git a/tests/test_growthbook.py b/tests/test_growthbook.py index 74b0265..59ec640 100644 --- a/tests/test_growthbook.py +++ b/tests/test_growthbook.py @@ -2022,9 +2022,9 @@ def mock_fetch_features(api_host, client_key, decryption_key=""): try: # Should have started background refresh task - assert feature_repo._refresh_thread is not None - assert feature_repo._refresh_thread.is_alive() - + poller = feature_repo._refresh_threads[("https://cdn.growthbook.io", "test-key")] + assert poller.is_alive() + # Initial evaluation should work assert gb.get_feature_value('test_feature', 'default') == "fresh" assert call_count == 1 # Initial load @@ -2057,7 +2057,7 @@ def mock_fetch_features(api_host, client_key, decryption_key=""): try: # Should NOT have started background refresh task - assert feature_repo._refresh_thread is None + assert feature_repo._refresh_threads == {} # Initial evaluation assert gb.get_feature_value('test_feature', 'default') == "normal" @@ -2094,21 +2094,416 @@ def test_stale_while_revalidate_cleanup(mocker): try: # Should have started background refresh task - assert feature_repo._refresh_thread is not None - assert feature_repo._refresh_thread.is_alive() - + poller_key = ("https://cdn.growthbook.io", "test-key") + assert feature_repo._refresh_threads[poller_key].is_alive() + # Destroy should clean up the background task gb.destroy() - + # Background task should be stopped - assert feature_repo._refresh_thread is None or not feature_repo._refresh_thread.is_alive() - + assert poller_key not in feature_repo._refresh_threads + finally: # Ensure cleanup even if test fails - if feature_repo._refresh_thread: - feature_repo.stop_background_refresh() + feature_repo.stop_background_refresh() + feature_repo.clear_cache() + + +# --- Background refresh pollers --------------------------------------------- + +def test_each_client_key_gets_its_own_poller(): + # A single shared thread meant the second SDK connection in a process got + # no refreshes at all: the call returned early because *a* thread was + # already running, whatever key it was polling for. + try: + feature_repo.start_background_refresh("https://cdn.growthbook.io", "key-a", "", 600, 300) + feature_repo.start_background_refresh("https://cdn.growthbook.io", "key-b", "", 600, 300) + + threads = feature_repo._refresh_threads + assert set(threads) == { + ("https://cdn.growthbook.io", "key-a"), + ("https://cdn.growthbook.io", "key-b"), + } + assert threads[("https://cdn.growthbook.io", "key-a")] is not threads[ + ("https://cdn.growthbook.io", "key-b") + ] + assert all(t.is_alive() for t in threads.values()) + + # Same key twice is still one poller. + feature_repo.start_background_refresh("https://cdn.growthbook.io", "key-a", "", 600, 300) + assert len(feature_repo._refresh_threads) == 2 + finally: + feature_repo.stop_background_refresh() + + +def test_stopping_one_poller_leaves_the_others_running(): + try: + feature_repo.start_background_refresh("https://cdn.growthbook.io", "key-a", "", 600, 300) + feature_repo.start_background_refresh("https://cdn.growthbook.io", "key-b", "", 600, 300) + + feature_repo.stop_background_refresh("https://cdn.growthbook.io", "key-a") + + assert set(feature_repo._refresh_threads) == {("https://cdn.growthbook.io", "key-b")} + assert feature_repo._refresh_threads[("https://cdn.growthbook.io", "key-b")].is_alive() + finally: + feature_repo.stop_background_refresh() + + # No arguments stops everything. + assert feature_repo._refresh_threads == {} + + +SWR_HOST = "https://cdn.growthbook.io" +SWR_PAYLOAD = {"features": {}, "savedGroups": {}} + + +def _swr_instance(client_key="shared-key", **kwargs): + return GrowthBook(api_host=SWR_HOST, client_key=client_key, stale_while_revalidate=True, **kwargs) + + +def test_destroying_one_instance_keeps_the_shared_poller_for_the_others(mocker): + # One instance per request plus a long-lived one on the same key is the + # documented pattern; destroying the short-lived one used to stop the + # poller they share. + mocker.patch.object(feature_repo, "_fetch_features", return_value=SWR_PAYLOAD) + poller_key = (SWR_HOST, "shared-key") + try: + long_lived = _swr_instance() + poller = feature_repo._refresh_threads[poller_key] + per_request = _swr_instance() + + per_request.destroy() + + assert feature_repo._refresh_threads.get(poller_key) is poller + assert poller.is_alive() + + long_lived.destroy() + + assert poller_key not in feature_repo._refresh_threads + assert not poller.is_alive() + finally: + feature_repo.stop_background_refresh() feature_repo.clear_cache() + +def test_destroy_twice_releases_the_poller_only_once(mocker): + mocker.patch.object(feature_repo, "_fetch_features", return_value=SWR_PAYLOAD) + poller_key = (SWR_HOST, "shared-key") + try: + a = _swr_instance() + b = _swr_instance() + + a.destroy() + a.destroy() + + assert feature_repo._refresh_threads[poller_key].is_alive() + b.destroy() + assert poller_key not in feature_repo._refresh_threads + finally: + feature_repo.stop_background_refresh() + feature_repo.clear_cache() + + +def test_a_released_lease_cannot_stop_a_replacement_poller(mocker): + # After a hard stop a new poller may start on the same key. The instance + # that held a share of the old one must not stop the new one on destroy. + mocker.patch.object(feature_repo, "_fetch_features", return_value=SWR_PAYLOAD) + poller_key = (SWR_HOST, "shared-key") + try: + old = _swr_instance() + feature_repo.stop_background_refresh() + new = _swr_instance() + replacement = feature_repo._refresh_threads[poller_key] + + old.destroy() + + assert feature_repo._refresh_threads.get(poller_key) is replacement + assert replacement.is_alive() + new.destroy() + finally: + feature_repo.stop_background_refresh() + feature_repo.clear_cache() + + +def test_direct_start_keeps_the_poller_past_instance_destroy(mocker): + # A caller that started the poller itself owns a share until it calls + # stop_background_refresh(). + mocker.patch.object(feature_repo, "_fetch_features", return_value=SWR_PAYLOAD) + poller_key = (SWR_HOST, "shared-key") + try: + feature_repo.start_background_refresh(SWR_HOST, "shared-key", "", 600, 300) + gb = _swr_instance() + + gb.destroy() + + assert feature_repo._refresh_threads[poller_key].is_alive() + finally: + feature_repo.stop_background_refresh() + feature_repo.clear_cache() + + +@pytest.mark.parametrize("stale_ttl", [-1, 0, 10 ** 9]) +def test_invalid_stale_ttl_does_not_start_a_poller(mocker, caplog, stale_ttl): + # stale_ttl is the sync poller's interval. Event.wait() returns at once on + # a non-positive delay, so -1 used to be a tight request loop. + fetch = mocker.patch.object(feature_repo, "_fetch_features", return_value=SWR_PAYLOAD) + try: + with caplog.at_level("WARNING", logger="growthbook"): + gb = _swr_instance(stale_ttl=stale_ttl) + assert feature_repo._refresh_threads == {} + assert "stale_ttl" in caplog.text + assert fetch.call_count == 1 # the initial load only + gb.destroy() + finally: + feature_repo.stop_background_refresh() + feature_repo.clear_cache() + + +@pytest.mark.parametrize("interval", [-1, 0]) +def test_start_background_refresh_rejects_a_non_positive_interval(mocker, caplog, interval): + fetch = mocker.patch.object(feature_repo, "_fetch_features", return_value=SWR_PAYLOAD) + try: + with caplog.at_level("WARNING", logger="growthbook"): + feature_repo.start_background_refresh(SWR_HOST, "shared-key", "", 600, interval) + assert feature_repo._refresh_threads == {} + assert "refresh_interval" in caplog.text + assert fetch.call_count == 0 + finally: + feature_repo.stop_background_refresh() + + +def test_background_refresh_backs_off_after_failures(mocker): + # Without backoff an unreachable CDN is retried at the configured interval + # forever. Waits are asserted on the stop event, which is what the worker + # sleeps on. + waits = [] + + class RecordingEvent: + def is_set(self): + return len(waits) >= 4 # stop after four cycles + + def wait(self, timeout=None): + waits.append(timeout) + return False + + mocker.patch.object(feature_repo, "_fetch_features", return_value=None) + feature_repo._background_refresh_worker( + "https://cdn.growthbook.io", "k", "", 600, 10, RecordingEvent() + ) + + # First wait is the plain interval; later ones grow and carry jitter. + assert waits[0] == 10 + assert 10 <= waits[1] <= 20 # base 10, attempt 1 -> 10 * (1..2) + assert 20 <= waits[2] <= 40 # attempt 2 -> 20 * (1..2) + assert waits[1] < waits[3] + + +def test_backoff_never_waits_less_than_the_interval(): + # With an interval above the cap, clipping to the cap would retry a failing + # CDN more often than a healthy one is polled. + from growthbook.growthbook import backoff_delay, MAX_REFRESH_BACKOFF_SECONDS + + for base in (MAX_REFRESH_BACKOFF_SECONDS + 1, 600, 3600): + for attempt in range(1, 10): + delay = backoff_delay(base, attempt) + assert base <= delay <= base * 2, (base, attempt, delay) + + +def test_backoff_does_not_overflow_after_many_failures(): + # Failures keep counting through a long outage (e.g. a wrong client key + # answering 404 forever). base * 2**n used to raise OverflowError once n + # reached 1024, which made the sync worker spin and ended async polling. + from growthbook.growthbook import backoff_delay, MAX_REFRESH_BACKOFF_SECONDS + + for attempt in (1025, 5000, 10**6): + delay = backoff_delay(60.0, attempt) + assert MAX_REFRESH_BACKOFF_SECONDS <= delay <= MAX_REFRESH_BACKOFF_SECONDS * 2 + + +def test_each_connection_only_receives_its_own_pollers_payload(mocker): + # The update callback list is shared by every connection in the process. + # Each key's poller used to broadcast to all of them, so two connections + # kept overwriting each other's flags with their own values. + payloads = { + "conn-a": {"features": {"flag": {"defaultValue": "a"}}}, + "conn-b": {"features": {"flag": {"defaultValue": "b"}}}, + } + mocker.patch.object( + feature_repo, "_fetch_features", + side_effect=lambda api_host, client_key, decryption_key="": payloads[client_key], + ) + + class OneCycle: + def __init__(self): + self.cycles = 0 + + def is_set(self): + return self.cycles >= 1 + + def wait(self, timeout=None): + self.cycles += 1 + return False + + try: + # Pollers only run with stale_while_revalidate, which also skips the + # per-evaluation cache reload that would mask the cross-talk. + gb_a = _swr_instance("conn-a") + gb_b = _swr_instance("conn-b") + assert gb_a.get_feature_value("flag", None) == "a" + assert gb_b.get_feature_value("flag", None) == "b" + + # One poll cycle for each connection, as their pollers would run. + payloads["conn-a"] = {"features": {"flag": {"defaultValue": "a2"}}} + feature_repo._background_refresh_worker(SWR_HOST, "conn-a", "", 600, 10, OneCycle()) + feature_repo._background_refresh_worker(SWR_HOST, "conn-b", "", 600, 10, OneCycle()) + + assert gb_a.get_feature_value("flag", None) == "a2" + assert gb_b.get_feature_value("flag", None) == "b" + gb_a.destroy() + gb_b.destroy() + finally: + feature_repo.stop_background_refresh() + feature_repo.clear_cache() + + +def test_unkeyed_feature_update_callback_still_hears_every_connection(): + repo = FeatureRepository() + heard = [] + repo.add_feature_update_callback(heard.append) + repo._notify_feature_update_callbacks({"features": {}}, SWR_HOST, "any-key") + repo._notify_feature_update_callbacks({"features": {"x": {}}}) + assert len(heard) == 2 + + +def test_unhashable_feature_update_callback_still_works(): + # A non-frozen dataclass with __call__ is unhashable. Routing callbacks + # through a dict made it raise and stopped every later callback too. + from dataclasses import dataclass + + @dataclass + class Sink: + # Distinct names: dataclass equality compares fields, and equal + # callbacks count as the same one, as with the original `in` check. + name: str + seen: list + + def __call__(self, data): + self.seen.append(data) + + repo = FeatureRepository() + unkeyed, keyed, after = Sink("unkeyed", []), Sink("keyed", []), [] + repo.add_feature_update_callback(unkeyed) + repo.add_feature_update_callback(keyed, SWR_HOST, "key-a") + repo.add_feature_update_callback(after.append) + repo.add_feature_update_callback(unkeyed) # re-adding doesn't duplicate + + repo._notify_feature_update_callbacks({"features": {}}, SWR_HOST, "key-b") + assert len(unkeyed.seen) == 1 and keyed.seen == [] and len(after) == 1 + + repo._notify_feature_update_callbacks({"features": {}}, SWR_HOST, "key-a") + assert len(keyed.seen) == 1 + + repo.remove_feature_update_callback(keyed) + repo._notify_feature_update_callbacks({"features": {}}, SWR_HOST, "key-a") + assert len(keyed.seen) == 1 and len(unkeyed.seen) == 3 + + +def test_concurrent_callback_removals_keep_live_callbacks(): + # remove finds an index and then deletes it. Two instances destroyed from + # different threads used to shift the list in between, so the wrong entry + # (a live client's callback) was deleted or the delete hit IndexError. + import threading + import time as time_module + + class Cb: + def __init__(self, name, slow=False): + self.name, self.slow = name, slow + + def __eq__(self, other): + match = isinstance(other, Cb) and other.name == self.name + if match and self.slow: + time_module.sleep(0.1) # gap between finding and deleting + return match + + __hash__ = None + + def __call__(self, data): + pass + + repo = FeatureRepository() + first, live, target = Cb("first"), Cb("live"), Cb("target", slow=True) + for cb in (first, live, target): + repo.add_feature_update_callback(cb, SWR_HOST, cb.name) + + # An equal but distinct object, like a fresh bound method on destroy(). + remover = threading.Thread(target=repo.remove_feature_update_callback, args=(Cb("target"),)) + remover.start() + time_module.sleep(0.03) + repo.remove_feature_update_callback(first) + remover.join() + + assert [cb.name for cb, _ in repo._feature_update_callbacks] == ["live"] + + +def test_joining_a_poller_with_another_interval_warns(mocker, caplog): + mocker.patch.object(feature_repo, "_fetch_features", return_value=SWR_PAYLOAD) + poller_key = (SWR_HOST, "mixed-key") + try: + a = _swr_instance("mixed-key", stale_ttl=3600) + with caplog.at_level("WARNING", logger="growthbook"): + b = _swr_instance("mixed-key", stale_ttl=30) + assert any("already runs every 3600.0s" in r.getMessage() for r in caplog.records) + # The running poller keeps the first instance's interval. + assert feature_repo._refresh_intervals[poller_key] == 3600.0 + + caplog.clear() + with caplog.at_level("WARNING", logger="growthbook"): + c = _swr_instance("mixed-key", stale_ttl=3600) + assert not [r for r in caplog.records if "already runs" in r.getMessage()] + for gb in (a, b, c): + gb.destroy() + assert poller_key not in feature_repo._refresh_intervals + finally: + feature_repo.stop_background_refresh() + feature_repo.clear_cache() + + +def test_background_refresh_backoff_is_capped_and_resets(): + from growthbook.growthbook import backoff_delay, MAX_REFRESH_BACKOFF_SECONDS + + # Proportional jitter keeps the delay within [cap, 2*cap] at the ceiling. + for attempt in range(1, 40): + assert backoff_delay(60, attempt) <= MAX_REFRESH_BACKOFF_SECONDS * 2 + assert backoff_delay(60, 30) >= MAX_REFRESH_BACKOFF_SECONDS + + # A successful refresh clears the failure count, so the next wait is the + # plain interval again. + waits = [] + + class Event: + def __init__(self): + self.results = iter([False, False, False, True]) + + def is_set(self): + return False + + def wait(self, timeout=None): + waits.append(timeout) + return next(self.results) + + responses = iter([None, {"features": {}}, None]) + feature_repo._fetch_features = lambda *a, **k: next(responses) # type: ignore[assignment] + try: + feature_repo._background_refresh_worker( + "https://cdn.growthbook.io", "k", "", 600, 10, Event() + ) + finally: + del feature_repo._fetch_features + + assert waits[0] == 10 # first cycle: plain interval + assert waits[1] > 10 # after the failure: backed off + assert waits[2] == 10 # after the success: reset + + def make_repo() -> FeatureRepository: repo=FeatureRepository() repo.cache.clear() diff --git a/tests/test_growthbook_client.py b/tests/test_growthbook_client.py index b0c7595..b5c9b8d 100644 --- a/tests/test_growthbook_client.py +++ b/tests/test_growthbook_client.py @@ -1780,3 +1780,220 @@ async def test_reduce_payload_keeps_zero_coverage(): assert reduced["features"][key]["rules"] == [{"force": True, "coverage": 0, "hashVersion": 1}] finally: await client.close() + + +# --- Polling interval ------------------------------------------------------- + +@pytest.mark.asyncio +async def test_polling_interval_bypasses_the_cache(): + """Without the bypass the loop re-reads the cached payload, so any interval + shorter than cache_ttl issues no requests at all.""" + EnhancedFeatureRepository._instances = {} + repo = EnhancedFeatureRepository("https://test.growthbook.io", "k", cache_ttl=60) + calls = [] + + async def fake_fetch(api_host, client_key): + calls.append(1) + return {"features": {"f": {"defaultValue": 1}}, "savedGroups": {}} + + with patch.object(repo, "_fetch_and_decode_async", side_effect=fake_fetch): + await repo._start_http_refresh(interval=0.02, bypass_cache=True) + await asyncio.sleep(0.3) + await repo.stop_refresh() + + assert len(calls) > 5, f"expected repeated polls, got {len(calls)}" + + +@pytest.mark.asyncio +async def test_polling_without_bypass_is_capped_by_the_cache(): + # Pins the reason the bypass exists; this is the pre-existing behavior. + EnhancedFeatureRepository._instances = {} + repo = EnhancedFeatureRepository("https://test.growthbook.io", "k2", cache_ttl=60) + calls = [] + + async def fake_fetch(api_host, client_key): + calls.append(1) + return {"features": {}, "savedGroups": {}} + + with patch.object(repo, "_fetch_and_decode_async", side_effect=fake_fetch): + await repo._start_http_refresh(interval=0.02) + await asyncio.sleep(0.3) + await repo.stop_refresh() + + assert len(calls) == 1 + + +@pytest.mark.asyncio +async def test_polling_runs_alongside_sse(): + """Polling is orthogonal to the strategy: a stream blocked by a proxy is + exactly when the app still needs refreshes. Only the network is stubbed, so + the two tasks have to actually coexist.""" + EnhancedFeatureRepository._instances = {} + repo = EnhancedFeatureRepository("https://test.growthbook.io", "k3") + calls = [] + + async def fake_fetch(api_host, client_key): + calls.append(1) + return {"features": {}, "savedGroups": {}} + + with patch.object(repo, "_fetch_and_decode_async", side_effect=fake_fetch), \ + patch.object(repo, "startAutoRefresh") as sse_start, \ + patch.object(repo, "stopAutoRefresh"): + await repo.start_feature_refresh( + FeatureRefreshStrategy.SERVER_SENT_EVENTS, polling_interval=0.02 + ) + await asyncio.sleep(0.3) + sse_task, poll_task = repo._refresh_task, repo._poll_task + await repo.stop_refresh() + + sse_start.assert_called_once() + assert len(calls) > 5, f"expected repeated polls alongside SSE, got {len(calls)}" + # stop_refresh tears both down. + assert sse_task is not None and sse_task.done() + assert poll_task is not None and poll_task.done() + assert repo._refresh_task is None and repo._poll_task is None + + +@pytest.mark.asyncio +async def test_polling_backs_off_when_fetch_returns_none(): + """A failed fetch is reported as None, not raised. It must still back off, + or an unreachable CDN gets a request every interval indefinitely.""" + EnhancedFeatureRepository._instances = {} + repo = EnhancedFeatureRepository("https://test.growthbook.io", "k4") + real_sleep = asyncio.sleep + sleeps = [] + results = iter([None, None, None, {"features": {}, "savedGroups": {}}, None]) + + async def fake_fetch(api_host, client_key): + return next(results) + + async def record_sleep(delay, *args, **kwargs): + sleeps.append(delay) + if len(sleeps) == 5: + repo._stop_event.set() + await real_sleep(0) + + with patch.object(repo, "_fetch_and_decode_async", side_effect=fake_fetch), \ + patch("growthbook.growthbook_client.asyncio.sleep", side_effect=record_sleep): + await repo._start_http_refresh(interval=10, bypass_cache=True) + task = repo._poll_task + await asyncio.wait_for(task, timeout=5) + await repo.stop_refresh() + + assert len(sleeps) == 5, sleeps + # Three failures: growing waits, never shorter than the interval. + assert 10 <= sleeps[0] < 20 + assert 20 <= sleeps[1] < 40 + assert 40 <= sleeps[2] < 80 + # Success resets to the plain interval; the next failure starts over. + assert sleeps[3] == 10 + assert 10 <= sleeps[4] < 20 + + +@pytest.mark.asyncio +async def test_polling_update_handler_error_does_not_back_off(caplog): + """The fetch succeeded, so a failing update handler must not slow polling: + it is logged and the next wait is the plain interval.""" + EnhancedFeatureRepository._instances = {} + repo = EnhancedFeatureRepository("https://test.growthbook.io", "k5") + real_sleep = asyncio.sleep + sleeps = [] + + async def fake_fetch(api_host, client_key): + return {"features": {}, "savedGroups": {}} + + async def failing_handler(response): + raise RuntimeError("handler bug") + + async def record_sleep(delay, *args, **kwargs): + sleeps.append(delay) + if len(sleeps) == 3: + repo._stop_event.set() + await real_sleep(0) + + with patch.object(repo, "_fetch_and_decode_async", side_effect=fake_fetch), \ + patch.object(repo, "_handle_feature_update", side_effect=failing_handler), \ + patch("growthbook.growthbook_client.asyncio.sleep", side_effect=record_sleep), \ + caplog.at_level("ERROR", logger="growthbook"): + await repo._start_http_refresh(interval=10, bypass_cache=True) + await asyncio.wait_for(repo._poll_task, timeout=5) + await repo.stop_refresh() + + assert sleeps == [10, 10, 10] + assert any(r.getMessage() == "Error handling polled feature update" for r in caplog.records) + + +@pytest.mark.asyncio +async def test_second_polling_interval_on_the_same_key_warns(caplog): + EnhancedFeatureRepository._instances = {} + repo = EnhancedFeatureRepository("https://test.growthbook.io", "k6") + gate = asyncio.Event() + + async def blocked_fetch(api_host, client_key): + await gate.wait() + return None + + with patch.object(repo, "_fetch_and_decode_async", side_effect=blocked_fetch): + await repo._start_http_refresh(interval=60, bypass_cache=True) + first_task = repo._poll_task + with caplog.at_level("WARNING", logger="growthbook"): + await repo._start_http_refresh(interval=10, bypass_cache=True) + # Same interval again: nothing to warn about. + await repo._start_http_refresh(interval=60, bypass_cache=True) + assert repo._poll_task is first_task + warnings = [r.getMessage() for r in caplog.records if "already running" in r.getMessage()] + assert len(warnings) == 1 and "every 60s" in warnings[0], warnings + await repo.stop_refresh() + assert repo._poll_config is None + + +@pytest.mark.asyncio +async def test_poll_does_not_roll_back_an_sse_update_applied_during_its_fetch(): + """With SSE and polling, an inline SSE payload can land while a poll's + fetch is in flight. The poll's (possibly older) response must not + overwrite it.""" + EnhancedFeatureRepository._instances = {} + repo = EnhancedFeatureRepository("https://test.growthbook.io", "k7") + real_sleep = asyncio.sleep + newer = {"features": {"flag": {"defaultValue": "new"}}, "savedGroups": {}} + older = {"features": {"flag": {"defaultValue": "old"}}, "savedGroups": {}} + fetches = [] + + async def fetch_while_sse_lands(api_host, client_key): + fetches.append(1) + # SSE applies the newer payload while this fetch is in flight. + await repo._handle_sse_event({"type": "features", "data": newer}) + return older + + async def stop_after_one_cycle(delay, *args, **kwargs): + repo._stop_event.set() + await real_sleep(0) + + with patch.object(repo, "_fetch_and_decode_async", side_effect=fetch_while_sse_lands), \ + patch("growthbook.growthbook_client.asyncio.sleep", side_effect=stop_after_one_cycle): + await repo._start_http_refresh(interval=10, bypass_cache=True) + await asyncio.wait_for(repo._poll_task, timeout=5) + await repo.stop_refresh() + + assert fetches == [1] + state = repo._feature_cache.get_current_state() + assert state["features"]["flag"]["defaultValue"] == "new" + + +def test_polling_interval_validation(): + from growthbook.common_types import validate_polling_interval as v + + assert v(None) is None + assert v(30) == 30.0 + assert v(0.5) == 0.5 + # Out of range is rejected, not clamped: Event.wait()/asyncio.sleep() + # return immediately on a negative delay, so clamping a typo to "as fast as + # possible" would turn it into a request flood. + assert v(-5) is None + assert v(0) is None + assert v(60 * 60 * 48) is None + assert v("30") is None + assert v(True) is None + # NaN passes both range comparisons; infinity is rejected too. + assert v(float("nan")) is None + assert v(float("inf")) is None