Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 36 additions & 11 deletions growthbook/growthbook.py
Original file line number Diff line number Diff line change
Expand Up @@ -504,12 +504,39 @@ def user_agent_suffix(self) -> Optional[str]:
def user_agent_suffix(self, value: Optional[str]) -> None:
self._user_agent_suffix = value

def _http_timeout(self) -> Optional[Timeout]:
# Each timeout is optional on its own; an unset one stays unbounded.
if self.http_connect_timeout is None and self.http_read_timeout is None:
return None
return Timeout(connect=self.http_connect_timeout, read=self.http_read_timeout)

def _aiohttp_session_kwargs(self) -> Dict[str, Any]:
# Async counterpart of _http_timeout(). Passing a bare ClientTimeout
# would drop aiohttp's own defaults (overall request limit, socket
# connect limit), so start from them and override only what is set.
if self.http_connect_timeout is None and self.http_read_timeout is None:
return {}
default = aiohttp.client.DEFAULT_TIMEOUT
return {
"timeout": aiohttp.ClientTimeout(
total=default.total,
connect=default.connect,
sock_connect=(
self.http_connect_timeout
if self.http_connect_timeout is not None
else default.sock_connect
),
sock_read=(
self.http_read_timeout
if self.http_read_timeout is not None
else default.sock_read
),
)
}

# Perform the GET request (separate method for easy mocking)
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)
self.http = self.http or PoolManager(timeout=self._http_timeout())
return self.http.request("GET", url, headers=headers or {})

def _get_headers(self, client_key: str, existing_headers: Optional[Dict[str, str]] = None) -> Dict[str, str]:
Expand All @@ -525,10 +552,7 @@ 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)
self.http = self.http or PoolManager(timeout=self._http_timeout())
body = json.dumps(payload).encode("utf-8")
return self.http.request("POST", url, body=body, headers=headers or {})

