: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(linkedin): implement creatives endpoint and analytics chunking l… (#57887)
Javier Bahamondesc97d48058424
diff --git a/posthog/temporal/data_imports/sources/linkedin_ads/client.py b/posthog/temporal/data_imports/sources/linkedin_ads/client.pyindex a9e59e2cd34e..952f913dbce9 100644--- a/posthog/temporal/data_imports/sources/linkedin_ads/client.py+++ b/posthog/temporal/data_imports/sources/linkedin_ads/client.py@@ -1,8 +1,10 @@import json+import datetime as dtfrom collections.abc import Generatorfrom typing import Any, Optionalimport requests+import structlogfrom linkedin_api.clients.restli.client import RestliClientfrom tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter@@ -14,9 +16,15 @@ from .schemas import (LinkedinAdsResource,)+logger = structlog.get_logger(__name__)+LINKEDIN_SPONSORED_URN_PREFIX = "urn:li:sponsored"MAX_PAGE_SIZE = 1000+CREATIVES_PAGE_SIZE = 100 # creatives backend returns transient 500s on heavier requestsAPI_VERSION = "202508"+# `q=analytics` truncates at 15k rows; we slice the date range to stay under it.+ANALYTICS_RESPONSE_CAP = 15000+ANALYTICS_CHUNK_DAYS = 7class LinkedinAdsRetryableError(Exception):@@ -61,32 +69,79 @@ class LinkedinAdsClient:starting_page_token=starting_page_token,)+ def get_creatives(+ self, account_id: str, starting_page_token: Optional[str] = None+ ) -> Generator[tuple[list[dict[str, Any]], Optional[str]], None, None]:+ """Get creatives with pagination. Uses `q=criteria` and reduced page size+ (the creatives backend 500s on heavier requests)."""+ account_endpoint = LINKEDIN_ADS_ENDPOINTS[LinkedinAdsResource.Accounts]+ creatives_endpoint = LINKEDIN_ADS_ENDPOINTS[LinkedinAdsResource.Creatives]+ yield from self._make_paginated_request(+ endpoint=LinkedinAdsResource.Creatives,+ path=f"/{account_endpoint}/{account_id}/{creatives_endpoint}",+ starting_page_token=starting_page_token,+ finder="criteria",+ page_size=CREATIVES_PAGE_SIZE,+ )+def get_analytics(self,account_id: str,pivot: LinkedinAdsPivot = LinkedinAdsPivot.CAMPAIGN,date_start: Optional[str] = None,date_end: Optional[str] = None,- ) -> list[dict[str, Any]]:- resource = (- LinkedinAdsResource.CampaignStats- if pivot == LinkedinAdsPivot.CAMPAIGN- else LinkedinAdsResource.CampaignGroupStats- )- fields = ",".join(self._get_fields_for_resource(resource))-- params: dict[str, Any] = {- "q": "analytics",- "pivot": pivot.value,- "timeGranularity": "DAILY",- "accounts": [f"{LINKEDIN_SPONSORED_URN_PREFIX}Account:{account_id}"],- "fields": fields,+ ) -> Generator[tuple[list[dict[str, Any]], None], None, None]:+ """Fetch analytics in weekly chunks to stay under the 15k-row response+ cap. Capped chunks yield partial data and log a warning — we don't+ retry/split because extra calls under rate-limit pressure cost more+ than the missing rows recover."""+ resource_by_pivot = {+ LinkedinAdsPivot.CAMPAIGN: LinkedinAdsResource.CampaignStats,+ LinkedinAdsPivot.CAMPAIGN_GROUP: LinkedinAdsResource.CampaignGroupStats,+ LinkedinAdsPivot.CREATIVE: LinkedinAdsResource.CreativeStats,}-- if date_start and date_end:- params["dateRange"] = self._format_date_range(date_start, date_end)-- return self._make_request(endpoint=resource, finder="analytics", extra_params=params)+ resource = resource_by_pivot.get(pivot, LinkedinAdsResource.CampaignStats)+ fields = ",".join(self._get_fields_for_resource(resource))+ accounts = [f"{LINKEDIN_SPONSORED_URN_PREFIX}Account:{account_id}"]++ def _build_params(chunk_start: Optional[str], chunk_end: Optional[str]) -> dict[str, Any]:+ params: dict[str, Any] = {+ "q": "analytics",+ "pivot": pivot.value,+ "timeGranularity": "DAILY",+ "accounts": accounts,+ "fields": fields,+ }+ if chunk_start and chunk_end:+ params["dateRange"] = self._format_date_range(chunk_start, chunk_end)+ return params++ if not (date_start and date_end):+ yield (+ self._make_request(endpoint=resource, finder="analytics", extra_params=_build_params(None, None)),+ None,+ )+ return++ chunk_start = dt.date.fromisoformat(date_start)+ end_date = dt.date.fromisoformat(date_end)+ while chunk_start <= end_date:+ chunk_end = min(chunk_start + dt.timedelta(days=ANALYTICS_CHUNK_DAYS - 1), end_date)+ elements = self._make_request(+ endpoint=resource,+ finder="analytics",+ extra_params=_build_params(chunk_start.isoformat(), chunk_end.isoformat()),+ )+ if len(elements) >= ANALYTICS_RESPONSE_CAP:+ logger.warning(+ "linkedin_ads.analytics_chunk_capped",+ pivot=pivot.value,+ chunk_start=chunk_start.isoformat(),+ chunk_end=chunk_end.isoformat(),+ received=len(elements),+ )+ yield elements, None+ chunk_start = chunk_end + dt.timedelta(days=1)def get_data_by_resource(self,@@ -98,8 +153,9 @@ class LinkedinAdsClient:) -> Generator[tuple[list[dict[str, Any]], Optional[str]], None, None]:"""Get data by resource, yielding each page and its nextPageToken (if any).- starting_page_token applies only to paginated endpoints (campaigns, campaign_groups)- and is ignored for single-shot endpoints (accounts, analytics).+ `starting_page_token` applies to the paginated entity endpoints (campaigns,+ campaign_groups, creatives) and is ignored for single-shot endpoints+ (accounts, analytics — analytics paginates by date-range chunking instead)."""if resource == LinkedinAdsResource.Accounts:yield self.get_accounts(), None@@ -107,8 +163,10 @@ class LinkedinAdsClient:yield from self.get_campaigns(account_id, starting_page_token=starting_page_token)elif resource == LinkedinAdsResource.CampaignGroups:yield from self.get_campaign_groups(account_id, starting_page_token=starting_page_token)+ elif resource == LinkedinAdsResource.Creatives:+ yield from self.get_creatives(account_id, starting_page_token=starting_page_token)elif resource in LINKEDIN_ADS_PIVOTS:- yield self.get_analytics(account_id, LINKEDIN_ADS_PIVOTS[resource], date_start, date_end), None+ yield from self.get_analytics(account_id, LINKEDIN_ADS_PIVOTS[resource], date_start, date_end)else:raise ValueError(f"Unsupported resource: {resource}")@@ -168,22 +226,23 @@ class LinkedinAdsClient:endpoint: LinkedinAdsResource,path: str,starting_page_token: Optional[str] = None,+ finder: str = "search",+ page_size: int = MAX_PAGE_SIZE,+ extra_params: Optional[dict[str, Any]] = None,) -> Generator[tuple[list[dict[str, Any]], Optional[str]], None, None]:- """Make paginated requests yielding each page with its nextPageToken.-- Yields (elements, next_page_token) where next_page_token is the token to request- the page AFTER the one just yielded (None for the final page). Callers can persist- this token to resume a run at the next page without re-fetching yielded data.- """+ """Yield each page as `(elements, next_page_token)` (None on the last page).+ Callers persist `next_page_token` to resume without re-fetching."""page_token = starting_page_tokenwhile True:fields = self._get_fields_for_resource(endpoint)- params = {"fields": ",".join(fields), "pageSize": MAX_PAGE_SIZE}+ params: dict[str, Any] = {"fields": ",".join(fields), "pageSize": page_size}+ if extra_params:+ params.update(extra_params)if page_token:params["pageToken"] = page_token- response = self._call_finder(resource_path=path, finder="search", params=params)+ response = self._call_finder(resource_path=path, finder=finder, params=params)if not response.elements:breakdiff --git a/posthog/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py b/posthog/temporal/data_imports/sources/linkedin_ads/linkedin_ads.pyindex d33515f82105..d340a97f9c1c 100644--- a/posthog/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py+++ b/posthog/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py@@ -4,6 +4,7 @@ import collections.abcfrom dataclasses import dataclassimport pyarrow as pa+import structlogfrom structlog.types import FilteringBoundLoggerfrom posthog.models.integration import Integration@@ -19,14 +20,14 @@ from products.data_warehouse.backend.types import IncrementalFieldTypefrom .client import LinkedinAdsClient, LinkedinAdsResourcefrom .schemas import FLOAT_FIELDS, RESOURCE_SCHEMAS, URN_COLUMNS, VIRTUAL_COLUMN_URN_MAPPING+module_logger = structlog.get_logger(__name__)+@dataclassclass LinkedInAdsResumeConfig:- """Resume state for LinkedIn Ads sync.-- page_token is the LinkedIn Marketing API `nextPageToken` that points to the next- page to fetch. Only paginated resources (campaigns, campaign_groups) produce a- meaningful token; single-shot resources (accounts, analytics) never save state.+ """Resume state for LinkedIn Ads sync — `nextPageToken` from the entity+ finders (campaigns, campaign_groups, creatives). Other endpoints don't save+ state (accounts is single-shot, analytics paginates by date-range chunking)."""page_token: str@@ -56,16 +57,13 @@ def get_incremental_fields() -> dict[str, list[tuple[str, IncrementalFieldType]]def _extract_type_and_id_from_urn(urn: str) -> tuple[str, int] | None:- """Extract ID from LinkedIn URN.-- Args:- urn: LinkedIn URN like "urn:li:sponsoredCampaign:12345678"-- Returns:- Tuple of type and integer ID or None if not found- """- _, _, urn_type, id_str = urn.split(":")- return urn_type, int(id_str)+ """Extract (type, int ID) from a LinkedIn URN like `urn:li:sponsoredCampaign:123`.+ Returns None on malformed input so callers can skip the row instead of crashing."""+ try:+ _, _, urn_type, id_str = urn.split(":")+ return urn_type, int(id_str)+ except (ValueError, AttributeError):+ return Nonedef get_schemas() -> dict[str, LinkedinAdsSchema]:@@ -186,7 +184,10 @@ def linkedin_ads_source(pending_next_page_token: str | None = Nonefor page, next_page_token in data_pages:- flattened_records = [_flatten_linkedin_record(record, schema) for record in page]+ # None signals an unflattenable PK (malformed creative URN) — drop the row.+ flattened_records = [+ flat for record in page if (flat := _flatten_linkedin_record(record, schema)) is not None+ ]for record in flattened_records:batcher.batch(record)if batcher.should_yield():@@ -235,8 +236,9 @@ def _convert_timestamp_to_date(last_modified: dict[str, int] | None) -> dt.datedef _flatten_linkedin_record(record: dict[str, typing.Any],schema: LinkedinAdsSchema,-) -> dict[str, typing.Any]:- """Flatten a LinkedIn API record to match schema."""+) -> dict[str, typing.Any] | None:+ """Flatten a LinkedIn API record to match schema. Returns None when the PK+ URN can't be parsed (would corrupt parquet schema inference)."""flattened: dict[str, typing.Any] = {}for field_name in schema.field_names:@@ -266,6 +268,14 @@ def _flatten_linkedin_record(flattened["created_time"] = created_timeflattened["last_modified_time"] = last_modified_time+ elif field_name in ("createdAt", "lastModifiedAt"):+ timestamp_ms = record.get(field_name)+ virtual_name = "created_time" if field_name == "createdAt" else "last_modified_time"+ if isinstance(timestamp_ms, int):+ flattened[virtual_name] = dt.datetime.fromtimestamp(timestamp_ms / 1000, tz=dt.UTC).date()+ else:+ flattened[virtual_name] = None+elif field_name in URN_COLUMNS:urn_value = record.get(field_name)extracted_id: int | None = None@@ -299,6 +309,17 @@ def _flatten_linkedin_record(if value is not None:if field_name in FLOAT_FIELDS:value = float(value)+ # Extract the int from creative `id` URN so it joins with `creative_id` in creative_stats.+ elif field_name == "id" and isinstance(value, str) and value.startswith("urn:li:"):+ urn_result = _extract_type_and_id_from_urn(value)+ if urn_result is None:+ module_logger.warning(+ "linkedin_ads.malformed_pk_urn",+ resource=schema.name,+ raw_id=value,+ )+ return None+ _, value = urn_resultflattened[field_name] = valuediff --git a/posthog/temporal/data_imports/sources/linkedin_ads/schemas.py b/posthog/temporal/data_imports/sources/linkedin_ads/schemas.pyindex b5effd06a688..9628f4aee119 100644--- a/posthog/temporal/data_imports/sources/linkedin_ads/schemas.py+++ b/posthog/temporal/data_imports/sources/linkedin_ads/schemas.py@@ -22,8 +22,10 @@ class LinkedinAdsResource(StrEnum):Accounts = "accounts"Campaigns = "campaigns"CampaignGroups = "campaign_groups"+ Creatives = "creatives"CampaignStats = "campaign_stats"CampaignGroupStats = "campaign_group_stats"+ CreativeStats = "creative_stats"class LinkedinAdsPivot(StrEnum):@@ -38,14 +40,17 @@ LINKEDIN_ADS_ENDPOINTS = {LinkedinAdsResource.Accounts: "adAccounts",LinkedinAdsResource.Campaigns: "adCampaigns",LinkedinAdsResource.CampaignGroups: "adCampaignGroups",+ LinkedinAdsResource.Creatives: "creatives",LinkedinAdsResource.CampaignStats: "adAnalytics",LinkedinAdsResource.CampaignGroupStats: "adAnalytics",+ LinkedinAdsResource.CreativeStats: "adAnalytics",}# Pivot mappings for analytics resourcesLINKEDIN_ADS_PIVOTS = {LinkedinAdsResource.CampaignStats: LinkedinAdsPivot.CAMPAIGN,LinkedinAdsResource.CampaignGroupStats: LinkedinAdsPivot.CAMPAIGN_GROUP,+ LinkedinAdsResource.CreativeStats: LinkedinAdsPivot.CREATIVE,}@@ -116,6 +121,27 @@ RESOURCE_SCHEMAS: dict[LinkedinAdsResource, ResourceSchema] = {"is_stats": False,"partition_size": 1,},+ LinkedinAdsResource.Creatives: {+ "resource_name": "creatives",+ # CreativeV11 rejects `type` and `changeAuditStamps` — don't add them here.+ "field_names": [+ "id",+ "account",+ "campaign",+ "name",+ "intendedStatus",+ "isServing",+ "review",+ "createdAt",+ "lastModifiedAt",+ ],+ "primary_key": ["id"],+ "partition_keys": ["created_time"],+ "partition_mode": "datetime",+ "partition_format": "week",+ "is_stats": False,+ "partition_size": 1,+ },LinkedinAdsResource.CampaignStats: {"resource_name": "campaign_stats","field_names": [@@ -172,4 +198,32 @@ RESOURCE_SCHEMAS: dict[LinkedinAdsResource, ResourceSchema] = {"is_stats": True,"partition_size": 1,},+ LinkedinAdsResource.CreativeStats: {+ "resource_name": "creative_stats",+ "field_names": [+ "impressions",+ "clicks",+ "dateRange",+ "pivotValues",+ "costInUsd",+ "costInLocalCurrency",+ "externalWebsiteConversions",+ "conversionValueInLocalCurrency",+ "landingPageClicks",+ "totalEngagements",+ "videoViews",+ "videoCompletions",+ "oneClickLeads",+ "follows",+ ],+ "primary_key": ["date_start", "date_end", "creative_id"],+ "filter_field_names": [+ ("date_start", IncrementalFieldType.Date),+ ],+ "partition_keys": ["date_start"],+ "partition_mode": "datetime",+ "partition_format": "week",+ "is_stats": True,+ "partition_size": 1,+ },}diff --git a/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py b/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.pyindex 983c4218a01f..dc1fe7f38f2e 100644--- a/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py+++ b/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py@@ -47,6 +47,20 @@ class TestLinkedinAdsHelperFunctions:assert result == ("sponsoredCampaign", 12345678)+ @pytest.mark.parametrize(+ "malformed",+ [+ "not-a-urn",+ "urn:li:sponsoredCampaign", # missing id segment+ "urn:li:sponsoredCampaign:not-an-int",+ "urn:li:sponsoredCampaign:123:extra", # too many segments+ "",+ ],+ )+ def test_extract_type_and_id_from_urn_malformed_returns_none(self, malformed):+ """Bad URNs return None instead of raising."""+ assert _extract_type_and_id_from_urn(malformed) is None+def test_convert_date_object_to_date_valid(self):"""Test converting LinkedIn date object to Python date."""date_obj = {"year": 2024, "month": 3, "day": 15}@@ -95,6 +109,7 @@ class TestFlattenLinkedinRecord:)result = _flatten_linkedin_record(record, schema)+ assert result is not Noneassert result["date_start"] == dt.date(2024, 1, 1)assert result["date_end"] == dt.date(2024, 1, 31)@@ -117,6 +132,7 @@ class TestFlattenLinkedinRecord:)result = _flatten_linkedin_record(record, schema)+ assert result is not Noneassert result["campaign_group_id"] == 123456789assert result["campaign_id"] == 987654321@@ -136,6 +152,7 @@ class TestFlattenLinkedinRecord:)result = _flatten_linkedin_record(record, schema)+ assert result is not Noneassert result["impressions"] == 1000assert result["clicks"] == 50@@ -162,6 +179,7 @@ class TestFlattenLinkedinRecord:)result = _flatten_linkedin_record(record, schema)+ assert result is not Noneassert result[field_name] == expected@@ -180,6 +198,7 @@ class TestFlattenLinkedinRecord:)result = _flatten_linkedin_record(record, schema)+ assert result is not Noneassert str(result["created_time"]) == "2024-03-05"assert str(result["last_modified_time"]) == "2024-03-06"@@ -199,6 +218,7 @@ class TestFlattenLinkedinRecord:)result = _flatten_linkedin_record(record, schema)+ assert result is not Noneassert result["campaign_id"] == 555666777assert result["account_id"] == 888999000@@ -218,6 +238,7 @@ class TestFlattenLinkedinRecord:)result = _flatten_linkedin_record(record, schema)+ assert result is not None# API returns dict objects, pipeline handles JSON conversion laterassert result["targetingCriteria"]["locations"] == ["US", "CA"]@@ -238,9 +259,92 @@ class TestFlattenLinkedinRecord:)result = _flatten_linkedin_record(record, schema)+ assert result is not None+ assert result is not Noneassert result["missing_field"] is None+ def test_flatten_creative_id_urn_extracted_to_int(self):+ """Creative `id` URN → int, so it joins with `creative_id` in creative_stats."""+ record = {"id": "urn:li:sponsoredCreative:147756353"}+ schema = LinkedinAdsSchema(+ name="creatives",+ primary_keys=["id"],+ field_names=["id"],+ partition_keys=[],+ partition_mode=None,+ partition_format=None,+ is_stats=False,+ partition_size=1,+ )++ result = _flatten_linkedin_record(record, schema)+ assert result is not None++ assert result is not None+ assert result["id"] == 147756353+ assert isinstance(result["id"], int)++ def test_flatten_drops_record_when_pk_urn_is_malformed(self):+ """Malformed PK URN → return None so the caller drops the row."""+ record = {"id": "urn:li:sponsoredCreative:not-an-int"}+ schema = LinkedinAdsSchema(+ name="creatives",+ primary_keys=["id"],+ field_names=["id"],+ partition_keys=[],+ partition_mode=None,+ partition_format=None,+ is_stats=False,+ partition_size=1,+ )++ result = _flatten_linkedin_record(record, schema)++ assert result is None++ def test_flatten_created_at_long_to_virtual_columns(self):+ """`createdAt` / `lastModifiedAt` longs → `created_time` / `last_modified_time` virtual cols."""+ # 1625668063000 ms = 2021-07-07 (UTC)+ record = {"createdAt": 1625668063000, "lastModifiedAt": 1656592925000}+ schema = LinkedinAdsSchema(+ name="creatives",+ primary_keys=[],+ field_names=["createdAt", "lastModifiedAt"],+ partition_keys=[],+ partition_mode=None,+ partition_format=None,+ is_stats=False,+ partition_size=1,+ )++ result = _flatten_linkedin_record(record, schema)+ assert result is not None++ assert result is not None+ assert result["created_time"] == dt.date(2021, 7, 7)+ assert result["last_modified_time"] == dt.date(2022, 6, 30)++ def test_flatten_created_at_missing_yields_none(self):+ """Missing/non-int `createdAt` → virtual column is None."""+ record: dict[str, typing.Any] = {"createdAt": None}+ schema = LinkedinAdsSchema(+ name="creatives",+ primary_keys=[],+ field_names=["createdAt"],+ partition_keys=[],+ partition_mode=None,+ partition_format=None,+ is_stats=False,+ partition_size=1,+ )++ result = _flatten_linkedin_record(record, schema)+ assert result is not None++ assert result is not None+ assert result["created_time"] is None+@mock.patch("posthog.temporal.data_imports.sources.linkedin_ads.linkedin_ads.Integration")class TestLinkedinAdsClientFunction:diff --git a/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_client.py b/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_client.pyindex 5aed602d0269..6695516fefce 100644--- a/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_client.py+++ b/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_client.py@@ -4,6 +4,7 @@ import pytestfrom unittest import mockimport requests+from structlog.testing import capture_logsfrom posthog.temporal.data_imports.sources.linkedin_ads.client import (LinkedinAdsClient,@@ -102,9 +103,34 @@ class TestLinkedinAdsClient:call_params = mock_client_instance.finder.call_args[1]["query_params"]assert call_params["pageToken"] == "resume-token-abc"+ @mock.patch("posthog.temporal.data_imports.sources.linkedin_ads.client.RestliClient")+ def test_get_creatives_uses_criteria_finder_and_reduced_page_size(self, mock_restli_client):+ """Creatives use `q=criteria` (not `search`) with a reduced pageSize."""+ from posthog.temporal.data_imports.sources.linkedin_ads.client import CREATIVES_PAGE_SIZE++ mock_response = mock.MagicMock()+ mock_response.status_code = 200+ mock_response.elements = [{"id": "urn:li:sponsoredCreative:1", "name": "Creative 1"}]+ mock_response.response.text = json.dumps({"metadata": {}})++ mock_client_instance = mock_restli_client.return_value+ mock_client_instance.finder.return_value = mock_response++ client = LinkedinAdsClient(self.access_token)+ pages = list(client.get_creatives(self.account_id))++ assert len(pages) == 1+ assert pages[0] == ([{"id": "urn:li:sponsoredCreative:1", "name": "Creative 1"}], None)+ assert mock_client_instance.finder.call_count == 1++ call_kwargs = mock_client_instance.finder.call_args[1]+ assert call_kwargs["finder_name"] == "criteria"+ assert call_kwargs["resource_path"] == f"/adAccounts/{self.account_id}/creatives"+ assert call_kwargs["query_params"]["pageSize"] == CREATIVES_PAGE_SIZE+@mock.patch("posthog.temporal.data_imports.sources.linkedin_ads.client.RestliClient")def test_get_analytics_success(self, mock_restli_client):- """Test successful analytics retrieval."""+ """Single weekly chunk yields the API's elements unchanged."""mock_response = mock.MagicMock()mock_response.status_code = 200mock_response.elements = [@@ -120,14 +146,116 @@ class TestLinkedinAdsClient:mock_client_instance.finder.return_value = mock_responseclient = LinkedinAdsClient(self.access_token)- result = client.get_analytics(- account_id=self.account_id, pivot=LinkedinAdsPivot.CAMPAIGN, date_start="2024-01-01", date_end="2024-01-31"+ pages = list(+ client.get_analytics(+ account_id=self.account_id,+ pivot=LinkedinAdsPivot.CAMPAIGN,+ date_start="2024-01-01",+ date_end="2024-01-05",+ )+ )++ assert len(pages) == 1+ elements, next_page_token = pages[0]+ assert next_page_token is None+ assert len(elements) == 1+ assert elements[0]["impressions"] == 1000+ assert elements[0]["clicks"] == 50+ assert elements[0]["costInUsd"] == 25.50+ assert mock_client_instance.finder.call_count == 1++ @mock.patch("posthog.temporal.data_imports.sources.linkedin_ads.client.RestliClient")+ def test_get_analytics_chunks_long_date_range_weekly(self, mock_restli_client):+ """Date ranges > 7 days slice into consecutive weekly chunks (no overlap, no gaps)."""+ mock_response = mock.MagicMock()+ mock_response.status_code = 200+ mock_response.elements = [{"impressions": 100}]++ mock_client_instance = mock_restli_client.return_value+ mock_client_instance.finder.return_value = mock_response++ client = LinkedinAdsClient(self.access_token)+ # 22-day range → ceil(22/7) = 4 weekly chunks: Jan 1–7, 8–14, 15–21, 22–22.+ pages = list(+ client.get_analytics(+ account_id=self.account_id,+ pivot=LinkedinAdsPivot.CREATIVE,+ date_start="2024-01-01",+ date_end="2024-01-22",+ )+ )++ assert len(pages) == 4+ assert mock_client_instance.finder.call_count == 4++ expected_ranges = [+ {"start": {"year": 2024, "month": 1, "day": 1}, "end": {"year": 2024, "month": 1, "day": 7}},+ {"start": {"year": 2024, "month": 1, "day": 8}, "end": {"year": 2024, "month": 1, "day": 14}},+ {"start": {"year": 2024, "month": 1, "day": 15}, "end": {"year": 2024, "month": 1, "day": 21}},+ {"start": {"year": 2024, "month": 1, "day": 22}, "end": {"year": 2024, "month": 1, "day": 22}},+ ]+ actual_ranges = [+ call_args[1]["query_params"]["dateRange"] for call_args in mock_client_instance.finder.call_args_list+ ]+ assert actual_ranges == expected_ranges++ @mock.patch("posthog.temporal.data_imports.sources.linkedin_ads.client.RestliClient")+ def test_get_analytics_logs_warning_when_chunk_hits_response_cap(self, mock_restli_client):+ """A capped chunk yields its partial data and logs a warning."""+ from posthog.temporal.data_imports.sources.linkedin_ads.client import ANALYTICS_RESPONSE_CAP++ capped_response = mock.MagicMock()+ capped_response.status_code = 200+ capped_response.elements = [{"impressions": i} for i in range(ANALYTICS_RESPONSE_CAP)]++ mock_client_instance = mock_restli_client.return_value+ mock_client_instance.finder.return_value = capped_response++ client = LinkedinAdsClient(self.access_token)+ # Use structlog's own capture_logs — caplog flattens the event_dict on the+ # way through stdlib so substring matches against `record.message` miss.+ with capture_logs() as logs:+ pages = list(+ client.get_analytics(+ account_id=self.account_id,+ pivot=LinkedinAdsPivot.CREATIVE,+ date_start="2024-01-01",+ date_end="2024-01-05",+ )+ )++ assert len(pages) == 1+ assert mock_client_instance.finder.call_count == 1+ assert len(pages[0][0]) == ANALYTICS_RESPONSE_CAP+ assert any(log.get("event") == "linkedin_ads.analytics_chunk_capped" for log in logs)++ @mock.patch("posthog.temporal.data_imports.sources.linkedin_ads.client.RestliClient")+ def test_get_analytics_same_day_range_makes_one_call(self, mock_restli_client):+ """Same-day range (typical incremental run) → one chunk, one call."""+ mock_response = mock.MagicMock()+ mock_response.status_code = 200+ mock_response.elements = [{"impressions": 42}]++ mock_client_instance = mock_restli_client.return_value+ mock_client_instance.finder.return_value = mock_response++ client = LinkedinAdsClient(self.access_token)+ pages = list(+ client.get_analytics(+ account_id=self.account_id,+ pivot=LinkedinAdsPivot.CAMPAIGN,+ date_start="2024-01-15",+ date_end="2024-01-15",+ ))- assert len(result) == 1- assert result[0]["impressions"] == 1000- assert result[0]["clicks"] == 50- assert result[0]["costInUsd"] == 25.50+ assert len(pages) == 1+ assert mock_client_instance.finder.call_count == 1+ date_range = mock_client_instance.finder.call_args[1]["query_params"]["dateRange"]+ assert date_range == {+ "start": {"year": 2024, "month": 1, "day": 15},+ "end": {"year": 2024, "month": 1, "day": 15},+ }def test_format_date_range(self):"""Test date range formatting for LinkedIn API."""