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(data-warehouse): align X Ads stats windows to the account's local midnight (#112155)

Tom Owers73ef54745c9d
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.py
index e873756fe01c..bb4283cff14a 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
@@ -1,12 +1,6 @@
import json
from collections.abc import Iterable
-from datetime import (
- UTC,
- date,
- datetime,
- timedelta,
- timezone as fixed_timezone,
-)
+from datetime import UTC, date, datetime, timedelta
from typing import Any, cast
from urllib.parse import parse_qs, urlparse
from zoneinfo import ZoneInfo
@@ -102,8 +96,8 @@ def test_stats_limits_daily_rows_currency_and_dst(
client: TwitterAdsClient, manager: MagicMock, table: str, incremental_since: date | None
) -> None:
account_timezone = ZoneInfo("America/Los_Angeles")
- timezone = fixed_timezone(timedelta(hours=-8))
calls = []
+ offsets = set()
campaigns = [{"id": f"campaign-{i:02}", "funding_instrument_id": "funding"} for i in range(21)]
line_items = [{"id": f"line-{i:02}", "campaign_id": campaign["id"]} for i, campaign in enumerate(campaigns)]
@@ -119,15 +113,16 @@ def test_stats_limits_daily_rows_currency_and_dst(
return response({"data": line_items})
if "/stats/" not in path:
return response({"data": {"timezone": account_timezone.key, "created_at": "2025-10-25T10:00:00Z"}})
- start = datetime.fromisoformat(params["start_time"][0]).astimezone(timezone)
- end = datetime.fromisoformat(params["end_time"][0]).astimezone(timezone)
+ start = datetime.fromisoformat(params["start_time"][0]).astimezone(account_timezone)
+ 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)
- assert params["start_time"][0].endswith("T08:00:00Z")
- assert params["end_time"][0].endswith("T08:00:00Z")
+ # 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
assert start.minute == end.minute == 0
+ offsets.update({start.utcoffset(), end.utcoffset()})
assert params["granularity"] == ["DAY"]
assert params["metric_groups"] == ["ENGAGEMENT,BILLING"]
assert params["entity"] == ["CAMPAIGN" if table == "campaign_stats" else "LINE_ITEM"]
@@ -170,6 +165,9 @@ def test_stats_limits_daily_rows_currency_and_dst(
assert min(row["date"] for row in rows) == start
assert max(row["date"] for row in rows) == date(2025, 11, 9)
assert {call[2] for call in calls} == set(PLACEMENTS)
+ # The window walked across the November fall-back, so it must have used both offsets. Without
+ # this the midnight assertions above would still pass on a range that never changes offset.
+ assert offsets == {timedelta(hours=-7), timedelta(hours=-8)}
assert resource.primary_keys == ["entity_id", "date", "placement"]
assert resource.partition_keys == ["date"]
assert resource.sort_mode is None
@@ -186,7 +184,7 @@ def test_stats_limits_daily_rows_currency_and_dst(
def test_stats_backfill_caps_start_date_for_old_accounts(client: TwitterAdsClient, manager: MagicMock) -> None:
- timezone = fixed_timezone(timedelta(hours=-8))
+ account_timezone = ZoneInfo("America/Los_Angeles")
starts = []
def send(request: requests.PreparedRequest, **kwargs: object) -> requests.Response:
@@ -198,7 +196,7 @@ def test_stats_backfill_caps_start_date_for_old_accounts(client: TwitterAdsClien
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())
+ starts.append(datetime.fromisoformat(params["start_time"][0]).astimezone(account_timezone).date())
return response({"data": [{"id": "campaign-00", "id_data": [{"segment": None, "metrics": {}}]}]})
with (
@@ -226,3 +224,75 @@ def test_daily_null_metrics_are_not_shifted(client: TwitterAdsClient) -> None:
assert [row["impressions"] for row in rows] == [10, None, 30]
assert [row["date"] for row in rows] == [date(2025, 1, 1), date(2025, 1, 2), date(2025, 1, 3)]
assert all(row["clicks"] is None for row in rows)
+
+
+def test_historical_window_uses_the_offset_in_force_on_that_date(client: TwitterAdsClient, manager: MagicMock) -> None:
+ # Reported from production: a backfill run in October (PDT) reached back to February (PST) and
+ # X answered 400, because every window carried today's offset instead of the one that applied
+ # on the day being requested.
+ windows = []
+
+ def send(request: requests.PreparedRequest, **kwargs: object) -> requests.Response:
+ url = request_url(request)
+ params = parse_qs(urlparse(url).query)
+ path = urlparse(url).path
+ if path.endswith("/funding_instruments"):
+ return response({"data": [{"id": "funding", "currency": "USD"}]})
+ if path.endswith("/campaigns"):
+ return response({"data": [{"id": "campaign", "funding_instrument_id": "funding"}]})
+ if "/stats/" not in path:
+ return response({"data": {"timezone": "America/Los_Angeles", "created_at": "2020-01-01T10:00:00Z"}})
+ windows.append((params["start_time"][0], params["end_time"][0]))
+ return response({"data": [{"id": "campaign", "id_data": [{"segment": None, "metrics": {}}]}]})
+
+ with (
+ time_machine.travel("2026-10-05T20:00:00Z", tick=False),
+ patch.object(client.session, "send", side_effect=send),
+ ):
+ resource = twitter_ads_source(client, "account", "campaign_stats", manager, date(2020, 2, 11))
+ list(sync_items(resource))
+
+ # 2020-02-11 is PST, so midnight in the ad account's timezone is 08:00Z, not the 07:00Z that
+ # October's PDT offset would produce.
+ assert windows[0][0] == "2020-02-11T08:00:00Z"
+ assert windows[0][1] == "2020-02-18T08:00:00Z"
+
+
+def test_error_detail_rides_along_with_the_status(client: TwitterAdsClient) -> None:
+ failure = requests.Response()
+ failure.status_code = 400
+ failure.url = "https://ads-api.x.com/12/stats/accounts/account"
+ failure._content = json.dumps(
+ {
+ "errors": [
+ {
+ "code": "INVALID_PARAMETER",
+ "message": "Expected a time aligned to midnight",
+ "parameter": "start_time",
+ }
+ ]
+ }
+ ).encode()
+
+ with patch.object(client.session, "send", return_value=failure):
+ with pytest.raises(requests.HTTPError) as raised:
+ client.get("stats/accounts/account")
+
+ message = str(raised.value)
+ # The status prefix is what `get_non_retryable_errors` matches on, and the detail is the only
+ # place X says which parameter it rejected.
+ assert "400 Client Error" in message
+ assert "INVALID_PARAMETER (start_time): Expected a time aligned to midnight" in message
+
+
+def test_error_without_a_parsable_body_keeps_the_bare_status(client: TwitterAdsClient) -> None:
+ failure = requests.Response()
+ failure.status_code = 503
+ failure.url = "https://ads-api.x.com/12/accounts/account"
+ failure._content = b""
+
+ with patch.object(client.session, "send", return_value=failure):
+ with pytest.raises(requests.HTTPError) as raised:
+ client.get("accounts/account")
+
+ assert "503 Server Error" in str(raised.value)
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.py
index 3de545c0e164..1140f44a636d 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
@@ -1,18 +1,12 @@
from collections.abc import Iterator
-from datetime import (
- UTC,
- date,
- datetime,
- time,
- timedelta,
- timezone as fixed_timezone,
-)
+from datetime import UTC, date, datetime, time, timedelta
from typing import Any
from urllib.parse import quote
from zoneinfo import ZoneInfo
from django.conf import settings
+import requests
from requests_oauthlib import OAuth1
from posthog.dataclasses import frozen
@@ -42,6 +36,53 @@ class TwitterAdsResumeConfig:
complete: bool = False
+# X rejects a DAY-granularity window wider than this.
+MAX_STATS_WINDOW = timedelta(days=7)
+
+# Cap on how much of X's error body rides along in the exception message.
+_MAX_ERROR_DETAIL = 300
+
+
+def _account_midnight(day: date, account_timezone: ZoneInfo) -> datetime:
+ """Midnight on `day` in the ad account's own timezone, as UTC.
+
+ X requires a DAY-granularity window to start and end at midnight in that timezone, and the
+ offset it wants is the one in force on `day` itself. Reusing today's offset for a historical
+ window sends an hour past midnight across a daylight-saving boundary, which X answers with a
+ 400 rather than a shifted result.
+ """
+ return datetime.combine(day, time.min, account_timezone).astimezone(UTC)
+
+
+def _error_detail(response: requests.Response) -> str:
+ """X's own explanation for a failed request, for the message a user and an engineer both read.
+
+ A bare status line says nothing about which parameter X objected to, and the body is the only
+ place that appears.
+ """
+ try:
+ body = response.json()
+ except ValueError:
+ return response.text.strip()[:_MAX_ERROR_DETAIL]
+
+ if not isinstance(body, dict):
+ return ""
+ errors = body.get("errors") or body.get("operation_errors") or []
+ if not isinstance(errors, list):
+ return ""
+ parts = []
+ for error in errors:
+ if not isinstance(error, dict):
+ continue
+ label = error.get("code") or ""
+ parameter = error.get("parameter")
+ if parameter:
+ label = f"{label} ({parameter})" if label else f"({parameter})"
+ message = error.get("message") or ""
+ parts.append(f"{label}: {message}" if label and message else label or message)
+ return "; ".join(part for part in parts if part)[:_MAX_ERROR_DETAIL]
+
+
class TwitterAdsClient:
def __init__(self, integration: Integration, api_version: str = API_VERSION) -> None:
if api_version != API_VERSION:
@@ -64,7 +105,14 @@ class TwitterAdsClient:
def get(self, path: str, params: dict[str, str | int] | None = None) -> dict[str, Any]:
response = self.session.get(f"{self.base_url}/{path}", params=params, timeout=60)
- response.raise_for_status()
+ try:
+ response.raise_for_status()
+ except requests.HTTPError as error:
+ # Keep the "<status> Client Error" prefix: `get_non_retryable_errors` matches on it.
+ detail = _error_detail(response)
+ if detail:
+ raise requests.HTTPError(f"{error}. {detail}", response=response, request=error.request) from None
+ raise
if response.status_code != 200:
raise ValueError("X Ads returned an unexpected response")
return response.json()
@@ -132,8 +180,6 @@ class TwitterAdsClient:
account = self.get(account_path, {"with_deleted": "true"})["data"]
account_timezone = ZoneInfo(account["timezone"])
account_now = datetime.now(account_timezone)
- # X requires the current account UTC offset even when querying historical days.
- timezone = fixed_timezone(account_now.utcoffset() or timedelta())
campaigns = self.entities(account_id, "campaigns")
funding = {row["id"]: row["currency"] for row in self.entities(account_id, "funding_instruments")}
campaign_currencies = {row["id"]: funding[row["funding_instrument_id"]] for row in campaigns}
@@ -150,7 +196,7 @@ class TwitterAdsClient:
start = date.fromisoformat(str(incremental_since)[:10])
else:
created_at = (
- datetime.fromisoformat(account["created_at"].replace("Z", "+00:00")).astimezone(timezone).date()
+ datetime.fromisoformat(account["created_at"].replace("Z", "+00:00")).astimezone(account_timezone).date()
)
start = max(created_at, account_now.date() - timedelta(days=MAX_STATS_BACKFILL_DAYS))
if state.next_date:
@@ -158,8 +204,13 @@ class TwitterAdsClient:
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)
- start_time = datetime.combine(start, time.min, timezone).astimezone(UTC)
- end_time = datetime.combine(window_end, time.min, timezone).astimezone(UTC)
+ 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(