: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(snapchat_ads): align stats day boundaries to ad account timezone (#65925)
Tom Owersaa010fab432b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/snapchat_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/snapchat_ads.pyindex a1e3a99962b3..75671f3f9e1f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/snapchat_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/snapchat_ads.py@@ -21,7 +21,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_aSnapchatAdsPaginator,SnapchatErrorHandler,SnapchatStatsResource,- fetch_account_currency,+ fetch_account_metadata,)@@ -94,6 +94,7 @@ def _build_chunk_resources(ad_account_id: str,should_use_incremental_field: bool,db_incremental_field_last_value: Optional[Any],+ account_timezone: Optional[str] = None,) -> tuple[list[dict], EndpointType]:endpoint_config = SNAPCHAT_ADS_CONFIG[endpoint]endpoint_type = endpoint_config.endpoint_type@@ -105,7 +106,11 @@ def _build_chunk_resources(if endpoint_type == EndpointType.STATS:chunk_resources = SnapchatStatsResource.setup_stats_resources(- base_resource, ad_account_id, should_use_incremental_field, db_incremental_field_last_value+ base_resource,+ ad_account_id,+ should_use_incremental_field,+ db_incremental_field_last_value,+ account_timezone,)else:chunk_resources = [base_resource]@@ -174,8 +179,17 @@ def _iter_rows(db_incremental_field_last_value: Optional[Any],should_use_incremental_field: bool,) -> Iterator[list[dict[str, Any]]]:+ # Stats endpoints need the account timezone to align DAY-granularity date+ # boundaries to the account's local midnight (Snapchat 400s otherwise), and+ # the currency to annotate the flattened rows. Fetch both once up front so the+ # timezone is available before the date chunks are generated.+ account_currency: Optional[str] = None+ account_timezone: Optional[str] = None+ if SNAPCHAT_ADS_CONFIG[endpoint].endpoint_type == EndpointType.STATS:+ account_currency, account_timezone = fetch_account_metadata(ad_account_id, access_token)+chunk_resources, endpoint_type = _build_chunk_resources(- endpoint, ad_account_id, should_use_incremental_field, db_incremental_field_last_value+ endpoint, ad_account_id, should_use_incremental_field, db_incremental_field_last_value, account_timezone)resume_config: Optional[SnapchatResumeConfig] = (@@ -189,10 +203,7 @@ def _iter_rows(start_chunk = 0resume_config = None- account_currency: Optional[str] = None- if endpoint_type == EndpointType.STATS:- account_currency = fetch_account_currency(ad_account_id, access_token)- else:+ if endpoint_type != EndpointType.STATS:assert len(chunk_resources) == 1, (f"Expected 1 resource for {endpoint_type} endpoint, got {len(chunk_resources)}")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/tests/test_snapchat_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/tests/test_snapchat_ads.pyindex b374216de783..caf1ae1d3e2c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/tests/test_snapchat_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/tests/test_snapchat_ads.py@@ -1,4 +1,5 @@from collections.abc import Callable, Iterator+from datetime import datetimefrom typing import Any, Optionalfrom unittest.mock import MagicMock, patch@@ -11,6 +12,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_a_iter_rows,)from products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_ads.source import SnapchatAdsSource+from products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_ads.utils import (+ SnapchatDateRangeManager,+ format_stats_day_boundary,+)class _FakeResource:@@ -260,8 +265,8 @@ class TestIterRowsMultiChunkStats:return_value=_fake_stats_chunks(2),),patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_ads.snapchat_ads.fetch_account_currency",- return_value="USD",+ "products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_ads.snapchat_ads.fetch_account_metadata",+ return_value=("USD", "America/Los_Angeles"),),):list(@@ -313,8 +318,8 @@ class TestIterRowsMultiChunkStats:return_value=_fake_stats_chunks(2),),patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_ads.snapchat_ads.fetch_account_currency",- return_value="USD",+ "products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_ads.snapchat_ads.fetch_account_metadata",+ return_value=("USD", "America/Los_Angeles"),),):list(@@ -337,6 +342,46 @@ class TestIterRowsMultiChunkStats:}+class TestStatsDayBoundaryTimezone:+ """Snapchat's DAY-granularity stats reject date boundaries that aren't the+ start of a day in the ad account's timezone (with the correct DST offset).+ These tests pin the localization that prevents the 400."""++ @parameterized.expand(+ [+ ("summer_pdt", datetime(2025, 7, 15), "America/Los_Angeles", "2025-07-15T00:00:00-07:00"),+ ("winter_pst", datetime(2025, 1, 15), "America/Los_Angeles", "2025-01-15T00:00:00-08:00"),+ ("utc", datetime(2025, 7, 15), "UTC", "2025-07-15T00:00:00+00:00"),+ ("no_timezone_stays_naive", datetime(2025, 7, 15), None, "2025-07-15T00:00:00"),+ ("invalid_timezone_falls_back", datetime(2025, 7, 15), "Not/AZone", "2025-07-15T00:00:00"),+ ]+ )+ def test_format_stats_day_boundary(+ self, _name: str, dt: datetime, account_timezone: Optional[str], expected: str+ ) -> None:+ assert format_stats_day_boundary(dt, account_timezone) == expected++ def test_generate_chunks_localizes_each_boundary_across_dst(self) -> None:+ # A range straddling the spring-forward boundary: each chunk must carry the+ # offset that aligns it to local midnight on its own date, not one fixed+ # offset for the whole range.+ chunks = SnapchatDateRangeManager.generate_chunks(+ "2025-01-01T00:00:00", "2025-08-01T00:00:00", account_timezone="America/Los_Angeles"+ )+ starts = [start for start, _ in chunks]++ assert chunks[0][0] == "2025-01-01T00:00:00-08:00"+ assert any(s.endswith("-08:00") for s in starts)+ assert any(s.endswith("-07:00") for s in starts)+ assert all("T00:00:00" in s for s in starts)++ def test_generate_chunks_naive_without_timezone(self) -> None:+ chunks = SnapchatDateRangeManager.generate_chunks(+ "2025-01-01T00:00:00", "2025-02-01T00:00:00", account_timezone=None+ )+ assert chunks == [("2025-01-01T00:00:00", "2025-02-01T00:00:00")]++class TestNonRetryableErrors:_patterns = SnapchatAdsSource().get_non_retryable_errors()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/utils.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/utils.pyindex 96ac8fdfc51a..411e76ed6f11 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snapchat_ads/utils.py@@ -2,6 +2,7 @@ import copyfrom collections.abc import Iterablefrom datetime import date, datetime, timedeltafrom typing import Any, Optional+from zoneinfo import ZoneInfoimport structlogfrom dateutil import parser@@ -25,11 +26,12 @@ SNAPCHAT_DATE_FORMAT = "%Y-%m-%dT00:00:00"RETRYABLE_STATUS_CODES = [429, 500, 503]-def fetch_account_currency(ad_account_id: str, access_token: str) -> str | None:- """Fetch the currency configured on the Snapchat ad account.+def fetch_account_metadata(ad_account_id: str, access_token: str) -> tuple[str | None, str | None]:+ """Fetch the currency and timezone configured on the Snapchat ad account.- Snapchat stats don't include currency per row (unlike Meta),- so we fetch it from the ad account endpoint once per sync.+ Snapchat stats don't include currency per row (unlike Meta), so we fetch it+ from the ad account endpoint once per sync. The account timezone is needed to+ align DAY-granularity stats date boundaries to the account's local midnight."""try:response = make_tracked_session().get(@@ -43,12 +45,30 @@ def fetch_account_currency(ad_account_id: str, access_token: str) -> str | None:if adaccounts:account = adaccounts[0].get("adaccount", {})currency = account.get("currency")+ timezone = account.get("timezone")if currency:logger.info("snapchat_ads_account_currency", ad_account_id=ad_account_id, currency=currency)- return str(currency)+ return (str(currency) if currency else None, str(timezone) if timezone else None)except Exception as e:- logger.warning("snapchat_ads_currency_fetch_failed", ad_account_id=ad_account_id, error=str(e))- return None+ logger.warning("snapchat_ads_account_metadata_fetch_failed", ad_account_id=ad_account_id, error=str(e))+ return (None, None)+++def format_stats_day_boundary(dt: datetime, account_timezone: str | None) -> str:+ """Render a stats date boundary the way Snapchat's DAY granularity requires.++ Snapchat rejects the request with a 400 unless start_time/end_time fall on the+ start of a day in the ad account's timezone, including the correct (DST-aware)+ UTC offset. A naive timestamp gets misaligned whenever the account isn't in UTC+ or the range crosses a DST change, so localize each boundary to the account+ timezone before formatting.+ """+ if account_timezone:+ try:+ return dt.replace(tzinfo=ZoneInfo(account_timezone)).isoformat()+ except Exception:+ logger.warning("snapchat_ads_invalid_account_timezone", timezone=account_timezone)+ return dt.strftime(SNAPCHAT_DATE_FORMAT)class SnapchatAdsAPIError(Exception):@@ -116,11 +136,18 @@ class SnapchatDateRangeManager:@staticmethoddef generate_chunks(- start_date: str, end_date: str, chunk_days: int = MAX_SNAPCHAT_DAYS_TO_QUERY+ start_date: str,+ end_date: str,+ chunk_days: int = MAX_SNAPCHAT_DAYS_TO_QUERY,+ account_timezone: str | None = None,) -> list[tuple[str, str]]:"""Generate date chunks that respect Snapchat's 31-day limit.Returns list of (start_date, end_date) tuples for sequential API calls.++ Day arithmetic stays on naive calendar dates so each chunk spans whole+ days; the boundaries are localized to ``account_timezone`` only at the+ formatting step so every boundary picks up its own DST-correct offset."""start_dt = datetime.fromisoformat(start_date)end_dt = datetime.fromisoformat(end_date)@@ -140,8 +167,8 @@ class SnapchatDateRangeManager:chunks.append((- current_start.strftime(SNAPCHAT_DATE_FORMAT),- chunk_end_for_api.strftime(SNAPCHAT_DATE_FORMAT),+ format_stats_day_boundary(current_start, account_timezone),+ format_stats_day_boundary(chunk_end_for_api, account_timezone),))@@ -231,9 +258,10 @@ class SnapchatStatsResource:end_date: str,ad_account_id: str,chunk_days: int = MAX_SNAPCHAT_DAYS_TO_QUERY,+ account_timezone: str | None = None,) -> list[dict]:"""Create chunked resources for date range queries."""- date_chunks = SnapchatDateRangeManager.generate_chunks(start_date, end_date, chunk_days)+ date_chunks = SnapchatDateRangeManager.generate_chunks(start_date, end_date, chunk_days, account_timezone)resources = []for i, (chunk_start, chunk_end) in enumerate(date_chunks):@@ -300,6 +328,7 @@ class SnapchatStatsResource:ad_account_id: str,should_use_incremental_field: bool,db_incremental_field_last_value: Optional[Any],+ account_timezone: str | None = None,) -> list[dict]:"""Setup stats resources with proper date chunking.@@ -309,7 +338,9 @@ class SnapchatStatsResource:should_use_incremental_field, db_incremental_field_last_value)- return cls.create_chunked_resources(base_resource_config, starts_at, ends_at, ad_account_id)+ return cls.create_chunked_resources(+ base_resource_config, starts_at, ends_at, ad_account_id, account_timezone=account_timezone+ )class SnapchatAdsPaginator(BasePaginator):