:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement the growthbook import source (#108648)
Tom Owers71091f1b601e
diff --git a/frontend/public/services/growthbook.png b/frontend/public/services/growthbook.pngnew file mode 100644index 000000000000..3a378e946900Binary files /dev/null and b/frontend/public/services/growthbook.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex fc7f0eda43e3..c58a4ab23e8b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -352,6 +352,7 @@ the row lists both.| greenhouse | HTTP | requests | ✅ || gridly | HTTP | requests | ✅ || groq | HTTP | requests | ✅ |+| growthbook | HTTP | requests + `rest_source.RESTClient` | ✅ || guardian | HTTP | requests | ✅ || gumroad | HTTP | requests | ✅ || guru | HTTP | requests | ✅ |@@ -1127,7 +1128,6 @@ doesn't conflict with concurrent PRs.- google_tasks- google_workspace_admin_reports- greythr-- growthbook- guesty- gumloop- harnessdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/growthbook.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/growthbook.pyindex 2b14e8766b96..09c99e59278a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/growthbook.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/growthbook.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass GrowthBookSourceConfig(config.Config):- pass+ api_key: str+ base_url: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/canonical_descriptions.pynew file mode 100644index 000000000000..5944d554fdb3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/canonical_descriptions.py@@ -0,0 +1,26 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "features": {+ "description": "Feature flags with default values, targeting rules, environments, and revision metadata."+ },+ "experiments": {"description": "Experiments with hypotheses, variations, phases, analysis settings, and status."},+ "metrics": {+ "description": "Legacy metric definitions with data sources, query settings, and measurement behavior."+ },+ "fact_tables": {"description": "Fact table definitions with SQL, identifier columns, and data source references."},+ "fact_metrics": {+ "description": "Metrics built from fact tables, including numerator, denominator, and analysis settings."+ },+ "segments": {"description": "Reusable experiment populations defined by queries or fact table filters."},+ "dimensions": {"description": "Query-based dimensions for grouping experiment results."},+ "projects": {"description": "Projects that organize feature flags, experiments, and access settings."},+ "environments": {+ "description": "Feature flag environments and their default states, project scopes, and parent environments."+ },+ "saved_groups": {"description": "Reusable targeting groups defined by attribute values or conditions."},+ "data_sources": {"description": "Data source definitions with identifier types and experiment assignment queries."},+ "members": {"description": "Organization members with global roles, project roles, and environment access."},+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/growthbook.py b/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/growthbook.pynew file mode 100644index 000000000000..f70c2de8b5b8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/growthbook.py@@ -0,0 +1,141 @@+from typing import Any+from urllib.parse import urlsplit++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import schema_for_resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.growthbook import (+ GrowthBookSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.growthbook.settings import (+ DEFAULT_BASE_URL,+ ENDPOINTS,+ PAGE_SIZE,+)++INVALID_URL = "Enter a GrowthBook API base URL using HTTPS, without credentials, query parameters, or a fragment."+UNSAFE_HOST = "The GrowthBook API host is not allowed. Use a publicly reachable host."+++@frozen+class GrowthBookResumeConfig:+ next_offset: int+++def client_config(config: GrowthBookSourceConfig, team_id: int) -> ClientConfig:+ base_url = ((config.base_url or "").strip() or DEFAULT_BASE_URL).rstrip("/")+ try:+ parsed = urlsplit(base_url)+ if (+ parsed.scheme != "https"+ or not parsed.hostname+ or parsed.username is not None+ or parsed.password is not None+ or parsed.query+ or parsed.fragment+ or parsed.port == 0+ or "\\" in base_url+ or "%" in parsed.netloc+ or any(character.isspace() for character in base_url)+ ):+ raise ValueError(INVALID_URL)+ except ValueError:+ raise ValueError(INVALID_URL) from None+ valid, _ = _is_host_safe(parsed.hostname, team_id)+ if not valid:+ raise ValueError(UNSAFE_HOST)+ return {+ "base_url": base_url,+ "auth": {"type": "bearer", "token": config.api_key},+ "headers": {"Accept": "application/json"},+ "allowed_hosts": [],+ "allow_redirects": False,+ "request_timeout": 30,+ }+++def endpoint_config(name: str, api_version: str, *, probe: bool = False) -> Endpoint:+ endpoint = schema_for_resource(ENDPOINTS, name)+ return {+ "path": endpoint.path.format(api_version=api_version),+ "data_selector": endpoint.data_selector,+ "data_selector_required": True,+ "params": {**endpoint.params, "limit": 1 if probe else PAGE_SIZE, "offset": 0} if endpoint.paginated else {},+ "paginator": {"type": "cursor", "cursor_path": "nextOffset", "cursor_param": "offset"}+ if endpoint.paginated and not probe+ else "single_page",+ }+++def probe_credentials(config: GrowthBookSourceConfig, team_id: int, schema_name: str, api_version: str) -> None:+ client = client_config(config, team_id)+ client["max_retries"] = 1+ resource = rest_api_resource(+ {+ "client": client,+ "resources": [{"name": schema_name, "endpoint": endpoint_config(schema_name, api_version, probe=True)}],+ },+ team_id,+ "growthbook-credential-validation",+ None,+ )+ list(resource)+++def growthbook_source(+ config: GrowthBookSourceConfig,+ inputs: SourceInputs,+ resumable_source_manager: ResumableSourceManager[GrowthBookResumeConfig],+ api_version: str,+) -> SourceResponse:+ endpoint = schema_for_resource(ENDPOINTS, inputs.schema_name)+ rest_config: RESTAPIConfig = {+ "client": client_config(config, inputs.team_id),+ "resources": [+ {+ "name": inputs.schema_name,+ "endpoint": endpoint_config(inputs.schema_name, api_version),+ "write_disposition": "replace",+ }+ ],+ }+ initial_state: dict[str, Any] | None = None+ if endpoint.paginated and resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ initial_state = {"cursor": resume.next_offset}++ def save_checkpoint(state: dict[str, Any] | None) -> None:+ if state is not None:+ resumable_source_manager.save_state(GrowthBookResumeConfig(next_offset=int(state["cursor"])))++ resource = rest_api_resource(+ rest_config,+ inputs.team_id,+ inputs.job_id,+ None,+ resume_hook=save_checkpoint if endpoint.paginated else None,+ initial_paginator_state=initial_state,+ )+ return SourceResponse(+ name=inputs.schema_name,+ items=lambda: resource,+ primary_keys=list(endpoint.primary_keys),+ partition_keys=[endpoint.partition_key] if endpoint.partition_key else None,+ partition_mode="datetime" if endpoint.partition_key else None,+ partition_format="month" if endpoint.partition_key else None,+ partition_size=1 if endpoint.partition_key else None,+ sort_mode=None,+ supports_resume=endpoint.paginated,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/settings.pynew file mode 100644index 000000000000..25335aef8291--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/settings.py@@ -0,0 +1,42 @@+from dataclasses import field++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.types import IncrementalField++DEFAULT_BASE_URL = "https://api.growthbook.io/api"+PAGE_SIZE = 100+++@frozen+class GrowthBookEndpoint:+ path: str+ data_selector: str+ primary_keys: tuple[str, ...] = ("id",)+ partition_key: str | None = "dateCreated"+ paginated: bool = True+ params: dict[str, str] = field(default_factory=dict)+++# GrowthBook only exposes v2 for features; the other entities retain their v1 routes.+ENDPOINTS: dict[str, GrowthBookEndpoint] = {+ "features": GrowthBookEndpoint(+ path="{api_version}/features", data_selector="features", params={"archived": "true"}+ ),+ "experiments": GrowthBookEndpoint(path="v1/experiments", data_selector="experiments"),+ "metrics": GrowthBookEndpoint(path="v1/metrics", data_selector="metrics", params={"includeArchived": "true"}),+ "fact_tables": GrowthBookEndpoint(path="v1/fact-tables", data_selector="factTables"),+ "fact_metrics": GrowthBookEndpoint(path="v1/fact-metrics", data_selector="factMetrics"),+ "segments": GrowthBookEndpoint(path="v1/segments", data_selector="segments"),+ "dimensions": GrowthBookEndpoint(path="v1/dimensions", data_selector="dimensions"),+ "projects": GrowthBookEndpoint(path="v1/projects", data_selector="projects"),+ "environments": GrowthBookEndpoint(+ path="v1/environments", data_selector="environments", partition_key=None, paginated=False+ ),+ "saved_groups": GrowthBookEndpoint(path="v1/saved-groups", data_selector="savedGroups"),+ "data_sources": GrowthBookEndpoint(path="v1/data-sources", data_selector="dataSources"),+ "members": GrowthBookEndpoint(path="v1/members", data_selector="members", partition_key=None),+}++# Timestamp fields in responses do not imply server-side timestamp filtering.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/source.pyindex 25ecad8c2739..04d9a89b31f0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/source.py@@ -1,28 +1,151 @@from typing import cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from requests.exceptions import HTTPError++from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.growthbook import (GrowthBookSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.growthbook.growthbook import (+ INVALID_URL,+ UNSAFE_HOST,+ GrowthBookResumeConfig,+ growthbook_source,+ probe_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.growthbook.settings import (+ DEFAULT_BASE_URL,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+INVALID_CREDENTIALS = "Your GrowthBook API key is invalid or expired. Update the key and reconnect."+MISSING_PERMISSIONS = "Your GrowthBook API key lacks read access to this table. Update its permissions and try again."+@SourceRegistry.register-class GrowthBookSource(SimpleSource[GrowthBookSourceConfig]):+class GrowthBookSource(ResumableSource[GrowthBookSourceConfig, GrowthBookResumeConfig]):+ lists_tables_without_credentials = True+ supported_versions = ("v2",)+ default_version = "v2"+ api_docs_url = "https://docs.growthbook.io/api/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.GROWTHBOOK+ @property+ def connection_host_fields(self) -> list[str]:+ return ["base_url"]++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.growthbook.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": INVALID_CREDENTIALS,+ "403 Client Error": MISSING_PERMISSIONS,+ INVALID_URL: INVALID_URL,+ UNSAFE_HOST: UNSAFE_HOST,+ }++ def get_schemas(+ self,+ config: GrowthBookSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: GrowthBookSourceConfig,+ team_id: int,+ schema_name: str | None = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ if schema_name is not None and schema_name not in ENDPOINTS:+ return False, "Unknown GrowthBook table. Refresh the table list and try again."+ try:+ probe_credentials(config, team_id, schema_name or "features", self.resolve_api_version(api_version))+ except ValueError as error:+ return False, str(error)+ except HTTPError as error:+ status = error.response.status_code if error.response is not None else None+ if status == 401:+ return False, INVALID_CREDENTIALS+ if status == 403:+ return (True, None) if schema_name is None else (False, MISSING_PERMISSIONS)+ raise+ return True, None++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GrowthBookResumeConfig]:+ return ResumableSourceManager(inputs, GrowthBookResumeConfig)++ def source_for_pipeline(+ self,+ config: GrowthBookSourceConfig,+ resumable_source_manager: ResumableSourceManager[GrowthBookResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return growthbook_source(config, inputs, resumable_source_manager, self.resolve_api_version(inputs.api_version))+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=ExternalDataSourceType.GROWTHBOOK,category=DataWarehouseSourceCategory.ANALYTICS,label="GrowthBook",+ docsUrl="https://posthog.com/docs/cdp/sources/growthbook",iconPath="/static/services/growthbook.png",keywords=["feature flags", "experiments", "ab testing", "growthbook"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ caption="Connect with a readonly secret API key from Settings > API Keys, or a personal access token with read access to the selected tables.",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ placeholder="secret_...",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ secret=True,+ ),+ SourceFieldInputConfig(+ name="base_url",+ label="API base URL",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ secret=False,+ placeholder=DEFAULT_BASE_URL,+ caption="For self-hosted GrowthBook, enter your public HTTPS API URL including /api.",+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/tests/conftest.py b/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/tests/conftest.pynew file mode 100644index 000000000000..8f9f23f59fb1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/tests/conftest.py@@ -0,0 +1,58 @@+from collections.abc import Iterator++import pytest+from unittest.mock import MagicMock, patch++import responses+import structlog++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.growthbook import (+ GrowthBookSourceConfig,+)+++def config() -> GrowthBookSourceConfig:+ return GrowthBookSourceConfig.from_dict({"api_key": "secret_test_growthbook"})+++def inputs() -> SourceInputs:+ return SourceInputs(+ schema_name="features",+ schema_id="schema-test",+ source_id="source-test",+ team_id=123,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id="job-test",+ logger=structlog.get_logger(),+ reset_pipeline=False,+ )+++def manager() -> MagicMock:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ return manager+++def http() -> Iterator[responses.RequestsMock]:+ with responses.RequestsMock() as http:+ yield http++[email protected](autouse=True)+def safe_host() -> Iterator[MagicMock]:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.growthbook.growthbook._is_host_safe",+ return_value=(True, None),+ ) as safe:+ yield safediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/tests/test_growthbook.py b/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/tests/test_growthbook.pynew file mode 100644index 000000000000..b8b802a8bff4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/tests/test_growthbook.py@@ -0,0 +1,168 @@+from collections.abc import Iterable+from typing import Any, cast+from urllib.parse import parse_qs, urlsplit++import pytest+from unittest.mock import MagicMock, patch++import responses+from requests.exceptions import HTTPError++from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.growthbook import (+ GrowthBookSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.growthbook.growthbook import (+ GrowthBookResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.growthbook.source import GrowthBookSource++[email protected]("resume_offset", [None, 100])+def test_pagination_and_resume(+ config: GrowthBookSourceConfig,+ inputs: SourceInputs,+ manager: MagicMock,+ http: responses.RequestsMock,+ resume_offset: int | None,+) -> None:+ manager.can_resume.return_value = resume_offset is not None+ manager.load_state.return_value = GrowthBookResumeConfig(next_offset=resume_offset or 0)+ offset = resume_offset or 0+ url = "https://api.growthbook.io/api/v2/features"+ first = {"id": "flag-one", "dateCreated": "2025-01-01T00:00:00Z", "archived": True}+ last = {"id": "flag-two", "dateCreated": "2025-01-02T00:00:00Z"}+ http.add(responses.GET, url, json={"features": [first], "hasMore": True, "nextOffset": offset + 7})+ http.add(responses.GET, url, json={"features": [last], "hasMore": False, "nextOffset": None})+ result = GrowthBookSource().source_for_pipeline(config, manager, inputs)+ batches = iter(cast(Iterable[Any], result.items()))+ assert next(batches) == [first]+ manager.save_state.assert_not_called()+ assert next(batches) == [last]+ manager.save_state.assert_called_once_with(GrowthBookResumeConfig(next_offset=offset + 7))+ assert list(batches) == []+ assert len(http.calls) == 2+ for call, expected_offset in zip(http.calls, [offset, offset + 7]):+ assert parse_qs(urlsplit(call.request.url).query) == {+ "limit": ["100"],+ "offset": [str(expected_offset)],+ "archived": ["true"],+ }+ assert call.request.headers["Authorization"] == "Bearer secret_test_growthbook"+ assert result.primary_keys == ["id"]+ assert result.partition_keys == ["dateCreated"]+ assert result.sort_mode is None+++ ("table", "path", "selector", "params", "partition_keys"),+ [+ ("experiments", "experiments", "experiments", {}, ["dateCreated"]),+ ("metrics", "metrics", "metrics", {"includeArchived": ["true"]}, ["dateCreated"]),+ ("fact_tables", "fact-tables", "factTables", {}, ["dateCreated"]),+ ("fact_metrics", "fact-metrics", "factMetrics", {}, ["dateCreated"]),+ ("segments", "segments", "segments", {}, ["dateCreated"]),+ ("dimensions", "dimensions", "dimensions", {}, ["dateCreated"]),+ ("projects", "projects", "projects", {}, ["dateCreated"]),+ ("environments", "environments", "environments", {}, None),+ ("saved_groups", "saved-groups", "savedGroups", {}, ["dateCreated"]),+ ("data_sources", "data-sources", "dataSources", {}, ["dateCreated"]),+ ("members", "members", "members", {}, None),+ ],+)+def test_table_responses_and_full_refresh_requests(+ config: GrowthBookSourceConfig,+ inputs: SourceInputs,+ manager: MagicMock,+ http: responses.RequestsMock,+ table: str,+ path: str,+ selector: str,+ params: dict[str, list[str]],+ partition_keys: list[str] | None,+) -> None:+ inputs.schema_name = table+ inputs.db_incremental_field_last_value = "2099-01-01T00:00:00Z"+ rows = [{"id": "example-record", "dateCreated": "2025-01-01T00:00:00Z"}]+ payload: dict[str, Any] = (+ {selector: rows} if table == "environments" else {selector: rows, "hasMore": False, "nextOffset": None}+ )+ http.add(responses.GET, f"https://api.growthbook.io/api/v1/{path}", json=payload)+ result = GrowthBookSource().source_for_pipeline(config, manager, inputs)+ assert list(cast(Iterable[Any], result.items())) == [rows]+ assert result.name == table+ assert result.primary_keys == ["id"]+ assert result.partition_keys == partition_keys+ assert len(http.calls) == 1+ assert parse_qs(urlsplit(http.calls[0].request.url).query) == (+ {} if table == "environments" else {"limit": ["100"], "offset": ["0"], **params}+ )+ if table == "environments":+ manager.can_resume.assert_not_called()+ assert not result.supports_resume++[email protected]("empty", [True, False])+def test_empty_collection_or_missing_envelope(+ config: GrowthBookSourceConfig,+ inputs: SourceInputs,+ manager: MagicMock,+ http: responses.RequestsMock,+ empty: bool,+) -> None:+ payload: dict[str, Any] = {"features": [], "nextOffset": None, "hasMore": False} if empty else {"unexpected": []}+ http.add(responses.GET, "https://api.growthbook.io/api/v2/features", json=payload)+ result = GrowthBookSource().source_for_pipeline(config, manager, inputs)+ if empty:+ assert list(cast(Iterable[Any], result.items())) == []+ else:+ with pytest.raises(ValueError, match="matched nothing"):+ list(cast(Iterable[Any], result.items()))+ assert len(http.calls) == 1+ manager.save_state.assert_not_called()++[email protected]("status", [401, 403, 429, 500])+def test_http_error_classification(+ config: GrowthBookSourceConfig,+ inputs: SourceInputs,+ manager: MagicMock,+ http: responses.RequestsMock,+ status: int,+) -> None:+ url = "https://api.growthbook.io/api/v2/features"+ http.add(responses.GET, url, status=status, json={"message": "Request failed"}, headers={"Retry-After": "1"})+ source = GrowthBookSource()+ if status in (401, 403):+ with pytest.raises(HTTPError) as error:+ list(cast(Iterable[Any], source.source_for_pipeline(config, manager, inputs).items()))+ assert error_message_matches(str(error.value), source.get_non_retryable_errors())+ assert len(http.calls) == 1+ else:+ http.add(responses.GET, url, json={"features": [{"id": "recovered"}], "nextOffset": None})+ with patch.object(cast(Any, RESTClient._send_request).retry, "sleep"):+ assert list(cast(Iterable[Any], source.source_for_pipeline(config, manager, inputs).items())) == [+ [{"id": "recovered"}]+ ]+ assert len(http.calls) == 2+++def test_self_hosted_url_and_redirect_rejection(+ inputs: SourceInputs,+ manager: MagicMock,+ http: responses.RequestsMock,+) -> None:+ config = GrowthBookSourceConfig.from_dict(+ {"api_key": "secret_test_growthbook", "base_url": "https://flags.example.com/custom/api/"}+ )+ http.add(+ responses.GET,+ "https://flags.example.com/custom/api/v2/features",+ status=302,+ headers={"Location": "https://other.example.com/api/v2/features"},+ )+ with pytest.raises(ValueError, match="redirect"):+ list(cast(Iterable[Any], GrowthBookSource().source_for_pipeline(config, manager, inputs).items()))+ assert len(http.calls) == 1diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/tests/test_growthbook_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/tests/test_growthbook_source.pynew file mode 100644index 000000000000..a8d58b0a17c7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/growthbook/tests/test_growthbook_source.py@@ -0,0 +1,130 @@+from urllib.parse import parse_qs, urlsplit++import pytest+from unittest.mock import MagicMock++import responses++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (+ RESTClientRetryableError,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import UnknownResourceError+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.growthbook import (+ GrowthBookSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.growthbook.source import GrowthBookSource+++ ("status", "schema_name", "expected", "message"),+ [+ (200, None, True, None),+ (401, None, False, "invalid or expired"),+ (403, None, True, None),+ (403, "projects", False, "read access"),+ (200, "projects", True, None),+ ],+)+def test_credential_probe_status_mapping(+ config: GrowthBookSourceConfig,+ http: responses.RequestsMock,+ status: int,+ schema_name: str | None,+ expected: bool,+ message: str | None,+) -> None:+ path = "v1/projects" if schema_name else "v2/features"+ selector = schema_name or "features"+ http.add(+ responses.GET,+ f"https://api.growthbook.io/api/{path}",+ status=status,+ json={selector: [], "nextOffset": 100, "hasMore": True},+ )+ valid, error = GrowthBookSource().validate_credentials(config, 123, schema_name)+ assert valid is expected+ if message is not None:+ assert error is not None and message in error+ else:+ assert error is None+ assert len(http.calls) == 1+ assert parse_qs(urlsplit(http.calls[0].request.url).query)["limit"] == ["1"]+ assert http.calls[0].request.headers["Authorization"] == "Bearer secret_test_growthbook"++[email protected]("status", [429, 503])+def test_transient_probe_failure_is_not_bad_credentials(+ config: GrowthBookSourceConfig,+ http: responses.RequestsMock,+ status: int,+) -> None:+ http.add(responses.GET, "https://api.growthbook.io/api/v2/features", status=status, json={"message": "Try again"})+ with pytest.raises(RESTClientRetryableError):+ GrowthBookSource().validate_credentials(config, 123)+++ "base_url",+ [+ "http://flags.example.com/api",+ "https://user:[email protected]/api",+ "https://flags.example.com/api?key=value",+ "https://flags.example.com/api#fragment",+ "https://",+ "https://flags.example.com:invalid/api",+ "https://flags.example.com\\@127.0.0.1/api",+ "https://flags.example.com%5c/api",+ ],+)+def test_malformed_urls_fail_before_sending_credentials(base_url: str, http: responses.RequestsMock) -> None:+ config = GrowthBookSourceConfig.from_dict({"api_key": "secret_test", "base_url": base_url})+ valid, message = GrowthBookSource().validate_credentials(config, 123)+ assert not valid+ assert message and "HTTPS" in message+ assert not http.calls+++def test_private_hosts_rejected_for_validation_and_sync(+ config: GrowthBookSourceConfig,+ inputs: SourceInputs,+ manager: MagicMock,+ http: responses.RequestsMock,+ safe_host: MagicMock,+) -> None:+ safe_host.return_value = (False, "private IP")+ valid, message = GrowthBookSource().validate_credentials(config, 123)+ assert not valid+ assert message and "publicly reachable" in message+ with pytest.raises(ValueError, match="publicly reachable"):+ GrowthBookSource().source_for_pipeline(config, manager, inputs)+ assert not http.calls+++def test_unknown_table_rejected_without_http(+ config: GrowthBookSourceConfig,+ inputs: SourceInputs,+ manager: MagicMock,+ http: responses.RequestsMock,+) -> None:+ inputs.schema_name = "unknown"+ valid, message = GrowthBookSource().validate_credentials(config, 123, inputs.schema_name)+ assert not valid+ assert message and "Unknown GrowthBook table" in message+ with pytest.raises(UnknownResourceError):+ GrowthBookSource().source_for_pipeline(config, manager, inputs)+ assert not http.calls+++ ("base_url", "expected_url"),+ [+ (" ", "https://api.growthbook.io/api/v2/features"),+ (" https://flags.example.com/custom/api/ ", "https://flags.example.com/custom/api/v2/features"),+ ],+)+def test_base_url_normalization(base_url: str, expected_url: str, http: responses.RequestsMock) -> None:+ config = GrowthBookSourceConfig.from_dict({"api_key": "secret_test", "base_url": base_url})+ http.add(responses.GET, expected_url, json={"features": []})+ assert GrowthBookSource().validate_credentials(config, 123) == (True, None)+ assert len(http.calls) == 1diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.pyindex 29d27bb64ef8..980b86b58b21 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py@@ -60,7 +60,6 @@ SOURCES_WITHOUT_AN_ICON_FILE = {"Fintoc","FlyIo","Groq",- "GrowthBook","Gumloop","Hatchet","Hetzner",