: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(google_ads): restart pagination on expired page token (#66928)
Tom Owers9cdfa0c10c5d
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 357f33ff9bc3..b2897a665998 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@@ -554,7 +554,7 @@ def _search_with_transient_retry(Each retry re-requests the same ``page_token``, so there is no partial state to reconcile. Thetransient status may itself arrive wrapped in a ``GoogleAdsException`` (see``_is_transient_grpc_error``). Non-transient errors re-raise immediately so the caller's- ``INVALID_PAGE_TOKEN`` handling and Temporal's retry policy still apply.+ stale-page-token handling and Temporal's retry policy still apply."""attempt = 0while True:@@ -567,17 +567,26 @@ def _search_with_transient_retry(time.sleep(min(2 * attempt, 30))-def _is_invalid_page_token_error(exc: GoogleAdsException) -> bool:- """Return True if a ``GoogleAdsException`` was caused by an expired/invalid page token.+_STALE_PAGE_TOKEN_REQUEST_ERRORS = ("INVALID_PAGE_TOKEN", "EXPIRED_PAGE_TOKEN")+++def _is_stale_page_token_error(exc: GoogleAdsException) -> bool:+ """Return True if a ``GoogleAdsException`` was caused by a stale page token.Google Ads search page tokens are ephemeral, but our resumption contractpersists 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.+ token Google no longer accepts, the API rejects the request with either+ ``request_error: INVALID_PAGE_TOKEN`` (malformed/unrecognised) or+ ``request_error: EXPIRED_PAGE_TOKEN`` (a once-valid token aged out between+ runs) — both mean the same thing for us: restart pagination from the first+ page. 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)+ if failure is None:+ return False+ failure_text = str(failure)+ return any(request_error in failure_text for request_error in _STALE_PAGE_TOKEN_REQUEST_ERRORS)def _search_as_arrow_tables(@@ -596,9 +605,10 @@ def _search_as_arrow_tables(yielded but never acked by a save is simply re-yielded. Merge semanticsover ``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.+ 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."""page_token = ""if resumable_source_manager.can_resume():@@ -623,7 +633,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_invalid_page_token_error(e):+ if page_token and _is_stale_page_token_error(e):resumable_source_manager.save_state(GoogleAdsResumeConfig(page_token=""))page_token = ""continuediff --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 9a2441d22f4b..26daa4368f7f 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,7 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_adsGoogleAdsColumn,GoogleAdsTable,_get_integration,- _is_invalid_page_token_error,+ _is_stale_page_token_error,_is_transient_client_init_error,_is_transient_grpc_error,_load_client_with_transient_retry,@@ -430,23 +430,33 @@ class _FakeResumableManager:self.saved_states.append(data.page_token)-class TestInvalidPageTokenDetection:+class TestStalePageTokenDetection:@pytest.mark.parametrize("exc, expected",[(_google_ads_exception(RequestErrorEnum.RequestError.INVALID_PAGE_TOKEN), True),+ # Google returns a distinct EXPIRED_PAGE_TOKEN when a once-valid token aged out+ # between runs — the resumption recovery must treat it the same as INVALID_PAGE_TOKEN.+ (_google_ads_exception(RequestErrorEnum.RequestError.EXPIRED_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+ def test_is_stale_page_token_error(self, exc, expected):+ assert _is_stale_page_token_error(exc) is expectedclass TestSearchPageTokenResumption:- def test_restarts_pagination_when_saved_page_token_expired(self):- service = _FakeService(_single_page())+ @pytest.mark.parametrize(+ "request_error",+ [+ RequestErrorEnum.RequestError.INVALID_PAGE_TOKEN,+ RequestErrorEnum.RequestError.EXPIRED_PAGE_TOKEN,+ ],+ )+ def test_restarts_pagination_when_saved_page_token_stale(self, request_error):+ service = _FakeService(_single_page(), error_on_token=_google_ads_exception(request_error))manager = _FakeResumableManager(saved_token="STALE_TOKEN")tables = list(