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.

feat(data-warehouse): sync google ads account change events (#115970)

Tom Owers876144e1150b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/canonical_descriptions.py
index 69d3e6c2945e..0402c4e87bb6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/canonical_descriptions.py
@@ -67,6 +67,24 @@ def _overview_stats_columns(**overrides: str) -> dict[str, str]:
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "change_event": {
+ "description": "Account configuration changes with their old and new field values. The API returns only the last 30 days; incremental sync retains imported history.",
+ "docs_url": "https://developers.google.com/google-ads/api/docs/change-event",
+ "columns": {
+ "customer_id": _IDS["customer_id"],
+ "customer_time_zone": "The account time zone used by change_event_change_date_time.",
+ "change_event_resource_name": "Unique change event resource name, including the account ID.",
+ "change_event_change_date_time": "Time of the change in the Google Ads account time zone, without an offset.",
+ "change_event_change_resource_type": "Type of resource that changed.",
+ "change_event_change_resource_name": "Resource name of the object that changed.",
+ "change_event_resource_change_operation": "Whether the change created, updated, or removed the object.",
+ "change_event_client_type": "Client used to make the change, such as the web client or API.",
+ "change_event_user_email": "Email of the user who made the change, when Google exposes it.",
+ "change_event_changed_fields": "Field mask identifying the fields that changed.",
+ "change_event_old_resource": "JSON representation of the changed resource before the change.",
+ "change_event_new_resource": "JSON representation of the changed resource after the change.",
+ },
+ },
"ad": {
"description": "An ad within an ad group (ad_group_ad), including its creative content and status.",
"docs_url": "https://developers.google.com/google-ads/api/fields/v17/ad_group_ad",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/change_events.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/change_events.py
new file mode 100644
index 000000000000..15c41257d45e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/change_events.py
@@ -0,0 +1,62 @@
+import datetime as dt
+from collections.abc import Callable, Iterator, Sequence
+from typing import Generic, TypeVar
+
+Row = TypeVar("Row")
+
+CHANGE_EVENT_ROW_LIMIT = 10_000
+CHANGE_EVENT_LOOKBACK_SECONDS = 24 * 60 * 60
+
+
+class ChangeEventReader(Generic[Row]):
+ def __init__(
+ self,
+ fields: Sequence[str],
+ fetch: Callable[[str], list[Row]],
+ safe_point: Callable[[], None],
+ ) -> None:
+ self.fields = fields
+ self.fetch = fetch
+ self.safe_point = safe_point
+
+ @staticmethod
+ def start_time(
+ now: dt.datetime,
+ watermark: dt.datetime | dt.date | str | None,
+ requested_start: dt.date | None,
+ ) -> dt.datetime:
+ # Google rejects queries outside its retention window, including the normal two-year backfill.
+ earliest = (now - dt.timedelta(days=29)).replace(hour=0, minute=0, second=0, microsecond=0)
+ if isinstance(watermark, str):
+ watermark = dt.datetime.fromisoformat(watermark)
+ if watermark is None:
+ watermark = requested_start
+ if isinstance(watermark, dt.date) and not isinstance(watermark, dt.datetime):
+ watermark = dt.datetime.combine(watermark, dt.time())
+ # The stored field is an account-local wall time; a cursor's UTC tag does not convert it.
+ return max(earliest, watermark.replace(tzinfo=None) if watermark is not None else earliest)
+
+ def read(self, start: dt.datetime, end: dt.datetime) -> Iterator[list[Row]]:
+ if start >= end:
+ return
+ query = (
+ f"SELECT {','.join(self.fields)} FROM change_event "
+ f"WHERE change_event.change_date_time >= '{start:%Y-%m-%d %H:%M:%S}' "
+ f"AND change_event.change_date_time < '{end:%Y-%m-%d %H:%M:%S}' "
+ f"ORDER BY change_event.change_date_time ASC LIMIT {CHANGE_EVENT_ROW_LIMIT}"
+ )
+ rows = self.fetch(query)
+ if len(rows) >= CHANGE_EVENT_ROW_LIMIT:
+ # Pagination cannot recover rows beyond GAQL LIMIT; retry disjoint, smaller time windows.
+ del rows
+ self.safe_point()
+ seconds = int((end - start).total_seconds())
+ if seconds <= 1:
+ raise ValueError("Google Ads change history reached 10,000 changes in one second. Contact support.")
+ middle = start + dt.timedelta(seconds=seconds // 2)
+ yield from self.read(start, middle)
+ yield from self.read(middle, end)
+ return
+ for offset in range(0, len(rows), 5000):
+ yield rows[offset : offset + 5000]
+ self.safe_point()
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.py
index 63b5087ed7da..cb3aac4cab9c 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
@@ -2,6 +2,7 @@ import time
import typing
import datetime as dt
import collections.abc
+from zoneinfo import ZoneInfo
from django.db import OperationalError, close_old_connections
@@ -45,6 +46,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.googleads import (
GoogleAdsSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.change_events import ChangeEventReader
from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.configs import (
GoogleAdsResumeConfig,
GoogleAdsSourceConfigUnion,
@@ -280,13 +282,14 @@ class GoogleAdsColumn(Column):
):
self.name = output_name if output_name is not None else qualified_name.replace(".", "_")
self.qualified_name = qualified_name
- self.data_type = data_type
+ self.data_type = ga_enums.GoogleAdsFieldDataTypeEnum.GoogleAdsFieldDataType(data_type.value)
self.type_url = type_url
# Some types require special handling, so we provide quick access to them
self.is_repeatable = is_repeatable
- self.is_enum = data_type == ga_enums.GoogleAdsFieldDataTypeEnum.GoogleAdsFieldDataType.ENUM
- self.is_message = data_type == ga_enums.GoogleAdsFieldDataTypeEnum.GoogleAdsFieldDataType.MESSAGE
- self.is_date = data_type == ga_enums.GoogleAdsFieldDataTypeEnum.GoogleAdsFieldDataType.DATE
+ self.is_enum = self.data_type == ga_enums.GoogleAdsFieldDataTypeEnum.GoogleAdsFieldDataType.ENUM
+ self.is_message = self.data_type == ga_enums.GoogleAdsFieldDataTypeEnum.GoogleAdsFieldDataType.MESSAGE
+ self.is_date = self.data_type == ga_enums.GoogleAdsFieldDataTypeEnum.GoogleAdsFieldDataType.DATE
+ self.is_datetime = qualified_name == "change_event.change_date_time"
@staticmethod
def _safe_get_enum(enum_cls, value) -> str:
@@ -297,6 +300,8 @@ class GoogleAdsColumn(Column):
def resolve_value(self, value):
"""Coerce a raw protobuf value to the appropriate Python type."""
+ if self.is_datetime:
+ return dt.datetime.fromisoformat(value) if value else None
if self.is_enum:
enum_cls = _resolve_protobuf_message_type_url(self.type_url)
if self.is_repeatable:
@@ -305,8 +310,8 @@ class GoogleAdsColumn(Column):
if self.is_message:
if self.is_repeatable:
- return list(map(MessageToJson, value))
- return MessageToJson(value)
+ return [MessageToJson(getattr(item, "_pb", item)) for item in value]
+ return MessageToJson(getattr(value, "_pb", value))
if self.is_date:
if self.is_repeatable:
@@ -324,6 +329,9 @@ class GoogleAdsColumn(Column):
"""
arrow_type: pa.DataType
+ if self.is_datetime:
+ return pa.field(self.name, pa.timestamp("us"))
+
match self.data_type:
case ga_enums.GoogleAdsFieldDataTypeEnum.GoogleAdsFieldDataType.BOOLEAN:
arrow_type = pa.bool_()
@@ -639,6 +647,43 @@ def google_ads_source(
name = NamingConvention.normalize_identifier(resource_name)
table = schema_for_resource(get_schemas(config, team_id, api_version), resource_name)
+ if table.name == "change_event":
+ if should_use_incremental_field and incremental_field != "change_event.change_date_time":
+ raise ValueError("Use change_event.change_date_time as the Google Ads change history cursor.")
+
+ def get_change_events() -> collections.abc.Iterator[pa.Table]:
+ customer_id = clean_customer_id(config.customer_id)
+ service = GoogleAdsSearchService(google_ads_client(config, team_id), api_version, customer_id)
+ customer_query = _search_with_transient_retry(
+ service, {"customer_id": customer_id, "query": "SELECT customer.time_zone FROM customer"}
+ )
+ customer = next(iter(customer_query), None)
+ if customer is None:
+ raise ValueError("Google Ads did not return the account time zone. Reconnect the account.")
+ now = dt.datetime.now(ZoneInfo(customer.customer.time_zone)).replace(tzinfo=None, microsecond=0)
+
+ def fetch(query: str) -> list[dict[str, typing.Any]]:
+ response = _search_with_transient_retry(service, {"customer_id": customer_id, "query": query})
+ return [row for page in response.pages for row in _response_as_dicts(page, table)]
+
+ reader = ChangeEventReader(
+ [column.qualified_name for column in table], fetch, resumable_source_manager.safe_point
+ )
+ start = reader.start_time(
+ now,
+ db_incremental_field_last_value if should_use_incremental_field else None,
+ parse_start_date(requested_start) if requested_start else None,
+ )
+ for rows in reader.read(start, now):
+ yield pa.Table.from_pylist(rows, schema=table.to_arrow_schema())
+
+ return SourceResponse(
+ name=name,
+ items=get_change_events,
+ primary_keys=table.primary_key,
+ supports_resume=should_use_incremental_field,
+ )
+
# Report tables always need a date filter, so a full-refresh schema is forced onto the
# incremental query path here. Record whether the pipeline itself is incremental first: only an
# incremental pipeline persists a cursor between runs, and the bounded windowed drain below is
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/schemas.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/schemas.py
index 49ea62053cdc..27764826936d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/schemas.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/schemas.py
@@ -11,6 +11,27 @@ FIELD_ALIASES: dict[str, str] = {
}
RESOURCE_SCHEMAS: dict[str, dict[str, Any]] = {
+ "change_event": {
+ "resource_name": "change_event",
+ "primary_key": ["customer.id", "change_event.resource_name"],
+ "should_sync_default": False,
+ "description": "Account changes with old and new field values. Google returns the last 30 days. Use incremental sync to retain imported history.",
+ "filter_field_names": [("change_event.change_date_time", IncrementalFieldType.DateTime)],
+ "field_names": [
+ "customer.id",
+ "customer.time_zone",
+ "change_event.resource_name",
+ "change_event.change_date_time",
+ "change_event.change_resource_type",
+ "change_event.change_resource_name",
+ "change_event.resource_change_operation",
+ "change_event.client_type",
+ "change_event.user_email",
+ "change_event.changed_fields",
+ "change_event.old_resource",
+ "change_event.new_resource",
+ ],
+ },
"ad": {
"resource_name": "ad_group_ad",
"primary_key": ["ad_group_ad.ad.id", "ad_group.id", "campaign.id", "customer.id"],
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.py
index da560a5d868f..a016d8f40a79 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
@@ -48,6 +48,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.googleads import (
GoogleAdsSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.change_events import (
+ CHANGE_EVENT_LOOKBACK_SECONDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.configs import (
GOOGLE_ADS_INITIAL_BACKFILL_DAYS,
GoogleAdsResumeConfig,
@@ -223,7 +226,7 @@ class GoogleAdsSource(
SourceSchema(
name=endpoint,
supports_incremental=ads_incremental_fields.get(endpoint, None) is not None,
- supports_append=ads_incremental_fields.get(endpoint, None) is not None,
+ supports_append=endpoint != "change_event" and ads_incremental_fields.get(endpoint, None) is not None,
incremental_fields=[
{"label": column_name, "type": column_type, "field": column_name, "field_type": column_type}
for column_name, column_type in ads_incremental_fields.get(endpoint, [])
@@ -233,7 +236,9 @@ class GoogleAdsSource(
# 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
+ CHANGE_EVENT_LOOKBACK_SECONDS
+ if endpoint == "change_event"
+ else GOOGLE_ADS_STATS_INCREMENTAL_LOOKBACK_SECONDS
if ads_incremental_fields.get(endpoint, None) is not None
else None
),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_change_events.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_change_events.py
new file mode 100644
index 000000000000..e1eeccc73f65
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_change_events.py
@@ -0,0 +1,55 @@
+import re
+import datetime as dt
+
+import pytest
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.change_events import ChangeEventReader
+
+
+class TestChangeEventReader:
+ @pytest.mark.parametrize(
+ "watermark, requested, expected",
+ [
+ (None, None, dt.datetime(2026, 3, 3)),
+ (None, dt.date(2020, 1, 1), dt.datetime(2026, 3, 3)),
+ (None, dt.date(2026, 3, 20), dt.datetime(2026, 3, 20)),
+ ("2020-01-01 00:00:00", None, dt.datetime(2026, 3, 3)),
+ ("2026-03-25 12:00:00", dt.date(2026, 3, 28), dt.datetime(2026, 3, 25, 12)),
+ (dt.datetime(2026, 3, 25, 12, tzinfo=dt.UTC), None, dt.datetime(2026, 3, 25, 12)),
+ ],
+ )
+ def test_bounds_backfill_and_preserves_account_local_cursor(self, watermark, requested, expected):
+ assert ChangeEventReader.start_time(dt.datetime(2026, 4, 1, 12), watermark, requested) == expected
+
+ def test_splits_saturated_queries_without_losing_boundary_events(self):
+ start = dt.datetime(2026, 4, 1, 12)
+ events = [(start + dt.timedelta(seconds=i // 5001), i) for i in range(20_004)]
+ queries: list[str] = []
+
+ def fetch(query: str) -> list[tuple[dt.datetime, int]]:
+ queries.append(query)
+ lower, upper = [dt.datetime.fromisoformat(value) for value in re.findall(r"'([^']+)'", query)]
+ return [event for event in events if lower <= event[0] < upper][:10_000]
+
+ reader = ChangeEventReader(["change_event.resource_name"], fetch, lambda: None)
+ batches = list(reader.read(start, start + dt.timedelta(seconds=4)))
+ assert [event for batch in batches for event in batch] == events
+ assert max(map(len, batches)) <= 5000
+ assert len(queries) == 7
+ assert "change_event.change_date_time >= '2026-04-01 12:00:00'" in queries[0]
+ assert "change_event.change_date_time < '2026-04-01 12:00:04'" in queries[0]
+ assert "ORDER BY change_event.change_date_time ASC LIMIT 10000" in queries[0]
+ assert all("segments.date" not in query for query in queries)
+
+ def test_fails_instead_of_returning_partial_history_at_one_second_limit(self):
+ reader = ChangeEventReader(["change_event.resource_name"], lambda query: list(range(10_000)), lambda: None)
+ with pytest.raises(ValueError, match="10,000 changes in one second"):
+ list(reader.read(dt.datetime(2026, 4, 1, 12), dt.datetime(2026, 4, 1, 12, 0, 1)))
+
+ def test_reaches_a_safe_point_after_an_empty_result(self):
+ safe_points: list[bool] = []
+ reader: ChangeEventReader[int] = ChangeEventReader(
+ ["change_event.resource_name"], lambda query: [], lambda: safe_points.append(True)
+ )
+ assert list(reader.read(dt.datetime(2026, 4, 1), dt.datetime(2026, 4, 2))) == []
+ assert safe_points == [True]
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.py
index de592e6abac5..8e41cb500164 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
@@ -2,6 +2,7 @@ import re
import time
import typing
import datetime as dt
+import importlib
import collections.abc
from types import SimpleNamespace
@@ -20,6 +21,7 @@ from google.ads.googleads.v23.enums import types as ga_enums
from google.ads.googleads.v23.errors.types.authorization_error import AuthorizationErrorEnum
from google.ads.googleads.v23.errors.types.errors import ErrorCode, GoogleAdsError, GoogleAdsFailure
from google.ads.googleads.v23.errors.types.request_error import RequestErrorEnum
+from google.ads.googleads.v23.resources.types.change_event import ChangeEvent
from google.api_core import exceptions as google_api_exceptions
from google.auth import exceptions as google_auth_exceptions
@@ -67,6 +69,36 @@ _CUSTOMER_ID_ERROR = "valid Google Ads customer ID"
_MANAGER_ID_ERROR = "valid Google Ads manager customer ID"
[email protected]("repeated", [False, True])
[email protected]("version", ["v23", "v24", "v25"])
+def test_change_resource_proto_plus_serializes_to_json(repeated, version):
+ enum_types = importlib.import_module(f"google.ads.googleads.{version}.enums.types")
+ value = ChangeEvent.ChangedResource(campaign={"name": "Example campaign"})
+ column = GoogleAdsColumn(
+ qualified_name="change_event.new_resource",
+ data_type=enum_types.GoogleAdsFieldDataTypeEnum.GoogleAdsFieldDataType.MESSAGE,
+ is_repeatable=repeated,
+ type_url="google.ads.googleads.v23.resources.ChangeEvent.ChangedResource",
+ )
+ result = column.resolve_value([value] if repeated else value)
+ assert '"name": "Example campaign"' in (result[0] if repeated else result)
+ assert column.to_arrow_field().type == (pa.list_(pa.string()) if repeated else pa.string())
+
+
[email protected]("version", ["v23", "v24", "v25"])
+def test_change_event_date_metadata_preserves_time_in_arrow(version):
+ enum_types = importlib.import_module(f"google.ads.googleads.{version}.enums.types")
+ column = GoogleAdsColumn(
+ qualified_name="change_event.change_date_time",
+ data_type=enum_types.GoogleAdsFieldDataTypeEnum.GoogleAdsFieldDataType.DATE,
+ is_repeatable=False,
+ type_url="",
+ )
+ value = column.resolve_value("2026-04-01 12:34:56.123456")
+ arrow = pa.Table.from_pylist([{column.name: value}], schema=pa.schema([column.to_arrow_field()]))
+ assert arrow.to_pylist() == [{column.name: dt.datetime(2026, 4, 1, 12, 34, 56, 123456)}]
+
+
class TestCleanCustomerId:
@pytest.mark.parametrize(
"raw, expected",
@@ -2068,9 +2100,10 @@ class TestResourceSchemaInvariants:
def test_incremental_tables_filter_on_a_selected_segments_date(self, alias):
# `requires_filter` tables are queried with a `segments.date` window and partitioned on
# `segments_date`. Declaring a different filter field, or not selecting segments.date, breaks
- # both the incremental window and the partitioning.
+ # both the incremental window and the partitioning. `change_event` is read by its own
+ # `ChangeEventReader` on `change_event.change_date_time` and is not partitioned.
contents = RESOURCE_SCHEMAS[alias]
- if "filter_field_names" not in contents:
+ if "filter_field_names" not in contents or alias == "change_event":
return
assert contents["filter_field_names"] == [("segments.date", IncrementalFieldType.Date)]
assert "segments.date" in contents["field_names"]