: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(data-warehouse): drain google ads report backlogs in bounded date windows (#72024)
Tom Owersf81778774cb1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.pyindex 4152755c4317..dbc0366ba24e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py@@ -8,6 +8,7 @@ from django.db import OperationalError, close_old_connectionsimport grpcimport pyarrow as pa+from dateutil import parser as dateutil_parserfrom google.ads.googleads import client as google_ads_client_modulefrom google.ads.googleads.client import GoogleAdsClientfrom google.ads.googleads.errors import GoogleAdsException@@ -49,6 +50,18 @@ from products.warehouse_sources.backend.types import IncrementalFieldType# `GoogleAdsServiceClient.DEFAULT_ENDPOINT`.GOOGLE_ADS_HOST = "googleads.googleapis.com"+# Incremental report tables (segments.date-partitioned) are drained in bounded ascending date+# windows instead of a single open-ended `segments.date >= cursor` scan. A months-long backlog in+# one run never finishes before the activity heartbeat times out — frequently as collateral when a+# co-tenant OOM-kills the shared multi-tenant worker pod — so the cursor never advances and every+# run re-extracts the same window forever (the stuck-cursor death spiral). Bounded windows keep+# each run short enough to complete and durably advance the cursor a step at a time; empty windows+# are traversed for free so a gap in the data can never stall the drain. Once caught up to today a+# single small window covers the tail, so this is a no-op for healthy tables. Tune to trade+# catch-up speed against per-run size.+GOOGLE_ADS_INCREMENTAL_WINDOW_DAYS = 7+GOOGLE_ADS_MAX_DATA_WINDOWS_PER_RUN = 5+# The Google Ads SDK hardcodes `grpc.max_receive_message_length` to 64 MiB. A single# `GoogleAdsService.Search` page can carry up to 10,000 rows, and wide resources routinely# serialize past 64 MiB — when that happens the gRPC client aborts the call with a@@ -452,6 +465,19 @@ def get_schemas(config: GoogleAdsSourceConfigUnion, team_id: int) -> TableSchemareturn table_schemas+def _incremental_value_as_date(value: dt.date | dt.datetime | str) -> dt.date:+ """Coerce a stored incremental cursor value to a plain date for window arithmetic.++ `process_incremental_value` normalizes a Date cursor to a `datetime.date`, but a raw string is+ handled too so a value read straight from `sync_type_config` never breaks the windowed drain.+ """+ if isinstance(value, dt.datetime):+ return value.date()+ if isinstance(value, dt.date):+ return value+ return dateutil_parser.parse(value).date()++def google_ads_source(config: GoogleAdsSourceConfigUnion,resource_name: str,@@ -480,32 +506,19 @@ def google_ads_source(incremental_field = "segments.date"incremental_field_type = IncrementalFieldType.Date- def get_rows() -> collections.abc.Iterator[pa.Table]:+ def compose_query(lower_literal: str | None, upper_literal: str | None) -> str:query = f"SELECT {','.join(f'{field.qualified_name}' for field in table)} FROM {table.name}"- if should_use_incremental_field:- if incremental_field is None or incremental_field_type is None:- raise ValueError("incremental_field and incremental_field_type can't be None")-- if db_incremental_field_last_value is None:- last_value: int | dt.datetime | dt.date | str = incremental_type_to_initial_value(- incremental_field_type- )- else:- last_value = db_incremental_field_last_value-- if isinstance(last_value, dt.datetime) or isinstance(last_value, dt.date):- last_value = f"'{last_value.isoformat()}'"-- query += f" WHERE {incremental_field} >= {last_value}"-- if incremental_field_type == IncrementalFieldType.Date:- # Dates require an upper bound too, so we pick something very in the future.- # TODO: Make sure to bump this before 2100-01-01.- query += f" AND {incremental_field} < '2100-01-01'"-+ conditions: list[str] = []+ if should_use_incremental_field and lower_literal is not None:+ conditions.append(f"{incremental_field} >= {lower_literal}")+ if upper_literal is not None:+ conditions.append(f"{incremental_field} < {upper_literal}")if table.extra_where:- query += f" {'AND' if 'WHERE' in query else 'WHERE'} {table.extra_where}"+ conditions.append(table.extra_where)++ if conditions:+ query += " WHERE " + " AND ".join(conditions)if should_use_incremental_field:# Ascending cursor order is load-bearing, not cosmetic. The pipeline advances@@ -518,18 +531,76 @@ def google_ads_source(# also let the per-chunk watermark skip past older rows Google hadn't returned yet.query += f" ORDER BY {incremental_field} ASC"+ return query++ def get_rows() -> collections.abc.Iterator[pa.Table]:client = google_ads_client(config, team_id)service: GoogleAdsServiceClient = client.get_service("GoogleAdsService", version="v23", interceptors=tracked_interceptors(GOOGLE_ADS_HOST))customer_id = clean_customer_id(config.customer_id)+ if not should_use_incremental_field:+ yield from _search_as_arrow_tables(+ service, customer_id, compose_query(None, None), table, resumable_source_manager+ )+ return++ if incremental_field is None or incremental_field_type is None:+ raise ValueError("incremental_field and incremental_field_type can't be None")++ # Bounded windowed drain: only date-partitioned report tables (`requires_filter`) with an+ # established cursor. A first sync (sentinel value) keeps the open-ended scan below so it+ # doesn't crawl a window at a time from the 1970 initial value.+ if (+ table.requires_filter+ and incremental_field_type == IncrementalFieldType.Date+ and db_incremental_field_last_value is not None+ ):+ start = _incremental_value_as_date(db_incremental_field_last_value)+ # Exclusive upper bound of today+1 keeps today in range, matching the open-ended scan.+ end = dt.date.today() + dt.timedelta(days=1)+ windows_with_data = 0+ first_window = True++ while start < end and windows_with_data < GOOGLE_ADS_MAX_DATA_WINDOWS_PER_RUN:+ window_end = min(start + dt.timedelta(days=GOOGLE_ADS_INCREMENTAL_WINDOW_DAYS), end)+ window_query = compose_query(f"'{start.isoformat()}'", f"'{window_end.isoformat()}'")++ had_data = False+ for pa_table in _search_as_arrow_tables(+ service, customer_id, window_query, table, resumable_source_manager, use_saved_state=first_window+ ):+ had_data = True+ yield pa_table++ # Empty windows don't count toward the per-run budget and don't stop the loop, so a+ # gap in the data is crossed within a single run instead of stalling the cursor on it.+ if had_data:+ windows_with_data += 1+ first_window = False+ start = window_end++ # The run walked its bounded set of windows; drop the checkpoint so the next job restarts+ # cleanly from the (now-advanced) DB cursor rather than a stale mid-window page token.+ resumable_source_manager.clear_state()+ return++ # First-ever sync (initial sentinel) or a non-date cursor: single open-ended ascending scan.+ if db_incremental_field_last_value is None:+ last_value: int | dt.datetime | dt.date | str = incremental_type_to_initial_value(incremental_field_type)+ else:+ last_value = db_incremental_field_last_value++ lower_literal = (+ f"'{last_value.isoformat()}'" if isinstance(last_value, dt.datetime | dt.date) else str(last_value)+ )+ # Dates require an upper bound too, so we pick something very in the future.+ # TODO: Make sure to bump this before 2100-01-01.+ upper_literal = "'2100-01-01'" if incremental_field_type == IncrementalFieldType.Date else None+yield from _search_as_arrow_tables(- service=service,- customer_id=customer_id,- query=query,- table=table,- resumable_source_manager=resumable_source_manager,+ service, customer_id, compose_query(lower_literal, upper_literal), table, resumable_source_manager)return SourceResponse(@@ -700,6 +771,7 @@ def _search_as_arrow_tables(query: str,table: GoogleAdsTable,resumable_source_manager: ResumableSourceManager[GoogleAdsResumeConfig],+ use_saved_state: bool = True,) -> collections.abc.Generator[pa.Table]:"""Paginate ``GoogleAdsService.search`` and yield each page as a ``pyarrow.Table``.@@ -716,8 +788,11 @@ def _search_as_arrow_tables(discard the saved token and restart pagination from the first page. Thesame merge semantics make re-yielding already-synced rows safe."""+ # `use_saved_state=False` is passed for every window after the first in a windowed drain: the+ # saved page token belongs to whichever window was in flight last time and is meaningless for a+ # later window's distinct query, so those windows always start their own pagination fresh.page_token = ""- if resumable_source_manager.can_resume():+ if use_saved_state and resumable_source_manager.can_resume():resume = resumable_source_manager.load_state()if resume is not None:page_token = resume.page_tokendiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.pyindex 0b84addce8f8..e939e30f6471 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py@@ -1,14 +1,18 @@+import reimport typing+import datetime as dtimport collections.abcfrom types import SimpleNamespaceimport pytest+from freezegun import freeze_timefrom unittest import mockfrom django.core.cache import cachefrom django.db import OperationalErrorimport grpc+import pyarrow as pafrom google.ads.googleads.errors import GoogleAdsExceptionfrom google.ads.googleads.v23.enums import types as ga_enumsfrom google.ads.googleads.v23.errors.types.errors import ErrorCode, GoogleAdsError, GoogleAdsFailure@@ -26,6 +30,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_adsclean_customer_id,)from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.google_ads import (+ GOOGLE_ADS_INCREMENTAL_WINDOW_DAYS,+ GOOGLE_ADS_MAX_DATA_WINDOWS_PER_RUN,GoogleAdsColumn,GoogleAdsTable,_get_integration,@@ -470,6 +476,11 @@ def _string_column(qualified_name: str) -> GoogleAdsColumn:)+def _pa_table_with_rows(num_rows: int) -> pa.Table:+ """A minimal Arrow table standing in for a window's extracted page; only its row count matters."""+ return pa.table({"campaign_id": [str(i) for i in range(num_rows)], "segments_date": ["2026-01-01"] * num_rows})++def _single_row_table() -> GoogleAdsTable:return GoogleAdsTable(name="campaign",@@ -1182,16 +1193,24 @@ class TestGoogleAdsQueryConstruction:description=None,)- def _run_source(self, table: GoogleAdsTable, **source_kwargs):+ def _run_source(self, table: GoogleAdsTable, *, window_rows: dict[str, int] | None = None, **source_kwargs):from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.google_ads import (google_ads_source,)- captured: dict = {}+ queries: list[str] = []- def fake_search(*, service, customer_id, query, table, resumable_source_manager):- captured["query"] = query- return iter([])+ def fake_search(*args, **kwargs):+ # The production code calls positionally; pull `query` (3rd positional) either way.+ query = kwargs.get("query", args[2] if len(args) > 2 else "")+ queries.append(query)+ rows = 0+ if window_rows is not None:+ match = re.search(r">= '(\d{4}-\d{2}-\d{2})'", query or "")+ if match:+ rows = window_rows.get(match.group(1), 0)+ # `_search_as_arrow_tables` only yields non-empty tables, so an empty window yields nothing.+ return iter([_pa_table_with_rows(rows)] if rows else [])assert table.alias is not Noneconfig = GoogleAdsSourceConfig(customer_id="1234567890", google_ads_integration_id=1)@@ -1208,37 +1227,92 @@ class TestGoogleAdsQueryConstruction:**source_kwargs,)list(typing.cast(collections.abc.Iterable, response.items()))- return response, captured["query"]-- def test_incremental_query_is_bounded_and_ordered_by_cursor(self):- import datetime as dt+ return response, queries++ def test_established_cursor_drains_in_bounded_windows(self):+ # An established cursor on a report table is drained in bounded date windows, not the+ # open-ended `< 2100` scan that re-extracted the whole backlog every run and OOM-spiralled.+ with freeze_time("2026-07-17"):+ response, queries = self._run_source(+ self._stats_table(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=dt.date(2026, 4, 2),+ incremental_field="segments.date",+ incremental_field_type=IncrementalFieldType.Date,+ )- response, query = self._run_source(- self._stats_table(),- should_use_incremental_field=True,- db_incremental_field_last_value=dt.date(2026, 4, 2),- incremental_field="segments.date",- incremental_field_type=IncrementalFieldType.Date,+ assert queries[0] == (+ "SELECT campaign.id,segments.date FROM campaign_stats "+ "WHERE segments.date >= '2026-04-02' AND segments.date < '2026-04-09' "+ "ORDER BY segments.date ASC")-- assert "WHERE segments.date >= '2026-04-02'" in query- # Ascending order is load-bearing: the pipeline advances the incremental watermark after- # every durably written chunk under sort_mode "asc". Unordered pages would let the- # watermark skip past unfetched older rows, and make every chunk's Delta merge touch the- # whole date window instead of a narrow band — the stuck-cursor OOM spiral.- assert query.endswith("ORDER BY segments.date ASC")+ assert all("2100-01-01" not in q for q in queries)assert response.sort_mode == "asc"- def test_stats_table_forces_incremental_and_still_orders(self):- # requires_filter tables force segments.date filtering even when the caller didn't pass- # incremental args (e.g. first backfill) — the ordering must apply on that path too.- _response, query = self._run_source(self._stats_table())+ def test_first_sync_uses_open_ended_scan_not_windows(self):+ # A first sync carries the 1970 sentinel cursor; windowing it would crawl 7 days at a time+ # from 1970 and never catch up, so first syncs must stay a single open-ended ascending scan.+ with freeze_time("2026-07-17"):+ _response, queries = self._run_source(+ self._stats_table(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ incremental_field="segments.date",+ incremental_field_type=IncrementalFieldType.Date,+ )++ assert queries == [+ "SELECT campaign.id,segments.date FROM campaign_stats "+ "WHERE segments.date >= '1970-01-01' AND segments.date < '2100-01-01' "+ "ORDER BY segments.date ASC"+ ]++ def test_run_stops_after_max_data_windows(self):+ # Every window has data; the run must stop after GOOGLE_ADS_MAX_DATA_WINDOWS_PER_RUN+ # non-empty windows so a single run stays short enough to complete and durably advance the+ # cursor, instead of re-extracting the whole backlog and dying to a heartbeat timeout.+ cursor = dt.date(2026, 1, 1)+ window_rows = {+ (cursor + dt.timedelta(days=GOOGLE_ADS_INCREMENTAL_WINDOW_DAYS * i)).isoformat(): 1+ for i in range(GOOGLE_ADS_MAX_DATA_WINDOWS_PER_RUN + 3)+ }++ with freeze_time("2026-07-17"):+ _response, queries = self._run_source(+ self._stats_table(),+ window_rows=window_rows,+ should_use_incremental_field=True,+ db_incremental_field_last_value=cursor,+ incremental_field="segments.date",+ incremental_field_type=IncrementalFieldType.Date,+ )++ assert len(queries) == GOOGLE_ADS_MAX_DATA_WINDOWS_PER_RUN+ assert "WHERE segments.date >= '2026-01-01' AND segments.date < '2026-01-08'" in queries[0]++ def test_empty_windows_are_crossed_within_one_run(self):+ # Data only appears in the fourth window. The three empty windows before it must be+ # traversed within the same run (not counted toward the budget, not stopping the loop), so+ # a gap in the data never permanently stalls the cursor short of the data behind it.+ cursor = dt.date(2026, 1, 1)+ data_window_start = cursor + dt.timedelta(days=GOOGLE_ADS_INCREMENTAL_WINDOW_DAYS * 3)+ window_rows = {data_window_start.isoformat(): 1}++ with freeze_time("2026-07-17"):+ _response, queries = self._run_source(+ self._stats_table(),+ window_rows=window_rows,+ should_use_incremental_field=True,+ db_incremental_field_last_value=cursor,+ incremental_field="segments.date",+ incremental_field_type=IncrementalFieldType.Date,+ )- assert "WHERE segments.date >=" in query- assert query.endswith("ORDER BY segments.date ASC")+ lower_bounds = [re.search(r">= '(\d{4}-\d{2}-\d{2})'", q).group(1) for q in queries] # type: ignore[union-attr]+ assert lower_bounds[:4] == ["2026-01-01", "2026-01-08", "2026-01-15", "2026-01-22"]def test_dimension_table_query_has_no_order_clause(self):- _response, query = self._run_source(_single_row_table())+ _response, queries = self._run_source(_single_row_table())- assert "WHERE" not in query- assert "ORDER BY" not in query+ assert "WHERE" not in queries[0]+ assert "ORDER BY" not in queries[0]