: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_ads): support LinkedIn Ads API version 202606 (#71665)
Tom Owers567e6419d80d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/client.pyindex 5db76680f1bd..7cfead6d3bde 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/client.py@@ -23,6 +23,8 @@ logger = structlog.get_logger(__name__)LINKEDIN_SPONSORED_URN_PREFIX = "urn:li:sponsored"MAX_PAGE_SIZE = 1000CREATIVES_PAGE_SIZE = 100 # creatives backend returns transient 500s on heavier requests+# Default LinkedIn Marketing API version header. Callers pass a resolved version through the+# source's version dispatch; this default backs the legacy `v1` pin and credential-probe paths.API_VERSION = "202508"# `q=analytics` silently truncates a response at 15k elements. With DAILY granularity an element@@ -119,12 +121,12 @@ def _retry_wait(retry_state: RetryCallState) -> float:class LinkedinAdsClient:"""LinkedIn Marketing API client."""- def __init__(self, access_token: str):+ def __init__(self, access_token: str, api_version: str = API_VERSION):if not access_token:raise ValueError("Access token required")self.access_token = access_tokenself.client = RestliClient()- self.api_version = API_VERSION+ self.api_version = api_versiondef get_accounts(self) -> list[dict[str, Any]]:"""Every ad account the authorized member can access. `q=search` is paginated, so a singlediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/linkedin_ads.pyindex e8cc96cb3e33..1d29e0aae4d1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py@@ -23,7 +23,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import LinkedinAdsSourceConfigfrom products.warehouse_sources.backend.types import IncrementalFieldType-from .client import LinkedinAdsClient, LinkedinAdsDailyRateLimitError, LinkedinAdsResource+from .client import API_VERSION, LinkedinAdsClient, LinkedinAdsDailyRateLimitError, LinkedinAdsResourcefrom .schemas import FLOAT_FIELDS, RESOURCE_SCHEMAS, URN_COLUMNS, VIRTUAL_COLUMN_URN_MAPPINGmodule_logger = structlog.get_logger(__name__)@@ -152,7 +152,9 @@ def _get_integration(integration_id: int, team_id: int) -> Integration:_backoff_sleep(attempt)-def linkedin_ads_client_for_integration(integration_id: int, team_id: int) -> LinkedinAdsClient:+def linkedin_ads_client_for_integration(+ integration_id: int, team_id: int, api_version: str = API_VERSION+) -> LinkedinAdsClient:"""Initialize a LinkedIn Ads client from an OAuth integration id."""integration = _get_integration(integration_id, team_id)@@ -169,12 +171,14 @@ def linkedin_ads_client_for_integration(integration_id: int, team_id: int) -> Liif not integration.access_token:raise LinkedinAdsMissingTokenError("LinkedIn Ads integration does not have an access token")- return LinkedinAdsClient(integration.access_token)+ return LinkedinAdsClient(integration.access_token, api_version=api_version)-def linkedin_ads_client(config: LinkedinAdsSourceConfig, team_id: int) -> LinkedinAdsClient:+def linkedin_ads_client(+ config: LinkedinAdsSourceConfig, team_id: int, api_version: str = API_VERSION+) -> LinkedinAdsClient:"""Initialize a LinkedIn Ads client with provided config."""- return linkedin_ads_client_for_integration(config.linkedin_ads_integration_id, team_id)+ return linkedin_ads_client_for_integration(config.linkedin_ads_integration_id, team_id, api_version=api_version)def linkedin_ads_source(@@ -187,6 +191,7 @@ def linkedin_ads_source(db_incremental_field_last_value: typing.Any = None,incremental_field: str | None = None,incremental_field_type: IncrementalFieldType | None = None,+ api_version: str = API_VERSION,) -> SourceResponse:"""A data warehouse LinkedIn Ads source.@@ -197,7 +202,7 @@ def linkedin_ads_source(schema = get_schemas()[resource_name]def get_rows() -> collections.abc.Iterator[pa.Table]:- client = linkedin_ads_client(config, team_id)+ client = linkedin_ads_client(config, team_id, api_version=api_version)resource = LinkedinAdsResource(resource_name)# Determine date range for analytics resourcesdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/source.pyindex d64c2a17ae4c..3920d683238a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/source.py@@ -19,6 +19,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (MARKETING_ANALYTICS_SUGGESTED_TABLE_TOOLTIP,+ UNVERSIONED_API_VERSION,FieldType,ResumableSource,)@@ -36,7 +37,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.schfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import LinkedinAdsSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType-from .client import LinkedinAdsApiError, LinkedinAdsDailyRateLimitError+from .client import API_VERSION, LinkedinAdsApiError, LinkedinAdsDailyRateLimitErrorfrom .linkedin_ads import (LinkedinAdsMissingTokenError,LinkedInAdsResumeConfig,@@ -47,10 +48,23 @@ from .linkedin_ads import (linkedin_ads_source,)+# LinkedIn's Marketing API uses monthly date-based versioning (YYYYMM) sent as a request header.+LINKEDIN_ADS_VERSION_202606 = "202606"++# Opaque source version label -> LinkedIn API version header. The legacy `v1` pin keeps sending the+# header it always has (`API_VERSION`), so existing syncs are byte-for-byte unchanged.+_API_HEADER_BY_VERSION = {+ UNVERSIONED_API_VERSION: API_VERSION,+ LINKEDIN_ADS_VERSION_202606: LINKEDIN_ADS_VERSION_202606,+}+@SourceRegistry.registerclass LinkedInAdsSource(ResumableSource[LinkedinAdsSourceConfig, LinkedInAdsResumeConfig], OAuthMixin):- api_docs_url = "https://learn.microsoft.com/en-us/linkedin/marketing/"+ api_docs_url = "https://learn.microsoft.com/en-us/linkedin/marketing/versioning"++ supported_versions = (UNVERSIONED_API_VERSION, LINKEDIN_ADS_VERSION_202606)+ default_version = LINKEDIN_ADS_VERSION_202606lists_tables_without_credentials = True # static endpoint catalog — safe for public docs@@ -145,8 +159,12 @@ class LinkedInAdsSource(ResumableSource[LinkedinAdsSourceConfig, LinkedInAdsResuself, integration_id: int, team_id: int, search: str | None = None) -> list[IntegrationAccount]:# A member's ad accounts are few, so `search` is ignored here and the endpoint filters the list.+ # List against the default version's header (not the client's legacy default) so the account+ # picker tracks the version new sources are created on, rather than the oldest declared label.try:- client = linkedin_ads_client_for_integration(integration_id, team_id)+ client = linkedin_ads_client_for_integration(+ integration_id, team_id, api_version=_API_HEADER_BY_VERSION[self.default_version]+ )except Integration.DoesNotExist as e:raise IntegrationAccountListingError("Your LinkedIn Ads connection is no longer available — it may have been disconnected. "@@ -247,12 +265,17 @@ class LinkedInAdsSource(ResumableSource[LinkedinAdsSourceConfig, LinkedInAdsResuresumable_source_manager: ResumableSourceManager[LinkedInAdsResumeConfig],inputs: SourceInputs,) -> SourceResponse:+ # `inputs.api_version` is already resolved upstream; resolving again is idempotent and keeps+ # this correct if ever called with a raw pin. An unmapped label passes through to LinkedIn.+ resolved_version = self.resolve_api_version(inputs.api_version)+ api_version = _API_HEADER_BY_VERSION.get(resolved_version, resolved_version)return linkedin_ads_source(config=config,resource_name=inputs.schema_name,team_id=inputs.team_id,resumable_source_manager=resumable_source_manager,logger=inputs.logger,+ api_version=api_version,should_use_incremental_field=inputs.should_use_incremental_field,incremental_field=inputs.incremental_field if inputs.should_use_incremental_field else None,incremental_field_type=inputs.incremental_field_type if inputs.should_use_incremental_field else None,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_client.pyindex 02b5cfc03387..0deacc1f1cca 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_client.py@@ -45,6 +45,21 @@ class TestLinkedinAdsClient:assert result == [{"id": "123", "name": "Test Account"}]mock_client_instance.finder.assert_called_once()+ @pytest.mark.parametrize("api_version", ["202508", "202606"])+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.client.RestliClient")+ def test_request_sends_configured_api_version(self, mock_restli_client, api_version):+ """The configured version must reach the Restli `version_string`, else every request hits+ the wrong LinkedIn API version regardless of the source's pin."""+ mock_response = mock.MagicMock()+ mock_response.status_code = 200+ mock_response.elements = [{"id": "123", "name": "Test Account"}]+ mock_restli_client.return_value.finder.return_value = mock_response++ client = LinkedinAdsClient(self.access_token, api_version=api_version)+ client.get_accounts()++ assert mock_restli_client.return_value.finder.call_args.kwargs["version_string"] == api_version+@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.client.RestliClient")def test_get_accounts_collects_every_page(self, mock_restli_client):page_one = mock.MagicMock()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_source.pyindex 3c99815d7072..7b70ff7676b8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_source.py@@ -5,7 +5,10 @@ from unittest import mockfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import LinkedinAdsSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.client import LinkedinAdsClient-from products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.source import LinkedInAdsSource+from products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.source import (+ LINKEDIN_ADS_VERSION_202606,+ LinkedInAdsSource,+)class TestLinkedInAdsSource:@@ -45,6 +48,49 @@ class TestLinkedInAdsSource:non_retryable_errors = self.source.get_non_retryable_errors()assert not any(key in other_error for key in non_retryable_errors)+ def test_defaults_new_sources_to_202606(self):+ assert self.source.default_version == LINKEDIN_ADS_VERSION_202606+ assert set(self.source.supported_versions) == {"v1", LINKEDIN_ADS_VERSION_202606}++ @pytest.mark.parametrize(+ "pinned_version,expected_header",+ [+ # Existing sources pinned to the legacy label must keep sending the header they always+ # sent (202508), so their syncs stay byte-for-byte unchanged after the default flip.+ ("v1", "202508"),+ (LINKEDIN_ADS_VERSION_202606, "202606"),+ # No pin resolves to the new default.+ (None, "202606"),+ # An undeclared pin is honored verbatim and passed straight through for LinkedIn to validate.+ ("209901", "209901"),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.source.linkedin_ads_source"+ )+ def test_source_for_pipeline_dispatches_resolved_api_version(+ self, mock_linkedin_ads_source, pinned_version, expected_header+ ):+ inputs = mock.MagicMock()+ inputs.api_version = pinned_version+ inputs.should_use_incremental_field = False++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_linkedin_ads_source.call_args.kwargs["api_version"] == expected_header++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.source.linkedin_ads_client_for_integration"+ )+ def test_get_oauth_accounts_uses_default_version_header(self, mock_client_for_integration):+ # The account picker must track the default version's header, not the client's legacy default,+ # so listing doesn't break for new sources once the oldest declared header sunsets.+ mock_client_for_integration.return_value.get_accounts.return_value = []++ self.source.get_oauth_accounts(integration_id=456, team_id=self.team_id)++ assert mock_client_for_integration.call_args.kwargs["api_version"] == "202606"+def test_validate_credentials_missing_account_id(self):"""Test credential validation with missing account ID."""invalid_config = LinkedinAdsSourceConfig(linkedin_ads_integration_id=456, account_id="")