: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 taboola import source (#63002)
Tom Owers4ed24089886c
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex c83475fdbdea..d4aefdae6219 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -167,6 +167,7 @@ the row lists both.| stripe | HTTP (vendor SDK) + Webhook | stripe (StripeClient + RequestsClient) + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || supabase | DB protocol | psycopg (delegates to PostgresSource) | ➖ || surveymonkey | HTTP | requests | ✅ |+| taboola | HTTP | requests | ✅ || temporalio | gRPC (vendor SDK) | temporalio (`Client`, Rust core via `temporalio.bridge`) | ⚠️ || tiktok_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || trello | HTTP | requests | ✅ |@@ -303,7 +304,6 @@ doesn't conflict with concurrent PRs.- sftp- sharepoint- surveymonkey-- taboola- twitter_ads- workday- xerodiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex f325d39d1f8e..b9a6ba527dcf 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -1318,7 +1318,9 @@ class SurveyMonkeySourceConfig(config.Config):@config.configclass TaboolaSourceConfig(config.Config):- pass+ client_id: str+ client_secret: str+ account_id: str@config.configdiff --git a/posthog/temporal/data_imports/sources/taboola/settings.py b/posthog/temporal/data_imports/sources/taboola/settings.pynew file mode 100644index 000000000000..946070b0243e--- /dev/null+++ b/posthog/temporal/data_imports/sources/taboola/settings.py@@ -0,0 +1,81 @@+from dataclasses import dataclass, field+from typing import Literal++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType++TABOOLA_TOKEN_URL = "https://backstage.taboola.com/backstage/oauth/token"+TABOOLA_API_BASE_URL = "https://backstage.taboola.com/backstage/api/1.0"++# Campaign-summary rows for recent days can restate as conversions settle, so+# incremental syncs re-pull a trailing window and merge on (date, campaign).+REPORT_LOOKBACK_DAYS = 30+# Default history pulled on the first sync of a report stream (the API retains+# up to 3 years).+REPORT_DEFAULT_BACKFILL_DAYS = 365+# Reports are windowed by start_date/end_date; request in bounded chunks so a+# multi-year backfill doesn't ride on one giant response.+REPORT_WINDOW_DAYS = 30++TaboolaEndpointKind = Literal["entity", "campaign_items", "report", "snapshot_report"]+++@dataclass+class TaboolaEndpointConfig:+ name: str+ kind: TaboolaEndpointKind+ # Path under {base}/{account_id} for entity endpoints, or the report path+ # segment for report endpoints.+ path: str = ""+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++TABOOLA_ENDPOINTS: dict[str, TaboolaEndpointConfig] = {+ # Entity endpoints return the full result set under `results` with no+ # updated-since filter — honest full refresh.+ "campaigns": TaboolaEndpointConfig(+ name="campaigns",+ kind="entity",+ path="/campaigns/",+ ),+ "campaign_items": TaboolaEndpointConfig(+ # Fan-out: GET /campaigns/{id}/items/ per campaign.+ name="campaign_items",+ kind="campaign_items",+ ),+ "conversion_rules": TaboolaEndpointConfig(+ name="conversion_rules",+ kind="entity",+ path="/universal_pixel/conversion_rule",+ ),+ # Date-windowed report with per-row date + campaign — incremental with a+ # restatement lookback.+ "campaign_summary_by_day": TaboolaEndpointConfig(+ name="campaign_summary_by_day",+ kind="report",+ path="/reports/campaign-summary/dimensions/campaign_day_breakdown",+ primary_keys=["date", "campaign"],+ incremental_fields=[+ {+ "label": "date",+ "type": IncrementalFieldType.DateTime,+ "field": "date",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ # Top-1000 aggregate over the requested window; rows carry no date, so this+ # is a trailing-window snapshot (full refresh).+ "top_campaign_content": TaboolaEndpointConfig(+ name="top_campaign_content",+ kind="snapshot_report",+ path="/reports/top-campaign-content/dimensions/item_breakdown",+ primary_keys=["campaign", "item"],+ ),+}++ENDPOINTS = tuple(TABOOLA_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in TABOOLA_ENDPOINTS.items() if config.incremental_fields+}diff --git a/posthog/temporal/data_imports/sources/taboola/source.py b/posthog/temporal/data_imports/sources/taboola/source.pyindex a5d96b3e8972..08076923eb69 100644--- a/posthog/temporal/data_imports/sources/taboola/source.py+++ b/posthog/temporal/data_imports/sources/taboola/source.py@@ -1,29 +1,141 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import TaboolaSourceConfig+from posthog.temporal.data_imports.sources.taboola.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.taboola.taboola import (+ TaboolaResumeConfig,+ taboola_source,+ validate_credentials as validate_taboola_credentials,+)from products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class TaboolaSource(SimpleSource[TaboolaSourceConfig]):+class TaboolaSource(ResumableSource[TaboolaSourceConfig, TaboolaResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.TABOOLA+ @property+ def connection_host_fields(self) -> list[str]:+ # account_id selects which Taboola account the stored credential is sent to, so+ # changing it must force re-entry of the secret (prevents credential retargeting).+ return ["account_id"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "400 Client Error: Bad Request for url: https://backstage.taboola.com/backstage/oauth/token": "Taboola rejected the token request. Please check your client ID and client secret.",+ "401 Client Error: Unauthorized for url: https://backstage.taboola.com": "Taboola authentication failed. Please check your client ID and client secret.",+ "403 Client Error: Forbidden for url: https://backstage.taboola.com": "Taboola denied access. Please check that your credentials can access this account ID.",+ "404 Client Error: Not Found for url: https://backstage.taboola.com": "Taboola account not found. Please check your account ID.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.TABOOLA,label="Taboola",+ caption="""Connect your Taboola account to pull your advertising data into the PostHog Data warehouse.++Backstage API credentials (client ID and secret) are issued by your Taboola account manager — they can't be self-served. Your account ID is the alphabetic account identifier shown in Taboola Ads (also called the account name).""",iconPath="/static/services/taboola.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/taboola",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="client_id",+ label="Client ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="account_id",+ label="Account ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="my-account",+ secret=False,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: TaboolaSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ 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: TaboolaSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_taboola_credentials(config.client_id, config.client_secret):+ return True, None++ return False, "Invalid Taboola credentials"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TaboolaResumeConfig]:+ return ResumableSourceManager[TaboolaResumeConfig](inputs, TaboolaResumeConfig)++ def source_for_pipeline(+ self,+ config: TaboolaSourceConfig,+ resumable_source_manager: ResumableSourceManager[TaboolaResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return taboola_source(+ client_id=config.client_id,+ client_secret=config.client_secret,+ account_id=config.account_id,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/posthog/temporal/data_imports/sources/taboola/taboola.py b/posthog/temporal/data_imports/sources/taboola/taboola.pynew file mode 100644index 000000000000..4f14aae30c9a--- /dev/null+++ b/posthog/temporal/data_imports/sources/taboola/taboola.py@@ -0,0 +1,231 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import quote, 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.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.taboola.settings import (+ REPORT_DEFAULT_BACKFILL_DAYS,+ REPORT_LOOKBACK_DAYS,+ REPORT_WINDOW_DAYS,+ TABOOLA_API_BASE_URL,+ TABOOLA_ENDPOINTS,+ TABOOLA_TOKEN_URL,+)++REQUEST_TIMEOUT_SECONDS = 120+# Rate limits are plan/endpoint dependent and poorly documented; back off on 429.+MAX_RETRY_ATTEMPTS = 5+++class TaboolaRetryableError(Exception):+ pass+++class TaboolaResumeConfig:+ # Reports: the start date (yyyy-mm-dd) of the next unfetched window.+ # campaign_items: the index of the next campaign to fetch items for.+ next_window_start: Optional[str] = None+ next_campaign_index: Optional[int] = None+++def _get_session(client_secret: str) -> requests.Session:+ return make_tracked_session(redact_values=(client_secret,))+++def _encode_path_segment(value: str) -> str:+ """Percent-encode a value before interpolating it into a URL path.++ ``account_id`` is a non-secret field a user can edit on an existing source while the+ saved credentials are preserved. Without encoding, a value containing ``/``, ``?``,+ ``#``, or ``.`` could redirect the authenticated request to an unintended Backstage+ endpoint. Encoding with ``safe=""`` keeps every delimiter inside the single path segment.+ """+ return quote(value, safe="")+++def _mint_token(session: requests.Session, client_id: str, client_secret: str) -> str:+ """Exchange client credentials for a bearer token (short-lived)."""+ response = session.post(+ TABOOLA_TOKEN_URL,+ data={"client_id": client_id, "client_secret": client_secret, "grant_type": "client_credentials"},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ # Transient token-endpoint failures must be retryable so the re-mint inside the+ # @retry-decorated fetch backs off instead of failing the whole sync.+ if response.status_code == 429 or response.status_code >= 500:+ raise TaboolaRetryableError(f"Taboola token endpoint error (retryable): status={response.status_code}")+ response.raise_for_status()+ return response.json()["access_token"]+++def _to_date(value: Any) -> Optional[date]:+ if isinstance(value, datetime):+ return value.date()+ if isinstance(value, date):+ return value+ if isinstance(value, str):+ try:+ return datetime.fromisoformat(value.replace("Z", "+00:00")).date()+ except ValueError:+ return None+ return None+++def validate_credentials(client_id: str, client_secret: str) -> bool:+ """Confirm the credentials are valid by minting a token."""+ try:+ _mint_token(_get_session(client_secret), client_id, client_secret)+ return True+ except Exception:+ return False+++def get_rows(+ client_id: str,+ client_secret: str,+ account_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TaboolaResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = TABOOLA_ENDPOINTS[endpoint]+ session = _get_session(client_secret)+ token = _mint_token(session, client_id, client_secret)+ account_base = f"{TABOOLA_API_BASE_URL}/{_encode_path_segment(account_id)}"++ @retry(+ retry=retry_if_exception_type((TaboolaRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=2, max=90),+ reraise=True,+ )+ def fetch(url: str) -> dict[str, Any]:+ nonlocal token+ response = session.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=REQUEST_TIMEOUT_SECONDS)++ # Access tokens are short-lived; re-mint once if one expires mid-sync.+ if response.status_code == 401:+ token = _mint_token(session, client_id, client_secret)+ response = session.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise TaboolaRetryableError(f"Taboola API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Taboola API error: status={response.status_code}, body={response.text[:500]}, url={url}")+ response.raise_for_status()++ return response.json()++ def results_of(data: Any) -> list[dict[str, Any]]:+ items = data.get("results") if isinstance(data, dict) else None+ return [row for row in items if isinstance(row, dict)] if isinstance(items, list) else []++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if config.kind == "entity":+ items = results_of(fetch(f"{account_base}{config.path}"))+ if items:+ yield items+ return++ if config.kind == "campaign_items":+ campaigns = results_of(fetch(f"{account_base}/campaigns/"))+ campaign_ids = [str(campaign["id"]) for campaign in campaigns if campaign.get("id") is not None]++ start_index = 0+ if resume_config is not None and resume_config.next_campaign_index is not None:+ start_index = resume_config.next_campaign_index+ logger.debug(f"Taboola: resuming campaign_items from campaign index {start_index}")++ for index in range(start_index, len(campaign_ids)):+ campaign_id = campaign_ids[index]+ items = results_of(fetch(f"{account_base}/campaigns/{_encode_path_segment(campaign_id)}/items/"))+ if items:+ yield items+ # Save state AFTER yielding so a crash re-yields the in-flight+ # campaign (merge dedupes on primary key).+ resumable_source_manager.save_state(TaboolaResumeConfig(next_campaign_index=index + 1))+ return++ if config.kind == "snapshot_report":+ # Trailing-window aggregate (rows carry no date) — full refresh.+ end = datetime.now(tz=UTC).date()+ start = end - timedelta(days=REPORT_LOOKBACK_DAYS)+ params = urlencode({"start_date": start.isoformat(), "end_date": end.isoformat()})+ items = results_of(fetch(f"{account_base}{config.path}?{params}"))+ if items:+ yield items+ return++ # Date-windowed report. Recent rows restate, so incremental runs re-pull a+ # trailing lookback window before the watermark.+ today = datetime.now(tz=UTC).date()+ start = today - timedelta(days=REPORT_DEFAULT_BACKFILL_DAYS)+ if should_use_incremental_field:+ watermark = _to_date(db_incremental_field_last_value)+ if watermark is not None:+ start = watermark - timedelta(days=REPORT_LOOKBACK_DAYS)++ if resume_config is not None and resume_config.next_window_start:+ resumed = _to_date(resume_config.next_window_start)+ if resumed is not None and resumed > start:+ start = resumed+ logger.debug(f"Taboola: resuming {endpoint} from window start {start.isoformat()}")++ while start <= today:+ window_end = min(start + timedelta(days=REPORT_WINDOW_DAYS - 1), today)+ params = urlencode({"start_date": start.isoformat(), "end_date": window_end.isoformat()})+ items = results_of(fetch(f"{account_base}{config.path}?{params}"))+ if items:+ yield items++ start = window_end + timedelta(days=1)+ if start <= today:+ # Save state AFTER yielding so a crash re-yields the in-flight window.+ resumable_source_manager.save_state(TaboolaResumeConfig(next_window_start=start.isoformat()))+++def taboola_source(+ client_id: str,+ client_secret: str,+ account_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[TaboolaResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = TABOOLA_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ client_id=client_id,+ client_secret=client_secret,+ account_id=account_id,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=list(config.primary_keys),+ partition_count=1,+ partition_size=1,+ # Report windows are walked oldest-first, so the date watermark only+ # moves forward; the lookback re-pull happens below the saved watermark+ # and merges on (date, campaign).+ sort_mode="asc",+ )diff --git a/posthog/temporal/data_imports/sources/taboola/tests/test_taboola.py b/posthog/temporal/data_imports/sources/taboola/tests/test_taboola.pynew file mode 100644index 000000000000..d9aaf5f61376--- /dev/null+++ b/posthog/temporal/data_imports/sources/taboola/tests/test_taboola.py@@ -0,0 +1,216 @@+from datetime import UTC, date, datetime, timedelta+from typing import Any++import pytest+from unittest import mock++from posthog.temporal.data_imports.sources.taboola.settings import (+ ENDPOINTS,+ REPORT_DEFAULT_BACKFILL_DAYS,+ REPORT_LOOKBACK_DAYS,+ TABOOLA_ENDPOINTS,+)+from posthog.temporal.data_imports.sources.taboola.taboola import (+ TaboolaResumeConfig,+ _to_date,+ get_rows,+ taboola_source,+ validate_credentials,+)++_MODULE = "posthog.temporal.data_imports.sources.taboola.taboola"+++def _make_manager(resume_state: TaboolaResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _response(body: Any, status_code: int = 200) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = body+ resp.status_code = status_code+ resp.ok = status_code < 400+ return resp+++def _token_response() -> mock.MagicMock:+ return _response({"access_token": "tok-1", "token_type": "bearer", "expires_in": 3600})+++class TestToDate:+ @pytest.mark.parametrize(+ "value, expected_iso",+ [+ (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "2024-01-02"),+ (date(2024, 1, 2), "2024-01-02"),+ ("2024-01-02", "2024-01-02"),+ ("2024-01-02T03:04:05Z", "2024-01-02"),+ ("junk", None),+ (None, None),+ ],+ )+ def test_parses(self, value, expected_iso):+ result = _to_date(value)+ assert (result.isoformat() if result else None) == expected_iso+++class TestValidateCredentials:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_valid_credentials_mint_a_token(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()++ assert validate_credentials("cid", "sec") is True+ body = mock_session.return_value.post.call_args.kwargs["data"]+ assert body == {"client_id": "cid", "client_secret": "sec", "grant_type": "client_credentials"}++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_invalid_credentials(self, mock_session):+ response = _response({}, status_code=401)+ response.raise_for_status.side_effect = Exception("401")+ mock_session.return_value.post.return_value = response++ assert validate_credentials("cid", "bad") is False+++class TestEntityEndpoints:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_campaigns_single_fetch(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = _response({"results": [{"id": "1"}, {"id": "2"}]})++ batches = list(get_rows("cid", "sec", "acct", "campaigns", mock.MagicMock(), _make_manager()))++ assert batches == [[{"id": "1"}, {"id": "2"}]]+ url = mock_session.return_value.get.call_args.args[0]+ assert url == "https://backstage.taboola.com/backstage/api/1.0/acct/campaigns/"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_mid_sync_401_re_mints_token(self, mock_session):+ mock_session.return_value.post.side_effect = [_token_response(), _token_response()]+ mock_session.return_value.get.side_effect = [+ _response({}, status_code=401),+ _response({"results": [{"id": "1"}]}),+ ]++ batches = list(get_rows("cid", "sec", "acct", "conversion_rules", mock.MagicMock(), _make_manager()))++ assert batches == [[{"id": "1"}]]+ assert mock_session.return_value.post.call_count == 2+++class TestCampaignItemsFanOut:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_fans_out_per_campaign_and_saves_progress(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.side_effect = [+ _response({"results": [{"id": 11}, {"id": 22}]}),+ _response({"results": [{"id": "i1", "campaign_id": "11"}]}),+ _response({"results": [{"id": "i2", "campaign_id": "22"}]}),+ ]++ manager = _make_manager()+ batches = list(get_rows("cid", "sec", "acct", "campaign_items", mock.MagicMock(), manager))++ assert [row["id"] for batch in batches for row in batch] == ["i1", "i2"]+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert urls[1].endswith("/acct/campaigns/11/items/")+ assert urls[2].endswith("/acct/campaigns/22/items/")+ assert [call.args[0].next_campaign_index for call in manager.save_state.call_args_list] == [1, 2]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resumes_from_saved_campaign_index(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.side_effect = [+ _response({"results": [{"id": 11}, {"id": 22}]}),+ _response({"results": [{"id": "i2"}]}),+ ]++ manager = _make_manager(TaboolaResumeConfig(next_campaign_index=1))+ batches = list(get_rows("cid", "sec", "acct", "campaign_items", mock.MagicMock(), manager))++ assert [row["id"] for batch in batches for row in batch] == ["i2"]+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert len(urls) == 2+ assert urls[1].endswith("/acct/campaigns/22/items/")+++class TestReportWindows:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_full_refresh_walks_windows_from_default_backfill(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = _response({"results": [{"date": "2024-01-01", "campaign": "1"}]})++ manager = _make_manager()+ batches = list(get_rows("cid", "sec", "acct", "campaign_summary_by_day", mock.MagicMock(), manager))++ assert len(batches) > 1+ first_url = mock_session.return_value.get.call_args_list[0].args[0]+ assert "start_date=" in first_url and "end_date=" in first_url+ # Walked oldest-first: every saved window start moves forward.+ starts = [call.args[0].next_window_start for call in manager.save_state.call_args_list]+ assert starts == sorted(starts)++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_incremental_starts_lookback_before_watermark(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = _response({"results": []})++ watermark = datetime.now(tz=UTC).date()+ list(+ get_rows(+ "cid",+ "sec",+ "acct",+ "campaign_summary_by_day",+ mock.MagicMock(),+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark.isoformat(),+ )+ )++ first_url = mock_session.return_value.get.call_args_list[0].args[0]+ expected_start = (watermark - timedelta(days=REPORT_LOOKBACK_DAYS)).isoformat()+ assert f"start_date={expected_start}" in first_url++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resume_window_start_supersedes_older_start(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = _response({"results": []})++ resume_start = datetime.now(tz=UTC).date().isoformat()+ manager = _make_manager(TaboolaResumeConfig(next_window_start=resume_start))+ list(get_rows("cid", "sec", "acct", "campaign_summary_by_day", mock.MagicMock(), manager))++ first_url = mock_session.return_value.get.call_args_list[0].args[0]+ assert f"start_date={resume_start}" in first_url+ assert mock_session.return_value.get.call_count == 1++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_snapshot_report_uses_trailing_window_single_fetch(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = _response({"results": [{"campaign": "1", "item": "9"}]})++ manager = _make_manager()+ batches = list(get_rows("cid", "sec", "acct", "top_campaign_content", mock.MagicMock(), manager))++ assert batches == [[{"campaign": "1", "item": "9"}]]+ assert mock_session.return_value.get.call_count == 1+ manager.save_state.assert_not_called()+++class TestTaboolaSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = TABOOLA_ENDPOINTS[endpoint]+ response = taboola_source("cid", "sec", "acct", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ assert response.sort_mode == "asc"++ def test_backfill_constants_are_sane(self):+ assert REPORT_LOOKBACK_DAYS < REPORT_DEFAULT_BACKFILL_DAYSdiff --git a/posthog/temporal/data_imports/sources/taboola/tests/test_taboola_source.py b/posthog/temporal/data_imports/sources/taboola/tests/test_taboola_source.pynew file mode 100644index 000000000000..6d183084f54d--- /dev/null+++ b/posthog/temporal/data_imports/sources/taboola/tests/test_taboola_source.py@@ -0,0 +1,138 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import TaboolaSourceConfig+from posthog.temporal.data_imports.sources.taboola.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.taboola.source import TaboolaSource+from posthog.temporal.data_imports.sources.taboola.taboola import TaboolaResumeConfig++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestTaboolaSource:+ def setup_method(self):+ self.source = TaboolaSource()+ self.team_id = 123+ self.config = TaboolaSourceConfig(client_id="cid", client_secret="sec", account_id="acct")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.TABOOLA++ def test_connection_host_fields_includes_account_id(self):+ assert self.source.connection_host_fields == ["account_id"]++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Taboola"+ assert config.label == "Taboola"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/taboola.png"++ field_names = [f.name for f in config.fields]+ assert field_names == ["client_id", "client_secret", "account_id"]++ def test_client_secret_field_is_secret_password(self):+ config = self.source.get_source_config+ secret_field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "client_secret"+ )+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD+ assert secret_field.secret is True+ assert secret_field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "400 Client Error: Bad Request for url: https://backstage.taboola.com/backstage/oauth/token",+ "401 Client Error: Unauthorized for url: https://backstage.taboola.com/backstage/api/1.0/acct/campaigns/",+ "403 Client Error: Forbidden for url: https://backstage.taboola.com/backstage/api/1.0/acct/campaigns/",+ "404 Client Error: Not Found for url: https://backstage.taboola.com/backstage/api/1.0/bad-acct/campaigns/",+ ],+ )+ def test_non_retryable_errors_match_known_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)++ def test_non_retryable_errors_does_not_match_server_errors(self):+ non_retryable_errors = self.source.get_non_retryable_errors()+ error = "500 Server Error for url: https://backstage.taboola.com/backstage/api/1.0/acct/campaigns/"+ assert not any(key in error for key in non_retryable_errors)++ def test_get_schemas(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ # Only the date-windowed report has a real server-side date filter.+ incremental = {name for name, schema in schemas.items() if schema.supports_incremental}+ assert incremental == {"campaign_summary_by_day"}+ assert schemas["campaign_summary_by_day"].incremental_fields == INCREMENTAL_FIELDS["campaign_summary_by_day"]+ assert schemas["campaigns"].incremental_fields == []++ 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",+ [+ (True, True),+ (False, False),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.taboola.source.validate_taboola_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid):+ 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+ if not expected_valid:+ assert error_message == "Invalid Taboola credentials"+ mock_validate.assert_called_once_with("cid", "sec")++ def test_get_resumable_source_manager_binds_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is TaboolaResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.taboola.source.taboola_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_taboola_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "campaign_summary_by_day"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-02"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_taboola_source.assert_called_once()+ kwargs = mock_taboola_source.call_args.kwargs+ assert kwargs["client_id"] == "cid"+ assert kwargs["client_secret"] == "sec"+ assert kwargs["account_id"] == "acct"+ assert kwargs["endpoint"] == "campaign_summary_by_day"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-02"++ @mock.patch("posthog.temporal.data_imports.sources.taboola.source.taboola_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_taboola_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "campaigns"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-01-02"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_taboola_source.call_args.kwargs["db_incremental_field_last_value"] is None