: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(twitter_ads): cap stats backfill start date to a supported window (#112150)
Tom Owersf3c4adb1ff17
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/settings.pyindex b057c252dbdf..4c649277e304 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/settings.py@@ -3,6 +3,9 @@ ENTITY_TABLES = ("campaigns", "line_items", "promoted_tweets", "funding_instrumeSTATS_TABLES = {"campaign_stats": "CAMPAIGN", "line_item_stats": "LINE_ITEM"}PLACEMENTS = ("ALL_ON_TWITTER", "SPOTLIGHT", "TREND")LOOKBACK_SECONDS = 3 * 24 * 60 * 60+# The synchronous stats endpoint we use rejects dates further back than this with a 400;+# X's docs say onboarding backfills should use the (unimplemented) async analytics endpoint instead.+MAX_STATS_BACKFILL_DAYS = 90REVOKED_GRANT = "Your X Ads connection is no longer valid. Reconnect your X account, then re-enable the sync."ACCOUNT_ACCESS_DENIED = ("The connected X account cannot access this ad account. Check its ad-account permissions, then reconnect."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/tests/test_twitter_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/tests/test_twitter_ads.pyindex 5278c2b99ffd..e873756fe01c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/tests/test_twitter_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/tests/test_twitter_ads.py@@ -23,7 +23,10 @@ from requests_oauthlib import OAuth1from posthog.models.integration.model import Integrationfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse-from products.warehouse_sources.backend.temporal.data_imports.sources.twitter_ads.settings import PLACEMENTS+from products.warehouse_sources.backend.temporal.data_imports.sources.twitter_ads.settings import (+ MAX_STATS_BACKFILL_DAYS,+ PLACEMENTS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.twitter_ads.twitter_ads import (TwitterAdsClient,TwitterAdsResumeConfig,@@ -182,6 +185,31 @@ def test_stats_limits_daily_rows_currency_and_dst(assert max(row["date"] for row in resumed) == date(2025, 11, 9)+def test_stats_backfill_caps_start_date_for_old_accounts(client: TwitterAdsClient, manager: MagicMock) -> None:+ timezone = fixed_timezone(timedelta(hours=-8))+ starts = []++ def send(request: requests.PreparedRequest, **kwargs: object) -> requests.Response:+ path = urlparse(request_url(request)).path+ if path.endswith("/funding_instruments"):+ return response({"data": [{"id": "funding", "currency": "EUR"}]})+ if path.endswith("/campaigns"):+ return response({"data": [{"id": "campaign-00", "funding_instrument_id": "funding"}]})+ if "/stats/" not in path:+ return response({"data": {"timezone": "America/Los_Angeles", "created_at": "2015-01-01T00:00:00Z"}})+ params = parse_qs(urlparse(request_url(request)).query)+ starts.append(datetime.fromisoformat(params["start_time"][0]).astimezone(timezone).date())+ return response({"data": [{"id": "campaign-00", "id_data": [{"segment": None, "metrics": {}}]}]})++ with (+ time_machine.travel("2025-11-10T20:00:00Z", tick=False),+ patch.object(client.session, "send", side_effect=send),+ ):+ resource = twitter_ads_source(client, "account", "campaign_stats", manager, None)+ list(sync_items(resource))+ assert min(starts) == date(2025, 11, 10) - timedelta(days=MAX_STATS_BACKFILL_DAYS)++def test_daily_null_metrics_are_not_shifted(client: TwitterAdsClient) -> None:rows = client.stats_rows({diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/twitter_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/twitter_ads.pyindex c1d395848217..3de545c0e164 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/twitter_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter_ads/twitter_ads.py@@ -24,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typfrom products.warehouse_sources.backend.temporal.data_imports.sources.twitter_ads.settings import (API_VERSION,ENTITY_TABLES,+ MAX_STATS_BACKFILL_DAYS,MISSING_APP,MISSING_INTEGRATION,PARTITION_KEYS,@@ -145,11 +146,13 @@ class TwitterAdsClient:entity_ids = sorted(row["id"] for row in entities)if not entity_ids:return- start = (- date.fromisoformat(str(incremental_since)[:10])- if incremental_since is not None- else datetime.fromisoformat(account["created_at"].replace("Z", "+00:00")).astimezone(timezone).date()- )+ if incremental_since is not None:+ start = date.fromisoformat(str(incremental_since)[:10])+ else:+ created_at = (+ datetime.fromisoformat(account["created_at"].replace("Z", "+00:00")).astimezone(timezone).date()+ )+ start = max(created_at, account_now.date() - timedelta(days=MAX_STATS_BACKFILL_DAYS))if state.next_date:start = date.fromisoformat(state.next_date)end = date.fromisoformat(state.end_date) if state.end_date else account_now.date()