: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
fix(linkedin_ads): bound initial analytics sync to a 5-year lookback (#64613)
Tom Owers171660b27db8
diff --git a/posthog/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py b/posthog/temporal/data_imports/sources/linkedin_ads/linkedin_ads.pyindex f86d834f3593..1a603a38e3ae 100644--- a/posthog/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py+++ b/posthog/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py@@ -11,7 +11,6 @@ from structlog.types import FilteringBoundLoggerfrom posthog.models.integration import Integrationfrom posthog.temporal.data_imports.naming_convention import NamingConvention-from posthog.temporal.data_imports.pipelines.helpers import incremental_type_to_initial_value, initial_datetimefrom posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcherfrom posthog.temporal.data_imports.pipelines.pipeline.typings import PartitionFormat, PartitionMode, SourceResponsefrom posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager@@ -24,6 +23,12 @@ from .schemas import FLOAT_FIELDS, RESOURCE_SCHEMAS, URN_COLUMNS, VIRTUAL_COLUMNmodule_logger = structlog.get_logger(__name__)+# On the first sync there's no saved cursor, so analytics would otherwise start from the epoch.+# Syncing stats from 1970 fans out into dozens of empty yearly windows per stats resource, and that+# call volume exhausts LinkedIn's per-member/app daily budget and trips the 429 DAY throttle. Cap the+# initial lookback like the other ad-reporting sources do (mirrors Bing Ads' 5-year window).+INITIAL_ANALYTICS_LOOKBACK_DAYS = 365 * 5+@dataclassclass LinkedInAdsResumeConfig:@@ -141,28 +146,25 @@ def linkedin_ads_source(now = dt.datetime.now()date_start = Nonedate_end = now.strftime("%Y-%m-%d")+ default_start = (now - dt.timedelta(days=INITIAL_ANALYTICS_LOOKBACK_DAYS)).strftime("%Y-%m-%d")if should_use_incremental_field and schema.filter_field_names:if incremental_field is None or incremental_field_type is None:raise ValueError("incremental_field and incremental_field_type can't be None")if db_incremental_field_last_value is None:- last_value: int | dt.datetime | dt.date | str = incremental_type_to_initial_value(- incremental_field_type- )+ date_start = default_startelse:- last_value = db_incremental_field_last_value-- if isinstance(last_value, dt.datetime):- date_start = last_value.strftime("%Y-%m-%d")- elif isinstance(last_value, dt.date):- date_start = last_value.isoformat()- elif isinstance(last_value, str):- date_start = last_value+ last_value: int | dt.datetime | dt.date | str = db_incremental_field_last_value+ if isinstance(last_value, dt.datetime):+ date_start = last_value.strftime("%Y-%m-%d")+ elif isinstance(last_value, dt.date):+ date_start = last_value.isoformat()+ elif isinstance(last_value, str):+ date_start = last_valueelse:- start_date = initial_datetime- date_start = start_date.strftime("%Y-%m-%d")+ date_start = default_startresume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else Nonestarting_page_token = resume_config.page_token if resume_config is not None else Nonediff --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 1292f58370a1..e7bc3c9d9f6f 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@@ -11,6 +11,7 @@ import pyarrow as pafrom posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcherfrom posthog.temporal.data_imports.sources.generated_configs import LinkedinAdsSourceConfigfrom posthog.temporal.data_imports.sources.linkedin_ads.linkedin_ads import (+ INITIAL_ANALYTICS_LOOKBACK_DAYS,LinkedInAdsResumeConfig,LinkedinAdsSchema,_convert_date_object_to_date,@@ -624,3 +625,64 @@ class TestLinkedinAdsSource:rows = list(items)assert rows == []manager.save_state.assert_not_called()++ @pytest.mark.parametrize("should_use_incremental_field", [True, False])+ def test_initial_sync_starts_from_bounded_lookback_not_epoch(self, mock_client_func, should_use_incremental_field):+ """First sync of an analytics resource has no cursor. The start date must be the bounded+ lookback, not 1970 — syncing stats from the epoch fans out into decades of empty yearly+ windows that exhaust LinkedIn's daily call budget."""+ mock_client = mock.MagicMock()+ mock_client.get_data_by_resource.return_value = [([], None)]+ mock_client_func.return_value = mock_client++ config = LinkedinAdsSourceConfig(linkedin_ads_integration_id=123, account_id="456")+ manager = _make_resume_manager()++ result = linkedin_ads_source(+ config=config,+ resource_name="campaign_stats",+ team_id=789,+ resumable_source_manager=manager,+ logger=mock.MagicMock(),+ should_use_incremental_field=should_use_incremental_field,+ incremental_field="date_start" if should_use_incremental_field else None,+ incremental_field_type=IncrementalFieldType.Date if should_use_incremental_field else None,+ db_incremental_field_last_value=None,+ )++ items = result.items()+ assert isinstance(items, Iterable)+ list(items)++ date_start = mock_client.get_data_by_resource.call_args[1]["date_start"]+ parsed = dt.date.fromisoformat(date_start)+ expected_floor = (dt.datetime.now() - dt.timedelta(days=INITIAL_ANALYTICS_LOOKBACK_DAYS)).date()+ assert abs((parsed - expected_floor).days) <= 1++ def test_incremental_resume_uses_saved_cursor_not_lookback(self, mock_client_func):+ """A resumed incremental sync must honour the saved cursor verbatim — the lookback floor+ only applies to the first sync, never clamps an existing cursor."""+ mock_client = mock.MagicMock()+ mock_client.get_data_by_resource.return_value = [([], None)]+ mock_client_func.return_value = mock_client++ config = LinkedinAdsSourceConfig(linkedin_ads_integration_id=123, account_id="456")+ manager = _make_resume_manager()++ result = linkedin_ads_source(+ config=config,+ resource_name="campaign_stats",+ team_id=789,+ resumable_source_manager=manager,+ logger=mock.MagicMock(),+ should_use_incremental_field=True,+ incremental_field="date_start",+ incremental_field_type=IncrementalFieldType.Date,+ db_incremental_field_last_value=dt.date(2024, 1, 1),+ )++ items = result.items()+ assert isinstance(items, Iterable)+ list(items)++ assert mock_client.get_data_by_resource.call_args[1]["date_start"] == "2024-01-01"