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.

fix(google_ads): restart pagination when a resumed page token expired (#63773)

Tom Owers45d3df30a4dc
diff --git a/posthog/temporal/data_imports/sources/google_ads/google_ads.py b/posthog/temporal/data_imports/sources/google_ads/google_ads.py
index 643daf04e119..cc474e563107 100644
--- a/posthog/temporal/data_imports/sources/google_ads/google_ads.py
+++ b/posthog/temporal/data_imports/sources/google_ads/google_ads.py
@@ -8,6 +8,7 @@ from django.db import close_old_connections
import pyarrow as pa
from google.ads.googleads import client as google_ads_client_module
from google.ads.googleads.client import GoogleAdsClient
+from google.ads.googleads.errors import GoogleAdsException
from google.ads.googleads.v23.common import types as ga_common
from google.ads.googleads.v23.enums import types as ga_enums
from google.ads.googleads.v23.resources import types as ga_resources
@@ -439,6 +440,19 @@ def google_ads_source(
)
+def _is_invalid_page_token_error(exc: GoogleAdsException) -> bool:
+ """Return True if a ``GoogleAdsException`` was caused by an expired/invalid page token.
+
+ Google Ads search page tokens are ephemeral, but our resumption contract
+ persists them (see ``_search_as_arrow_tables``). When a sync resumes from a
+ token Google has already expired, the API rejects the request with
+ ``request_error: INVALID_PAGE_TOKEN``. The proto text representation is the
+ same for proto-plus and raw protobuf failures, so we match on it directly.
+ """
+ failure = getattr(exc, "failure", None)
+ return failure is not None and "INVALID_PAGE_TOKEN" in str(failure)
+
+
def _search_as_arrow_tables(
service: GoogleAdsServiceClient,
customer_id: str | None,
@@ -454,6 +468,10 @@ def _search_as_arrow_tables(
page. On restart we re-enter at that saved token, so any page that was
yielded but never acked by a save is simply re-yielded. Merge semantics
over ``primary_keys`` dedupe those repeated rows.
+ * A resumed token may have expired between runs (Google Ads page tokens are
+ short-lived). If Google rejects it with ``INVALID_PAGE_TOKEN`` we discard
+ the saved token and restart pagination from the first page — the same
+ merge semantics make re-yielding already-synced rows safe.
"""
page_token = ""
if resumable_source_manager.can_resume():
@@ -465,13 +483,23 @@ def _search_as_arrow_tables(
# `GoogleAdsServiceClient.search` only accepts `customer_id` and `query`
# as convenience kwargs — `page_token` must be passed via the `request`
# argument (a dict is coerced to ``SearchGoogleAdsRequest`` by gapic).
- response = service.search(
- request={
- "customer_id": customer_id,
- "query": query,
- "page_token": page_token,
- }
- )
+ try:
+ response = service.search(
+ request={
+ "customer_id": customer_id,
+ "query": query,
+ "page_token": page_token,
+ }
+ )
+ except GoogleAdsException as e:
+ # Only a non-empty (resumed or mid-stream) token can be stale; an empty
+ # token always requests the first page, so the guard also prevents an
+ # infinite restart loop if the first page itself were ever rejected.
+ if page_token and _is_invalid_page_token_error(e):
+ resumable_source_manager.save_state(GoogleAdsResumeConfig(page_token=""))
+ page_token = ""
+ continue
+ raise
# ``response.pages`` is a gapic pager — we only consume the first page per
# request and drive pagination ourselves so the saved ``page_token`` is
diff --git a/posthog/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py b/posthog/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py
index 2430fcc6d385..ff8300480459 100644
--- a/posthog/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py
+++ b/posthog/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py
@@ -1,9 +1,22 @@
+from types import SimpleNamespace
+
import pytest
from unittest import mock
+from google.ads.googleads.errors import GoogleAdsException
+from google.ads.googleads.v23.enums import types as ga_enums
+from google.ads.googleads.v23.errors.types.errors import ErrorCode, GoogleAdsError, GoogleAdsFailure
+from google.ads.googleads.v23.errors.types.request_error import RequestErrorEnum
+
from posthog.models.integration import Integration
from posthog.temporal.data_imports.sources.generated_configs import GoogleAdsSourceConfig
-from posthog.temporal.data_imports.sources.google_ads.configs import clean_customer_id
+from posthog.temporal.data_imports.sources.google_ads.configs import GoogleAdsResumeConfig, clean_customer_id
+from posthog.temporal.data_imports.sources.google_ads.google_ads import (
+ GoogleAdsColumn,
+ GoogleAdsTable,
+ _is_invalid_page_token_error,
+ _search_as_arrow_tables,
+)
from posthog.temporal.data_imports.sources.google_ads.source import GoogleAdsSource
_CUSTOMER_ID_ERROR = "valid Google Ads customer ID"
@@ -270,3 +283,163 @@ class TestValidateCredentials:
assert ok is False
assert "reconnect your Google Ads account" in (message or "")
+
+
+def _google_ads_exception(request_error: int) -> GoogleAdsException:
+ failure = GoogleAdsFailure(
+ errors=[
+ GoogleAdsError(
+ error_code=ErrorCode(request_error=request_error),
+ message="Page token is invalid."
+ if request_error == RequestErrorEnum.RequestError.INVALID_PAGE_TOKEN
+ else "boom",
+ )
+ ]
+ )
+ return GoogleAdsException(error=None, call=None, failure=failure, request_id="req-1")
+
+
+def _string_column(qualified_name: str) -> GoogleAdsColumn:
+ return GoogleAdsColumn(
+ qualified_name=qualified_name,
+ data_type=ga_enums.GoogleAdsFieldDataTypeEnum.GoogleAdsFieldDataType.STRING, # type: ignore[arg-type]
+ is_repeatable=False,
+ type_url="",
+ )
+
+
+def _single_row_table() -> GoogleAdsTable:
+ return GoogleAdsTable(
+ name="campaign",
+ alias="campaign",
+ columns=[_string_column("campaign.name")],
+ parents=None,
+ requires_filter=False,
+ primary_key=[],
+ should_sync_default=True,
+ description=None,
+ )
+
+
+def _single_page() -> SimpleNamespace:
+ return SimpleNamespace(
+ field_mask=SimpleNamespace(paths=["campaign.name"]),
+ results=[SimpleNamespace(campaign=SimpleNamespace(name="Acme"))],
+ next_page_token="",
+ )
+
+
+class _FakeService:
+ """Raises INVALID_PAGE_TOKEN for any non-empty token, succeeds on the first page."""
+
+ def __init__(self, page: SimpleNamespace, error_on_token: GoogleAdsException | None = None):
+ self.page = page
+ self.error_on_token = error_on_token or _google_ads_exception(RequestErrorEnum.RequestError.INVALID_PAGE_TOKEN)
+ self.calls: list[str] = []
+
+ def search(self, request: dict):
+ self.calls.append(request["page_token"])
+ if request["page_token"]:
+ raise self.error_on_token
+ return SimpleNamespace(pages=iter([self.page]))
+
+
+class _FakeResumableManager:
+ def __init__(self, saved_token: str | None):
+ self._saved = saved_token
+ self.saved_states: list[str] = []
+
+ def can_resume(self) -> bool:
+ return self._saved is not None
+
+ def load_state(self) -> GoogleAdsResumeConfig | None:
+ return GoogleAdsResumeConfig(page_token=self._saved) if self._saved is not None else None
+
+ def save_state(self, data: GoogleAdsResumeConfig) -> None:
+ self.saved_states.append(data.page_token)
+
+
+class TestInvalidPageTokenDetection:
+ @pytest.mark.parametrize(
+ "exc, expected",
+ [
+ (_google_ads_exception(RequestErrorEnum.RequestError.INVALID_PAGE_TOKEN), True),
+ (_google_ads_exception(RequestErrorEnum.RequestError.RESOURCE_NAME_MISSING), False),
+ # A non-``GoogleAdsException`` shape (no ``failure``) must not match.
+ (SimpleNamespace(failure=None), False),
+ ],
+ )
+ def test_is_invalid_page_token_error(self, exc, expected):
+ assert _is_invalid_page_token_error(exc) is expected
+
+
+class TestSearchPageTokenResumption:
+ def test_restarts_pagination_when_saved_page_token_expired(self):
+ service = _FakeService(_single_page())
+ manager = _FakeResumableManager(saved_token="STALE_TOKEN")
+
+ tables = list(
+ _search_as_arrow_tables(
+ service=service, # type: ignore[arg-type]
+ customer_id="1234567890",
+ query="SELECT campaign.name FROM campaign",
+ table=_single_row_table(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ )
+ )
+
+ # The stale token was tried, rejected, then pagination restarted from the first page.
+ assert service.calls == ["STALE_TOKEN", ""]
+ # The stale token is cleared from saved state so a later resume won't reuse it.
+ assert manager.saved_states == [""]
+ # Rows are still yielded — the data was never lost.
+ assert [t.to_pylist() for t in tables] == [[{"campaign_name": "Acme"}]]
+
+ def test_other_google_ads_errors_propagate(self):
+ service = _FakeService(
+ _single_page(),
+ error_on_token=_google_ads_exception(RequestErrorEnum.RequestError.RESOURCE_NAME_MISSING),
+ )
+ manager = _FakeResumableManager(saved_token="STALE_TOKEN")
+
+ with pytest.raises(GoogleAdsException):
+ list(
+ _search_as_arrow_tables(
+ service=service, # type: ignore[arg-type]
+ customer_id="1234567890",
+ query="SELECT campaign.name FROM campaign",
+ table=_single_row_table(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ )
+ )
+
+ # No restart attempt — the token was never reset.
+ assert manager.saved_states == []
+
+ def test_invalid_page_token_without_saved_state_does_not_loop(self):
+ # Guards against an infinite restart loop: with no resumable token, an
+ # INVALID_PAGE_TOKEN on the first (empty-token) request must propagate.
+ always_failing = SimpleNamespace(
+ calls=[],
+ )
+
+ def _always_raise(request: dict):
+ always_failing.calls.append(request["page_token"])
+ raise _google_ads_exception(RequestErrorEnum.RequestError.INVALID_PAGE_TOKEN)
+
+ always_failing.search = _always_raise
+ manager = _FakeResumableManager(saved_token=None)
+
+ with pytest.raises(GoogleAdsException):
+ list(
+ _search_as_arrow_tables(
+ service=always_failing, # type: ignore[arg-type]
+ customer_id="1234567890",
+ query="SELECT campaign.name FROM campaign",
+ table=_single_row_table(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ )
+ )
+
+ assert always_failing.calls == [""]
+ assert manager.saved_states == []