: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
feat(data-warehouse): add 5 missing Google Search Console tables (#77280)
Tom Owers9907d53f8752
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.mdindex 715398be5dba..d857847b5a64 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md@@ -280,14 +280,31 @@ Have: `accounts`, `campaigns`, `campaign_groups`, `creatives`, `conversions`, `c- [ ] Budget and bid data on campaigns. (skipped: `dailyBudget`, `unitCost` and `costType` already sync on `campaigns` and `totalBudget` on `campaign_groups`; the remainder would mean adding columns to live tables)- [ ] Video ad analytics. (skipped: `videoViews` and `videoCompletions` already sync on the stats tables; the extra quartile metrics would mean adding columns to live tables)-### Google Search Console — needs confirmation--Seven tables, all of them `search_analytics` dimension bundles.--- [ ] `sitemaps` — submission status, errors, indexed counts.-- [ ] `sites` — the property list itself.-- [ ] URL inspection results (index status per URL).-- [ ] Additional dimension combinations, notably date + page + query together, and country + device.+### Google Search Console — spec-verified++Diffed against the [Search Console API discovery document](https://searchconsole.googleapis.com/$discovery/rest?version=v1)+(revision 20260803) on 2026-08-04.++Have: `search_analytics_by_date`, `search_analytics_by_query`, `search_analytics_by_page`,+`search_analytics_by_country`, `search_analytics_by_device`, `search_analytics_by_country_device`,+`search_analytics_by_query_page`, `search_analytics_by_search_appearance`, `search_analytics_by_hour`,+`sites`, `sitemaps`, `sitemap_contents`.++- [x] `sitemaps` — submission status, errors, indexed counts. (`indexed` itself is marked deprecated+ "do not use" in the discovery document, so the per-content-type `submitted` count ships instead,+ as a `sitemap_contents` table.)+- [x] `sites` — the property list itself.+- [ ] URL inspection results (index status per URL). (skipped: `urlInspection.index.inspect` is a+ per-URL POST with no listing endpoint, and nothing in the API yields a bounded URL list —+ `sitemaps.list` returns sitemap file paths, not the URLs inside them. Combined with the+ 2,000 inspections per property per day quota, there is no way to drive it as a table.)+- [x] Additional dimension combinations: country + device. (date + page + query already shipped as+ `search_analytics_by_query_page`.) Also added `search_analytics_by_hour`, the only dimension+ Google serves outside the 16-month daily window — it retains 10 days and needs+ `dataState: hourly_all`.+- [ ] Per search type (`type`: image, video, news, discover, googleNews) variants of the dimension+ bundles. (skipped: real endpoint, but the docs do not state which dimensions each type supports,+ so the table set could not be pinned down from the spec alone.)### Clerk — spec-verifieddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/canonical_descriptions.pynew file mode 100644index 000000000000..5ba8c8f26578--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/canonical_descriptions.py@@ -0,0 +1,103 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+ CanonicalEndpoint,+)++_SEARCH_ANALYTICS_DOCS_URL = "https://developers.google.com/webmaster-tools/v1/searchanalytics/query"+_SITES_DOCS_URL = "https://developers.google.com/webmaster-tools/v1/sites/list"+_SITEMAPS_DOCS_URL = "https://developers.google.com/webmaster-tools/v1/sitemaps/list"++# Every search analytics table carries the same four metrics, plus the dimensions it groups by.+_METRIC_COLUMNS = {+ "clicks": "Number of clicks on a result that led to the property.",+ "impressions": "Number of times a link to the property appeared in search results for the user.",+ "ctr": "Click-through rate, as a fraction between 0 and 1 (clicks divided by impressions).",+ "position": "Average position of the property's topmost result, where 1 is the top result.",+}++_DATE_COLUMN = {+ "date": "The day the metrics were recorded, in Pacific time (UTC-7:00/8:00).",+}+++def _search_analytics(description: str, **dimensions: str) -> CanonicalEndpoint:+ return {+ "description": description,+ "docs_url": _SEARCH_ANALYTICS_DOCS_URL,+ "columns": {**_DATE_COLUMN, **dimensions, **_METRIC_COLUMNS},+ }+++_QUERY_COLUMN = "The search query the user typed. Queries made by very few users are withheld by Google."+_PAGE_COLUMN = "The canonical URL of the result page the user saw."+_COUNTRY_COLUMN = "Country the search was made from, as a three-letter ISO 3166-1 alpha-3 code."+_DEVICE_COLUMN = "Device the search was made on: DESKTOP, MOBILE, or TABLET."++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "search_analytics_by_date": _search_analytics("Daily search performance totals for the property."),+ "search_analytics_by_query": _search_analytics(+ "Daily search performance for the property, grouped by search query.",+ query=_QUERY_COLUMN,+ ),+ "search_analytics_by_page": _search_analytics(+ "Daily search performance for the property, grouped by landing page.",+ page=_PAGE_COLUMN,+ ),+ "search_analytics_by_country": _search_analytics(+ "Daily search performance for the property, grouped by the searcher's country.",+ country=_COUNTRY_COLUMN,+ ),+ "search_analytics_by_device": _search_analytics(+ "Daily search performance for the property, grouped by device type.",+ device=_DEVICE_COLUMN,+ ),+ "search_analytics_by_country_device": _search_analytics(+ "Daily search performance for the property, grouped by country and device together.",+ country=_COUNTRY_COLUMN,+ device=_DEVICE_COLUMN,+ ),+ "search_analytics_by_query_page": _search_analytics(+ "Daily search performance for the property, grouped by search query and landing page.",+ query=_QUERY_COLUMN,+ page=_PAGE_COLUMN,+ ),+ "search_analytics_by_search_appearance": _search_analytics(+ "Daily search performance for the property, grouped by how the result was presented in search.",+ searchAppearance="The search result feature the result appeared as, for example RICH_RESULT or VIDEO.",+ ),+ "search_analytics_by_hour": _search_analytics(+ "Hourly search performance totals for the property, covering the last 10 days.",+ hour="Start of the hour the metrics were recorded, in Pacific time (UTC-7:00/8:00).",+ ),+ "sites": {+ "description": "Search Console properties the connected Google account has access to.",+ "docs_url": _SITES_DOCS_URL,+ "columns": {+ "siteUrl": "The property, either a URL prefix such as https://example.com/ or a domain property such as sc-domain:example.com.",+ "permissionLevel": "The account's permission level on the property: SITE_OWNER, SITE_FULL_USER, SITE_RESTRICTED_USER, or SITE_UNVERIFIED_USER.",+ },+ },+ "sitemaps": {+ "description": "Sitemaps submitted for the property, with Google's processing status for each.",+ "docs_url": _SITEMAPS_DOCS_URL,+ "columns": {+ "path": "The URL of the sitemap.",+ "type": "The type of sitemap, for example SITEMAP, RSS_FEED, ATOM_FEED, or URL_LIST.",+ "lastSubmitted": "When the sitemap was submitted to Google.",+ "lastDownloaded": "When Google last downloaded the sitemap.",+ "errors": "Number of errors in the sitemap itself, which stop it being processed correctly.",+ "warnings": "Number of warnings for URLs in the sitemap. Generally non-critical.",+ "isPending": "True while Google has not yet processed the sitemap.",+ "isSitemapsIndex": "True when the sitemap is an index that points at other sitemaps.",+ },+ },+ "sitemap_contents": {+ "description": "URL counts per content type for each submitted sitemap, one row per sitemap and content type.",+ "docs_url": _SITEMAPS_DOCS_URL,+ "columns": {+ "path": "The URL of the sitemap this content type belongs to.",+ "type": "The content type, for example WEB, IMAGE, VIDEO, or NEWS.",+ "submitted": "Number of URLs of this content type in the sitemap.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.pyindex 7e12c4d2a76e..4a222a517109 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py@@ -25,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_GoogleSearchConsoleSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.google_search_console.settings import (+ PROPERTY_SCHEMAS,SEARCH_ANALYTICS_SCHEMAS,)@@ -60,6 +61,7 @@ ROW_LIMIT = 25000HISTORY_DAYS = 16 * 30 # Google retains ~16 months of Search Analytics dataFRESHNESS_LAG_DAYS = 3 # GSC publishes data with a 2-3 day lag+DEFAULT_DATA_STATE = "final" # complete data only; the hourly table overrides this# Search Analytics is rate-limited at 1,200 QPM per site and per user, plus a# per-second (QPS) burst cap. Paginating day-by-day across ~16 months of history@@ -234,6 +236,12 @@ def list_sites(session: AuthorizedSession) -> list[dict[str, Any]]:return response.json().get("siteEntry", [])+def list_sitemaps(session: AuthorizedSession, site_url: str) -> list[dict[str, Any]]:+ response = session.get(f"{GSC_API_BASE}/sites/{quote(site_url, safe='')}/sitemaps")+ response.raise_for_status()+ return response.json().get("sitemap", [])++def _is_quota_error(response: requests.Response) -> bool:"""Whether a failed response is a transient rate-limit/quota error worth retrying.@@ -310,6 +318,7 @@ def _query_search_analytics(dimensions: list[str],start_row: int,row_limit: int = ROW_LIMIT,+ data_state: str = DEFAULT_DATA_STATE,) -> list[dict[str, Any]]:body = {"startDate": start_date,@@ -317,7 +326,7 @@ def _query_search_analytics("dimensions": dimensions,"rowLimit": row_limit,"startRow": start_row,- "dataState": "final",+ "dataState": data_state,}url = f"{GSC_API_BASE}/sites/{quote(site_url, safe='')}/searchAnalytics/query"@@ -406,9 +415,30 @@ def _query_search_analytics(raise GoogleSearchConsoleQuotaExceededError(f"Search Analytics quota for '{site_url}' exhausted")+def _parse_api_datetime(value: Any) -> dt.datetime | None:+ """Parse an RFC 3339 timestamp from the API, returning None for anything unparseable."""+ if not isinstance(value, str) or not value:+ return None+ try:+ return dt.datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+++def _as_int(value: Any) -> int:+ """Coerce an API counter to int. Google serializes int64 fields as JSON strings."""+ try:+ return int(value)+ except (TypeError, ValueError):+ return 0++def _row_to_dict(row: dict[str, Any], dimensions: list[str], iter_date: dt.date | None = None) -> dict[str, Any]:keys = row["keys"]out: dict[str, Any] = {dim: keys[i] if i < len(keys) else None for i, dim in enumerate(dimensions)}+ if "hour" in out:+ # The `hour` dimension comes back as an ISO-8601 offset date-time in Pacific time.+ out["hour"] = _parse_api_datetime(out["hour"])if "date" in out and out["date"] is not None:out["date"] = dt.date.fromisoformat(out["date"])elif "date" not in out and iter_date is not None:@@ -433,17 +463,19 @@ def _today() -> dt.date:return dt.date.today()-def _initial_start_date(today: dt.date) -> dt.date:- return today - dt.timedelta(days=HISTORY_DAYS)+def _initial_start_date(today: dt.date, history_days: int = HISTORY_DAYS) -> dt.date:+ return today - dt.timedelta(days=history_days)def _resolve_window(today: dt.date,db_incremental_field_last_value: Any,+ history_days: int = HISTORY_DAYS,+ end_lag_days: int = FRESHNESS_LAG_DAYS,) -> tuple[dt.date, dt.date]:- end_date = today - dt.timedelta(days=FRESHNESS_LAG_DAYS)+ end_date = today - dt.timedelta(days=end_lag_days)if db_incremental_field_last_value is None:- return _initial_start_date(today), end_date+ return _initial_start_date(today, history_days), end_dateif isinstance(db_incremental_field_last_value, dt.datetime):last = db_incremental_field_last_value.date()@@ -452,7 +484,7 @@ def _resolve_window(else:last = dt.date.fromisoformat(str(db_incremental_field_last_value)[:10])- start = max(last, _initial_start_date(today))+ start = max(last, _initial_start_date(today, history_days))return start, end_date@@ -465,6 +497,76 @@ def _iter_dates(start: dt.date, end: dt.date) -> collections.abc.Iterator[dt.datcurrent += dt.timedelta(days=1)+def _site_to_dict(site: dict[str, Any]) -> dict[str, Any]:+ return {+ "siteUrl": site.get("siteUrl"),+ "permissionLevel": site.get("permissionLevel"),+ }+++def _sitemap_to_dict(sitemap: dict[str, Any]) -> dict[str, Any]:+ # Booleans and counters are omitted by Google when they're false/zero. Filling them in+ # keeps the stored Delta column types stable across syncs, the same reason `_row_to_dict`+ # pins its metric types.+ return {+ "path": sitemap.get("path"),+ "type": sitemap.get("type"),+ "lastSubmitted": _parse_api_datetime(sitemap.get("lastSubmitted")),+ "lastDownloaded": _parse_api_datetime(sitemap.get("lastDownloaded")),+ "errors": _as_int(sitemap.get("errors", 0)),+ "warnings": _as_int(sitemap.get("warnings", 0)),+ "isPending": bool(sitemap.get("isPending", False)),+ "isSitemapsIndex": bool(sitemap.get("isSitemapsIndex", False)),+ }+++def _sitemap_content_rows(sitemap: dict[str, Any]) -> list[dict[str, Any]]:+ # `indexed` is on the API response but marked deprecated ("do not use"), so it is not synced.+ return [+ {+ "path": sitemap.get("path"),+ "type": content.get("type"),+ "submitted": _as_int(content.get("submitted", 0)),+ }+ for content in sitemap.get("contents", [])+ ]+++def _property_rows(+ config: GoogleSearchConsoleSourceConfig,+ resource_name: str,+ team_id: int,+) -> collections.abc.Iterator[list[dict[str, Any]]]:+ session = google_search_console_session(config.google_search_console_integration_id, team_id)++ if resource_name == "sites":+ rows = [_site_to_dict(site) for site in list_sites(session)]+ else:+ sitemaps = list_sitemaps(session, normalize_site_url(config.site_url))+ if resource_name == "sitemaps":+ rows = [_sitemap_to_dict(sitemap) for sitemap in sitemaps]+ else:+ rows = [row for sitemap in sitemaps for row in _sitemap_content_rows(sitemap)]++ if rows:+ yield rows+++def _property_source(+ config: GoogleSearchConsoleSourceConfig,+ resource_name: str,+ team_id: int,+) -> SourceResponse:+ return SourceResponse(+ name=NamingConvention.normalize_identifier(resource_name),+ items=lambda: _property_rows(config, resource_name, team_id),+ primary_keys=list(PROPERTY_SCHEMAS[resource_name]["primary_key"]),+ # A snapshot of the current state, with no timestamp to order or partition on.+ # Google documents no ordering for either list endpoint, so no sort mode is declared.+ sort_mode=None,+ )++def google_search_console_source(config: GoogleSearchConsoleSourceConfig,resource_name: str,@@ -473,12 +575,19 @@ def google_search_console_source(should_use_incremental_field: bool = False,db_incremental_field_last_value: Any = None,) -> SourceResponse:+ if resource_name in PROPERTY_SCHEMAS:+ return _property_source(config, resource_name, team_id)+if resource_name not in SEARCH_ANALYTICS_SCHEMAS:raise ValueError(f"Unknown Google Search Console schema: {resource_name}")schema = SEARCH_ANALYTICS_SCHEMAS[resource_name]dimensions = schema["dimensions"]primary_keys = list(schema["primary_key"])+ data_state = schema.get("data_state", DEFAULT_DATA_STATE)+ history_days = schema.get("history_days", HISTORY_DAYS)+ end_lag_days = schema.get("end_lag_days", FRESHNESS_LAG_DAYS)+ ignore_watermark = schema.get("ignore_incremental_watermark", False)# Match the canonicalization done at validation time so a property that validated (e.g. a# percent-encoded or trailing-slash-less entry) resolves to the same string Google expects.@@ -490,7 +599,9 @@ def google_search_console_source(today = _today()start_date, end_date = _resolve_window(today,- db_incremental_field_last_value if should_use_incremental_field else None,+ db_incremental_field_last_value if (should_use_incremental_field and not ignore_watermark) else None,+ history_days=history_days,+ end_lag_days=end_lag_days,)resume_date: str | None = None@@ -519,6 +630,7 @@ def google_search_console_source(end_date=iso,dimensions=dimensions,start_row=start_row,+ data_state=data_state,)if not rows:breakdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/settings.pyindex ec8f6d0e45bb..5ebed0f4a83f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/settings.py@@ -1,4 +1,4 @@-from typing import TypedDict+from typing import NotRequired, TypedDictfrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType@@ -8,6 +8,17 @@ class SearchAnalyticsSchema(TypedDict):primary_key: list[str]should_sync_default: booldescription: str | None+ # `dataState` sent with the query. Defaults to final (complete) data.+ data_state: NotRequired[str]+ # How far back the first sync reaches, when the endpoint retains less than the+ # 16 months Search Analytics keeps for daily data.+ history_days: NotRequired[int]+ # How many days behind today the window ends, covering Google's publishing lag.+ end_lag_days: NotRequired[int]+ # Refetch the whole retention window every sync instead of resuming at the+ # watermark. Only sane for tables whose window is a handful of days and whose+ # rows Google keeps restating.+ ignore_incremental_watermark: NotRequired[bool]# Each schema maps to a single Search Analytics query with a fixed dimension set.@@ -56,6 +67,33 @@ SEARCH_ANALYTICS_SCHEMAS: dict[str, SearchAnalyticsSchema] = {"should_sync_default": False,"description": "Daily performance broken out by device (DESKTOP, MOBILE, TABLET).",},+ "search_analytics_by_country_device": {+ "dimensions": ["date", "country", "device"],+ "primary_key": ["date", "country", "device"],+ "should_sync_default": False,+ "description": (+ "Daily performance broken out by country and device together. Low cardinality "+ "(countries x three device types), so it stays well under the row sampling cap."+ ),+ },+ # `hour` is the only dimension Google serves outside the 16-month daily window: it+ # retains 10 days and requires `dataState: hourly_all`, which mixes complete and+ # partial rows. Because Google keeps restating those rows for a few days, every sync+ # refetches the whole 10-day window rather than resuming at the watermark.+ "search_analytics_by_hour": {+ "dimensions": ["hour"],+ "primary_key": ["date", "hour"],+ "should_sync_default": False,+ "description": (+ "Hourly totals for clicks, impressions, CTR, and average position. Google only "+ "keeps 10 days of hourly data, and the most recent hours are partial until they "+ "settle, so recent rows can change between syncs."+ ),+ "data_state": "hourly_all",+ "history_days": 10,+ "end_lag_days": 0,+ "ignore_incremental_watermark": True,+ },"search_analytics_by_query_page": {"dimensions": ["date", "query", "page"],"primary_key": ["date", "query", "page"],@@ -85,6 +123,43 @@ SEARCH_ANALYTICS_SCHEMAS: dict[str, SearchAnalyticsSchema] = {}+class PropertySchema(TypedDict):+ primary_key: list[str]+ should_sync_default: bool+ description: str | None+++# Property-level metadata, sourced from `sites.list` and `sitemaps.list`. Both are single+# unpaginated GETs returning tens of rows, with no timestamp filter to sync incrementally+# on, so they are full-refresh snapshots of the current state.+PROPERTY_SCHEMAS: dict[str, PropertySchema] = {+ "sites": {+ "primary_key": ["siteUrl"],+ "should_sync_default": True,+ "description": (+ "Every Search Console property the connected Google account can see, with the "+ "account's permission level on each one."+ ),+ },+ "sitemaps": {+ "primary_key": ["path"],+ "should_sync_default": True,+ "description": (+ "Sitemaps submitted for this property, with when Google last downloaded each one "+ "and how many errors and warnings it found."+ ),+ },+ "sitemap_contents": {+ "primary_key": ["path", "type"],+ "should_sync_default": True,+ "description": (+ "URL counts per content type (web, image, video, news) for each submitted sitemap. "+ "One row per sitemap and content type."+ ),+ },+}++SEARCH_ANALYTICS_INCREMENTAL_FIELD: IncrementalField = {"label": "date","field": "date",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/source.pyindex 3ef82ac3a788..244bab43a430 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/source.py@@ -16,6 +16,9 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.models.integration import Integrationfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (IntegrationAccount,IntegrationAccountListingError,@@ -37,6 +40,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_seasuggest_registered_site,)from products.warehouse_sources.backend.temporal.data_imports.sources.google_search_console.settings import (+ PROPERTY_SCHEMAS,SEARCH_ANALYTICS_INCREMENTAL_FIELD,SEARCH_ANALYTICS_SCHEMAS,)@@ -144,6 +148,18 @@ class GoogleSearchConsoleSource()for name, schema in SEARCH_ANALYTICS_SCHEMAS.items()]+ # Property metadata is a full snapshot each sync: both endpoints return the current+ # state with no timestamp to filter on, so there is nothing to sync incrementally.+ schemas += [+ SourceSchema(+ name=name,+ supports_incremental=False,+ supports_append=False,+ description=property_schema["description"],+ should_sync_default=property_schema["should_sync_default"],+ )+ for name, property_schema in PROPERTY_SCHEMAS.items()+ ]if names is not None:names_set = set(names)@@ -151,6 +167,13 @@ class GoogleSearchConsoleSource(return schemas+ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.google_search_console.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS+def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GoogleSearchConsoleResumeConfig]:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.pyindex 6dbc74379516..5b40741d69f1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py@@ -242,7 +242,7 @@ def test_source_yields_rows_and_advances_dates(monkeypatch):queries: list[tuple[str, int]] = []- def fake_query(session, site_url, start_date, end_date, dimensions, start_row, row_limit=25000):+ def fake_query(session, site_url, start_date, end_date, dimensions, start_row, row_limit=25000, data_state="final"):queries.append((start_date, start_row))pages = pages_per_date.get(start_date, [[]])return pages.pop(0) if pages else []@@ -282,7 +282,7 @@ def test_source_resumes_from_saved_state(monkeypatch):fake_today = dt.date(2026, 4, 30)queries: list[tuple[str, int]] = []- def fake_query(session, site_url, start_date, end_date, dimensions, start_row, row_limit=25000):+ def fake_query(session, site_url, start_date, end_date, dimensions, start_row, row_limit=25000, data_state="final"):queries.append((start_date, start_row))return []@@ -341,6 +341,244 @@ def test_source_response_has_partition_metadata():assert response.partition_size == 1+def test_hourly_schema_refetches_full_window_with_hourly_data_state(monkeypatch):+ # Hourly data is only retained for 10 days and Google keeps restating the most recent+ # hours, so the table must ignore the watermark and refetch the whole window each sync.+ # Resuming at the watermark would freeze partial rows at their first-imported values,+ # and reusing the daily window would fire ~16 months of pointless requests.+ config = GoogleSearchConsoleSourceConfig(+ site_url="https://example.com/",+ google_search_console_integration_id=1,+ )+ fake_today = dt.date(2026, 4, 30)+ calls: list[dict] = []++ def fake_query(**kwargs):+ calls.append(kwargs)+ return []++ monkeypatch.setattr(gsc, "_today", lambda: fake_today)+ monkeypatch.setattr(gsc, "google_search_console_session", lambda *a, **kw: mock.MagicMock())+ monkeypatch.setattr(gsc, "_query_search_analytics", fake_query)++ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ response = google_search_console_source(+ config=config,+ resource_name="search_analytics_by_hour",+ team_id=1,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=dt.date(2026, 4, 29),+ )+ list(response.items()) # type: ignore[arg-type]++ queried_dates = [call["start_date"] for call in calls]+ assert queried_dates[0] == "2026-04-20"+ assert queried_dates[-1] == "2026-04-30"+ assert {call["data_state"] for call in calls} == {"hourly_all"}+ assert {tuple(call["dimensions"]) for call in calls} == {("hour",)}+ assert response.primary_keys == ["date", "hour"]+++def test_daily_schemas_keep_final_data_state_and_freshness_lag(monkeypatch):+ config = GoogleSearchConsoleSourceConfig(+ site_url="https://example.com/",+ google_search_console_integration_id=1,+ )+ fake_today = dt.date(2026, 4, 30)+ calls: list[dict] = []++ def fake_query(**kwargs):+ calls.append(kwargs)+ return []++ monkeypatch.setattr(gsc, "_today", lambda: fake_today)+ monkeypatch.setattr(gsc, "google_search_console_session", lambda *a, **kw: mock.MagicMock())+ monkeypatch.setattr(gsc, "_query_search_analytics", fake_query)++ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ response = google_search_console_source(+ config=config,+ resource_name="search_analytics_by_country_device",+ team_id=1,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=dt.date(2026, 4, 25),+ )+ list(response.items()) # type: ignore[arg-type]++ assert [call["start_date"] for call in calls] == ["2026-04-25", "2026-04-26", "2026-04-27"]+ assert {call["data_state"] for call in calls} == {"final"}+ assert response.primary_keys == ["date", "country", "device"]+++def test_row_to_dict_parses_hour_dimension():+ # The hour dimension arrives as an ISO-8601 offset string; storing it raw would make the+ # column a string and break time filtering on the warehouse table.+ row = {"keys": ["2026-04-15T13:00:00-07:00"], "clicks": 2, "impressions": 9, "ctr": 0.2, "position": 1.5}+ out = _row_to_dict(row, ["hour"], iter_date=dt.date(2026, 4, 15))++ assert out["hour"] == dt.datetime(2026, 4, 15, 13, 0, tzinfo=dt.timezone(-dt.timedelta(hours=7)))+ assert out["date"] == dt.date(2026, 4, 15)+++def test_row_to_dict_tolerates_unparseable_hour():+ row = {"keys": ["not-a-timestamp"], "clicks": 0, "impressions": 0, "ctr": 0, "position": 0}+ out = _row_to_dict(row, ["hour"], iter_date=dt.date(2026, 4, 15))++ assert out["hour"] is None+++def test_sitemap_to_dict_fills_omitted_counters_and_flags():+ # Google omits zero counters and false flags entirely. Left missing, the first sync would+ # store the column with whatever type the first present value had (or not at all), so a+ # later sitemap with errors could not be merged in.+ out = gsc._sitemap_to_dict(+ {+ "path": "https://example.com/sitemap.xml",+ "type": "SITEMAP",+ "lastSubmitted": "2026-04-15T10:30:00.000Z",+ }+ )++ assert out["errors"] == 0+ assert out["warnings"] == 0+ assert out["isPending"] is False+ assert out["isSitemapsIndex"] is False+ assert out["lastSubmitted"] == dt.datetime(2026, 4, 15, 10, 30, tzinfo=dt.UTC)+ assert out["lastDownloaded"] is None+++def test_sitemap_to_dict_coerces_string_serialized_counters():+ # `errors` and `warnings` are int64 fields, which Google serializes as JSON strings.+ out = gsc._sitemap_to_dict({"path": "https://example.com/sitemap.xml", "errors": "3", "warnings": "12"})++ assert out["errors"] == 3+ assert out["warnings"] == 12+++def test_sitemap_content_rows_carry_parent_path():+ # `type` alone is not unique across sitemaps, so every content row must carry its parent+ # sitemap path — that pair is the table's primary key.+ rows = gsc._sitemap_content_rows(+ {+ "path": "https://example.com/sitemap.xml",+ "contents": [{"type": "WEB", "submitted": "120"}, {"type": "IMAGE"}],+ }+ )++ assert rows == [+ {"path": "https://example.com/sitemap.xml", "type": "WEB", "submitted": 120},+ {"path": "https://example.com/sitemap.xml", "type": "IMAGE", "submitted": 0},+ ]+++def test_sitemap_content_rows_for_sitemap_without_contents():+ assert gsc._sitemap_content_rows({"path": "https://example.com/sitemap.xml"}) == []+++ "resource_name,primary_keys",+ [+ ("sites", ["siteUrl"]),+ ("sitemaps", ["path"]),+ ("sitemap_contents", ["path", "type"]),+ ],+)+def test_property_source_response_is_unpartitioned_snapshot(resource_name, primary_keys):+ # These tables have no date column, so declaring the daily partitioning the search+ # analytics tables use would point the pipeline at a field that does not exist.+ config = GoogleSearchConsoleSourceConfig(+ site_url="https://example.com/",+ google_search_console_integration_id=1,+ )+ response = google_search_console_source(+ config=config,+ resource_name=resource_name,+ team_id=1,+ resumable_source_manager=mock.MagicMock(),+ )++ assert response.primary_keys == primary_keys+ assert response.partition_keys is None+ assert response.partition_mode is None+ assert response.sort_mode is None+++ "resource_name,expected",+ [+ (+ "sites",+ [{"siteUrl": "https://example.com/", "permissionLevel": "siteOwner"}],+ ),+ (+ "sitemap_contents",+ [{"path": "https://example.com/sitemap.xml", "type": "WEB", "submitted": 5}],+ ),+ ],+)+def test_property_source_yields_rows(monkeypatch, resource_name, expected):+ config = GoogleSearchConsoleSourceConfig(+ site_url="https://example.com/",+ google_search_console_integration_id=1,+ )+ monkeypatch.setattr(gsc, "google_search_console_session", lambda *a, **kw: mock.MagicMock())+ monkeypatch.setattr(+ gsc,+ "list_sites",+ lambda _session: [{"siteUrl": "https://example.com/", "permissionLevel": "siteOwner"}],+ )+ monkeypatch.setattr(+ gsc,+ "list_sitemaps",+ lambda _session, _site: [+ {"path": "https://example.com/sitemap.xml", "contents": [{"type": "WEB", "submitted": 5}]}+ ],+ )++ response = google_search_console_source(+ config=config,+ resource_name=resource_name,+ team_id=1,+ resumable_source_manager=mock.MagicMock(),+ )++ assert list(response.items()) == [expected] # type: ignore[arg-type]+++def test_property_source_yields_nothing_when_property_has_no_sitemaps(monkeypatch):+ config = GoogleSearchConsoleSourceConfig(+ site_url="https://example.com/",+ google_search_console_integration_id=1,+ )+ monkeypatch.setattr(gsc, "google_search_console_session", lambda *a, **kw: mock.MagicMock())+ monkeypatch.setattr(gsc, "list_sitemaps", lambda _session, _site: [])++ response = google_search_console_source(+ config=config,+ resource_name="sitemaps",+ team_id=1,+ resumable_source_manager=mock.MagicMock(),+ )++ assert list(response.items()) == [] # type: ignore[arg-type]+++def test_list_sitemaps_percent_encodes_the_property(monkeypatch):+ session = mock.MagicMock()+ session.get.return_value = _fake_response(200, {"sitemap": [{"path": "https://example.com/sitemap.xml"}]})++ sitemaps = gsc.list_sitemaps(session, "sc-domain:example.com")++ assert sitemaps == [{"path": "https://example.com/sitemap.xml"}]+ # The property is a path segment, so `sc-domain:` and any `/` in a URL-prefix property+ # must be escaped or Google resolves a different (or non-existent) route.+ session.get.assert_called_once_with(f"{gsc.GSC_API_BASE}/sites/sc-domain%3Aexample.com/sitemaps")++def test_unknown_resource_name_raises():config = GoogleSearchConsoleSourceConfig(site_url="https://example.com/",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console_source.pyindex 94d22d1d42a1..74c19374e92e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/tests/test_google_search_console_source.py@@ -10,6 +10,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_seaGoogleSearchConsoleResumeConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.google_search_console.settings import (+ PROPERTY_SCHEMAS,SEARCH_ANALYTICS_SCHEMAS,)from products.warehouse_sources.backend.temporal.data_imports.sources.google_search_console.source import (@@ -42,8 +43,10 @@ def test_get_source_config_fields():def test_get_schemas_returns_all_schemas_with_date_incremental():schemas = GoogleSearchConsoleSource().get_schemas(_config(), team_id=1)- assert {s.name for s in schemas} == set(SEARCH_ANALYTICS_SCHEMAS.keys())+ assert {s.name for s in schemas} == set(SEARCH_ANALYTICS_SCHEMAS.keys()) | set(PROPERTY_SCHEMAS.keys())for schema in schemas:+ if schema.name in PROPERTY_SCHEMAS:+ continueassert schema.supports_incremental is Trueassert schema.supports_append is Trueassert schema.incremental_fields == [@@ -56,10 +59,23 @@ def test_get_schemas_returns_all_schemas_with_date_incremental():]-def test_get_schemas_only_query_page_default():[email protected]("name", sorted(PROPERTY_SCHEMAS.keys()))+def test_property_schemas_are_not_incremental(name):+ # `sites.list` and `sitemaps.list` return the current state with no timestamp to filter on,+ # so offering incremental sync would checkpoint a watermark that can never advance.+ schema = next(s for s in GoogleSearchConsoleSource().get_schemas(_config(), team_id=1) if s.name == name)++ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []+++def test_get_schemas_default_on_tables():schemas = GoogleSearchConsoleSource().get_schemas(_config(), team_id=1)by_default_on = {s.name for s in schemas if s.should_sync_default}- assert by_default_on == {"search_analytics_by_query_page"}+ # Search analytics tables are opt-in apart from the most useful one; the property metadata+ # tables are one cheap request each per sync, so they stay on.+ assert by_default_on == {"search_analytics_by_query_page", *PROPERTY_SCHEMAS.keys()}def test_search_appearance_schema_uses_solo_dimension_with_date_in_pk():@@ -79,6 +95,15 @@ def test_get_schemas_filters_by_names():assert {s.name for s in schemas} == {"search_analytics_by_date", "search_analytics_by_query"}+def test_canonical_descriptions_cover_every_schema():+ # A table shipped without a canonical entry silently falls back to LLM-generated+ # descriptions, which is what the curated file exists to avoid.+ source = GoogleSearchConsoleSource()+ names = {s.name for s in source.get_schemas(_config(), team_id=1)}++ assert names <= set(source.get_canonical_descriptions().keys())++def test_get_resumable_source_manager_uses_resume_config():inputs = mock.MagicMock()manager = GoogleSearchConsoleSource().get_resumable_source_manager(inputs)