Skip to content

: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.

feat(data-warehouse): implement adroll import source (#62952)

Tom Owerseaf9f5ee8210
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 2faab42d9676..4aa5fecd925f 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -44,6 +44,7 @@ the row lists both.
| Source | Comm method | Primary library | Tracked transport |
| ---------------- | --------------------------- | --------------------------------------------------------------- | --------------------------- |
+| adroll | HTTP | requests | ✅ |
| aircall | HTTP | requests | ✅ |
| airtable | HTTP | requests | ✅ |
| amplitude | HTTP | requests | ✅ |
@@ -209,7 +210,6 @@ doesn't conflict with concurrent PRs.
- adobe_analytics
- adobe_commerce
- adp_workforce_now
-- adroll
- adyen
- amazon_ads
- amazon_s3
diff --git a/posthog/temporal/data_imports/sources/adroll/adroll.py b/posthog/temporal/data_imports/sources/adroll/adroll.py
new file mode 100644
index 000000000000..0ca2986487af
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/adroll/adroll.py
@@ -0,0 +1,115 @@
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.adroll.settings import ADROLL_ENDPOINTS
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+
+ADROLL_BASE_URL = "https://services.adroll.com"
+REQUEST_TIMEOUT_SECONDS = 60
+# Quota is requests/day (default 100), so retry sparingly.
+MAX_RETRY_ATTEMPTS = 3
+
+
+class AdRollRetryableError(Exception):
+ pass
+
+
+def _get_session(personal_access_token: str) -> requests.Session:
+ return make_tracked_session(
+ headers={"Authorization": f"Token {personal_access_token}"},
+ redact_values=(personal_access_token,),
+ )
+
+
+def validate_credentials(client_id: str, personal_access_token: str) -> bool:
+ """Confirm the PAT + apikey pair is valid with a cheap organization probe."""
+ try:
+ response = _get_session(personal_access_token).get(
+ f"{ADROLL_BASE_URL}/api/v1/organization/get?{urlencode({'apikey': client_id})}",
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def get_rows(
+ client_id: str,
+ personal_access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ config = ADROLL_ENDPOINTS[endpoint]
+ session = _get_session(personal_access_token)
+
+ @retry(
+ retry=retry_if_exception_type((AdRollRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=5, max=120),
+ reraise=True,
+ )
+ def fetch(path: str, params: dict[str, Any]) -> dict[str, Any]:
+ # Every request needs the app's Client ID as the apikey param, even
+ # with PAT auth.
+ url = f"{ADROLL_BASE_URL}{path}?{urlencode({**params, 'apikey': client_id})}"
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise AdRollRetryableError(f"AdRoll API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"AdRoll API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ def advertisable_eids() -> list[str]:
+ data = fetch(ADROLL_ENDPOINTS["advertisables"].path, {})
+ results = data.get("results", []) or []
+ return [item["eid"] for item in results if item.get("eid")]
+
+ if not config.advertisable_scoped:
+ data = fetch(config.path, {})
+ items = data.get("results", []) or []
+ if items:
+ yield items
+ return
+
+ # advertisable_scoped endpoints always define a parent_key (enforced in
+ # AdRollEndpointConfig.__post_init__); narrow the Optional for the row build.
+ parent_key = config.parent_key
+ assert parent_key is not None
+ for eid in advertisable_eids():
+ data = fetch(config.path, {"advertisable": eid})
+ items = [{**item, parent_key: eid} for item in (data.get("results", []) or [])]
+ if items:
+ yield items
+
+
+def adroll_source(
+ client_id: str,
+ personal_access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ config = ADROLL_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ client_id=client_id,
+ personal_access_token=personal_access_token,
+ endpoint=endpoint,
+ logger=logger,
+ ),
+ primary_keys=[config.primary_key],
+ partition_count=1,
+ partition_size=1,
+ sort_mode="asc",
+ )
diff --git a/posthog/temporal/data_imports/sources/adroll/settings.py b/posthog/temporal/data_imports/sources/adroll/settings.py
new file mode 100644
index 000000000000..ed52cb294037
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/adroll/settings.py
@@ -0,0 +1,43 @@
+from dataclasses import dataclass
+from typing import Optional
+
+
+@dataclass
+class AdRollEndpointConfig:
+ name: str
+ # Path under https://services.adroll.com.
+ path: str
+ primary_key: str = "eid"
+ # Fan-out parent (campaigns/ads are fetched per advertisable EID).
+ advertisable_scoped: bool = False
+ parent_key: Optional[str] = None
+
+ def __post_init__(self) -> None:
+ if self.advertisable_scoped and self.parent_key is None:
+ raise ValueError(f"advertisable_scoped endpoint '{self.name}' must define parent_key")
+
+
+# AdRoll's default quota is only 100 API requests per day, so v1 ships the
+# small entity hierarchy (1 + 2×advertisables requests per sync). Entity
+# endpoints have no updated_at filter — full refresh. Performance metrics are
+# GraphQL-only (POST /reporting/api/v1/query) and a follow-up.
+ADROLL_ENDPOINTS: dict[str, AdRollEndpointConfig] = {
+ "advertisables": AdRollEndpointConfig(
+ name="advertisables",
+ path="/api/v1/organization/get_advertisables",
+ ),
+ "campaigns": AdRollEndpointConfig(
+ name="campaigns",
+ path="/api/v1/campaign/get_all",
+ advertisable_scoped=True,
+ parent_key="_advertisable_eid",
+ ),
+ "ads": AdRollEndpointConfig(
+ name="ads",
+ path="/api/v1/ad/get_all",
+ advertisable_scoped=True,
+ parent_key="_advertisable_eid",
+ ),
+}
+
+ENDPOINTS = tuple(ADROLL_ENDPOINTS.keys())
diff --git a/posthog/temporal/data_imports/sources/adroll/source.py b/posthog/temporal/data_imports/sources/adroll/source.py
index 7d8c413d794a..e25827da8363 100644
--- a/posthog/temporal/data_imports/sources/adroll/source.py
+++ b/posthog/temporal/data_imports/sources/adroll/source.py
@@ -1,12 +1,22 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.adroll.adroll import (
+ adroll_source,
+ validate_credentials as validate_adroll_credentials,
+)
+from posthog.temporal.data_imports.sources.adroll.settings import ENDPOINTS
from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import AdRollSourceConfig
from products.data_warehouse.backend.types import ExternalDataSourceType
@@ -18,12 +28,84 @@ class AdRollSource(SimpleSource[AdRollSourceConfig]):
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ADROLL
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://services.adroll.com": "AdRoll authentication failed. Please check your personal access token and Client ID.",
+ "403 Client Error: Forbidden for url: https://services.adroll.com": "AdRoll denied access. Please check that your token has access to this organization's data.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.AD_ROLL,
label="AdRoll",
+ caption="""Enter your AdRoll (NextRoll) API credentials to pull your advertising entity data into the PostHog Data warehouse.
+
+Create a personal access token and an app in the [NextRoll developer console](https://developers.nextroll.com/) — the app's Client ID is sent as the `apikey` on every request. Note that NextRoll's default quota is 100 API requests per day; contact NextRoll support to raise it for larger accounts.""",
iconPath="/static/services/adroll.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/adroll",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="client_id",
+ label="Client ID (apikey)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="personal_access_token",
+ label="Personal access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: AdRollSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Entity endpoints have no updated_at filter — full refresh. Metrics
+ # are GraphQL-only and a follow-up.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ for endpoint in ENDPOINTS
+ ]
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+
+ return schemas
+
+ def validate_credentials(
+ self, config: AdRollSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_adroll_credentials(config.client_id, config.personal_access_token):
+ return True, None
+
+ return False, "Invalid AdRoll credentials"
+
+ def source_for_pipeline(self, config: AdRollSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ return adroll_source(
+ client_id=config.client_id,
+ personal_access_token=config.personal_access_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
)
diff --git a/posthog/temporal/data_imports/sources/adroll/tests/test_adroll.py b/posthog/temporal/data_imports/sources/adroll/tests/test_adroll.py
new file mode 100644
index 000000000000..97ae51cf40e8
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/adroll/tests/test_adroll.py
@@ -0,0 +1,150 @@
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.adroll.adroll import (
+ MAX_RETRY_ATTEMPTS,
+ AdRollRetryableError,
+ adroll_source,
+ get_rows,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.adroll.settings import ADROLL_ENDPOINTS, ENDPOINTS
+
+_MODULE = "posthog.temporal.data_imports.sources.adroll.adroll"
+
+
+def _response(results: list[dict[str, Any]]) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = {"results": results}
+ resp.status_code = 200
+ resp.ok = True
+ return resp
+
+
+def _error_response(status_code: int) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.status_code = status_code
+ resp.ok = False
+ resp.text = "error"
+ return resp
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected",
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ (500, False),
+ ],
+ )
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ assert validate_credentials("cid", "pat") is expected
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_validate_includes_apikey_and_token_header(self, mock_session):
+ response = mock.MagicMock()
+ response.status_code = 200
+ mock_session.return_value.get.return_value = response
+
+ validate_credentials("cid", "pat")
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert parse_qs(urlparse(url).query)["apikey"] == ["cid"]
+ headers = mock_session.call_args.kwargs["headers"]
+ assert headers["Authorization"] == "Token pat"
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_validate_credentials_swallows_exceptions(self, mock_session):
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("cid", "pat") is False
+
+
+class TestGetRows:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_advertisables_single_fetch(self, mock_session):
+ mock_session.return_value.get.return_value = _response([{"eid": "ADV1"}])
+
+ batches = list(get_rows("cid", "pat", "advertisables", mock.MagicMock()))
+
+ assert batches == [[{"eid": "ADV1"}]]
+ url = mock_session.return_value.get.call_args.args[0]
+ assert urlparse(url).path == "/api/v1/organization/get_advertisables"
+ assert parse_qs(urlparse(url).query)["apikey"] == ["cid"]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_campaigns_fan_out_over_advertisables(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response([{"eid": "ADV1"}, {"eid": "ADV2"}]),
+ _response([{"eid": "C1"}]),
+ _response([{"eid": "C2"}]),
+ ]
+
+ batches = list(get_rows("cid", "pat", "campaigns", mock.MagicMock()))
+
+ flat = [item for batch in batches for item in batch]
+ assert [(c["eid"], c["_advertisable_eid"]) for c in flat] == [("C1", "ADV1"), ("C2", "ADV2")]
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert parse_qs(urlparse(urls[1]).query)["advertisable"] == ["ADV1"]
+ assert parse_qs(urlparse(urls[2]).query)["advertisable"] == ["ADV2"]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_advertisables_without_eid_are_skipped(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response([{"name": "broken"}]),
+ ]
+
+ assert list(get_rows("cid", "pat", "ads", mock.MagicMock())) == []
+ assert mock_session.return_value.get.call_count == 1
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_empty_response_yields_nothing(self, mock_session):
+ mock_session.return_value.get.return_value = _response([])
+
+ assert list(get_rows("cid", "pat", "advertisables", mock.MagicMock())) == []
+
+ @mock.patch("time.sleep")
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_retries_retryable_status_then_succeeds(self, mock_session, _mock_sleep):
+ mock_session.return_value.get.side_effect = [
+ _error_response(500),
+ _error_response(429),
+ _response([{"eid": "ADV1"}]),
+ ]
+
+ batches = list(get_rows("cid", "pat", "advertisables", mock.MagicMock()))
+
+ assert batches == [[{"eid": "ADV1"}]]
+ assert mock_session.return_value.get.call_count == MAX_RETRY_ATTEMPTS
+
+ @mock.patch("time.sleep")
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_retries_exhausted_raises(self, mock_session, _mock_sleep):
+ mock_session.return_value.get.return_value = _error_response(500)
+
+ with pytest.raises(AdRollRetryableError):
+ list(get_rows("cid", "pat", "advertisables", mock.MagicMock()))
+
+ assert mock_session.return_value.get.call_count == MAX_RETRY_ATTEMPTS
+
+
+class TestAdRollSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = ADROLL_ENDPOINTS[endpoint]
+ response = adroll_source("cid", "pat", endpoint, mock.MagicMock())
+
+ assert response.name == endpoint
+ assert response.primary_keys == [config.primary_key]
+ assert response.sort_mode == "asc"
+ assert response.partition_mode is None
+ assert response.partition_keys is None
diff --git a/posthog/temporal/data_imports/sources/adroll/tests/test_adroll_source.py b/posthog/temporal/data_imports/sources/adroll/tests/test_adroll_source.py
new file mode 100644
index 000000000000..758d548856b8
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/adroll/tests/test_adroll_source.py
@@ -0,0 +1,109 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.adroll.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.adroll.source import AdRollSource
+from posthog.temporal.data_imports.sources.generated_configs import AdRollSourceConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestAdRollSource:
+ def setup_method(self):
+ self.source = AdRollSource()
+ self.team_id = 123
+ self.config = AdRollSourceConfig(client_id="cid", personal_access_token="pat")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.ADROLL
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "AdRoll"
+ assert config.label == "AdRoll"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/adroll.png"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["client_id", "personal_access_token"]
+
+ def test_pat_field_is_secret_password(self):
+ config = self.source.get_source_config
+ token_field = next(
+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "personal_access_token"
+ )
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.secret is True
+ assert token_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://services.adroll.com/api/v1/organization/get_advertisables",
+ "403 Client Error: Forbidden for url: https://services.adroll.com/api/v1/campaign/get_all",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_vendor_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://services.adroll.com/api/v1/ad/get_all",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_vendor_error for key in non_retryable_errors)
+
+ def test_get_schemas_are_full_refresh_only(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ assert all(not schema.supports_incremental for schema in schemas)
+ assert all(not schema.supports_append for schema in schemas)
+ assert all(schema.incremental_fields == [] for schema in schemas)
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["campaigns"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "campaigns"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid AdRoll credentials"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.adroll.source.validate_adroll_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with("cid", "pat")
+
+ @mock.patch("posthog.temporal.data_imports.sources.adroll.source.adroll_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_adroll_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "campaigns"
+
+ self.source.source_for_pipeline(self.config, inputs)
+
+ mock_adroll_source.assert_called_once()
+ kwargs = mock_adroll_source.call_args.kwargs
+ assert kwargs["client_id"] == "cid"
+ assert kwargs["personal_access_token"] == "pat"
+ assert kwargs["endpoint"] == "campaigns"
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index c00b3dc5a785..cb6a1bcf80d2 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -115,7 +115,8 @@ class ActiveCampaignSourceConfig(config.Config):
@config.config
class AdRollSourceConfig(config.Config):
- pass
+ client_id: str
+ personal_access_token: str
@config.config