: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): order google ads extraction by cursor and cap date keys at day (#71336)
Tom Owers18712919b3f7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition.pyindex 51b188a7ec8c..339c026d3912 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/repartition.py@@ -42,7 +42,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.utils import (append_partition_key_to_table,+ normalize_column_name,)+from products.warehouse_sources.backend.types import IncrementalFieldTypeif TYPE_CHECKING:from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.delta_table_helper import (@@ -252,6 +254,45 @@ async def _live_missing_data_file(live_uri: str, storage_options: dict[str, str]return referenced+# Arrow/discovery type names that carry day granularity and no time-of-day component.+# Prefix-matched carefully: "datetime*"/"timestamp*" must NOT match.+_DATE_ONLY_COLUMN_TYPE_PREFIXES = ("date32", "date64")+++def _datetime_tier_ceiling(schema: ExternalDataSchema) -> PartitionFormat:+ """The finest datetime tier that can physically split this schema's partition key.++ A date-typed key (e.g. Google Ads `segments.date`) carries no time-of-day, so every row of a+ day lands in the same `hour` bucket — an hour rewrite is a full-table rewrite that changes+ nothing, and afterwards the controller parks at "finest tier" with the table still OOMing.+ Cap such keys at `day`. Detected from either the incremental cursor being the partition key+ and declared `date`, or discovery metadata typing the key column as a date.+ """+ keys = schema.partitioning_keys or schema.primary_key_columns or []+ if len(keys) != 1:+ return DATETIME_FORMAT_TIERS[-1]+ key = normalize_column_name(keys[0])++ incremental_field = schema.incremental_field+ if (+ incremental_field is not None+ and normalize_column_name(incremental_field) == key+ and schema.incremental_field_type == IncrementalFieldType.Date+ ):+ return "day"++ for column in (schema.schema_metadata or {}).get("columns") or []:+ if not isinstance(column, dict):+ continue+ if normalize_column_name(str(column.get("name") or "")) != key:+ continue+ data_type = str(column.get("data_type") or "").lower()+ if data_type == "date" or data_type.startswith(_DATE_ONLY_COLUMN_TYPE_PREFIXES):+ return "day"++ return DATETIME_FORMAT_TIERS[-1]++def select_repartition_target(schema: ExternalDataSchema,partition_bytes: dict[str | None, int],@@ -297,17 +338,20 @@ def select_repartition_target(if mode == "datetime":current_format: PartitionFormat = schema.partition_format or "month"try:- next_index = DATETIME_FORMAT_TIERS.index(current_format) + 1+ current_index = DATETIME_FORMAT_TIERS.index(current_format)except ValueError:- next_index = 1- if next_index >= len(DATETIME_FORMAT_TIERS):- # Already at the finest tier (hour) — can't go finer. Caller alerts.+ current_index = 0+ # A date-granular key caps out at `day`; a table already at or past its ceiling (e.g.+ # no-op'd to `hour` before the ceiling existed) has nothing finer to gain either.+ ceiling_index = DATETIME_FORMAT_TIERS.index(_datetime_tier_ceiling(schema))+ if current_index >= ceiling_index:+ # Already at the finest usable tier — can't go finer. Caller alerts.return None, "datetime_at_finest_tier"return RepartitionTarget(partition_keys=keys,trigger_reason="",partition_mode="datetime",- partition_format=DATETIME_FORMAT_TIERS[next_index],+ partition_format=DATETIME_FORMAT_TIERS[current_index + 1],), "selected"# Unpartitioned but over budget: attempt to enable partitioning via auto-detection. Needs keys.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition.pyindex 935317945a9c..7eac3d5fb6e8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test_repartition.py@@ -38,6 +38,9 @@ def _schema(**kwargs):"partition_format": None,"partitioning_keys": None,"primary_key_columns": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "schema_metadata": None,}defaults.update(kwargs)return SimpleNamespace(**defaults)@@ -126,6 +129,77 @@ class TestSelectRepartitionTarget:1000,None,),+ # A date-typed partition key (e.g. Google Ads segments.date) has no time-of-day, so an+ # `hour` rewrite is a full-table no-op that then parks the controller at "finest tier"+ # with the table still OOMing. Day is the ceiling for such keys.+ (+ "date_granular_cursor_key_caps_at_day",+ {+ "partition_mode": "datetime",+ "partition_format": "day",+ "partitioning_keys": ["segments_date"],+ "incremental_field": "segments.date",+ "incremental_field_type": "date",+ },+ {"2024-01-01": 5000},+ 1000,+ None,+ ),+ # Already no-op'd to hour before the ceiling existed (the four prod Google Ads tables):+ # must skip, never select a coarsening rewrite back toward the ceiling.+ (+ "date_granular_key_already_at_hour_skips",+ {+ "partition_mode": "datetime",+ "partition_format": "hour",+ "partitioning_keys": ["segments_date"],+ "incremental_field": "segments.date",+ "incremental_field_type": "date",+ },+ {"2024-01-01T00": 5000},+ 1000,+ None,+ ),+ # Discovery metadata typing the key as a date caps it too, without an incremental cursor.+ (+ "date_typed_metadata_column_caps_at_day",+ {+ "partition_mode": "datetime",+ "partition_format": "day",+ "partitioning_keys": ["report_date"],+ "schema_metadata": {"columns": [{"name": "report_date", "data_type": "date32[day]"}]},+ },+ {"2024-01-01": 5000},+ 1000,+ None,+ ),+ # A timestamp-typed key must NOT be capped ("datetime64"/"timestamp" are not dates).+ (+ "timestamp_typed_metadata_column_still_offers_hour",+ {+ "partition_mode": "datetime",+ "partition_format": "day",+ "partitioning_keys": ["created_at"],+ "schema_metadata": {"columns": [{"name": "created_at", "data_type": "timestamp[us]"}]},+ },+ {"2024-01-01": 5000},+ 1000,+ {"partition_mode": "datetime", "partition_format": "hour"},+ ),+ # A date cursor that is NOT the partition key says nothing about the key's granularity.+ (+ "date_cursor_on_different_key_still_offers_hour",+ {+ "partition_mode": "datetime",+ "partition_format": "day",+ "partitioning_keys": ["created_at"],+ "incremental_field": "report_date",+ "incremental_field_type": "date",+ },+ {"2024-01-01": 5000},+ 1000,+ {"partition_mode": "datetime", "partition_format": "hour"},+ ),("unpartitioned_with_keys_enables_partitioning",{"partition_mode": None, "primary_key_columns": ["id"]},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 991ea7facfc4..4152755c4317 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@@ -507,6 +507,17 @@ def google_ads_source(if table.extra_where:query += f" {'AND' if 'WHERE' in query else 'WHERE'} {table.extra_where}"+ if should_use_incremental_field:+ # Ascending cursor order is load-bearing, not cosmetic. The pipeline advances+ # `incremental_field_last_value` after every durably written chunk (sort_mode+ # defaults to "asc"), so ordered pages make each chunk (a) advance the watermark+ # monotonically — an OOM/crash mid-sync resumes from the newest landed date instead+ # of re-extracting the whole window forever (the stuck-cursor death spiral) — and+ # (b) touch only a narrow band of date partitions per Delta merge, instead of every+ # partition in the window when pages arrive date-scattered. Unordered pages would+ # also let the per-chunk watermark skip past older rows Google hadn't returned yet.+ query += f" ORDER BY {incremental_field} ASC"+client = google_ads_client(config, team_id)service: GoogleAdsServiceClient = client.get_service("GoogleAdsService", version="v23", interceptors=tracked_interceptors(GOOGLE_ADS_HOST)diff --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 cf31e5098ac1..a5bf2502d464 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,3 +1,5 @@+import typing+import collections.abcfrom types import SimpleNamespaceimport pytest@@ -1129,3 +1131,80 @@ class TestOverviewStatsSchemas:assert overview["field_names"] == [f for f in stats["field_names"] if f != "segments.click_type"]assert overview["primary_key"] == [k for k in stats["primary_key"] if k != "segments.click_type"]assert overview["filter_field_names"] == [("segments.date", IncrementalFieldType.Date)]+++class TestGoogleAdsQueryConstruction:+ _MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.google_ads"++ def _stats_table(self) -> GoogleAdsTable:+ return GoogleAdsTable(+ name="campaign_stats",+ alias="campaign_stats",+ columns=[_string_column("campaign.id"), _string_column("segments.date")],+ parents=None,+ requires_filter=True,+ primary_key=["campaign_id", "segments_date"],+ should_sync_default=True,+ description=None,+ )++ def _run_source(self, table: GoogleAdsTable, **source_kwargs):+ from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.google_ads import (+ google_ads_source,+ )++ captured: dict = {}++ def fake_search(*, service, customer_id, query, table, resumable_source_manager):+ captured["query"] = query+ return iter([])++ assert table.alias is not None+ config = GoogleAdsSourceConfig(customer_id="1234567890", google_ads_integration_id=1)+ with (+ mock.patch(f"{self._MODULE}.get_schemas", return_value={table.alias: table}),+ mock.patch(f"{self._MODULE}.google_ads_client"),+ mock.patch(f"{self._MODULE}._search_as_arrow_tables", side_effect=fake_search),+ ):+ response = google_ads_source(+ config,+ table.alias,+ team_id=1,+ resumable_source_manager=mock.Mock(),+ **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++ 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 "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 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())++ assert "WHERE segments.date >=" in query+ assert query.endswith("ORDER BY segments.date ASC")++ def test_dimension_table_query_has_no_order_clause(self):+ _response, query = self._run_source(_single_row_table())++ assert "WHERE" not in query+ assert "ORDER BY" not in query