Expand Down Expand Up @@ -560,7 +584,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(**self._aiohttp_session_kwargs()) as session:
async with session.post(url, json=payload, headers=headers) as response:
if response.status >= 400:
logger.warning(
Expand Down Expand Up @@ -657,7 +681,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(**self._aiohttp_session_kwargs()) as session:
async with session.get(url, headers=headers) as response:
# Handle 304 Not Modified - content hasn't changed
if response.status == 304:
Expand Down Expand Up @@ -1090,8 +1114,9 @@ def __init__(
# before the first eval. Matches the JS SDK init() behavior.
self.load_features()

if http_connect_timeout and http_read_timeout:
if http_connect_timeout is not None:
feature_repo.http_connect_timeout = http_connect_timeout
if http_read_timeout is not None:
feature_repo.http_read_timeout = http_read_timeout

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Startup ignores configured timeouts

The new one-sided timeout support still fails when GrowthBook loads during construction. With a fresh feature_repo, enabling streaming, stale_while_revalidate, or remote_eval calls load_features() before these assignments. That request creates PoolManager(timeout=None). Later requests reuse the same pool, so the configured timeout never applies and requests can wait indefinitely.

Move these assignments before plugins and automatic loads, and add a constructor-level test.

Knowledge Base Used: Client lifecycle and feature refresh

Prompt To Fix With AI
This is a comment left during a code review.
Path: growthbook/growthbook.py
Line: 1117-1120

Comment:
**Startup ignores configured timeouts**

The new one-sided timeout support still fails when `GrowthBook` loads during construction. With a fresh `feature_repo`, enabling `streaming`, `stale_while_revalidate`, or `remote_eval` calls `load_features()` before these assignments. That request creates `PoolManager(timeout=None)`. Later requests reuse the same pool, so the configured timeout never applies and requests can wait indefinitely.

Move these assignments before plugins and automatic loads, and add a constructor-level test.

**Knowledge Base Used:** [Client lifecycle and feature refresh](https://app.greptile.com/-/switch-tenant?tenant=growthbook&next=%2Fcustom-context%2Fknowledge-base%2Fgrowthbook%2Fgrowthbook-python%2F-%2Fdocs%2Fclient-lifecycle-and-feature-refresh.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.


def _remote_eval_payload(self) -> Dict[str, Any]:
Expand Down
129 changes: 129 additions & 0 deletions tests/test_http_timeouts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
"""Options.http_connect_timeout / http_read_timeout must reach every HTTP path."""
from unittest.mock import patch

import aiohttp
import pytest

from growthbook.growthbook import FeatureRepository


class _FakeResponse:
status = 500

async def __aenter__(self):
return self

async def __aexit__(self, *exc):
return False


class _FakeSession:
"""Stands in for aiohttp.ClientSession and records its constructor kwargs."""

created = []

def __init__(self, **kwargs):
self.kwargs = kwargs
_FakeSession.created.append(self)

async def __aenter__(self):
return self

async def __aexit__(self, *exc):
return False

def get(self, *args, **kwargs):
return _FakeResponse()

def post(self, *args, **kwargs):
return _FakeResponse()


@pytest.fixture
def fake_session():
_FakeSession.created = []
with patch("growthbook.growthbook.aiohttp.ClientSession", _FakeSession):
yield _FakeSession


def _repo(connect=None, read=None):
repo = FeatureRepository()
repo.http_connect_timeout = connect
repo.http_read_timeout = read
return repo


@pytest.mark.asyncio
async def test_async_get_applies_http_timeouts(fake_session):
repo = _repo(connect=3, read=7)

assert await repo._fetch_and_decode_async("https://cdn.growthbook.io", "sdk-abc123") is None

(session,) = fake_session.created
timeout = session.kwargs["timeout"]
assert isinstance(timeout, aiohttp.ClientTimeout)
assert timeout.sock_connect == 3
assert timeout.sock_read == 7


@pytest.mark.asyncio
async def test_async_post_applies_http_timeouts(fake_session):
repo = _repo(connect=3, read=7)

assert await repo._fetch_and_decode_post_async(
"https://cdn.growthbook.io", "sdk-abc123", {"attributes": {}}
) is None

(session,) = fake_session.created
timeout = session.kwargs["timeout"]
assert timeout.sock_connect == 3
assert timeout.sock_read == 7


@pytest.mark.asyncio
@pytest.mark.parametrize("connect, read", [(3, 7), (3, None), (None, 7)])
async def test_async_keeps_aiohttp_defaults_for_unset_fields(fake_session, connect, read):
default = aiohttp.client.DEFAULT_TIMEOUT
repo = _repo(connect=connect, read=read)

await repo._fetch_and_decode_async("https://cdn.growthbook.io", "sdk-abc123")

timeout = fake_session.created[0].kwargs["timeout"]
# The overall request limit must survive setting either option.
assert timeout.total == default.total
assert timeout.connect == default.connect
assert timeout.sock_connect == (connect if connect is not None else default.sock_connect)
assert timeout.sock_read == (read if read is not None else default.sock_read)


@pytest.mark.asyncio
async def test_async_keeps_aiohttp_defaults_without_timeouts(fake_session):
repo = _repo()

await repo._fetch_and_decode_async("https://cdn.growthbook.io", "sdk-abc123")

assert "timeout" not in fake_session.created[0].kwargs


@pytest.mark.parametrize(
"connect, read",
[(3, 7), (3, None), (None, 7)],
)
def test_sync_pool_manager_applies_each_timeout(connect, read):
repo = _repo(connect=connect, read=read)

with patch("growthbook.growthbook.PoolManager") as pool_manager:
repo._get("https://cdn.growthbook.io/api/features/sdk-abc123")

timeout = pool_manager.call_args.kwargs["timeout"]
assert timeout.connect_timeout == connect
assert timeout.read_timeout == read


def test_sync_pool_manager_has_no_timeout_by_default():
repo = _repo()

with patch("growthbook.growthbook.PoolManager") as pool_manager:
repo._get("https://cdn.growthbook.io/api/features/sdk-abc123")

assert pool_manager.call_args.kwargs["timeout"] is None