From 719f5920f08cebe68efd44fd4979ce9b1a6ded82 Mon Sep 17 00:00:00 2001 From: Volodymyr Nazarkevych Date: Wed, 18 Nov 2026 19:35:42 +0200 Subject: [PATCH 1/6] feat: configurable, finite HTTP request timeouts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A feature fetch could block forever. The sync transport built `PoolManager(timeout=None)` whenever the timeout options were unset, which urllib3 resolves to `Timeout(connect=None, read=None, total=None)` — no bound at all. Against a slow or black-hole endpoint, `load_features()` never returned and the caller had no way to cap it. Reproduced against a socket that accepts and then stays silent: the fetch was still blocked after 8 seconds. Adds `request_timeout` (seconds, connect and read alike) defaulting to 2, so an unconfigured SDK is bounded and falls back to cache or an inline payload instead of hanging. `None` opts back into waiting forever. Four further defects in the same area: Each override had to be set with the other. `if connect and read` meant configuring just one silently applied neither; they now resolve independently and inherit `request_timeout` when absent. That same falsy check made `0` disable both timeouts. Non-positive and non-numeric values are now rejected — `timeout=0` reads as "no timeout" in several HTTP stacks, so accepting it would turn a typo back into the unbounded wait this default exists to prevent. Validation runs at construction, not at first request. The async fetches built a bare `aiohttp.ClientSession()`, so these options never reached them and aiohttp's own 300s default applied — bounded, but neither configurable nor a sensible startup budget. They now use the same resolved values (`sock_connect` / `sock_read`; `total` would also cut a legitimately large payload). The pool was cached on first use, so the first request's timeout stuck for the process lifetime, and the sync client applied the options *after* any constructor-time load. The pool is now rebuilt when the configuration changes, and the options are applied before the initial fetch. tests/test_request_timeout.py covers the bound against a black-hole endpoint, the finite default, independent overrides, rejection of 0 and of non-numbers, fail-fast construction, and pool rebuilding. --- README.md | 21 +++++++ growthbook/common_types.py | 53 +++++++++++++++- growthbook/growthbook.py | 71 +++++++++++++++------ growthbook/growthbook_client.py | 10 ++- tests/test_request_timeout.py | 108 ++++++++++++++++++++++++++++++++ 5 files changed, 239 insertions(+), 24 deletions(-) create mode 100644 tests/test_request_timeout.py diff --git a/README.md b/README.md index 89602bb..2ba7d74 100644 --- a/README.md +++ b/README.md @@ -338,6 +338,27 @@ To use the built-in fetching and caching logic, in the `GrowthBook` constructor, Then, call the `load_features()` method to initiate the HTTP request with a cache layer. +#### Request timeouts + +Feature fetches and remote-eval calls are bounded by `request_timeout` +(seconds, applied to both connect and read), defaulting to 2 seconds. On +timeout the SDK falls back to its cache or an inline payload, so a slow or +unreachable endpoint bounds startup instead of blocking it. + +```python +gb = GrowthBook( + api_host = "https://cdn.growthbook.io", + client_key = "sdk-abc123", + request_timeout = 5, # seconds; None waits indefinitely +) +``` + +`http_connect_timeout` and `http_read_timeout` override it per phase; either +can be set on its own and the other inherits `request_timeout`. A value of `0` +or below is rejected at construction rather than treated as "no timeout" — +pass `None` if you really want to wait forever. The same options apply to +`Options` for the async client. + Here's a full example: ```python diff --git a/growthbook/common_types.py b/growthbook/common_types.py index 3d005d9..c391723 100644 --- a/growthbook/common_types.py +++ b/growthbook/common_types.py @@ -37,6 +37,11 @@ logger = logging.getLogger("growthbook") +# Seconds. Finite so a hung endpoint can't block startup forever; generous +# enough to survive a cold TLS handshake on a slow link. Matches the bound the +# other SDKs settled on. +DEFAULT_REQUEST_TIMEOUT = 2.0 + # Generic feature/experiment value type. Deliberately unbounded: a JSONValue # bound would reject TypedDict/dataclass-shaped fallbacks (see JS SDK issue #1729, # where the equivalent bound was shipped and then reverted). @@ -771,8 +776,17 @@ class Options: on_experiment_viewed: Optional[AsyncTrackingCallback] = None on_feature_usage: Optional[AsyncFeatureUsageCallback] = None tracking_plugins: Optional[List["PluginLike"]] = None - http_connect_timeout: Optional[int] = None - http_read_timeout: Optional[int] = None + # Seconds allowed for a feature fetch or remote-eval call — connect and + # read alike. Finite by default so a slow or black-hole endpoint bounds + # startup instead of blocking it: on timeout the SDK falls back to cache or + # an inline payload. Pass None to opt back into waiting forever; 0 or a + # negative value is rejected at construction rather than silently meaning + # "no timeout". + request_timeout: Optional[float] = DEFAULT_REQUEST_TIMEOUT + # Finer-grained overrides. Either may be set on its own; whichever is None + # falls back to request_timeout. + http_connect_timeout: Optional[float] = None + http_read_timeout: Optional[float] = None event_logger: Optional[AsyncEventLogger] = None remote_eval: bool = False cache_key_attributes: Optional[List[str]] = None @@ -900,6 +914,41 @@ def is_cloud_host(api_host: Optional[str]) -> bool: return host == "growthbook.io" or host.endswith(".growthbook.io") +def resolve_request_timeouts( + request_timeout: Optional[float], + connect_timeout: Optional[float] = None, + read_timeout: Optional[float] = None, +) -> Tuple[Optional[float], Optional[float]]: + """Return the (connect, read) seconds to apply, validating as it goes. + + Each specific override stands on its own; whichever is None inherits + request_timeout. `None` throughout means "wait forever" — an explicit + opt-out, never the result of a falsy 0. + + Raises ValueError on a non-positive or non-numeric value. Rejecting rather + than clamping is deliberate: `timeout=0` reads as "no timeout" in several + HTTP stacks, so silently accepting it would turn a typo into the unbounded + wait this default exists to prevent.""" + for name, value in ( + ("request_timeout", request_timeout), + ("http_connect_timeout", connect_timeout), + ("http_read_timeout", read_timeout), + ): + if value is None: + continue + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError(f"{name} must be a number of seconds, got {value!r}") + if value <= 0: + raise ValueError( + f"{name} must be greater than 0, got {value!r}; " + "pass None to wait indefinitely" + ) + + connect = connect_timeout if connect_timeout is not None else request_timeout + read = read_timeout if read_timeout is not None else request_timeout + return connect, read + + def validate_remote_eval_options( client_key: Optional[str], decryption_key: Optional[str], diff --git a/growthbook/growthbook.py b/growthbook/growthbook.py index e98e740..7b96348 100644 --- a/growthbook/growthbook.py +++ b/growthbook/growthbook.py @@ -38,7 +38,9 @@ FeatureRule, TrackingBuffer, TrackingDedupeKey, + DEFAULT_REQUEST_TIMEOUT, build_remote_eval_payload, + resolve_request_timeouts, features_from_dict, tracking_dedupe_key, tracking_user_context, @@ -381,8 +383,12 @@ class FeatureRepository(object): def __init__(self) -> None: self.cache: AbstractFeatureCache = InMemoryFeatureCache() self.http: Optional[PoolManager] = None - self.http_connect_timeout: Optional[int] = None - self.http_read_timeout: Optional[int] = None + # Timeout the cached pool was built with, so a later configuration + # change rebuilds it instead of silently keeping the first one. + self._http_timeout_key: Optional[Tuple[Optional[float], Optional[float]]] = None + self.request_timeout: Optional[float] = DEFAULT_REQUEST_TIMEOUT + self.http_connect_timeout: Optional[float] = None + self.http_read_timeout: Optional[float] = None self.sse_client: Optional[SSEClient] = None self._feature_update_callbacks: List[Callable[[Dict[str, Any]], None]] = [] @@ -505,12 +511,37 @@ def user_agent_suffix(self, value: Optional[str]) -> None: self._user_agent_suffix = value # Perform the GET request (separate method for easy mocking) + def _pool(self) -> PoolManager: + """The shared pool, rebuilt when the configured timeouts change. + + Each override applies on its own — the old `connect and read` meant + setting just one silently did nothing, and a 0 disabled both — and the + resolved values are finite unless the caller opted out with None. + """ + connect, read = resolve_request_timeouts( + self.request_timeout, self.http_connect_timeout, self.http_read_timeout + ) + key = (connect, read) + if self.http is None or self._http_timeout_key != key: + self.http = PoolManager(timeout=Timeout(connect=connect, read=read)) + self._http_timeout_key = key + return self.http + + def _client_timeout(self) -> "aiohttp.ClientTimeout": + """aiohttp equivalent of the pool's timeouts. + + The async fetches used to build a bare ClientSession, so these options + never reached them and aiohttp's own 300s default applied — bounded, + but neither configurable nor a sensible startup budget.""" + connect, read = resolve_request_timeouts( + self.request_timeout, self.http_connect_timeout, self.http_read_timeout + ) + # sock_read bounds the gap between bytes; total would also cover a + # legitimately large payload, which is not what a timeout should cut. + return aiohttp.ClientTimeout(sock_connect=connect, sock_read=read) + def _get(self, url: str, headers: Optional[Dict[str, str]] = None) -> "BaseHTTPResponse": - timeout = None - if self.http_connect_timeout and self.http_read_timeout: - timeout = Timeout(connect=self.http_connect_timeout, read=self.http_read_timeout) - self.http = self.http or PoolManager(timeout=timeout) - return self.http.request("GET", url, headers=headers or {}) + return self._pool().request("GET", url, headers=headers or {}) def _get_headers(self, client_key: str, existing_headers: Optional[Dict[str, str]] = None) -> Dict[str, str]: headers = existing_headers or {} @@ -525,12 +556,8 @@ def _get_headers(self, client_key: str, existing_headers: Optional[Dict[str, str # Perform the POST request (separate method for easy mocking) def _post(self, url: str, payload: Dict[str, Any], headers: Optional[Dict[str, str]] = None) -> "BaseHTTPResponse": - timeout = None - if self.http_connect_timeout and self.http_read_timeout: - timeout = Timeout(connect=self.http_connect_timeout, read=self.http_read_timeout) - self.http = self.http or PoolManager(timeout=timeout) body = json.dumps(payload).encode("utf-8") - return self.http.request("POST", url, body=body, headers=headers or {}) + return self._pool().request("POST", url, body=body, headers=headers or {}) def _fetch_and_decode_post( self, api_host: str, client_key: str, payload: Dict[str, Any] @@ -560,7 +587,7 @@ async def _fetch_and_decode_post_async( headers["Content-Type"] = "application/json" logger.debug(f"[Async] Remote-eval POST to {url}") try: - async with aiohttp.ClientSession() as session: + async with aiohttp.ClientSession(timeout=self._client_timeout()) as session: async with session.post(url, json=payload, headers=headers) as response: if response.status >= 400: logger.warning( @@ -657,7 +684,7 @@ async def _fetch_and_decode_async(self, api_host: str, client_key: str) -> Optio logger.debug(f"[Async] No ETag cache found for URL: {url}") try: - async with aiohttp.ClientSession() as session: + async with aiohttp.ClientSession(timeout=self._client_timeout()) as session: async with session.get(url, headers=headers) as response: # Handle 304 Not Modified - content hasn't changed if response.status == 304: @@ -938,8 +965,9 @@ def __init__( groups: Optional[Dict[str, Any]] = None, overrides: Optional[Dict[str, Any]] = None, forcedVariations: Optional[Dict[str, Any]] = None, - http_connect_timeout: Optional[int] = None, - http_read_timeout: Optional[int] = None, + request_timeout: Optional[float] = DEFAULT_REQUEST_TIMEOUT, + http_connect_timeout: Optional[float] = None, + http_read_timeout: Optional[float] = None, savedGroups: Optional[Dict[str, Any]] = None, remoteEval: bool = False, cacheKeyAttributes: Optional[List[str]] = None, @@ -1075,6 +1103,14 @@ def __init__( self._initialize_plugins() + # Before any load below: these used to be applied at the end of + # __init__, so a constructor-time fetch ran on the previous timeouts. + # Validated here so a bad value fails fast instead of at first request. + resolve_request_timeouts(request_timeout, http_connect_timeout, http_read_timeout) + feature_repo.request_timeout = request_timeout + feature_repo.http_connect_timeout = http_connect_timeout + feature_repo.http_read_timeout = http_read_timeout + if self._streaming: self.load_features() self.start_auto_refresh() @@ -1090,9 +1126,6 @@ def __init__( # before the first eval. Matches the JS SDK init() behavior. self.load_features() - if http_connect_timeout and http_read_timeout: - feature_repo.http_connect_timeout = http_connect_timeout - feature_repo.http_read_timeout = http_read_timeout def _remote_eval_payload(self) -> Dict[str, Any]: return build_remote_eval_payload( diff --git a/growthbook/growthbook_client.py b/growthbook/growthbook_client.py index aff2fb1..79e0d18 100644 --- a/growthbook/growthbook_client.py +++ b/growthbook/growthbook_client.py @@ -43,6 +43,7 @@ FeatureRefreshStrategy, AbstractAsyncStickyBucketService, Experiment, + DEFAULT_REQUEST_TIMEOUT, build_remote_eval_payload, features_from_dict, features_to_dicts, @@ -162,10 +163,11 @@ def __init__(self, client_key: str, decryption_key: str = "", cache_ttl: int = 60, - http_connect_timeout: Optional[int] = None, - http_read_timeout: Optional[int] = None, + http_connect_timeout: Optional[float] = None, + http_read_timeout: Optional[float] = None, remote_eval_cache_size: int = 1000, - remote_eval: bool = False) -> None: + remote_eval: bool = False, + request_timeout: Optional[float] = DEFAULT_REQUEST_TIMEOUT) -> None: FeatureRepository.__init__(self) self._api_host = api_host self._client_key = client_key @@ -186,6 +188,7 @@ def __init__(self, self._callbacks: List[Callable[[Dict[str, Any]], Awaitable[None]]] = [] self._last_successful_refresh: Optional[datetime] = None self._refresh_in_progress = asyncio.Lock() + self.request_timeout = request_timeout self.http_connect_timeout = http_connect_timeout self.http_read_timeout = http_read_timeout @@ -721,6 +724,7 @@ def __init__( self.options.http_read_timeout, self.options.remote_eval_cache_size, self.options.remote_eval, + self.options.request_timeout, ) if self.options.client_key else None diff --git a/tests/test_request_timeout.py b/tests/test_request_timeout.py new file mode 100644 index 0000000..6284ca6 --- /dev/null +++ b/tests/test_request_timeout.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python +"""Request timeout configuration. + +The default has to be finite: before it, `PoolManager(timeout=None)` meant +`Timeout(connect=None, read=None, total=None)`, so a fetch against a slow or +black-hole endpoint blocked startup forever with no caller-visible bound. +""" + +import socket +import threading + +import pytest + +from growthbook import GrowthBook, FeatureRepository +from growthbook.common_types import ( + DEFAULT_REQUEST_TIMEOUT, + Options, + resolve_request_timeouts, +) + + +@pytest.fixture +def black_hole(): + """An endpoint that accepts the connection and then says nothing.""" + srv = socket.socket() + srv.bind(("127.0.0.1", 0)) + srv.listen(5) + accepted = [] + + def accept_forever(): + while True: + try: + accepted.append(srv.accept()[0]) + except OSError: + return + + threading.Thread(target=accept_forever, daemon=True).start() + host, port = srv.getsockname() + yield f"http://{host}:{port}" + srv.close() + for conn in accepted: + conn.close() + + +def test_fetch_is_bounded_by_default(black_hole): + repo = FeatureRepository() + repo.request_timeout = 0.3 + + done = threading.Event() + + def fetch(): + try: + repo._get(f"{black_hole}/api/features/k") + except Exception: + pass + done.set() + + threading.Thread(target=fetch, daemon=True).start() + assert done.wait(timeout=10), "the fetch never returned — timeout not applied" + + +def test_default_is_finite(): + # The point of the change: an unconfigured repository still has a bound. + assert DEFAULT_REQUEST_TIMEOUT > 0 + assert Options().request_timeout == DEFAULT_REQUEST_TIMEOUT + assert FeatureRepository().request_timeout == DEFAULT_REQUEST_TIMEOUT + + +def test_each_override_applies_on_its_own(): + # The old `connect and read` guard meant setting one alone did nothing. + assert resolve_request_timeouts(5, 1, None) == (1, 5) + assert resolve_request_timeouts(5, None, 2) == (5, 2) + assert resolve_request_timeouts(5, None, None) == (5, 5) + # None opts out entirely, and stays opted out. + assert resolve_request_timeouts(None, None, None) == (None, None) + + +def test_zero_is_rejected_rather_than_disabling(): + # `timeout=0` reads as "no timeout" in several HTTP stacks, and the old + # falsy check made it disable both. A typo must not reinstate the hang. + for kwargs in ({"request_timeout": 0}, {"connect_timeout": 0}, {"read_timeout": 0}): + args = {"request_timeout": 1, **kwargs} + with pytest.raises(ValueError, match="greater than 0"): + resolve_request_timeouts(**args) + + with pytest.raises(ValueError, match="greater than 0"): + resolve_request_timeouts(-1) + with pytest.raises(ValueError, match="number of seconds"): + resolve_request_timeouts("2") # type: ignore[arg-type] + + +def test_invalid_timeout_fails_at_construction(): + with pytest.raises(ValueError): + GrowthBook(request_timeout=0) + + +def test_pool_is_rebuilt_when_timeouts_change(): + # The pool used to be cached on first use, so the first request's timeout + # stuck for the process lifetime. + repo = FeatureRepository() + repo.request_timeout = 5 + first = repo._pool() + assert repo._pool() is first # unchanged config reuses the pool + + repo.request_timeout = 1 + second = repo._pool() + assert second is not first + assert second.connection_pool_kw["timeout"].connect_timeout == 1 From d41430cd9a2e61887c7e3de41093f26fd147fd1b Mon Sep 17 00:00:00 2001 From: Volodymyr Nazarkevych Date: Mon, 23 Nov 2026 17:23:26 +0200 Subject: [PATCH 2/6] fix: per-instance, per-attempt request timeouts; keep injected pools - Disable urllib3 retries for feature and remote-eval requests. The default Retry(3) re-sent a timed-out GET, so the real bound was ~4x the timeout (2.01s and 4 connections for 0.5s; now 0.55s and 1). Redirects are still followed; Retry-After is not honored. - GrowthBook() no longer writes its timeouts into the process-wide feature_repo. They stay on the instance and are applied for the duration of its own calls through a context variable, falling back field by field to feature_repo's attributes, so direct repo configuration keeps working and the last-constructed instance no longer wins. The SWR poller thread inherits the timeouts of the instance that started it. - Never replace self.http: the pool is created once if absent, and timeouts go per request, so an injected ProxyManager or custom-CA pool is kept. - request_timeout moves to the end of GrowthBook.__init__ so existing positional call sites keep their meaning. Not passing it (UNSET) means "use feature_repo.request_timeout"; None still opts out. - README: per-attempt bound, per-instance scope, injected pools, and an upgrade note. DEFAULT_REQUEST_TIMEOUT comment no longer claims parity with other SDKs. --- README.md | 21 ++++ growthbook/common_types.py | 13 ++- growthbook/growthbook.py | 187 +++++++++++++++++++++++----------- tests/test_request_timeout.py | 108 +++++++++++++++++--- 4 files changed, 257 insertions(+), 72 deletions(-) diff --git a/README.md b/README.md index 2ba7d74..1d11c93 100644 --- a/README.md +++ b/README.md @@ -359,6 +359,27 @@ or below is rejected at construction rather than treated as "no timeout" — pass `None` if you really want to wait forever. The same options apply to `Options` for the async client. +The bound is per attempt and there are no retries: a request that times out +fails over to the cache instead of being re-sent. + +Timeouts passed to `GrowthBook(...)` apply to that instance's requests only; +constructing another instance doesn't change them. Anything an instance +doesn't set falls back to the shared repository, so process-wide defaults can +still be set once: + +```python +from growthbook import feature_repo + +feature_repo.request_timeout = 5 +``` + +A pool you assign to `feature_repo.http` (for example a `ProxyManager`) is kept +as is; the timeouts are applied per request. + +**Upgrading:** requests used to wait indefinitely (sync) or up to 300 seconds +(async) by default. To keep that behavior, pass `request_timeout=None`, or set +`feature_repo.request_timeout = None` once for the whole process. + Here's a full example: ```python diff --git a/growthbook/common_types.py b/growthbook/common_types.py index c391723..c669ae4 100644 --- a/growthbook/common_types.py +++ b/growthbook/common_types.py @@ -38,10 +38,19 @@ logger = logging.getLogger("growthbook") # Seconds. Finite so a hung endpoint can't block startup forever; generous -# enough to survive a cold TLS handshake on a slow link. Matches the bound the -# other SDKs settled on. +# enough to survive a cold TLS handshake on a slow link. Stricter by design +# than SDKs that leave requests unbounded unless the caller sets a timeout. DEFAULT_REQUEST_TIMEOUT = 2.0 + +class _Unset(Enum): + """Sentinel type for "argument not passed", where None is itself a + meaningful value (e.g. request_timeout=None waits indefinitely).""" + TOKEN = 0 + + +UNSET = _Unset.TOKEN + # Generic feature/experiment value type. Deliberately unbounded: a JSONValue # bound would reject TypedDict/dataclass-shaped fallbacks (see JS SDK issue #1729, # where the equivalent bound was shipped and then reverted). diff --git a/growthbook/growthbook.py b/growthbook/growthbook.py index 7b96348..253047d 100644 --- a/growthbook/growthbook.py +++ b/growthbook/growthbook.py @@ -5,6 +5,8 @@ More info at https://www.growthbook.io """ import atexit +import contextvars +from contextlib import contextmanager import json import threading import logging @@ -12,7 +14,7 @@ from abc import ABC, abstractmethod from dataclasses import replace -from typing import TYPE_CHECKING, Optional, Any, Set, Tuple, List, Dict, Callable, cast +from typing import TYPE_CHECKING, Optional, Any, Set, Tuple, List, Dict, Callable, Iterator, Union, cast from typing_extensions import deprecated @@ -39,6 +41,8 @@ TrackingBuffer, TrackingDedupeKey, DEFAULT_REQUEST_TIMEOUT, + UNSET, + _Unset, build_remote_eval_payload, resolve_request_timeouts, features_from_dict, @@ -56,6 +60,7 @@ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives import padding from urllib3 import PoolManager, Timeout +from urllib3.util.retry import Retry if TYPE_CHECKING: # Only present in urllib3 2.x; the runtime dependency allows 1.x too. @@ -379,13 +384,33 @@ async def _stop_session(self, timeout: float = 10) -> None: # ... (imports) +# (connect, read) seconds for HTTP calls made on behalf of one GrowthBook +# instance. Set only for the duration of that instance's call into the shared +# feature_repo, so instances never write their timeouts into process-wide +# state. Context variables are per thread and per asyncio task, so concurrent +# instances can't see each other's values. Unset means the repository's own +# attributes apply. +_request_timeouts: "contextvars.ContextVar[Optional[Tuple[Optional[float], Optional[float]]]]" = ( + contextvars.ContextVar("growthbook_request_timeouts", default=None) +) + +# urllib3's default Retry(3) re-sends a GET that timed out, so the real bound +# was about (1 + retries) x the timeout. Connection, read and status failures +# are not retried — the SDK already falls back to cache or an inline payload — +# and Retry-After is ignored, since honoring it is another unbounded wait. +# Redirects are still followed. +_NO_RETRY = Retry( + connect=0, read=0, other=0, status=0, redirect=3, + respect_retry_after_header=False, +) + + class FeatureRepository(object): def __init__(self) -> None: self.cache: AbstractFeatureCache = InMemoryFeatureCache() self.http: Optional[PoolManager] = None - # Timeout the cached pool was built with, so a later configuration - # change rebuilds it instead of silently keeping the first one. - self._http_timeout_key: Optional[Tuple[Optional[float], Optional[float]]] = None + # Process-wide defaults, used when no GrowthBook instance has set its + # own timeouts for the current call (see `_request_timeouts`). self.request_timeout: Optional[float] = DEFAULT_REQUEST_TIMEOUT self.http_connect_timeout: Optional[float] = None self.http_read_timeout: Optional[float] = None @@ -511,37 +536,47 @@ def user_agent_suffix(self, value: Optional[str]) -> None: self._user_agent_suffix = value # Perform the GET request (separate method for easy mocking) - def _pool(self) -> PoolManager: - """The shared pool, rebuilt when the configured timeouts change. - - Each override applies on its own — the old `connect and read` meant - setting just one silently did nothing, and a 0 disabled both — and the - resolved values are finite unless the caller opted out with None. - """ - connect, read = resolve_request_timeouts( + def _timeouts(self) -> Tuple[Optional[float], Optional[float]]: + """The (connect, read) seconds for the current call. + + A GrowthBook instance's own settings win for the duration of its call; + otherwise this repository's attributes apply. Each override applies on + its own — the old `connect and read` meant setting just one silently + did nothing, and a 0 disabled both — and the result is finite unless + the caller opted out with None.""" + scoped = _request_timeouts.get() + if scoped is not None: + return scoped + return resolve_request_timeouts( self.request_timeout, self.http_connect_timeout, self.http_read_timeout ) - key = (connect, read) - if self.http is None or self._http_timeout_key != key: - self.http = PoolManager(timeout=Timeout(connect=connect, read=read)) - self._http_timeout_key = key + + def _pool(self) -> PoolManager: + """The shared pool. Created once, and never replaced: a pool assigned + from outside (a ProxyManager for a corporate proxy, a custom CA bundle) + is kept. Timeouts are applied per request instead.""" + if self.http is None: + self.http = PoolManager() return self.http + def _request_kwargs(self) -> Dict[str, Any]: + connect, read = self._timeouts() + return {"timeout": Timeout(connect=connect, read=read), "retries": _NO_RETRY} + def _client_timeout(self) -> "aiohttp.ClientTimeout": - """aiohttp equivalent of the pool's timeouts. + """aiohttp equivalent of the sync timeouts. The async fetches used to build a bare ClientSession, so these options never reached them and aiohttp's own 300s default applied — bounded, - but neither configurable nor a sensible startup budget.""" - connect, read = resolve_request_timeouts( - self.request_timeout, self.http_connect_timeout, self.http_read_timeout - ) + but neither configurable nor a sensible startup budget. aiohttp does + not retry, so no retry policy is needed here.""" + connect, read = self._timeouts() # sock_read bounds the gap between bytes; total would also cover a # legitimately large payload, which is not what a timeout should cut. return aiohttp.ClientTimeout(sock_connect=connect, sock_read=read) def _get(self, url: str, headers: Optional[Dict[str, str]] = None) -> "BaseHTTPResponse": - return self._pool().request("GET", url, headers=headers or {}) + return self._pool().request("GET", url, headers=headers or {}, **self._request_kwargs()) def _get_headers(self, client_key: str, existing_headers: Optional[Dict[str, str]] = None) -> Dict[str, str]: headers = existing_headers or {} @@ -557,7 +592,9 @@ def _get_headers(self, client_key: str, existing_headers: Optional[Dict[str, str # Perform the POST request (separate method for easy mocking) def _post(self, url: str, payload: Dict[str, Any], headers: Optional[Dict[str, str]] = None) -> "BaseHTTPResponse": body = json.dumps(payload).encode("utf-8") - return self._pool().request("POST", url, body=body, headers=headers or {}) + return self._pool().request( + "POST", url, body=body, headers=headers or {}, **self._request_kwargs() + ) def _fetch_and_decode_post( self, api_host: str, client_key: str, payload: Dict[str, Any] @@ -847,9 +884,12 @@ def start_background_refresh(self, api_host: str, client_key: str, decryption_ke return # Already running self._refresh_stop_event.clear() + # Run in a copy of the caller's context so the poller keeps the + # timeouts of the instance that started it. + ctx = contextvars.copy_context() self._refresh_thread = threading.Thread( - target=self._background_refresh_worker, - args=(api_host, client_key, decryption_key, ttl, refresh_interval), + target=ctx.run, + args=(self._background_refresh_worker, api_host, client_key, decryption_key, ttl, refresh_interval), daemon=True ) self._refresh_thread.start() @@ -965,7 +1005,6 @@ def __init__( groups: Optional[Dict[str, Any]] = None, overrides: Optional[Dict[str, Any]] = None, forcedVariations: Optional[Dict[str, Any]] = None, - request_timeout: Optional[float] = DEFAULT_REQUEST_TIMEOUT, http_connect_timeout: Optional[float] = None, http_read_timeout: Optional[float] = None, savedGroups: Optional[Dict[str, Any]] = None, @@ -985,6 +1024,11 @@ def __init__( # set_remote_group_ids). remote_group_ids: Optional[List[str]] = None, remoteGroupIds: Optional[List[str]] = None, + # Appended last so every earlier positional index is preserved. + # Seconds for feature fetches and remote-eval calls made by this + # instance; None waits indefinitely. Not passing it uses + # feature_repo.request_timeout (DEFAULT_REQUEST_TIMEOUT unless changed). + request_timeout: Union[float, None, _Unset] = UNSET, ) -> None: remote_eval = remote_eval or remoteEval self._remote_group_ids = remote_group_ids if remote_group_ids is not None else remoteGroupIds @@ -1103,13 +1147,15 @@ def __init__( self._initialize_plugins() - # Before any load below: these used to be applied at the end of - # __init__, so a constructor-time fetch ran on the previous timeouts. - # Validated here so a bad value fails fast instead of at first request. - resolve_request_timeouts(request_timeout, http_connect_timeout, http_read_timeout) - feature_repo.request_timeout = request_timeout - feature_repo.http_connect_timeout = http_connect_timeout - feature_repo.http_read_timeout = http_read_timeout + # Kept on the instance, never written to the shared feature_repo: the + # last constructed instance must not reset every other one. Applied + # per call via `_timeout_scope`. Set before any load below so a + # constructor-time fetch uses them, and validated here so a bad value + # fails fast instead of at first request. + self._request_timeout = request_timeout + self._http_connect_timeout = http_connect_timeout + self._http_read_timeout = http_read_timeout + self._resolve_timeouts() if self._streaming: self.load_features() @@ -1117,16 +1163,41 @@ 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 - ) + with self._timeout_scope(): + feature_repo.start_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. self.load_features() + def _resolve_timeouts(self) -> Tuple[Optional[float], Optional[float]]: + """This instance's (connect, read) seconds. Whatever it didn't set + falls back, field by field, to the shared repository's attributes, so + configuring feature_repo directly still works.""" + request_timeout = ( + feature_repo.request_timeout if isinstance(self._request_timeout, _Unset) + else self._request_timeout + ) + return resolve_request_timeouts( + request_timeout, + self._http_connect_timeout if self._http_connect_timeout is not None + else feature_repo.http_connect_timeout, + self._http_read_timeout if self._http_read_timeout is not None + else feature_repo.http_read_timeout, + ) + + @contextmanager + def _timeout_scope(self) -> Iterator[None]: + token = _request_timeouts.set(self._resolve_timeouts()) + try: + yield + finally: + _request_timeouts.reset(token) + def _remote_eval_payload(self) -> Dict[str, Any]: return build_remote_eval_payload( with_remote_group_ids(self._attributes, self._remote_group_ids), self._forcedVariations, self._url, @@ -1191,16 +1262,17 @@ def load_features(self, force_refresh: bool = False) -> None: would just return the stale cached payload — defeating the invalidation.""" payload = self._remote_eval_payload() if self._remoteEval else None - response = feature_repo.load_features( - self._api_host, - self._client_key, - self._decryption_key, - self._cache_ttl, - remote_eval=self._remoteEval, - payload=payload, - cache_key_attributes=self._cacheKeyAttributes, - force_refresh=force_refresh, - ) + with self._timeout_scope(): + response = feature_repo.load_features( + self._api_host, + self._client_key, + self._decryption_key, + self._cache_ttl, + remote_eval=self._remoteEval, + payload=payload, + cache_key_attributes=self._cacheKeyAttributes, + force_refresh=force_refresh, + ) if response is not None: self._ingest_payload(response) @@ -1209,16 +1281,17 @@ async def load_features_async(self, force_refresh: bool = False) -> None: raise ValueError("Must specify `client_key` to refresh features") payload = self._remote_eval_payload() if self._remoteEval else None - features = await feature_repo.load_features_async( - self._api_host, - self._client_key, - self._decryption_key, - self._cache_ttl, - remote_eval=self._remoteEval, - payload=payload, - cache_key_attributes=self._cacheKeyAttributes, - force_refresh=force_refresh, - ) + with self._timeout_scope(): + features = await feature_repo.load_features_async( + self._api_host, + self._client_key, + self._decryption_key, + self._cache_ttl, + remote_eval=self._remoteEval, + payload=payload, + cache_key_attributes=self._cacheKeyAttributes, + force_refresh=force_refresh, + ) if features is not None: self._ingest_payload(features) diff --git a/tests/test_request_timeout.py b/tests/test_request_timeout.py index 6284ca6..d737858 100644 --- a/tests/test_request_timeout.py +++ b/tests/test_request_timeout.py @@ -6,12 +6,15 @@ black-hole endpoint blocked startup forever with no caller-visible bound. """ +import inspect import socket import threading +import time +from unittest.mock import MagicMock, patch import pytest -from growthbook import GrowthBook, FeatureRepository +from growthbook import GrowthBook, FeatureRepository, feature_repo from growthbook.common_types import ( DEFAULT_REQUEST_TIMEOUT, Options, @@ -19,6 +22,15 @@ ) +class BlackHole(str): + """The endpoint URL, plus the connections it accepted.""" + + def __new__(cls, url, accepted): + obj = super().__new__(cls, url) + obj.accepted = accepted + return obj + + @pytest.fixture def black_hole(): """An endpoint that accepts the connection and then says nothing.""" @@ -36,7 +48,7 @@ def accept_forever(): threading.Thread(target=accept_forever, daemon=True).start() host, port = srv.getsockname() - yield f"http://{host}:{port}" + yield BlackHole(f"http://{host}:{port}", accepted) srv.close() for conn in accepted: conn.close() @@ -94,15 +106,85 @@ def test_invalid_timeout_fails_at_construction(): GrowthBook(request_timeout=0) -def test_pool_is_rebuilt_when_timeouts_change(): - # The pool used to be cached on first use, so the first request's timeout - # stuck for the process lifetime. +def test_timed_out_get_is_not_retried(black_hole): + # urllib3's default Retry(3) re-sent the GET after each timeout, so the + # real bound was about 4x the configured one. + repo = FeatureRepository() + repo.request_timeout = 0.3 + started = time.monotonic() + with pytest.raises(Exception): + repo._get(f"{black_hole}/api/features/k") + elapsed = time.monotonic() - started + + assert elapsed < 0.9, f"took {elapsed:.2f}s for a 0.3s timeout" + assert len(black_hole.accepted) == 1 + + +def test_injected_pool_is_kept_and_gets_the_timeout(): + # A pool assigned from outside (proxy, custom CA) must not be replaced. repo = FeatureRepository() - repo.request_timeout = 5 - first = repo._pool() - assert repo._pool() is first # unchanged config reuses the pool - - repo.request_timeout = 1 - second = repo._pool() - assert second is not first - assert second.connection_pool_kw["timeout"].connect_timeout == 1 + injected = MagicMock() + repo.http = injected + repo.request_timeout = 3 + repo._get("https://example.invalid/api/features/k") + repo._post("https://example.invalid/api/eval/k", {}) + + assert repo.http is injected + for call in injected.request.call_args_list: + assert call.kwargs["timeout"].connect_timeout == 3 + assert call.kwargs["timeout"].read_timeout == 3 + + +def test_constructor_does_not_touch_the_shared_repo(): + # Every GrowthBook() used to write its timeouts into the process-wide + # feature_repo: the last one constructed won for everyone, and a value + # configured on feature_repo directly was wiped to None. + old = feature_repo.http_connect_timeout + feature_repo.http_connect_timeout = 0.5 + try: + GrowthBook(request_timeout=10, http_read_timeout=7) + GrowthBook() + assert feature_repo.request_timeout == DEFAULT_REQUEST_TIMEOUT + assert feature_repo.http_connect_timeout == 0.5 + assert feature_repo.http_read_timeout is None + finally: + feature_repo.http_connect_timeout = old + + +def test_each_instance_fetches_with_its_own_timeout(): + seen = [] + long_lived = GrowthBook(api_host="https://example.invalid", client_key="a", request_timeout=10) + per_request = GrowthBook(api_host="https://example.invalid", client_key="b") + + def fake_get(url, headers=None): + seen.append(feature_repo._timeouts()) + raise RuntimeError("offline") + + with patch.object(feature_repo, "_get", side_effect=fake_get): + long_lived.load_features(force_refresh=True) + per_request.load_features(force_refresh=True) + # Outside any instance call the repository defaults apply again. + assert feature_repo._timeouts() == (DEFAULT_REQUEST_TIMEOUT, DEFAULT_REQUEST_TIMEOUT) + + assert seen == [(10, 10), (DEFAULT_REQUEST_TIMEOUT, DEFAULT_REQUEST_TIMEOUT)] + + +def test_direct_repo_configuration_still_applies(): + # Configuring feature_repo directly keeps working for instances that don't + # set their own value, field by field. + old = feature_repo.http_connect_timeout + feature_repo.http_connect_timeout = 0.5 + try: + assert GrowthBook()._resolve_timeouts() == (0.5, DEFAULT_REQUEST_TIMEOUT) + assert GrowthBook(http_connect_timeout=1)._resolve_timeouts() == (1, DEFAULT_REQUEST_TIMEOUT) + # An explicit None opts this instance out, unlike not passing it. + assert GrowthBook(request_timeout=None)._resolve_timeouts() == (0.5, None) + finally: + feature_repo.http_connect_timeout = old + + +def test_request_timeout_is_the_last_constructor_parameter(): + # Appended last so existing positional call sites keep their meaning. + params = list(inspect.signature(GrowthBook.__init__).parameters) + assert params[-1] == "request_timeout" + assert params.index("http_connect_timeout") == params.index("forcedVariations") + 1 From a19a21702629943e24e28029715fcf626f327238 Mon Sep 17 00:00:00 2001 From: Volodymyr Nazarkevych Date: Mon, 30 Nov 2026 13:20:29 +0200 Subject: [PATCH 3/6] chore: require urllib3>=1.26 for no-retry requests The feature and remote-eval requests use Retry(other=0), and the `other` parameter only exists since urllib3 1.26. setup.py and pyproject.toml accepted any urllib3, so an older pinned version failed at import time. requirements.txt already required >=1.26.0. --- pyproject.toml | 2 +- setup.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index ed2c790..8a92c2a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -44,7 +44,7 @@ keywords = ["growthbook"] dependencies = [ "cryptography", "typing_extensions>=4.5", - "urllib3", + "urllib3>=1.26.0", "aiohttp>=3.6.0", ] classifiers = [ diff --git a/setup.py b/setup.py index d0f3bc1..5f6ad52 100644 --- a/setup.py +++ b/setup.py @@ -11,7 +11,7 @@ requirements = [ 'cryptography', 'typing_extensions>=4.5', - 'urllib3', + 'urllib3>=1.26.0', # Retry(other=...) used for no-retry requests 'aiohttp>=3.6.0', # For async HTTP support ] From 04cc9fbeafee2d34422c72553ae3e0af8b85b3b7 Mon Sep 17 00:00:00 2001 From: Volodymyr Nazarkevych Date: Mon, 30 Nov 2026 13:20:29 +0200 Subject: [PATCH 4/6] fix: close remaining request-timeout gaps from review - Async: keep aiohttp's overall limit unless both phases are bounded. request_timeout=None used to build a ClientTimeout with no limit at all, and opting out of only one phase left that phase unbounded. - Validate GrowthBookClient Options at construction. A bad value used to raise inside the first fetch, where it was swallowed. - Validate GrowthBook timeouts before any side effect (callback registration, plugin startup), and name feature_repo in the error when the bad value is inherited from it. - Disable retries only on the pool the SDK creates; an injected pool keeps its own retry policy. Release the SDK's pool once it is replaced. - README: document the opt-out bounds, injected-pool retries, the shared background poller and the async repository singleton. - Tests: per-phase async timeouts, an async black-hole bound, fail-fast validation, injected-pool retries and pool release. --- README.md | 19 +++++-- growthbook/growthbook.py | 93 +++++++++++++++++++++++-------- growthbook/growthbook_client.py | 9 +++ tests/test_request_timeout.py | 97 ++++++++++++++++++++++++++++++++- 4 files changed, 187 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 1d11c93..6c59f54 100644 --- a/README.md +++ b/README.md @@ -356,11 +356,14 @@ gb = GrowthBook( `http_connect_timeout` and `http_read_timeout` override it per phase; either can be set on its own and the other inherits `request_timeout`. A value of `0` or below is rejected at construction rather than treated as "no timeout" — -pass `None` if you really want to wait forever. The same options apply to -`Options` for the async client. +pass `None` to opt out (the sync client then waits indefinitely, the async +client falls back to aiohttp's own 300-second limit). The same options apply +to `Options` for the async client, and are validated when `GrowthBookClient` +is constructed. -The bound is per attempt and there are no retries: a request that times out -fails over to the cache instead of being re-sent. +The bound is per attempt and, on the pool the SDK creates, there are no +retries: a request that times out fails over to the cache instead of being +re-sent. A pool you assign yourself keeps its own retry policy (see below). Timeouts passed to `GrowthBook(...)` apply to that instance's requests only; constructing another instance doesn't change them. Anything an instance @@ -373,8 +376,14 @@ from growthbook import feature_repo feature_repo.request_timeout = 5 ``` +The stale-while-revalidate background poller is shared by the process and +keeps the timeouts of the instance that started it. The async client shares one +feature repository per `(api_host, client_key)`, so a second `GrowthBookClient` +with the same host and key uses the timeouts of the first one. + A pool you assign to `feature_repo.http` (for example a `ProxyManager`) is kept -as is; the timeouts are applied per request. +as is, including its retry policy; only the timeouts are applied per request. +Retries are disabled only on the pool the SDK creates itself. **Upgrading:** requests used to wait indefinitely (sync) or up to 300 seconds (async) by default. To keep that behavior, pass `request_timeout=None`, or set diff --git a/growthbook/growthbook.py b/growthbook/growthbook.py index 253047d..ad6b042 100644 --- a/growthbook/growthbook.py +++ b/growthbook/growthbook.py @@ -409,6 +409,8 @@ class FeatureRepository(object): def __init__(self) -> None: self.cache: AbstractFeatureCache = InMemoryFeatureCache() self.http: Optional[PoolManager] = None + # The pool _pool() created, as opposed to one assigned from outside. + self._own_http: Optional[PoolManager] = None # Process-wide defaults, used when no GrowthBook instance has set its # own timeouts for the current call (see `_request_timeouts`). self.request_timeout: Optional[float] = DEFAULT_REQUEST_TIMEOUT @@ -555,13 +557,26 @@ def _pool(self) -> PoolManager: """The shared pool. Created once, and never replaced: a pool assigned from outside (a ProxyManager for a corporate proxy, a custom CA bundle) is kept. Timeouts are applied per request instead.""" + if self._own_http is not None and self.http is not self._own_http: + # Our pool was replaced from outside: close its idle keep-alive + # sockets and drop the reference so it can be collected. + self._own_http.clear() + self._own_http = None if self.http is None: self.http = PoolManager() + self._own_http = self.http return self.http - def _request_kwargs(self) -> Dict[str, Any]: + def _request_kwargs(self, pool: PoolManager) -> Dict[str, Any]: connect, read = self._timeouts() - return {"timeout": Timeout(connect=connect, read=read), "retries": _NO_RETRY} + kwargs: Dict[str, Any] = {"timeout": Timeout(connect=connect, read=read)} + # Retries are disabled only on our own pool. A pool assigned from + # outside keeps the retry policy its owner configured (a ProxyManager + # with backoff, say); overriding it per request would contradict + # keeping that pool as is. + if pool is self._own_http: + kwargs["retries"] = _NO_RETRY + return kwargs def _client_timeout(self) -> "aiohttp.ClientTimeout": """aiohttp equivalent of the sync timeouts. @@ -571,12 +586,29 @@ def _client_timeout(self) -> "aiohttp.ClientTimeout": but neither configurable nor a sensible startup budget. aiohttp does not retry, so no retry policy is needed here.""" connect, read = self._timeouts() + default = aiohttp.client.DEFAULT_TIMEOUT + if connect is None and read is None: + # Explicit opt-out (request_timeout=None): keep aiohttp's own + # bound, as before these options reached the async path, rather + # than a session with no limit at all. + return default # sock_read bounds the gap between bytes; total would also cover a # legitimately large payload, which is not what a timeout should cut. - return aiohttp.ClientTimeout(sock_connect=connect, sock_read=read) + # So total is dropped only when both phases are bounded. A phase opted + # out with None keeps aiohttp's default for it, and since that default + # can itself be None (sock_read, and sock_connect on older aiohttp), + # aiohttp's overall limit stays as the backstop. + both_bounded = connect is not None and read is not None + return aiohttp.ClientTimeout( + total=None if both_bounded else default.total, + connect=default.connect, + sock_connect=connect if connect is not None else default.sock_connect, + sock_read=read if read is not None else default.sock_read, + ) def _get(self, url: str, headers: Optional[Dict[str, str]] = None) -> "BaseHTTPResponse": - return self._pool().request("GET", url, headers=headers or {}, **self._request_kwargs()) + pool = self._pool() + return pool.request("GET", url, headers=headers or {}, **self._request_kwargs(pool)) def _get_headers(self, client_key: str, existing_headers: Optional[Dict[str, str]] = None) -> Dict[str, str]: headers = existing_headers or {} @@ -592,8 +624,9 @@ def _get_headers(self, client_key: str, existing_headers: Optional[Dict[str, str # Perform the POST request (separate method for easy mocking) def _post(self, url: str, payload: Dict[str, Any], headers: Optional[Dict[str, str]] = None) -> "BaseHTTPResponse": body = json.dumps(payload).encode("utf-8") - return self._pool().request( - "POST", url, body=body, headers=headers or {}, **self._request_kwargs() + pool = self._pool() + return pool.request( + "POST", url, body=body, headers=headers or {}, **self._request_kwargs(pool) ) def _fetch_and_decode_post( @@ -1030,6 +1063,17 @@ def __init__( # feature_repo.request_timeout (DEFAULT_REQUEST_TIMEOUT unless changed). request_timeout: Union[float, None, _Unset] = UNSET, ) -> None: + # Kept on the instance, never written to the shared feature_repo: the + # last constructed instance must not reset every other one. Applied + # per call via `_timeout_scope`. Validated first, before any side + # effect (feature-update callback registration, plugin startup, a + # constructor-time fetch), so a bad value fails fast and leaves + # nothing running behind it. + self._request_timeout = request_timeout + self._http_connect_timeout = http_connect_timeout + self._http_read_timeout = http_read_timeout + self._resolve_timeouts() + 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 @@ -1147,16 +1191,6 @@ def __init__( self._initialize_plugins() - # Kept on the instance, never written to the shared feature_repo: the - # last constructed instance must not reset every other one. Applied - # per call via `_timeout_scope`. Set before any load below so a - # constructor-time fetch uses them, and validated here so a bad value - # fails fast instead of at first request. - self._request_timeout = request_timeout - self._http_connect_timeout = http_connect_timeout - self._http_read_timeout = http_read_timeout - self._resolve_timeouts() - if self._streaming: self.load_features() self.start_auto_refresh() @@ -1173,22 +1207,33 @@ def __init__( # before the first eval. Matches the JS SDK init() behavior. self.load_features() - def _resolve_timeouts(self) -> Tuple[Optional[float], Optional[float]]: """This instance's (connect, read) seconds. Whatever it didn't set falls back, field by field, to the shared repository's attributes, so configuring feature_repo directly still works.""" + own_request_timeout = ( + None if isinstance(self._request_timeout, _Unset) else self._request_timeout + ) + # This instance's own arguments first, so their errors name them. + resolve_request_timeouts( + own_request_timeout, self._http_connect_timeout, self._http_read_timeout + ) request_timeout = ( feature_repo.request_timeout if isinstance(self._request_timeout, _Unset) else self._request_timeout ) - return resolve_request_timeouts( - request_timeout, - self._http_connect_timeout if self._http_connect_timeout is not None - else feature_repo.http_connect_timeout, - self._http_read_timeout if self._http_read_timeout is not None - else feature_repo.http_read_timeout, - ) + try: + return resolve_request_timeouts( + request_timeout, + self._http_connect_timeout if self._http_connect_timeout is not None + else feature_repo.http_connect_timeout, + self._http_read_timeout if self._http_read_timeout is not None + else feature_repo.http_read_timeout, + ) + except ValueError as e: + # Only an inherited value can still be invalid here: point at the + # shared repository instead of an argument the caller never passed. + raise ValueError(f"feature_repo.{e}") from e @contextmanager def _timeout_scope(self) -> Iterator[None]: diff --git a/growthbook/growthbook_client.py b/growthbook/growthbook_client.py index 79e0d18..42434ac 100644 --- a/growthbook/growthbook_client.py +++ b/growthbook/growthbook_client.py @@ -45,6 +45,7 @@ Experiment, DEFAULT_REQUEST_TIMEOUT, build_remote_eval_payload, + resolve_request_timeouts, features_from_dict, features_to_dicts, snapshot_user_context, @@ -652,6 +653,14 @@ def __init__( else Options(**options) if options else Options() ) + # Fail fast, like the sync constructor: otherwise a bad value only + # raises inside the first fetch, where the fetch's error handling + # swallows it and the client silently runs without features. + resolve_request_timeouts( + self.options.request_timeout, + self.options.http_connect_timeout, + self.options.http_read_timeout, + ) if self.options.remote_eval: validate_remote_eval_options( diff --git a/tests/test_request_timeout.py b/tests/test_request_timeout.py index d737858..d0df394 100644 --- a/tests/test_request_timeout.py +++ b/tests/test_request_timeout.py @@ -12,9 +12,10 @@ import time from unittest.mock import MagicMock, patch +import aiohttp import pytest -from growthbook import GrowthBook, FeatureRepository, feature_repo +from growthbook import GrowthBook, GrowthBookClient, FeatureRepository, feature_repo from growthbook.common_types import ( DEFAULT_REQUEST_TIMEOUT, Options, @@ -54,21 +55,68 @@ def accept_forever(): conn.close() -def test_fetch_is_bounded_by_default(black_hole): +def test_fetch_is_bounded_by_configured_timeout(black_hole): repo = FeatureRepository() repo.request_timeout = 0.3 done = threading.Event() + elapsed = [] def fetch(): + started = time.monotonic() try: repo._get(f"{black_hole}/api/features/k") except Exception: pass + elapsed.append(time.monotonic() - started) done.set() threading.Thread(target=fetch, daemon=True).start() assert done.wait(timeout=10), "the fetch never returned — timeout not applied" + assert elapsed[0] < 0.9, f"took {elapsed[0]:.2f}s for a 0.3s timeout" + + +@pytest.mark.asyncio +async def test_async_fetch_is_bounded_by_configured_timeout(black_hole): + repo = FeatureRepository() + repo.request_timeout = 0.3 + started = time.monotonic() + # The async fetch logs and swallows the timeout, returning no payload. + assert await repo._fetch_and_decode_async(black_hole, "k") is None + elapsed = time.monotonic() - started + + assert elapsed < 0.9, f"took {elapsed:.2f}s for a 0.3s timeout" + + +def test_async_opt_out_keeps_aiohttp_default_bound(): + # None used to produce ClientTimeout() with no limit at all, although the + # upgrade note promises the old async behavior (aiohttp's 300s default). + repo = FeatureRepository() + repo.request_timeout = None + assert repo._client_timeout() == aiohttp.client.DEFAULT_TIMEOUT + + +_DEFAULT = aiohttp.client.DEFAULT_TIMEOUT + + +@pytest.mark.parametrize( + "connect, read, expected", + [ + # One phase opted out: its aiohttp default may be None (sock_read + # always is), so the overall limit must stay as the backstop. + (2, None, (_DEFAULT.total, 2, _DEFAULT.sock_read)), + (None, 3, (_DEFAULT.total, _DEFAULT.sock_connect, 3)), + # Both bounded: total is dropped so a large payload isn't cut. + (2, 3, (None, 2, 3)), + ], +) +def test_async_timeout_per_phase(connect, read, expected): + repo = FeatureRepository() + repo.request_timeout = None + repo.http_connect_timeout = connect + repo.http_read_timeout = read + timeout = repo._client_timeout() + assert (timeout.total, timeout.sock_connect, timeout.sock_read) == expected def test_default_is_finite(): @@ -106,6 +154,38 @@ def test_invalid_timeout_fails_at_construction(): GrowthBook(request_timeout=0) +def test_invalid_timeout_fails_before_any_side_effect(): + # Validation used to run after plugins started and after the instance had + # registered its callback on the shared repository. + callbacks = list(feature_repo._feature_update_callbacks) + with patch.object(GrowthBook, "_initialize_plugins") as init_plugins: + with pytest.raises(ValueError): + GrowthBook(client_key="k", request_timeout=0) + init_plugins.assert_not_called() + assert feature_repo._feature_update_callbacks == callbacks + + +def test_invalid_async_options_fail_at_construction(): + # Raised inside the first fetch before, where it was swallowed and the + # client ran without features. + with pytest.raises(ValueError, match="request_timeout"): + GrowthBookClient(Options(request_timeout=0)) + with pytest.raises(ValueError, match="http_read_timeout"): + GrowthBookClient({"http_read_timeout": -1}) + + +def test_invalid_shared_repo_timeout_is_named_as_such(): + old = feature_repo.request_timeout + feature_repo.request_timeout = 0 + try: + with pytest.raises(ValueError, match=r"^feature_repo\.request_timeout"): + GrowthBook() + # An instance that sets its own value doesn't inherit the bad one. + GrowthBook(request_timeout=1) + finally: + feature_repo.request_timeout = old + + def test_timed_out_get_is_not_retried(black_hole): # urllib3's default Retry(3) re-sent the GET after each timeout, so the # real bound was about 4x the configured one. @@ -133,6 +213,19 @@ def test_injected_pool_is_kept_and_gets_the_timeout(): for call in injected.request.call_args_list: assert call.kwargs["timeout"].connect_timeout == 3 assert call.kwargs["timeout"].read_timeout == 3 + # Its owner's retry policy is kept, not overridden per request. + assert "retries" not in call.kwargs + + +def test_replaced_own_pool_is_released(): + repo = FeatureRepository() + own = repo._pool() + with patch.object(own, "clear") as clear: + injected = MagicMock() + repo.http = injected + assert repo._pool() is injected + clear.assert_called_once() + assert repo._own_http is None def test_constructor_does_not_touch_the_shared_repo(): From 764fe1a5d3f5787b11f202f7c703467bb8ba032c Mon Sep 17 00:00:00 2001 From: Volodymyr Nazarkevych Date: Mon, 30 Nov 2026 13:45:13 +0200 Subject: [PATCH 5/6] fix: bound DNS lookup, keep Options field order, reject non-finite timeouts --- README.md | 3 ++- growthbook/common_types.py | 30 ++++++++++++++++--------- growthbook/growthbook.py | 6 ++++- tests/test_request_timeout.py | 41 ++++++++++++++++++++++++++++++----- 4 files changed, 63 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 6c59f54..6b58092 100644 --- a/README.md +++ b/README.md @@ -355,7 +355,8 @@ gb = GrowthBook( `http_connect_timeout` and `http_read_timeout` override it per phase; either can be set on its own and the other inherits `request_timeout`. A value of `0` -or below is rejected at construction rather than treated as "no timeout" — +or below, NaN or infinity is rejected at construction rather than treated as +"no timeout" — pass `None` to opt out (the sync client then waits indefinitely, the async client falls back to aiohttp's own 300-second limit). The same options apply to `Options` for the async client, and are validated when `GrowthBookClient` diff --git a/growthbook/common_types.py b/growthbook/common_types.py index c669ae4..aabab8a 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 @@ -785,15 +786,8 @@ class Options: on_experiment_viewed: Optional[AsyncTrackingCallback] = None on_feature_usage: Optional[AsyncFeatureUsageCallback] = None tracking_plugins: Optional[List["PluginLike"]] = None - # Seconds allowed for a feature fetch or remote-eval call — connect and - # read alike. Finite by default so a slow or black-hole endpoint bounds - # startup instead of blocking it: on timeout the SDK falls back to cache or - # an inline payload. Pass None to opt back into waiting forever; 0 or a - # negative value is rejected at construction rather than silently meaning - # "no timeout". - request_timeout: Optional[float] = DEFAULT_REQUEST_TIMEOUT - # Finer-grained overrides. Either may be set on its own; whichever is None - # falls back to request_timeout. + # Per-phase overrides of request_timeout (declared last, below). Either + # may be set on its own; whichever is None falls back to request_timeout. http_connect_timeout: Optional[float] = None http_read_timeout: Optional[float] = None event_logger: Optional[AsyncEventLogger] = None @@ -808,6 +802,15 @@ class Options: # sticky_bucket_cache_size. Non-positive values disable caching. sticky_bucket_cache_ttl: float = 0 sticky_bucket_cache_size: int = 1000 + # Appended last so every existing positional argument keeps its meaning + # (Options is a plain positional dataclass). + # Seconds allowed for a feature fetch or remote-eval call — connect and + # read alike. Finite by default so a slow or black-hole endpoint bounds + # startup instead of blocking it: on timeout the SDK falls back to cache or + # an inline payload. Pass None to opt out (the async client then keeps + # aiohttp's own limit); 0, a negative or a non-finite value is rejected at + # construction rather than silently meaning "no timeout". + request_timeout: Optional[float] = DEFAULT_REQUEST_TIMEOUT @dataclass @@ -934,7 +937,7 @@ def resolve_request_timeouts( request_timeout. `None` throughout means "wait forever" — an explicit opt-out, never the result of a falsy 0. - Raises ValueError on a non-positive or non-numeric value. Rejecting rather + Raises ValueError on a non-positive, non-finite or non-numeric value. Rejecting rather than clamping is deliberate: `timeout=0` reads as "no timeout" in several HTTP stacks, so silently accepting it would turn a typo into the unbounded wait this default exists to prevent.""" @@ -952,6 +955,13 @@ def resolve_request_timeouts( f"{name} must be greater than 0, got {value!r}; " "pass None to wait indefinitely" ) + if not math.isfinite(value): + # NaN slips past `<= 0` (every comparison is False) and infinity + # is not a usable socket timeout; None is the way to opt out. + raise ValueError( + f"{name} must be a finite number of seconds, got {value!r}; " + "pass None to wait indefinitely" + ) connect = connect_timeout if connect_timeout is not None else request_timeout read = read_timeout if read_timeout is not None else request_timeout diff --git a/growthbook/growthbook.py b/growthbook/growthbook.py index ad6b042..1265f22 100644 --- a/growthbook/growthbook.py +++ b/growthbook/growthbook.py @@ -598,10 +598,14 @@ def _client_timeout(self) -> "aiohttp.ClientTimeout": # out with None keeps aiohttp's default for it, and since that default # can itself be None (sock_read, and sock_connect on older aiohttp), # aiohttp's overall limit stays as the backstop. + # The connect limit goes to `connect` as well as `sock_connect`: + # sock_connect covers only the TCP connect, while `connect` covers + # acquiring the connection as a whole, hostname lookup included. Without + # it a stalled DNS lookup has no deadline once total is dropped. both_bounded = connect is not None and read is not None return aiohttp.ClientTimeout( total=None if both_bounded else default.total, - connect=default.connect, + connect=connect if connect is not None else default.connect, sock_connect=connect if connect is not None else default.sock_connect, sock_read=read if read is not None else default.sock_read, ) diff --git a/tests/test_request_timeout.py b/tests/test_request_timeout.py index d0df394..77c943b 100644 --- a/tests/test_request_timeout.py +++ b/tests/test_request_timeout.py @@ -6,6 +6,7 @@ black-hole endpoint blocked startup forever with no caller-visible bound. """ +import dataclasses import inspect import socket import threading @@ -104,10 +105,11 @@ def test_async_opt_out_keeps_aiohttp_default_bound(): [ # One phase opted out: its aiohttp default may be None (sock_read # always is), so the overall limit must stay as the backstop. - (2, None, (_DEFAULT.total, 2, _DEFAULT.sock_read)), - (None, 3, (_DEFAULT.total, _DEFAULT.sock_connect, 3)), - # Both bounded: total is dropped so a large payload isn't cut. - (2, 3, (None, 2, 3)), + (2, None, (_DEFAULT.total, 2, 2, _DEFAULT.sock_read)), + (None, 3, (_DEFAULT.total, _DEFAULT.connect, _DEFAULT.sock_connect, 3)), + # Both bounded: total is dropped so a large payload isn't cut, and the + # connect limit also covers hostname lookup via `connect`. + (2, 3, (None, 2, 2, 3)), ], ) def test_async_timeout_per_phase(connect, read, expected): @@ -116,7 +118,15 @@ def test_async_timeout_per_phase(connect, read, expected): repo.http_connect_timeout = connect repo.http_read_timeout = read timeout = repo._client_timeout() - assert (timeout.total, timeout.sock_connect, timeout.sock_read) == expected + assert (timeout.total, timeout.connect, timeout.sock_connect, timeout.sock_read) == expected + + +def test_async_default_bounds_dns_lookup(): + # sock_connect covers only the TCP connect. With total dropped and + # connect left None, a stalled DNS lookup had no deadline at all. + timeout = FeatureRepository()._client_timeout() + assert timeout.total is None + assert timeout.connect == DEFAULT_REQUEST_TIMEOUT def test_default_is_finite(): @@ -149,6 +159,17 @@ def test_zero_is_rejected_rather_than_disabling(): resolve_request_timeouts("2") # type: ignore[arg-type] +@pytest.mark.parametrize("value", [float("nan"), float("inf")]) +def test_non_finite_timeout_is_rejected(value): + # NaN passes `value <= 0`, and infinity is not a usable socket timeout. + with pytest.raises(ValueError, match="finite"): + resolve_request_timeouts(value) + with pytest.raises(ValueError, match="finite"): + GrowthBook(http_read_timeout=value) + with pytest.raises(ValueError, match="finite"): + GrowthBookClient(Options(http_connect_timeout=value)) + + def test_invalid_timeout_fails_at_construction(): with pytest.raises(ValueError): GrowthBook(request_timeout=0) @@ -281,3 +302,13 @@ def test_request_timeout_is_the_last_constructor_parameter(): params = list(inspect.signature(GrowthBook.__init__).parameters) assert params[-1] == "request_timeout" assert params.index("http_connect_timeout") == params.index("forcedVariations") + 1 + + +def test_options_request_timeout_is_the_last_field(): + # Options is a positional dataclass: inserting the field mid-list shifted + # http_connect_timeout, http_read_timeout, event_logger and the rest. + names = [f.name for f in dataclasses.fields(Options)] + assert names[-1] == "request_timeout" + assert names.index("http_connect_timeout") == names.index("tracking_plugins") + 1 + assert names.index("http_read_timeout") == names.index("http_connect_timeout") + 1 + assert names.index("event_logger") == names.index("http_read_timeout") + 1 From 2412979338f841210a4837a1c5c92b108e447dff Mon Sep 17 00:00:00 2001 From: Volodymyr Nazarkevych Date: Thu, 3 Dec 2026 15:47:31 +0200 Subject: [PATCH 6/6] docs: fix async opt-out advice in the request timeout upgrade note feature_repo.request_timeout = None doesn't reach GrowthBookClient: its repository takes Options.request_timeout, which still defaults to 2s. Show Options(request_timeout=None) for the async client and keep the shared setting as a sync-only option. --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d13c655..ebfc597 100644 --- a/README.md +++ b/README.md @@ -387,8 +387,9 @@ as is, including its retry policy; only the timeouts are applied per request. Retries are disabled only on the pool the SDK creates itself. **Upgrading:** requests used to wait indefinitely (sync) or up to 300 seconds -(async) by default. To keep that behavior, pass `request_timeout=None`, or set -`feature_repo.request_timeout = None` once for the whole process. +(async) by default. To keep that behavior, use `GrowthBook(request_timeout=None)` +or `GrowthBookClient(Options(request_timeout=None))`. For sync clients only, +you can also set `feature_repo.request_timeout = None` once for the whole process. Here's a full example: