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): recover from stale page token with unrecognised error code (#67523)

Tom Owersbc00a6e67187
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 0f6a4caabaf3..991ea7facfc4 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
@@ -659,6 +659,30 @@ def _is_stale_page_token_error(exc: GoogleAdsException) -> bool:
return any(request_error in failure_text for request_error in _STALE_PAGE_TOKEN_REQUEST_ERRORS)
+def _is_rejected_page_token_error(exc: GoogleAdsException, page_token: str) -> bool:
+ """Return True if the failure names ``page_token`` as the value that triggered it.
+
+ Google sometimes rejects a stale page token with a ``request_error`` code newer than the
+ pinned client library knows, which the SDK surfaces as ``request_error: UNKNOWN`` /
+ "The error code is not in this version." rather than the ``INVALID_PAGE_TOKEN`` /
+ ``EXPIRED_PAGE_TOKEN`` that ``_is_stale_page_token_error`` matches — so that check misses it
+ and the sync fails permanently. The failure still echoes the offending value in an error
+ ``trigger``, so when a trigger equals the token we sent, treat it as a stale token and
+ restart pagination from the first page. Matched on the exact token (not the volatile error
+ code) to stay low-false-positive.
+ """
+ if not page_token:
+ return False
+ failure = getattr(exc, "failure", None)
+ if failure is None:
+ return False
+ for error in getattr(failure, "errors", None) or []:
+ trigger = getattr(error, "trigger", None)
+ if trigger is not None and getattr(trigger, "string_value", None) == page_token:
+ return True
+ return False
+
+
def _search_as_arrow_tables(
service: GoogleAdsServiceClient,
customer_id: str | None,
@@ -676,9 +700,10 @@ def _search_as_arrow_tables(
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`` or
- ``EXPIRED_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.
+ ``EXPIRED_PAGE_TOKEN`` — or an unrecognised error code whose ``trigger``
+ names the token we sent (see ``_is_rejected_page_token_error``) — 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():
@@ -703,7 +728,7 @@ def _search_as_arrow_tables(
# 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_stale_page_token_error(e):
+ if page_token and (_is_stale_page_token_error(e) or _is_rejected_page_token_error(e, page_token)):
resumable_source_manager.save_state(GoogleAdsResumeConfig(page_token=""))
page_token = ""
continue
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 ddb3658060ff..4ccce4a77b2e 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
@@ -24,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads
GoogleAdsColumn,
GoogleAdsTable,
_get_integration,
+ _is_rejected_page_token_error,
_is_stale_page_token_error,
_is_transient_client_init_error,
_is_transient_grpc_error,
@@ -396,6 +397,18 @@ def _google_ads_exception(request_error: int) -> GoogleAdsException:
return GoogleAdsException(error=None, call=None, failure=failure, request_id="req-1")
+def _google_ads_exception_with_trigger(request_error: int, trigger_value: str) -> GoogleAdsException:
+ # A failure whose request_error code the pinned library can't decode (surfaced as UNKNOWN /
+ # "The error code is not in this version.") but whose trigger still echoes the offending value.
+ error = GoogleAdsError(
+ error_code=ErrorCode(request_error=request_error),
+ message="The error code is not in this version.",
+ )
+ error.trigger.string_value = trigger_value
+ failure = GoogleAdsFailure(errors=[error])
+ 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,
@@ -473,6 +486,29 @@ class TestStalePageTokenDetection:
assert _is_stale_page_token_error(exc) is expected
+class TestRejectedPageTokenDetection:
+ @pytest.mark.parametrize(
+ "exc, page_token, expected",
+ [
+ # Google rejected our token with a code the pinned library can't decode, but the
+ # failure trigger echoes the exact token we sent — recognise it as a stale token.
+ (
+ _google_ads_exception_with_trigger(RequestErrorEnum.RequestError.UNKNOWN, "SAVED_TOKEN"),
+ "SAVED_TOKEN",
+ True,
+ ),
+ # A trigger naming some other value must not be mistaken for a rejected page token.
+ (_google_ads_exception_with_trigger(RequestErrorEnum.RequestError.UNKNOWN, "other"), "SAVED_TOKEN", False),
+ # An empty page token (first-page request) can never be the rejected value.
+ (_google_ads_exception_with_trigger(RequestErrorEnum.RequestError.UNKNOWN, ""), "", False),
+ # A non-``GoogleAdsException`` shape (no ``failure``) must not match.
+ (SimpleNamespace(failure=None), "SAVED_TOKEN", False),
+ ],
+ )
+ def test_is_rejected_page_token_error(self, exc, page_token, expected):
+ assert _is_rejected_page_token_error(exc, page_token) is expected
+
+
class TestSearchPageTokenResumption:
@pytest.mark.parametrize(
"request_error",
@@ -502,6 +538,30 @@ class TestSearchPageTokenResumption:
# Rows are still yielded — the data was never lost.
assert [t.to_pylist() for t in tables] == [[{"campaign_name": "Acme"}]]
+ def test_restarts_pagination_when_page_token_rejected_with_unrecognised_code(self):
+ # Google rejected the saved token with a request_error code the pinned library can't
+ # decode (UNKNOWN / "The error code is not in this version."), so the code-text match
+ # misses it; the trigger echoing the token is the only stable signal to restart.
+ service = _FakeService(
+ _single_page(),
+ error_on_token=_google_ads_exception_with_trigger(RequestErrorEnum.RequestError.UNKNOWN, "STALE_TOKEN"),
+ )
+ 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]
+ )
+ )
+
+ assert service.calls == ["STALE_TOKEN", ""]
+ assert manager.saved_states == [""]
+ assert [t.to_pylist() for t in tables] == [[{"campaign_name": "Acme"}]]
+
def test_other_google_ads_errors_propagate(self):
service = _FakeService(
_single_page(),