: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(warehouse): re-read recent days on Google Ads incremental syncs (#66449)
Daniel RC7932884e8c48
diff --git a/products/data_warehouse/backend/presentation/views/external_data_source.py b/products/data_warehouse/backend/presentation/views/external_data_source.pyindex c989f30f9a49..70b463bcfa39 100644--- a/products/data_warehouse/backend/presentation/views/external_data_source.py+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py@@ -1900,6 +1900,12 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi# Mirror the schema-update path's IntegerField(min_value=0, max_value=5_184_000) so both# creation paths reject the same inputs instead of silently dropping null/float values.lookback_seconds = schema.get("incremental_field_lookback_seconds")+ # When the caller didn't set a lookback, fall back to the source-defined default+ # (e.g. Google Ads stats tables, whose recent rows Google keeps revising for days).+ # This loop is the single creation choke point, so the default reaches both the+ # wizard and one-shot flows; it's then validated by the bounds check just below.+ if lookback_seconds is None and source_schema is not None:+ lookback_seconds = source_schema.default_incremental_lookback_secondsif lookback_seconds is not None:# Coerce whole-number floats (e.g. 90.0) the way DRF's IntegerField does.if isinstance(lookback_seconds, float) and lookback_seconds.is_integer():diff --git a/products/warehouse_sources/backend/migrations/0052_backfill_google_ads_incremental_lookback.py b/products/warehouse_sources/backend/migrations/0052_backfill_google_ads_incremental_lookback.pynew file mode 100644index 000000000000..5be845051e90--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0052_backfill_google_ads_incremental_lookback.py@@ -0,0 +1,60 @@+import time++from django.db import migrations++# Keep in sync with GOOGLE_ADS_STATS_INCREMENTAL_LOOKBACK_SECONDS in the Google Ads source+# (products/warehouse_sources/.../sources/google_ads/source.py). Inlined here so this+# point-in-time backfill stays self-contained and doesn't import app code that may change.+DEFAULT_LOOKBACK_SECONDS = 30 * 24 * 60 * 60 # 30 days++BATCH_SIZE = 1000+++def backfill_google_ads_lookback(apps, schema_editor):+ # Existing Google Ads incremental stats schemas were created before the source set a+ # default lookback, so they re-fetch only the newest day and freeze every prior day at+ # its first-imported, not-yet-final value. Give them the same overlap re-read window new+ # schemas now get. Only the incremental schemas matter — the lookback is a no-op on+ # full_refresh, which re-reads everything anyway.+ ExternalDataSchema = apps.get_model("warehouse_sources", "ExternalDataSchema")++ base_qs = (+ ExternalDataSchema.objects.filter(+ source__source_type="GoogleAds",+ sync_type="incremental",+ deleted=False,+ )+ .order_by("id")+ .only("id", "sync_type_config")+ )++ last_id = None+ while True:+ batch_qs = base_qs if last_id is None else base_qs.filter(id__gt=last_id)+ batch = list(batch_qs[:BATCH_SIZE])+ if not batch:+ break++ to_update = []+ for schema in batch:+ config = schema.sync_type_config or {}+ # Only set it when absent — preserve an explicit user value, including 0+ # ("no overlap re-read"), so absence is the sole trigger and reruns are idempotent.+ if "incremental_field_lookback_seconds" not in config:+ config["incremental_field_lookback_seconds"] = DEFAULT_LOOKBACK_SECONDS+ schema.sync_type_config = config+ to_update.append(schema)++ if to_update:+ ExternalDataSchema.objects.bulk_update(to_update, ["sync_type_config"])++ last_id = batch[-1].id+ time.sleep(0.1)+++class Migration(migrations.Migration):+ dependencies = [("warehouse_sources", "0051_warehousecolumnstatistics")]++ operations = [+ migrations.RunPython(backfill_google_ads_lookback, migrations.RunPython.noop, elidable=True),+ ]diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txtindex 4b25fc5745ab..b419e063bdcc 100644--- a/products/warehouse_sources/backend/migrations/max_migration.txt+++ b/products/warehouse_sources/backend/migrations/max_migration.txt@@ -1 +1 @@-0051_warehousecolumnstatistics+0052_backfill_google_ads_incremental_lookbackdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.pyindex bb6c2bd0cc56..e2655525a6d0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/schema.py@@ -44,6 +44,12 @@ class SourceSchema:label: str | None = Nonedetected_primary_keys: list[str] | None = Nonerls_warning: str | None = None+ # Per-source default for the incremental overlap re-read window, applied at schema+ # creation when the caller doesn't set one. Sources whose recent rows get restated+ # upstream (e.g. Google Ads stats tables, which Google keeps revising for days) set+ # this so each incremental run re-reads a trailing window instead of freezing a day+ # at its first-imported value. Only consumed for schemas synced incrementally.+ default_incremental_lookback_seconds: int | None = Nonedef _select_incremental_field(incremental_fields: list[IncrementalField]) -> IncrementalField | None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/source.pyindex 04ed6595ecdf..57a83420b445 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/source.py@@ -39,6 +39,18 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads)from products.warehouse_sources.backend.types import ExternalDataSourceType+# Default incremental overlap re-read window for Google Ads stats tables (the 12 schemas+# carrying a `segments.date` filter). Google reports recent-day cost/conversion data as+# provisional and keeps revising it for days after the fact (see "About data freshness":+# https://support.google.com/google-ads/answer/2544985), so an incremental sync that only+# re-fetches the newest day freezes each day at its first-imported, not-yet-final value.+# Re-reading a 30-day trailing window each run lets those days catch up as Google finalizes+# them; merge-by-primary-key makes the overlap idempotent. 30 days also covers the App-+# campaign conversion attribution window for the conversion metrics in these tables. These+# tables are small, so the extra re-read is negligible. Tunable; stays under the 60-day cap+# enforced at the creation/update endpoints.+GOOGLE_ADS_STATS_INCREMENTAL_LOOKBACK_SECONDS = 30 * 24 * 60 * 60+@SourceRegistry.registerclass GoogleAdsSource(@@ -122,6 +134,13 @@ class GoogleAdsSource(],description=endpoint_config.description,should_sync_default=endpoint_config.should_sync_default,+ # Only the incremental stats tables (those with a segments.date filter) need the+ # lookback; the full-refresh dimension tables re-read everything each run anyway.+ default_incremental_lookback_seconds=(+ GOOGLE_ADS_STATS_INCREMENTAL_LOOKBACK_SECONDS+ if ads_incremental_fields.get(endpoint, None) is not None+ else None+ ),)for endpoint, endpoint_config in google_ads_schemas.items()]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 5061d870fa70..9a2441d22f4b 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@@ -260,6 +260,37 @@ class TestGoogleAdsNonRetryableErrors:assert "admin" in friendly.lower()+class TestGoogleAdsLookbackDefault:+ _SCHEMAS_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.google_ads.get_schemas"++ def test_incremental_stats_schemas_get_default_lookback_dimensions_do_not(self):+ from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.source import (+ GOOGLE_ADS_STATS_INCREMENTAL_LOOKBACK_SECONDS,+ )++ config = GoogleAdsSourceConfig(customer_id="1234567890", google_ads_integration_id=1)+ # get_schemas() queries the Google Ads API for selectable fields; the static incremental-field+ # map (real, not mocked) is what marks a table incremental, so stub the network call with one+ # stats table (has a segments.date filter) and one dimension table (does not).+ fake_tables = {+ "campaign_stats": SimpleNamespace(description=None, should_sync_default=True),+ "campaign": SimpleNamespace(description=None, should_sync_default=True),+ }+ with mock.patch(self._SCHEMAS_PATH, return_value=fake_tables):+ schemas = {s.name: s for s in GoogleAdsSource().get_schemas(config, team_id=1)}++ assert schemas["campaign_stats"].supports_incremental is True+ assert (+ schemas["campaign_stats"].default_incremental_lookback_seconds+ == GOOGLE_ADS_STATS_INCREMENTAL_LOOKBACK_SECONDS+ )+ assert schemas["campaign"].supports_incremental is False+ assert schemas["campaign"].default_incremental_lookback_seconds is None+ # The default must satisfy the 60-day cap the creation/update endpoints enforce, or creation+ # would reject it.+ assert 0 < GOOGLE_ADS_STATS_INCREMENTAL_LOOKBACK_SECONDS <= 5_184_000++class TestGrpcReceiveLimit:# The largest search page observed aborting syncs in production was ~103 MB; the gRPC# client must accept at least that much for the resource to sync at all.diff --git a/products/warehouse_sources/backend/tests/test_migration_0052.py b/products/warehouse_sources/backend/tests/test_migration_0052.pynew file mode 100644index 000000000000..9b8920ae97fa--- /dev/null+++ b/products/warehouse_sources/backend/tests/test_migration_0052.py@@ -0,0 +1,76 @@+from typing import Any++from posthog.test.base import TestMigrations+++class BackfillGoogleAdsIncrementalLookbackMigrationTest(TestMigrations):+ """0051 backfills a default incremental lookback onto existing Google Ads incremental stats+ schemas, which were created before the source set one and so re-fetch only the newest day,+ freezing every prior day at its first-imported, not-yet-final value. It must touch only Google+ Ads incremental schemas with no lookback yet — never full_refresh, never other sources, never a+ soft-deleted row, and never an explicit user value (including 0, which means "no overlap").+ """++ migrate_from = "0051_warehousecolumnstatistics"+ migrate_to = "0052_backfill_google_ads_incremental_lookback"++ DEFAULT = 30 * 24 * 60 * 60++ @property+ def app(self) -> str:+ return "warehouse_sources"++ def setUpBeforeMigration(self, apps: Any) -> None:+ Organization = apps.get_model("posthog", "Organization")+ Project = apps.get_model("posthog", "Project")+ Team = apps.get_model("posthog", "Team")+ ExternalDataSource = apps.get_model("warehouse_sources", "ExternalDataSource")+ ExternalDataSchema = apps.get_model("warehouse_sources", "ExternalDataSchema")+ self.ExternalDataSchema = ExternalDataSchema++ org = Organization.objects.create(name="Org")+ project = Project.objects.create(id=987_654, organization=org, name="Proj")+ team = Team.objects.create(organization=org, project=project, name="Team")++ google = ExternalDataSource.objects.create(+ team=team, source_id="g", connection_id="cg", status="Completed", source_type="GoogleAds"+ )+ postgres = ExternalDataSource.objects.create(+ team=team, source_id="p", connection_id="cp", status="Completed", source_type="Postgres"+ )++ incremental = {"incremental_field": "segments.date", "incremental_field_type": "date"}++ def make(source, name, sync_type, config, deleted=False) -> str:+ return ExternalDataSchema.objects.create(+ team=team, source=source, name=name, sync_type=sync_type, sync_type_config=config, deleted=deleted+ ).id++ self.needs_backfill_id = make(google, "campaign_stats", "incremental", {**incremental})+ self.explicit_value_id = make(+ google, "ad_stats", "incremental", {**incremental, "incremental_field_lookback_seconds": 86_400}+ )+ self.explicit_zero_id = make(+ google, "keyword_stats", "incremental", {**incremental, "incremental_field_lookback_seconds": 0}+ )+ self.full_refresh_id = make(google, "campaign", "full_refresh", {})+ self.other_source_id = make(+ postgres, "users", "incremental", {"incremental_field": "updated_at", "incremental_field_type": "timestamp"}+ )+ self.deleted_id = make(google, "video_stats", "incremental", {**incremental}, deleted=True)++ def _config(self, schema_id: str) -> dict:+ return self.ExternalDataSchema.objects.get(id=schema_id).sync_type_config++ def test_backfills_only_google_ads_incremental_schemas_missing_a_lookback(self) -> None:+ # The broken case the migration fixes: a Google Ads incremental schema with no lookback.+ assert self._config(self.needs_backfill_id)["incremental_field_lookback_seconds"] == self.DEFAULT++ # An explicit user value is preserved — including 0, which means "no overlap re-read".+ assert self._config(self.explicit_value_id)["incremental_field_lookback_seconds"] == 86_400+ assert self._config(self.explicit_zero_id)["incremental_field_lookback_seconds"] == 0++ # Untouched: full_refresh (lookback is a no-op there), other source types, soft-deleted rows.+ assert "incremental_field_lookback_seconds" not in self._config(self.full_refresh_id)+ assert "incremental_field_lookback_seconds" not in self._config(self.other_source_id)+ assert "incremental_field_lookback_seconds" not in self._config(self.deleted_id)