: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(meta_ads): clamp insights since date to supported window (#63969)
Tom Owerscbbd6af72243
diff --git a/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py b/posthog/temporal/data_imports/sources/meta_ads/meta_ads.pyindex 1c526c4f5ff2..ef9c44ebb2e8 100644--- a/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py+++ b/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py@@ -19,11 +19,25 @@ from posthog.temporal.data_imports.sources.meta_ads.schemas import RESOURCE_SCHEfrom products.data_warehouse.backend.types import IncrementalFieldType-# Meta Ads API only supports data from the last 3 years+# Meta Ads API only supports data from the last 3 years. Meta's insights endpoints+# reject a `time_range` whose start is beyond ~37 months from today with error code+# 3018 ("The start date of the time range cannot be beyond 37 months from the current+# date"); 3 * 365 days stays comfortably inside that window.META_ADS_MAX_HISTORY_DAYS = 3 * 365DEFAULT_SYNC_LOOKBACK_DAYS = 90+def _earliest_supported_since(today: dt.date) -> dt.date:+ """Earliest ``since`` date Meta will accept for an insights ``time_range``.++ Meta rejects insights queries whose start is beyond ~37 months from today with+ error code 3018. We clamp to ``META_ADS_MAX_HISTORY_DAYS`` (kept safely under that+ limit) so a `since` derived from an aged incremental cursor — or from a dormant+ account whose latest activity sits near the boundary — never trips it.+ """+ return today - dt.timedelta(days=META_ADS_MAX_HISTORY_DAYS)++@dataclassclass MetaAdsResumeConfig:"""Resume state for a Meta Ads sync.@@ -513,6 +527,11 @@ def meta_ads_source(raise ValueError("Access token is required for Meta Ads integration")# Determine date range for incremental sync+ today = dt.date.today()+ # Never request data older than Meta will serve, otherwise it returns a hard+ # 400 (code 3018) and the whole sync fails instead of importing the supported+ # window. Data beyond this point is unavailable from Meta regardless.+ earliest_since = _earliest_supported_since(today)time_range = Noneif should_use_incremental_field:@@ -520,21 +539,22 @@ def meta_ads_source(raise ValueError("incremental_field and incremental_field_type can't be None")if db_incremental_field_last_value is None:- last_value: dt.date = dt.date.today() - dt.timedelta(days=sync_lookback_days)+ last_value: dt.date = today - dt.timedelta(days=sync_lookback_days)else:last_value = db_incremental_field_last_value- start_date = last_value.strftime("%Y-%m-%d")- # Meta Ads API is day based so only import if the day is complete- end_date = dt.date.today().strftime("%Y-%m-%d")+ since = last_value.date() if isinstance(last_value, dt.datetime) else last_value+ since = max(since, earliest_since)time_range = {- "since": start_date,- "until": end_date,+ "since": since.strftime("%Y-%m-%d"),+ # Meta Ads API is day based so only import if the day is complete+ "until": today.strftime("%Y-%m-%d"),}elif schema.is_stats:+ since = max(today - dt.timedelta(days=sync_lookback_days), earliest_since)time_range = {- "since": (dt.date.today() - dt.timedelta(days=sync_lookback_days)).strftime("%Y-%m-%d"),- "until": dt.date.today().strftime("%Y-%m-%d"),+ "since": since.strftime("%Y-%m-%d"),+ "until": today.strftime("%Y-%m-%d"),}formatted_url = schema.url.format(diff --git a/posthog/temporal/data_imports/sources/meta_ads/test_meta_ads.py b/posthog/temporal/data_imports/sources/meta_ads/test_meta_ads.pyindex 6e7ade32057b..7efe9e3374cc 100644--- a/posthog/temporal/data_imports/sources/meta_ads/test_meta_ads.py+++ b/posthog/temporal/data_imports/sources/meta_ads/test_meta_ads.py@@ -1,16 +1,20 @@import json-from typing import Any+import datetime as dt+from typing import Any, castimport pytest+from freezegun import freeze_timefrom unittest import mockfrom posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom posthog.temporal.data_imports.sources.generated_configs import MetaAdsSourceConfigfrom posthog.temporal.data_imports.sources.meta_ads import meta_ads as meta_ads_modulefrom posthog.temporal.data_imports.sources.meta_ads.meta_ads import (+ META_ADS_MAX_HISTORY_DAYS,META_AUTH_ERROR_MESSAGE,PAGE_LIMIT_FALLBACK_SIZES,MetaAdsResumeConfig,+ _earliest_supported_since,_is_permanent_auth_error,_iter_simple_pagination,_iter_time_range_pagination,@@ -18,9 +22,12 @@ from posthog.temporal.data_imports.sources.meta_ads.meta_ads import (_override_limit,_strip_access_token,get_integration,+ meta_ads_source,)from posthog.temporal.data_imports.sources.meta_ads.source import MetaAdsSource+from products.data_warehouse.backend.types import IncrementalFieldType+def _mock_response(status: int, body: dict) -> mock.MagicMock:response = mock.MagicMock()@@ -819,6 +826,84 @@ class TestNonRetryableErrors:assert _is_permanent_auth_error(_mock_response(400, body)) is expected+@freeze_time("2026-06-16")+class TestTimeRangeClamping:+ """Meta rejects insights time ranges starting beyond ~37 months (error 3018).++ The `since` we build must stay inside Meta's supported window, even when it is+ derived from an aged incremental cursor.++ The date is frozen so the ``today`` captured in the test and the+ ``dt.date.today()`` read inside ``get_rows`` always agree (no midnight race).+ """++ def _capture_time_range(self, monkeypatch, **source_kwargs: Any) -> dict | None:+ integration = mock.MagicMock()+ integration.access_token = "token"+ monkeypatch.setattr(meta_ads_module, "get_integration", lambda config, team_id: integration)++ captured: dict[str, Any] = {}++ def fake_request(url, params, access_token, time_range, resumable_source_manager):+ captured["time_range"] = time_range+ yield from ()++ monkeypatch.setattr(meta_ads_module, "_make_paginated_api_request", fake_request)++ config = mock.MagicMock()+ config.account_id = "act_123"+ config.meta_ads_integration_id = 1+ config.sync_lookback_days = source_kwargs.pop("sync_lookback_days", None)++ response = meta_ads_source(+ resource_name="campaign_stats",+ config=config,+ team_id=1,+ resumable_source_manager=_build_manager(),+ **source_kwargs,+ )+ list(cast(Any, response.items()))+ return captured["time_range"]++ @pytest.mark.parametrize(+ "days_ago,should_clamp",+ [+ # A dormant account's stored cursor has aged past Meta's 37-month limit.+ (META_ADS_MAX_HISTORY_DAYS + 200, True),+ # A recent cursor sits comfortably inside the supported window.+ (5, False),+ ],+ )+ def test_incremental_cursor_clamping(self, monkeypatch, days_ago: int, should_clamp: bool) -> None:+ today = dt.date.today()+ cursor = today - dt.timedelta(days=days_ago)++ time_range = self._capture_time_range(+ monkeypatch,+ should_use_incremental_field=True,+ incremental_field="date_start",+ incremental_field_type=IncrementalFieldType.Date,+ db_incremental_field_last_value=cursor,+ )++ assert time_range is not None+ expected_since = _earliest_supported_since(today) if should_clamp else cursor+ assert time_range["since"] == expected_since.strftime("%Y-%m-%d")+ assert time_range["until"] == today.strftime("%Y-%m-%d")++ def test_stats_lookback_is_clamped_to_supported_window(self, monkeypatch) -> None:+ today = dt.date.today()++ time_range = self._capture_time_range(+ monkeypatch,+ sync_lookback_days=10_000, # capped to META_ADS_MAX_HISTORY_DAYS upstream+ should_use_incremental_field=False,+ )++ assert time_range is not None+ assert time_range["since"] == _earliest_supported_since(today).strftime("%Y-%m-%d")++class TestGetIntegration:def test_refreshes_stale_db_connection_before_query(self, monkeypatch) -> None:# `get_integration` runs lazily inside `get_rows` on a worker thread whose