Skip to content

: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.

fix(warehouse-sources): request x ads stats in six-day windows (#129910)

estefaniaa692c53ee889
diff --git a/products/warehouse_sources/sources/twitter_ads/source.py b/products/warehouse_sources/sources/twitter_ads/source.py
index 4d50b2c5eacc..67aa87cc1cdc 100644
--- a/products/warehouse_sources/sources/twitter_ads/source.py
+++ b/products/warehouse_sources/sources/twitter_ads/source.py
@@ -210,4 +210,5 @@ class TwitterAdsSource(ResumableSource[TwitterAdsSourceConfig, TwitterAdsResumeC
inputs.schema_name,
resumable_source_manager,
inputs.db_incremental_field_last_value if inputs.should_use_incremental_field else None,
+ inputs.logger,
)
diff --git a/products/warehouse_sources/sources/twitter_ads/tests/test_twitter_ads.py b/products/warehouse_sources/sources/twitter_ads/tests/test_twitter_ads.py
index d79a86b7c4f9..3b104418e206 100644
--- a/products/warehouse_sources/sources/twitter_ads/tests/test_twitter_ads.py
+++ b/products/warehouse_sources/sources/twitter_ads/tests/test_twitter_ads.py
@@ -67,7 +67,7 @@ def test_signing_pagination_and_resume(client: TwitterAdsClient, manager: MagicM
response({"data": [{"id": "two", "deleted": True}], "next_cursor": None}),
],
) as send:
- resource = twitter_ads_source(client, "account", "campaigns", manager, None)
+ resource = twitter_ads_source(client, "account", "campaigns", manager, None, MagicMock())
assert list(sync_items(resource)) == [[{"id": "one"}], [{"id": "two", "deleted": True}]]
requests_sent = [call.args[0] for call in send.call_args_list]
assert isinstance(client.session.auth, OAuth1)
@@ -98,7 +98,7 @@ def test_entity_page_request_respects_per_table_limits(
client: TwitterAdsClient, manager: MagicMock, table: str, count: str, sort_by: list[str] | None
) -> None:
with patch.object(client.session, "send", return_value=response({"data": [], "next_cursor": None})) as send:
- list(sync_items(twitter_ads_source(client, "account", table, manager, None)))
+ list(sync_items(twitter_ads_source(client, "account", table, manager, None, MagicMock())))
url = urlparse(request_url(send.call_args.args[0]))
params = parse_qs(url.query)
assert url.path == f"/12/accounts/account/{table}"
@@ -149,7 +149,8 @@ def test_stats_limits_daily_rows_currency_and_dst(
end = datetime.fromisoformat(params["end_time"][0]).astimezone(account_timezone)
ids = params["entity_ids"][0].split(",")
assert len(ids) <= 20
- assert end.astimezone(UTC) - start.astimezone(UTC) <= timedelta(days=7)
+ # X rejects every exact week on a half-hour-offset account with a misleading entity error.
+ assert end.astimezone(UTC) - start.astimezone(UTC) < timedelta(days=7)
# X rejects a DAY window whose bounds are not midnight in the ad account's own timezone,
# which means the offset in force on each date rather than today's.
assert start.hour == end.hour == 0
@@ -185,7 +186,7 @@ def test_stats_limits_daily_rows_currency_and_dst(
time_machine.travel("2025-11-10T20:00:00Z", tick=False),
patch.object(client.session, "send", side_effect=send),
):
- resource = twitter_ads_source(client, "account", table, manager, incremental_since)
+ resource = twitter_ads_source(client, "account", table, manager, incremental_since, MagicMock())
rows = [row for page in sync_items(resource) for row in page]
start = incremental_since or date(2025, 10, 25)
today = datetime(2025, 11, 10, 20, tzinfo=UTC).astimezone(account_timezone).date()
diff --git a/products/warehouse_sources/sources/twitter_ads/tests/test_twitter_ads_source.py b/products/warehouse_sources/sources/twitter_ads/tests/test_twitter_ads_source.py
index 8015ee41860c..b3413c071d0d 100644
--- a/products/warehouse_sources/sources/twitter_ads/tests/test_twitter_ads_source.py
+++ b/products/warehouse_sources/sources/twitter_ads/tests/test_twitter_ads_source.py
@@ -119,4 +119,4 @@ def test_unsupported_version_and_unknown_table_fail_before_http() -> None:
with pytest.raises(ValueError, match="Unsupported X Ads API version"):
TwitterAdsClient(integration, "11")
with pytest.raises(ValueError, match="Unknown X Ads table"):
- twitter_ads_source(TwitterAdsClient(integration), "account", "unknown", MagicMock(), None)
+ twitter_ads_source(TwitterAdsClient(integration), "account", "unknown", MagicMock(), None, MagicMock())
diff --git a/products/warehouse_sources/sources/twitter_ads/twitter_ads.py b/products/warehouse_sources/sources/twitter_ads/twitter_ads.py
index c23c2b225b6a..b83341f31162 100644
--- a/products/warehouse_sources/sources/twitter_ads/twitter_ads.py
+++ b/products/warehouse_sources/sources/twitter_ads/twitter_ads.py
@@ -6,6 +6,7 @@ from zoneinfo import ZoneInfo
import requests
from requests_oauthlib import OAuth1
+from structlog.types import FilteringBoundLogger
from products.warehouse_sources.sources.sdk import (
IntegrationRecord,
@@ -38,11 +39,13 @@ class TwitterAdsResumeConfig:
complete: bool = False
-# X rejects a stats window wider than this.
-MAX_STATS_WINDOW = timedelta(days=7)
+# X caps a stats window at 7 days but rejects some exact weeks: one with a fall-back hour, and every week on a
+# half-hour-offset account, which X reports as a misleading INVALID_PARAMETER (entity) error.
+STATS_WINDOW = timedelta(days=6)
# Cap on how much of X's error body rides along in the exception message.
_MAX_ERROR_DETAIL = 300
+_MAX_LOGGED_BODY = 2000
def _account_midnight(day: date, account_timezone: ZoneInfo) -> datetime:
@@ -181,6 +184,7 @@ class TwitterAdsClient:
manager: ResumableSourceManager[TwitterAdsResumeConfig],
state: TwitterAdsResumeConfig,
incremental_since: str | date | datetime | None,
+ logger: FilteringBoundLogger,
) -> Iterator[list[dict[str, Any]]]:
account_path = f"accounts/{quote(account_id, safe='')}"
account = self.get(account_path, {"with_deleted": "true"})["data"]
@@ -209,33 +213,36 @@ class TwitterAdsClient:
start = date.fromisoformat(state.next_date)
end = date.fromisoformat(state.end_date) if state.end_date else account_now.date()
while start < end:
- window_end = min(start + timedelta(days=7), end)
+ window_end = min(start + STATS_WINDOW, end)
# X checks for whole hours in the account's timezone, not UTC, so local midnight on a
# half-hour offset (18:30Z for UTC+5:30) is valid and a whole UTC hour (19:00Z) is not.
start_time = _account_midnight(start, account_timezone)
end_time = _account_midnight(window_end, account_timezone)
- # A week containing a fall-back transition spans 169 hours, one over X's ceiling, so
- # hand that window a day back rather than letting the request 400.
- while end_time - start_time > MAX_STATS_WINDOW:
- window_end -= timedelta(days=1)
- end_time = _account_midnight(window_end, account_timezone)
for batch_start in range(0, len(entity_ids), 20):
for placement in PLACEMENTS:
- payload = self.get(
- f"stats/{account_path}",
- {
- "entity": STATS_TABLES[table],
- "entity_ids": ",".join(entity_ids[batch_start : batch_start + 20]),
- # X's docs say a bare date means midnight in the account's timezone, but
- # X rejects bare dates for DAY windows on non-UTC accounts with
- # INVALID_TIME_WINDOW. Send local midnight as a UTC timestamp instead.
- "start_time": _utc_param(start_time),
- "end_time": _utc_param(end_time),
- "granularity": "DAY",
- "placement": placement,
- "metric_groups": "ENGAGEMENT,BILLING",
- },
- )
+ params: dict[str, str | int] = {
+ "entity": STATS_TABLES[table],
+ "entity_ids": ",".join(entity_ids[batch_start : batch_start + 20]),
+ # X's docs say a bare date means midnight in the account's timezone, but
+ # X rejects bare dates for DAY windows on non-UTC accounts with
+ # INVALID_TIME_WINDOW. Send local midnight as a UTC timestamp instead.
+ "start_time": _utc_param(start_time),
+ "end_time": _utc_param(end_time),
+ "granularity": "DAY",
+ "placement": placement,
+ "metric_groups": "ENGAGEMENT,BILLING",
+ }
+ try:
+ payload = self.get(f"stats/{account_path}", params)
+ except requests.HTTPError as error:
+ if error.response is not None:
+ # The exception message keeps a short summary; the body also echoes how X parsed the request.
+ logger.warning(
+ "twitter_ads_stats_rejected",
+ params=params,
+ body=error.response.text[:_MAX_LOGGED_BODY],
+ )
+ raise
rows = self.stats_rows(payload, start, window_end, placement, currencies, account_id)
if batch_start + 20 >= len(entity_ids) and placement == PLACEMENTS[-1]:
manager.save_state(
@@ -253,6 +260,7 @@ def twitter_ads_source(
table: str,
manager: ResumableSourceManager[TwitterAdsResumeConfig],
incremental_since: str | date | datetime | None,
+ logger: FilteringBoundLogger,
) -> SourceResponse:
if table not in ENTITY_TABLES and table not in STATS_TABLES:
raise ValueError("Unknown X Ads table")
@@ -262,7 +270,7 @@ def twitter_ads_source(
if state.complete:
return
if table in STATS_TABLES:
- yield from client.stats(account_id, table, manager, state, incremental_since)
+ yield from client.stats(account_id, table, manager, state, incremental_since, logger)
else:
for page in client.pages(f"accounts/{quote(account_id, safe='')}/{table}", state.cursor):
cursor = page.get("next_cursor")