: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(data-warehouse): add a deadline and keepalive to google ads calls (#112654)
Tom Owersb47bd07e03fe
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/configs.pyindex 92f347efd610..67359dad3b7b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/configs.py@@ -36,15 +36,17 @@ def parse_start_date(value: str) -> datetime.date:return datetime.datetime.fromisoformat(value.strip()).date()[email protected](frozen=True)class GoogleAdsResumeConfig:"""Resumable state for the Google Ads source.`page_token` is the opaque continuation token returned by- `GoogleAdsService.search` for the next page to fetch.+ `GoogleAdsService.search` for the next page to fetch. `campaign_id` names the campaign+ shard that the token belongs to, for resources that are read one campaign at a time."""page_token: str+ campaign_id: str | None = Nonedef clean_customer_id(s: str | None) -> str | None: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 fc6866c083ba..63b5087ed7da 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@@ -79,6 +79,13 @@ GOOGLE_ADS_INCREMENTAL_WINDOW_DAYS = 7# new ground rather than the run — see the arming rule in the drain loop.GOOGLE_ADS_MAX_DRAIN_SECONDS = 10 * 60+# Resources read one campaign at a time. An unfiltered query on a very large account makes Google+# scan the whole account before it returns a first page, so one call can run past the call deadline+# on every attempt. One query per campaign keeps each first page cheap and lets a retry resume at+# the campaign it stopped in.+_CAMPAIGN_SHARDED_RESOURCES = frozenset({"keyword_view"})+_CAMPAIGN_ID_QUERY = "SELECT campaign.id FROM campaign ORDER BY campaign.id ASC"+# Lower bound for the "where does this resource's data begin" request. Google serves a date this old# and returns nothing from before an account existed, so it needs no per-account tuning._GOOGLE_ADS_EARLIEST_QUERYABLE_DATE = "1970-01-01"@@ -93,20 +100,45 @@ _GOOGLE_ADS_EARLIEST_QUERYABLE_DATE = "1970-01-01"GRPC_MAX_RECEIVE_MESSAGE_LENGTH = 512 * 1024 * 1024_GRPC_MAX_RECEIVE_MESSAGE_LENGTH_KEY = "grpc.max_receive_message_length"+# Every Google Ads call gets a deadline. A call without one can hang forever on a dead connection.+# A hung call never returns to the import loop, so the worker shutdown check never runs and the pod+# stays alive until the drain limit. Normal calls finish in seconds. A full page of a wide resource+# can take minutes, so this value is generous. A call that exceeds it raises DEADLINE_EXCEEDED.+GOOGLE_ADS_CALL_TIMEOUT_SECONDS = 10 * 60++# HTTP/2 keepalive pings let gRPC detect a connection that a proxy or NAT silently dropped. The+# call then fails with UNAVAILABLE and the transient retry replaces the channel stream, instead of+# waiting for the full call deadline.+GOOGLE_ADS_KEEPALIVE_TIME_MS = 60 * 1000+GOOGLE_ADS_KEEPALIVE_TIMEOUT_MS = 20 * 1000++_GRPC_KEEPALIVE_OPTIONS: tuple[tuple[str, int], ...] = (+ ("grpc.keepalive_time_ms", GOOGLE_ADS_KEEPALIVE_TIME_MS),+ ("grpc.keepalive_timeout_ms", GOOGLE_ADS_KEEPALIVE_TIMEOUT_MS),+ ("grpc.keepalive_permit_without_calls", 0),+)+++def _set_grpc_channel_option(key: str, value: int) -> None:+ options = google_ads_client_module._GRPC_CHANNEL_OPTIONS+ for index, (existing_key, _value) in enumerate(options):+ if existing_key == key:+ options[index] = (key, value)+ return+ options.append((key, value))+def _ensure_grpc_receive_limit() -> None:- """Raise the Google Ads gRPC client's inbound message cap in place.+ """Raise the Google Ads gRPC client's inbound message cap in place and enable keepalive pings.``get_service`` reads the SDK's module-level ``_GRPC_CHANNEL_OPTIONS`` each time it builds- a channel, so rewriting the entry here makes every channel we subsequently create pick up- the higher limit. The update is idempotent and safe to call repeatedly.+ a channel, so rewriting the entries here makes every channel we subsequently create pick up+ the higher limit and the keepalive settings. The update is idempotent and safe to call+ repeatedly."""- options = google_ads_client_module._GRPC_CHANNEL_OPTIONS- for index, (key, _value) in enumerate(options):- if key == _GRPC_MAX_RECEIVE_MESSAGE_LENGTH_KEY:- options[index] = (key, GRPC_MAX_RECEIVE_MESSAGE_LENGTH)- return- options.append((_GRPC_MAX_RECEIVE_MESSAGE_LENGTH_KEY, GRPC_MAX_RECEIVE_MESSAGE_LENGTH))+ _set_grpc_channel_option(_GRPC_MAX_RECEIVE_MESSAGE_LENGTH_KEY, GRPC_MAX_RECEIVE_MESSAGE_LENGTH)+ for key, value in _GRPC_KEEPALIVE_OPTIONS:+ _set_grpc_channel_option(key, value)def _backoff_sleep(attempt: int) -> None:@@ -622,10 +654,12 @@ def google_ads_source(incremental_field = "segments.date"incremental_field_type = IncrementalFieldType.Date- def compose_query(lower_literal: str | None, upper_literal: str | None) -> str:+ def compose_query(lower_literal: str | None, upper_literal: str | None, extra_condition: str | None = None) -> str:query = f"SELECT {','.join(f'{field.qualified_name}' for field in table)} FROM {table.name}"conditions: list[str] = []+ if extra_condition:+ conditions.append(extra_condition)if should_use_incremental_field and lower_literal is not None:conditions.append(f"{incremental_field} >= {lower_literal}")if upper_literal is not None:@@ -654,6 +688,9 @@ def google_ads_source(service = GoogleAdsSearchService(google_ads_client(config, team_id), api_version, customer_id)if not should_use_incremental_field:+ if table.name in _CAMPAIGN_SHARDED_RESOURCES:+ yield from _search_by_campaign(service, customer_id, compose_query, table, resumable_source_manager)+ returnyield from _search_as_arrow_tables(service, customer_id, compose_query(None, None), table, resumable_source_manager)@@ -830,6 +867,25 @@ def _is_transient_grpc_error(exc: BaseException) -> bool:return True+class GoogleAdsCallDeadlineExceeded(Exception):+ """A Google Ads call ran past ``GOOGLE_ADS_CALL_TIMEOUT_SECONDS``.++ Retryable by Temporal's activity retry policy. The retry builds a fresh channel and resumes+ from the saved page token, so it is not retried in-process: the worker must get control back to+ see a shutdown request.+ """+++def _is_deadline_exceeded_error(exc: BaseException) -> bool:+ if isinstance(exc, google_api_exceptions.DeadlineExceeded):+ return True+ candidate: typing.Any = exc.error if isinstance(exc, GoogleAdsException) else exc+ if isinstance(candidate, google_api_exceptions.DeadlineExceeded):+ return True+ code = getattr(candidate, "code", None)+ return callable(code) and code() == grpc.StatusCode.DEADLINE_EXCEEDED++_T = typing.TypeVar("_T")@@ -848,6 +904,10 @@ def _call_with_transient_retry(try:return call()except Exception as e:+ if _is_deadline_exceeded_error(e):+ raise GoogleAdsCallDeadlineExceeded(+ f"Google Ads call did not finish within {GOOGLE_ADS_CALL_TIMEOUT_SECONDS} seconds"+ ) from eattempt += 1if attempt >= max_attempts or not _is_transient_grpc_error(e):raise@@ -867,7 +927,9 @@ def _search_with_transient_retry(``_is_transient_grpc_error``). Non-transient errors re-raise immediately so the caller'sstale-page-token handling and Temporal's retry policy still apply."""- return _call_with_transient_retry(lambda: service.search(request=request), max_attempts=max_attempts)+ return _call_with_transient_retry(+ lambda: service.search(request=request, timeout=GOOGLE_ADS_CALL_TIMEOUT_SECONDS), max_attempts=max_attempts+ )def _search_fields_with_transient_retry(@@ -883,7 +945,10 @@ def _search_fields_with_transient_retry(error from failing the whole import. Non-transient errors re-raise immediately so the caller'shandling and Temporal's retry policy still apply."""- return _call_with_transient_retry(lambda: service.search_google_ads_fields(query=query), max_attempts=max_attempts)+ return _call_with_transient_retry(+ lambda: service.search_google_ads_fields(query=query, timeout=GOOGLE_ADS_CALL_TIMEOUT_SECONDS),+ max_attempts=max_attempts,+ )_STALE_PAGE_TOKEN_REQUEST_ERRORS = ("INVALID_PAGE_TOKEN", "EXPIRED_PAGE_TOKEN")@@ -982,7 +1047,9 @@ def _find_manager_customer_id(client: GoogleAdsClient, customer_id: str, api_vercustomer_service = client.get_service("CustomerService", version=api_version, interceptors=tracked_interceptors(GOOGLE_ADS_HOST))- resource_names = customer_service.list_accessible_customers().resource_names+ resource_names = customer_service.list_accessible_customers(+ timeout=GOOGLE_ADS_CALL_TIMEOUT_SECONDS+ ).resource_namescandidates = [name.rsplit("/", 1)[-1] for name in resource_names]if customer_id in candidates:return None@@ -994,7 +1061,9 @@ def _find_manager_customer_id(client: GoogleAdsClient, customer_id: str, api_ver"GoogleAdsService", version=api_version, interceptors=tracked_interceptors(GOOGLE_ADS_HOST))try:- response = service.search(request={"customer_id": candidate, "query": query})+ response = service.search(+ request={"customer_id": candidate, "query": query}, timeout=GOOGLE_ADS_CALL_TIMEOUT_SECONDS+ )page = next(iter(response.pages), None)except Exception:continue@@ -1028,9 +1097,9 @@ class GoogleAdsSearchService:"GoogleAdsService", version=self._api_version, interceptors=tracked_interceptors(GOOGLE_ADS_HOST))- def search(self, request: dict) -> pagers.SearchPager:+ def search(self, request: dict, timeout: float = GOOGLE_ADS_CALL_TIMEOUT_SECONDS) -> pagers.SearchPager:try:- return self._service.search(request=request)+ return self._service.search(request=request, timeout=timeout)except Exception as e:if self._recovery_attempted or not self._customer_id or not _is_permission_denied_error(e):raise@@ -1045,7 +1114,61 @@ class GoogleAdsSearchService:)self._client.login_customer_id = manager_customer_idself._service = self._build_service()- return self._service.search(request=request)+ return self._service.search(request=request, timeout=timeout)+++def _list_campaign_ids(service: GoogleAdsSearchService | GoogleAdsServiceClient, customer_id: str | None) -> list[str]:+ campaign_ids: list[str] = []+ page_token = ""+ while True:+ response = _search_with_transient_retry(+ service, {"customer_id": customer_id, "query": _CAMPAIGN_ID_QUERY, "page_token": page_token}+ )+ page = next(iter(response.pages), None)+ if page is None:+ break+ campaign_ids.extend(str(_traverse_attributes(row, "campaign", "id")) for row in page.results)+ page_token = page.next_page_token+ if not page_token:+ break+ return campaign_ids+++def _search_by_campaign(+ service: GoogleAdsSearchService | GoogleAdsServiceClient,+ customer_id: str | None,+ compose_query: collections.abc.Callable[[str | None, str | None, str | None], str],+ table: GoogleAdsTable,+ resumable_source_manager: ResumableSourceManager[GoogleAdsResumeConfig],+) -> collections.abc.Generator[pa.Table]:+ """Read a full-refresh resource one campaign at a time, in ascending campaign id order.++ The saved state names the campaign in flight and its page token. A retry skips the campaigns+ before it. Saved state without a campaign id, or naming a campaign that is gone, restarts the+ whole resource, which is safe because the merge over the primary key dedupes repeated rows.+ """+ campaign_ids = _list_campaign_ids(service, customer_id)++ resume_campaign_id: str | None = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and resume.campaign_id in campaign_ids:+ resume_campaign_id = resume.campaign_id+ if resume_campaign_id is not None:+ campaign_ids = campaign_ids[campaign_ids.index(resume_campaign_id) :]++ for index, campaign_id in enumerate(campaign_ids):+ next_campaign_id = campaign_ids[index + 1] if index + 1 < len(campaign_ids) else None+ yield from _search_as_arrow_tables(+ service,+ customer_id,+ compose_query(None, None, f"campaign.id = {campaign_id}"),+ table,+ resumable_source_manager,+ use_saved_state=index == 0 and resume_campaign_id is not None,+ campaign_id=campaign_id,+ next_campaign_id=next_campaign_id,+ )def _search_as_arrow_tables(@@ -1055,6 +1178,8 @@ def _search_as_arrow_tables(table: GoogleAdsTable,resumable_source_manager: ResumableSourceManager[GoogleAdsResumeConfig],use_saved_state: bool = True,+ campaign_id: str | None = None,+ next_campaign_id: str | None = None,) -> collections.abc.Generator[pa.Table]:"""Paginate ``GoogleAdsService.search`` and yield each page as a ``pyarrow.Table``.@@ -1070,6 +1195,9 @@ def _search_as_arrow_tables(names the token we sent (see ``_is_rejected_page_token_error``) — wediscard the saved token and restart pagination from the first page. Thesame merge semantics make re-yielding already-synced rows safe.+ * ``next_campaign_id`` is the campaign a campaign-sharded caller reads next. Once this+ campaign's last page has no further token, we save state pointing at that campaign so a+ resume does not restart this one."""# `use_saved_state=False` is passed for every window after the first in a windowed drain: the# saved page token belongs to whichever window was in flight last time and is meaningless for a@@ -1098,7 +1226,7 @@ def _search_as_arrow_tables(# 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) or _is_rejected_page_token_error(e, page_token)):- resumable_source_manager.save_state(GoogleAdsResumeConfig(page_token=""))+ resumable_source_manager.save_state(GoogleAdsResumeConfig(page_token="", campaign_id=campaign_id))page_token = ""continueraise@@ -1116,9 +1244,11 @@ def _search_as_arrow_tables(next_page_token = page.next_page_tokenif not next_page_token:+ if next_campaign_id is not None:+ resumable_source_manager.save_state(GoogleAdsResumeConfig(page_token="", campaign_id=next_campaign_id))break- resumable_source_manager.save_state(GoogleAdsResumeConfig(page_token=next_page_token))+ resumable_source_manager.save_state(GoogleAdsResumeConfig(page_token=next_page_token, campaign_id=campaign_id))page_token = next_page_tokendiff --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 924f6072aafe..ab9ea965e935 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@@ -38,11 +38,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_adsclean_customer_id,)from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.google_ads import (+ GOOGLE_ADS_CALL_TIMEOUT_SECONDS,GOOGLE_ADS_INCREMENTAL_WINDOW_DAYS,+ GoogleAdsCallDeadlineExceeded,GoogleAdsColumn,GoogleAdsSearchService,GoogleAdsTable,_get_integration,+ _is_deadline_exceeded_error,_is_permission_denied_error,_is_rejected_page_token_error,_is_stale_page_token_error,@@ -51,6 +54,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads_load_client_with_transient_retry,_resolve_protobuf_message_type_url,_search_as_arrow_tables,+ _search_by_campaign,_search_fields_with_transient_retry,get_schemas,google_ads_source,@@ -637,7 +641,7 @@ class _FakeService: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):+ def search(self, request: dict, timeout: float | None = None):self.calls.append(request["page_token"])if request["page_token"]:raise self.error_on_token@@ -780,7 +784,7 @@ class TestSearchPageTokenResumption:calls=[],)- def _always_raise(request: dict):+ def _always_raise(request: dict, timeout: float | None = None):always_failing.calls.append(request["page_token"])raise _google_ads_exception(RequestErrorEnum.RequestError.INVALID_PAGE_TOKEN)@@ -1011,7 +1015,7 @@ class _FlakyService:self.fail_times = fail_timesself.calls = 0- def search(self, request: dict):+ def search(self, request: dict, timeout: float | None = None):self.calls += 1if self.calls <= self.fail_times:raise self.error@@ -1133,7 +1137,7 @@ class _FakeSearchService:# The header is baked in when the service is built, as the real SDK does.self._login_customer_id = login_customer_id- def search(self, request: dict):+ def search(self, request: dict, timeout: float | None = None):customer_id = request["customer_id"]self._client.searches.append((customer_id, self._login_customer_id))@@ -1165,7 +1169,7 @@ class _FakeGoogleAdsClient:def get_service(self, name: str, version: str | None = None, interceptors: object = None):if name == "CustomerService":return SimpleNamespace(- list_accessible_customers=lambda: SimpleNamespace(+ list_accessible_customers=lambda timeout=None: SimpleNamespace(resource_names=[f"customers/{customer_id}" for customer_id in self.accessible]))@@ -1255,7 +1259,7 @@ class _FlakyFieldService:self.fail_times = fail_timesself.calls = 0- def search_google_ads_fields(self, query: str):+ def search_google_ads_fields(self, query: str, timeout: float | None = None):self.calls += 1if self.calls <= self.fail_times:raise self.error@@ -2137,3 +2141,180 @@ class TestBreakdownStatsDefaultOff:@pytest.mark.parametrize("alias", ["keyword", "keyword_stats", "landing_page_stats"])def test_search_performance_tables_are_preselected(alias: str) -> None:assert RESOURCE_SCHEMAS[alias].get("should_sync_default", True) is True+++class TestGrpcKeepalive:+ def test_channel_options_enable_keepalive_once(self):+ from google.ads.googleads import client as google_ads_client_module++ from products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.google_ads import (+ _ensure_grpc_receive_limit,+ )++ _ensure_grpc_receive_limit()+ _ensure_grpc_receive_limit()++ keys = [key for key, _ in google_ads_client_module._GRPC_CHANNEL_OPTIONS]+ options = dict(google_ads_client_module._GRPC_CHANNEL_OPTIONS)+ for key in ("grpc.keepalive_time_ms", "grpc.keepalive_timeout_ms", "grpc.keepalive_permit_without_calls"):+ assert keys.count(key) == 1+ assert options["grpc.keepalive_time_ms"] > options["grpc.keepalive_timeout_ms"] > 0+++class TestCallDeadline:+ @pytest.mark.parametrize(+ "error, expected",+ [+ (google_api_exceptions.DeadlineExceeded("504 Deadline Exceeded"), True),+ (_StatusCodeRpcError(grpc.StatusCode.DEADLINE_EXCEEDED), True),+ (_google_ads_exception_wrapping(_StatusCodeRpcError(grpc.StatusCode.DEADLINE_EXCEEDED)), True),+ (_grpc_unavailable_error(), False),+ (google_api_exceptions.ServiceUnavailable("502:Bad Gateway"), False),+ (ValueError("boom"), False),+ ],+ )+ def test_is_deadline_exceeded_error(self, error, expected):+ assert _is_deadline_exceeded_error(error) is expected++ @pytest.mark.parametrize(+ "error",+ [+ google_api_exceptions.DeadlineExceeded("504 Deadline Exceeded"),+ _google_ads_exception_wrapping(_StatusCodeRpcError(grpc.StatusCode.DEADLINE_EXCEEDED)),+ ],+ )+ def test_deadline_is_raised_without_in_process_retry(self, error):+ service = _FlakyService(_single_page(), error=error, fail_times=10)+ manager = _FakeResumableManager(saved_token=None)++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.google_ads.google_ads.time.sleep"+ ) as sleep:+ with pytest.raises(GoogleAdsCallDeadlineExceeded):+ 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 == 1+ sleep.assert_not_called()++ def test_every_search_call_carries_the_deadline(self):+ timeouts: list[float | None] = []++ class _Recorder:+ def search(self, request: dict, timeout: float | None = None):+ timeouts.append(timeout)+ return SimpleNamespace(pages=iter([_single_page()]))++ list(+ _search_as_arrow_tables(+ service=_Recorder(), # type: ignore[arg-type]+ customer_id="1234567890",+ query="SELECT campaign.name FROM campaign",+ table=_single_row_table(),+ resumable_source_manager=_FakeResumableManager(saved_token=None), # type: ignore[arg-type]+ )+ )++ assert timeouts == [GOOGLE_ADS_CALL_TIMEOUT_SECONDS]+++class _ShardedManager:+ def __init__(self, saved: GoogleAdsResumeConfig | None = None):+ self._saved = saved+ self.saved_states: list[tuple[str, str | None]] = []++ def can_resume(self) -> bool:+ return self._saved is not None++ def load_state(self) -> GoogleAdsResumeConfig | None:+ return self._saved++ def save_state(self, data: GoogleAdsResumeConfig) -> None:+ self.saved_states.append((data.page_token, data.campaign_id))+++class _ShardedService:+ """Serves a campaign id list, then one one-row page per campaign-filtered query."""++ def __init__(self, campaign_ids: list[str]):+ self.campaign_ids = campaign_ids+ self.queries: list[tuple[str, str]] = []++ def search(self, request: dict, timeout: float | None = None):+ query = request["query"]+ self.queries.append((query, request["page_token"]))+ if query.startswith("SELECT campaign.id FROM campaign"):+ results = [SimpleNamespace(campaign=SimpleNamespace(id=int(i))) for i in self.campaign_ids]+ page = SimpleNamespace(results=results, next_page_token="")+ else:+ campaign_id = query.rsplit("campaign.id = ", 1)[1]+ page = SimpleNamespace(+ field_mask=SimpleNamespace(paths=["campaign.name"]),+ results=[SimpleNamespace(campaign=SimpleNamespace(name=f"c{campaign_id}"))],+ next_page_token="",+ )+ return SimpleNamespace(pages=iter([page]))+++class TestCampaignShardedSearch:+ def _compose(self, lower, upper, extra=None) -> str:+ return (+ f"SELECT campaign.name FROM keyword_view WHERE {extra}"+ if extra+ else "SELECT campaign.name FROM keyword_view"+ )++ def _run(self, service: _ShardedService, manager: _ShardedManager) -> list[str]:+ tables = _search_by_campaign(+ service, # type: ignore[arg-type]+ "1234567890",+ self._compose,+ _single_row_table(),+ manager, # type: ignore[arg-type]+ )+ return [row["campaign_name"] for t in tables for row in t.to_pylist()]++ @pytest.mark.parametrize(+ "saved, expected_names",+ [+ (None, ["c1", "c2", "c3"]),+ (GoogleAdsResumeConfig(page_token="", campaign_id="2"), ["c2", "c3"]),+ (GoogleAdsResumeConfig(page_token="", campaign_id="3"), ["c3"]),+ # State from before sharding, or naming a deleted campaign, restarts the whole resource.+ (GoogleAdsResumeConfig(page_token="TOKEN"), ["c1", "c2", "c3"]),+ (GoogleAdsResumeConfig(page_token="TOKEN", campaign_id="99"), ["c1", "c2", "c3"]),+ ],+ )+ def test_resumes_at_saved_campaign(self, saved, expected_names):+ service = _ShardedService(["1", "2", "3"])++ assert self._run(service, _ShardedManager(saved)) == expected_names++ def test_checkpoints_next_campaign_and_filters_each_query(self):+ service = _ShardedService(["1", "2", "3"])+ manager = _ShardedManager()++ self._run(service, manager)++ assert manager.saved_states == [("", "2"), ("", "3")]+ shard_queries = [q for q, _ in service.queries if "keyword_view" in q]+ assert shard_queries == [self._compose(None, None, f"campaign.id = {i}") for i in (1, 2, 3)]++ def test_saved_page_token_is_only_sent_for_its_own_campaign(self):+ service = _ShardedService(["1", "2"])+ manager = _ShardedManager(GoogleAdsResumeConfig(page_token="TOKEN", campaign_id="1"))++ self._run(service, manager)++ shard_calls = [(q.rsplit("= ", 1)[1], token) for q, token in service.queries if "keyword_view" in q]+ assert shard_calls == [("1", "TOKEN"), ("2", "")]++ def test_no_campaigns_yields_nothing(self):+ assert self._run(_ShardedService([]), _ShardedManager()) == []