: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): implement google analytics import source (#63233)
Tom Owers94dab1720106
diff --git a/frontend/src/lib/integrations/utils.ts b/frontend/src/lib/integrations/utils.tsindex bef963ffb529..55923c2eb04e 100644--- a/frontend/src/lib/integrations/utils.ts+++ b/frontend/src/lib/integrations/utils.ts@@ -15,6 +15,7 @@ import IconGoogleCloudStorage from 'public/services/google-cloud-storage.png'import IconGoogleCloud from 'public/services/google-cloud.png'import IconGoogleSearchConsole from 'public/services/google-search-console.svg'import IconGoogleSheets from 'public/services/google-sheets.svg'+import IconGoogleAnalytics from 'public/services/google_analytics.png'import IconHubspot from 'public/services/hubspot.png'import IconIntercom from 'public/services/intercom.png'import IconJira from 'public/services/jira.svg'@@ -40,6 +41,7 @@ export const ICONS: Record<IntegrationKind, any> = {'google-cloud-storage': IconGoogleCloudStorage,'google-cloud-service-account': IconGoogleCloud,'google-ads': IconGoogleAds,+ 'google-analytics': IconGoogleAnalytics,'google-search-console': IconGoogleSearchConsole,'google-sheets': IconGoogleSheets,snapchat: IconSnapchat,@@ -75,6 +77,8 @@ export const getIntegrationNameFromKind = (kind: string): string => {return 'Google Cloud Storage'case 'google-ads':return 'Google Ads'+ case 'google-analytics':+ return 'Google Analytics'case 'google-search-console':return 'Google Search Console'case 'google-cloud-service-account':diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex e9446a002017..a5ed670a5650 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -24123,6 +24123,7 @@"google-cloud-service-account","google-cloud-storage","google-ads",+ "google-analytics","google-search-console","google-sheets","linkedin-ads",diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 4d5a9637884d..f3a962a18cea 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5240,6 +5240,7 @@ export const INTEGRATION_KINDS = ['google-cloud-service-account','google-cloud-storage','google-ads',+ 'google-analytics','google-search-console','google-sheets','linkedin-ads',diff --git a/posthog/migrations/1222_alter_integration_kind_google_analytics.py b/posthog/migrations/1222_alter_integration_kind_google_analytics.pynew file mode 100644index 000000000000..bea530bfc64c--- /dev/null+++ b/posthog/migrations/1222_alter_integration_kind_google_analytics.py@@ -0,0 +1,58 @@+# Generated by Django 5.2.14 on 2026-06-12 11:44++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1221_oauthaccesstoken_scope_trgm"),+ ]++ operations = [+ migrations.AlterField(+ model_name="integration",+ name="kind",+ field=models.CharField(+ choices=[+ ("anthropic", "Anthropic"),+ ("apns", "Apple Push"),+ ("azure-blob", "Azure Blob"),+ ("bing-ads", "Bing Ads"),+ ("clickup", "Clickup"),+ ("customerio-app", "Customerio App"),+ ("customerio-track", "Customerio Track"),+ ("customerio-webhook", "Customerio Webhook"),+ ("databricks", "Databricks"),+ ("email", "Email"),+ ("firebase", "Firebase"),+ ("github", "Github"),+ ("gitlab", "Gitlab"),+ ("google-ads", "Google Ads"),+ ("google-analytics", "Google Analytics"),+ ("google-cloud-service-account", "Google Cloud Service Account"),+ ("google-cloud-storage", "Google Cloud Storage"),+ ("google-pubsub", "Google Pubsub"),+ ("google-search-console", "Google Search Console"),+ ("google-sheets", "Google Sheets"),+ ("hubspot", "Hubspot"),+ ("intercom", "Intercom"),+ ("jira", "Jira"),+ ("linear", "Linear"),+ ("linkedin-ads", "Linkedin Ads"),+ ("meta-ads", "Meta Ads"),+ ("pinterest-ads", "Pinterest Ads"),+ ("postgresql", "Postgresql"),+ ("reddit-ads", "Reddit Ads"),+ ("salesforce", "Salesforce"),+ ("slack", "Slack"),+ ("slack-posthog-code", "Slack Posthog Code"),+ ("snapchat", "Snapchat"),+ ("stripe", "Stripe"),+ ("tiktok-ads", "Tiktok Ads"),+ ("twilio", "Twilio"),+ ("vercel", "Vercel"),+ ],+ max_length=32,+ ),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex d4feacee9cfa..e78e55ae4293 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1221_oauthaccesstoken_scope_trgm+1222_alter_integration_kind_google_analyticsdiff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 9c94ef4206d1..6be8387f9a16 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -162,6 +162,7 @@ class Integration(models.Model):GITHUB = "github"GITLAB = "gitlab"GOOGLE_ADS = "google-ads"+ GOOGLE_ANALYTICS = "google-analytics"GOOGLE_CLOUD_SERVICE_ACCOUNT = "google-cloud-service-account"GOOGLE_CLOUD_STORAGE = "google-cloud-storage"GOOGLE_PUBSUB = "google-pubsub"@@ -297,6 +298,7 @@ class OauthIntegration:"salesforce","hubspot","google-ads",+ "google-analytics","google-search-console","google-sheets","snapchat",@@ -406,6 +408,23 @@ class OauthIntegration:id_path="sub",name_path="email",)+ elif kind == "google-analytics":+ if not settings.GOOGLE_ANALYTICS_APP_CLIENT_ID or not settings.GOOGLE_ANALYTICS_APP_CLIENT_SECRET:+ raise NotImplementedError("Google Analytics app not configured")++ return OauthConfig(+ authorize_url="https://accounts.google.com/o/oauth2/v2/auth",+ # forces the consent screen, otherwise we won't receive a refresh token+ additional_authorize_params={"access_type": "offline", "prompt": "consent"},+ token_info_url="https://openidconnect.googleapis.com/v1/userinfo",+ token_info_config_fields=["sub", "email"],+ token_url="https://oauth2.googleapis.com/token",+ client_id=settings.GOOGLE_ANALYTICS_APP_CLIENT_ID,+ client_secret=settings.GOOGLE_ANALYTICS_APP_CLIENT_SECRET,+ scope="https://www.googleapis.com/auth/analytics.readonly https://www.googleapis.com/auth/userinfo.email",+ id_path="sub",+ name_path="email",+ )elif kind == "google-search-console":if not settings.GOOGLE_SEARCH_CONSOLE_APP_CLIENT_ID or not settings.GOOGLE_SEARCH_CONSOLE_APP_CLIENT_SECRET:raise NotImplementedError("Google Search Console app not configured")diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 710d1a3848a3..278e5611a4aa 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -1716,6 +1716,7 @@ class IntegrationKind(StrEnum):GOOGLE_CLOUD_SERVICE_ACCOUNT = "google-cloud-service-account"GOOGLE_CLOUD_STORAGE = "google-cloud-storage"GOOGLE_ADS = "google-ads"+ GOOGLE_ANALYTICS = "google-analytics"GOOGLE_SEARCH_CONSOLE = "google-search-console"GOOGLE_SHEETS = "google-sheets"LINKEDIN_ADS = "linkedin-ads"diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.pyindex 75f4f2bfe6d3..94fe501b8a93 100644--- a/posthog/settings/integrations.py+++ b/posthog/settings/integrations.py@@ -22,6 +22,9 @@ GOOGLE_ADS_DEVELOPER_TOKEN = get_from_env("GOOGLE_ADS_DEVELOPER_TOKEN", "")GOOGLE_SEARCH_CONSOLE_APP_CLIENT_ID = get_from_env("GOOGLE_SEARCH_CONSOLE_APP_CLIENT_ID", "")GOOGLE_SEARCH_CONSOLE_APP_CLIENT_SECRET = get_from_env("GOOGLE_SEARCH_CONSOLE_APP_CLIENT_SECRET", "")+GOOGLE_ANALYTICS_APP_CLIENT_ID = get_from_env("GOOGLE_ANALYTICS_APP_CLIENT_ID", "")+GOOGLE_ANALYTICS_APP_CLIENT_SECRET = get_from_env("GOOGLE_ANALYTICS_APP_CLIENT_SECRET", "")+SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = get_from_env("SOCIAL_AUTH_GOOGLE_OAUTH2_KEY", "")SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = get_from_env("SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET", "")diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 01b849e48ad4..a63631b941e8 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -104,6 +104,7 @@ the row lists both.| gocardless | HTTP | requests | ✅ || gong | HTTP | requests | ✅ || google_ads | gRPC | google-ads (googleads.client) | ✅ |+| google_analytics | HTTP | requests (`AuthorizedSession` + `TrackedHTTPAdapter`) | ✅ || google_sheets | HTTP (vendor SDK) | gspread | ✅ || granola | HTTP | requests | ✅ || gorgias | HTTP | requests | ✅ |@@ -267,7 +268,6 @@ doesn't conflict with concurrent PRs.- firebase- freshbooks- google_ad_manager-- google_analytics- google_cloud_storage- google_drive- gustodiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex b607ac4320d2..517806abaa9c 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -679,7 +679,8 @@ class GoogleAdsSourceConfig(config.Config):@config.configclass GoogleAnalyticsSourceConfig(config.Config):- pass+ property_id: str+ google_analytics_integration_id: int = config.value(converter=config.str_to_int)@config.configdiff --git a/posthog/temporal/data_imports/sources/google_analytics/google_analytics.py b/posthog/temporal/data_imports/sources/google_analytics/google_analytics.pynew file mode 100644index 000000000000..f472d2fbc662--- /dev/null+++ b/posthog/temporal/data_imports/sources/google_analytics/google_analytics.py@@ -0,0 +1,331 @@+import time+import datetime as dt+import dataclasses+import collections.abc+from typing import Any++from django.conf import settings+from django.db import close_old_connections++import requests+import structlog+from google.auth.transport.requests import AuthorizedSession+from google.oauth2.credentials import Credentials as OAuthCredentials++from posthog.models.integration import Integration+from posthog.temporal.data_imports.naming_convention import NamingConvention+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_adapter+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import GoogleAnalyticsSourceConfig+from posthog.temporal.data_imports.sources.google_analytics.settings import GOOGLE_ANALYTICS_REPORT_SCHEMAS++logger = structlog.get_logger(__name__)++GA4_API_BASE = "https://analyticsdata.googleapis.com/v1beta"++# GA4 standard properties retain aggregate report data well beyond event-level+# retention, so a 2-year initial backfill is safe and matches what other GA4+# connectors default to.+HISTORY_DAYS = 730++# GA4 can re-state a day's aggregates for up to ~48h after the day ends+# (processing latency), so incremental syncs re-fetch a small window before the+# last synced date and merge-mode dedupe replaces the stale rows.+LOOKBACK_DAYS = 2++# Each runReport call covers one date-range chunk; offset pagination walks rows+# within the chunk. Chunking bounds response payloads and gives resume points,+# while staying far cheaper on Data API quota tokens than day-by-day requests.+CHUNK_DAYS = 30+PAGE_LIMIT = 50000 # runReport allows up to 250k rows/request; keep payloads modest++# The Data API reports quota exhaustion (property tokens, concurrent requests)+# as HTTP 429 RESOURCE_EXHAUSTED. These are transient — back off and retry+# inline, then fall back to a Temporal activity retry via the resumable state.+QUOTA_MAX_RETRIES = 5+QUOTA_BACKOFF_BASE_SECONDS = 5.0++_INTEGER_METRIC_TYPES = frozenset({"TYPE_INTEGER"})+++class GoogleAnalyticsQuotaExceededError(Exception):+ """Raised when Data API quota stays exhausted after in-line retries.++ Deliberately NOT matched by `get_non_retryable_errors` so Temporal retries+ the activity later (the resumable source picks up from the last saved+ chunk), which is the right recovery for hourly/daily property token quotas.+ """+++class GoogleAnalyticsResumeConfig:+ chunk_start: str # ISO date of the chunk currently being fetched+ offset: int # next row offset within that chunk+++def _credentials(integration_id: int, team_id: int) -> OAuthCredentials:+ # Invoked lazily from inside `get_rows` on a worker thread, so the pooled+ # Django connection has often been idle long enough for Postgres to close it+ # server-side — drop any stale connection before the ORM read.+ close_old_connections()+ integration = Integration.objects.get(id=integration_id, team_id=team_id)+ return OAuthCredentials(+ token=None,+ refresh_token=integration.refresh_token,+ client_id=settings.GOOGLE_ANALYTICS_APP_CLIENT_ID,+ client_secret=settings.GOOGLE_ANALYTICS_APP_CLIENT_SECRET,+ token_uri="https://oauth2.googleapis.com/token",+ scopes=["https://www.googleapis.com/auth/analytics.readonly"],+ )+++def google_analytics_session(integration_id: int, team_id: int) -> AuthorizedSession:+ creds = _credentials(integration_id, team_id)+ session = AuthorizedSession(creds)+ adapter = make_tracked_adapter()+ session.mount("https://", adapter)+ session.mount("http://", adapter)+ return session+++def normalize_property_id(property_id: str) -> str:+ """Accept both a bare numeric ID and the `properties/123` resource name users may paste."""+ cleaned = property_id.strip()+ if cleaned.startswith("properties/"):+ cleaned = cleaned[len("properties/") :]+ return cleaned+++def get_property_metadata(session: AuthorizedSession, property_id: str) -> dict[str, Any]:+ """Fetch the property's dimension/metric metadata — the cheapest call that proves read access."""+ pid = normalize_property_id(property_id)+ response = session.get(f"{GA4_API_BASE}/properties/{pid}/metadata")+ response.raise_for_status()+ return response.json()+++def _is_quota_error(response: requests.Response) -> bool:+ """The Data API reports quota exhaustion as 429 RESOURCE_EXHAUSTED — unlike+ older Google APIs it does not overload 403 for rate limits."""+ return response.status_code == 429+++def _quota_backoff_seconds(response: requests.Response, attempt: int) -> float:+ """Seconds to wait before retrying a quota error: honor `Retry-After`, else exponential."""+ retry_after = response.headers.get("Retry-After")+ if retry_after is not None:+ try:+ return float(retry_after)+ except ValueError:+ pass+ return QUOTA_BACKOFF_BASE_SECONDS * (2**attempt)+++def _run_report(+ session: AuthorizedSession,+ property_id: str,+ start_date: str,+ end_date: str,+ dimensions: list[str],+ metrics: list[str],+ offset: int,+ limit: int = PAGE_LIMIT,+) -> dict[str, Any]:+ pid = normalize_property_id(property_id)+ body = {+ "dateRanges": [{"startDate": start_date, "endDate": end_date}],+ "dimensions": [{"name": dim} for dim in dimensions],+ "metrics": [{"name": metric} for metric in metrics],+ # Ascending date order keeps the pipeline's incremental watermark moving forward.+ "orderBys": [{"dimension": {"dimensionName": "date"}}],+ "limit": limit,+ "offset": offset,+ }+ url = f"{GA4_API_BASE}/properties/{pid}:runReport"++ for attempt in range(QUOTA_MAX_RETRIES + 1):+ response = session.post(url, json=body)+ if response.ok:+ return response.json()++ # Surface Google's real reason — raise_for_status() discards the body where it lives.+ logger.warning(+ "GA4 runReport failed",+ property_id=pid,+ status_code=response.status_code,+ body=response.text,+ )++ if not _is_quota_error(response):+ # Permission / bad-request errors are fatal — let the HTTPError bubble up so+ # `get_non_retryable_errors` can match "403 Client Error" / "401 Client Error".+ response.raise_for_status()++ if attempt == QUOTA_MAX_RETRIES:+ raise GoogleAnalyticsQuotaExceededError(+ f"Data API quota for property '{pid}' still exhausted after {QUOTA_MAX_RETRIES} retries"+ )++ wait = _quota_backoff_seconds(response, attempt)+ logger.warning("GA4 quota exceeded, backing off", property_id=pid, attempt=attempt, wait_seconds=wait)+ time.sleep(wait)++ # Unreachable: the loop either returns, raises for status, or raises the quota error.+ raise AssertionError("unreachable")+++def _parse_ga4_date(value: str) -> dt.date | str:+ """GA4 returns the `date` dimension as YYYYMMDD."""+ try:+ return dt.datetime.strptime(value, "%Y%m%d").date()+ except ValueError:+ return value+++def _convert_metric_value(value: str, metric_type: str) -> Any:+ try:+ if metric_type in _INTEGER_METRIC_TYPES:+ return int(value)+ return float(value)+ except (TypeError, ValueError):+ return value+++def _rows_to_dicts(payload: dict[str, Any]) -> list[dict[str, Any]]:+ """Flatten runReport's header/value arrays into per-row dicts with typed values."""+ dimension_names = [header["name"] for header in payload.get("dimensionHeaders", [])]+ metric_headers = payload.get("metricHeaders", [])++ out: list[dict[str, Any]] = []+ for row in payload.get("rows", []):+ record: dict[str, Any] = {}+ for name, dim_value in zip(dimension_names, row.get("dimensionValues", [])):+ value = dim_value["value"]+ record[name] = _parse_ga4_date(value) if name == "date" else value+ for header, metric_value in zip(metric_headers, row.get("metricValues", [])):+ record[header["name"]] = _convert_metric_value(metric_value["value"], header.get("type", ""))+ out.append(record)+ return out+++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 _resolve_window(today: dt.date, db_incremental_field_last_value: Any) -> tuple[dt.date, dt.date]:+ # End at yesterday: today's aggregates are still accruing and would land as+ # permanently stale rows for schemas whose primary key is just `date`.+ end_date = today - dt.timedelta(days=1)+ if db_incremental_field_last_value is None:+ return _initial_start_date(today), end_date++ if isinstance(db_incremental_field_last_value, dt.datetime):+ last = db_incremental_field_last_value.date()+ elif isinstance(db_incremental_field_last_value, dt.date):+ last = db_incremental_field_last_value+ else:+ last = dt.date.fromisoformat(str(db_incremental_field_last_value)[:10])++ start = max(last - dt.timedelta(days=LOOKBACK_DAYS), _initial_start_date(today))+ return start, end_date+++def _iter_chunks(start: dt.date, end: dt.date) -> collections.abc.Iterator[tuple[dt.date, dt.date]]:+ current = start+ while current <= end:+ chunk_end = min(current + dt.timedelta(days=CHUNK_DAYS - 1), end)+ yield current, chunk_end+ current = chunk_end + dt.timedelta(days=1)+++def google_analytics_source(+ config: GoogleAnalyticsSourceConfig,+ resource_name: str,+ team_id: int,+ resumable_source_manager: ResumableSourceManager[GoogleAnalyticsResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> SourceResponse:+ if resource_name not in GOOGLE_ANALYTICS_REPORT_SCHEMAS:+ raise ValueError(f"Unknown Google Analytics schema: {resource_name}")++ schema = GOOGLE_ANALYTICS_REPORT_SCHEMAS[resource_name]+ dimensions = schema["dimensions"]+ metrics = schema["metrics"]+ primary_keys = list(schema["primary_key"])++ name = NamingConvention.normalize_identifier(resource_name)++ def get_rows() -> collections.abc.Iterator[list[dict[str, Any]]]:+ today = _today()+ start_date, end_date = _resolve_window(+ today,+ db_incremental_field_last_value if should_use_incremental_field else None,+ )++ resume_chunk_start: str | None = None+ resume_offset = 0+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ resume_chunk_start = resume.chunk_start+ resume_offset = resume.offset+ # Re-chunk from the saved chunk start so chunk boundaries always line+ # up with the saved offset, even if the incremental window start moved+ # between attempts. If the saved date is past end_date, no chunks run.+ start_date = max(start_date, dt.date.fromisoformat(resume_chunk_start))++ session = google_analytics_session(config.google_analytics_integration_id, team_id)++ for chunk_start, chunk_end in _iter_chunks(start_date, end_date):+ chunk_start_iso = chunk_start.isoformat()+ # The saved offset only applies to the exact chunk it was saved for.+ offset = resume_offset if chunk_start_iso == resume_chunk_start else 0++ while True:+ payload = _run_report(+ session=session,+ property_id=config.property_id,+ start_date=chunk_start_iso,+ end_date=chunk_end.isoformat(),+ dimensions=dimensions,+ metrics=metrics,+ offset=offset,+ )+ rows = _rows_to_dicts(payload)+ if not rows:+ break++ yield rows++ next_offset = offset + len(rows)+ row_count = payload.get("rowCount", 0)+ if next_offset >= row_count:+ # Chunk exhausted — persist the next chunk's starting state so a+ # restart picks up there with offset=0.+ next_chunk_iso = (chunk_end + dt.timedelta(days=1)).isoformat()+ resumable_source_manager.save_state(+ GoogleAnalyticsResumeConfig(chunk_start=next_chunk_iso, offset=0)+ )+ break++ resumable_source_manager.save_state(+ GoogleAnalyticsResumeConfig(chunk_start=chunk_start_iso, offset=next_offset)+ )+ offset = next_offset++ return SourceResponse(+ name=name,+ items=get_rows,+ primary_keys=primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=["date"],+ )diff --git a/posthog/temporal/data_imports/sources/google_analytics/settings.py b/posthog/temporal/data_imports/sources/google_analytics/settings.pynew file mode 100644index 000000000000..f1f9686ff6fa--- /dev/null+++ b/posthog/temporal/data_imports/sources/google_analytics/settings.py@@ -0,0 +1,139 @@+from typing import TypedDict++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++class GoogleAnalyticsReportSchema(TypedDict):+ dimensions: list[str]+ metrics: list[str]+ primary_key: list[str]+ should_sync_default: bool+ description: str | None+++# Each schema maps to a single GA4 Data API `runReport` request with a fixed+# dimension + metric set, mirroring the standard reports in the GA4 UI (and the+# default streams of other GA4 connectors). Every schema includes the `date`+# dimension so rows are day-grained, the primary key (date + dimensions) is+# stable for merge-mode dedupe, and incremental syncs can resume from the last+# synced date.+#+# Note on aggregation: GA4 reports are aggregates, not raw events. A metric+# value for (date, dimension-set) can be re-stated by Google for up to ~48+# hours after the day ends (processing latency), which is why the iterator+# re-fetches a small lookback window on incremental syncs.+GOOGLE_ANALYTICS_REPORT_SCHEMAS: dict[str, GoogleAnalyticsReportSchema] = {+ "website_overview": {+ "dimensions": ["date"],+ "metrics": [+ "totalUsers",+ "newUsers",+ "sessions",+ "sessionsPerUser",+ "screenPageViews",+ "averageSessionDuration",+ "bounceRate",+ ],+ "primary_key": ["date"],+ "should_sync_default": True,+ "description": "Daily totals for users, sessions, page views, session duration, and bounce rate.",+ },+ "daily_active_users": {+ "dimensions": ["date"],+ "metrics": ["active1DayUsers"],+ "primary_key": ["date"],+ "should_sync_default": False,+ "description": "1-day active users per day (DAU).",+ },+ "weekly_active_users": {+ "dimensions": ["date"],+ "metrics": ["active7DayUsers"],+ "primary_key": ["date"],+ "should_sync_default": False,+ "description": "Rolling 7-day active users per day (WAU).",+ },+ "four_weekly_active_users": {+ "dimensions": ["date"],+ "metrics": ["active28DayUsers"],+ "primary_key": ["date"],+ "should_sync_default": False,+ "description": "Rolling 28-day active users per day.",+ },+ "devices": {+ "dimensions": ["date", "deviceCategory", "operatingSystem", "browser"],+ "metrics": [+ "totalUsers",+ "newUsers",+ "sessions",+ "screenPageViews",+ "averageSessionDuration",+ "bounceRate",+ ],+ "primary_key": ["date", "deviceCategory", "operatingSystem", "browser"],+ "should_sync_default": True,+ "description": "Daily usage broken out by device category, operating system, and browser.",+ },+ "locations": {+ "dimensions": ["date", "country", "region", "city"],+ "metrics": [+ "totalUsers",+ "newUsers",+ "sessions",+ "screenPageViews",+ "averageSessionDuration",+ "bounceRate",+ ],+ "primary_key": ["date", "country", "region", "city"],+ "should_sync_default": True,+ "description": "Daily usage broken out by country, region, and city.",+ },+ "pages": {+ "dimensions": ["date", "hostName", "pagePathPlusQueryString"],+ "metrics": [+ "screenPageViews",+ "sessions",+ "totalUsers",+ "averageSessionDuration",+ "bounceRate",+ ],+ "primary_key": ["date", "hostName", "pagePathPlusQueryString"],+ "should_sync_default": True,+ "description": "Daily page performance broken out by host name and page path (including query string).",+ },+ "traffic_sources": {+ "dimensions": ["date", "sessionSource", "sessionMedium"],+ "metrics": [+ "totalUsers",+ "newUsers",+ "sessions",+ "screenPageViews",+ "averageSessionDuration",+ "bounceRate",+ ],+ "primary_key": ["date", "sessionSource", "sessionMedium"],+ "should_sync_default": True,+ "description": "Daily traffic broken out by session source and medium.",+ },+ "user_acquisition": {+ "dimensions": ["date", "firstUserSource", "firstUserMedium"],+ "metrics": ["totalUsers", "newUsers", "sessions", "engagedSessions"],+ "primary_key": ["date", "firstUserSource", "firstUserMedium"],+ "should_sync_default": False,+ "description": "Daily acquisition broken out by the source and medium that first acquired each user.",+ },+ "events": {+ "dimensions": ["date", "eventName"],+ "metrics": ["eventCount", "totalUsers", "eventCountPerUser"],+ "primary_key": ["date", "eventName"],+ "should_sync_default": False,+ "description": "Daily event counts broken out by event name.",+ },+}+++GOOGLE_ANALYTICS_INCREMENTAL_FIELD: IncrementalField = {+ "label": "date",+ "field": "date",+ "type": IncrementalFieldType.Date,+ "field_type": IncrementalFieldType.Date,+}diff --git a/posthog/temporal/data_imports/sources/google_analytics/source.py b/posthog/temporal/data_imports/sources/google_analytics/source.pyindex 84a0db85fae5..37381ccc36d9 100644--- a/posthog/temporal/data_imports/sources/google_analytics/source.py+++ b/posthog/temporal/data_imports/sources/google_analytics/source.py@@ -1,24 +1,139 @@-from typing import cast+from typing import Optional, cast++import requestsfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldOauthConfig,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from posthog.temporal.data_imports.sources.common.mixins import OAuthMixinfrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import GoogleAnalyticsSourceConfig+from posthog.temporal.data_imports.sources.google_analytics.google_analytics import (+ GoogleAnalyticsResumeConfig,+ get_property_metadata,+ google_analytics_session,+ google_analytics_source,+ normalize_property_id,+)+from posthog.temporal.data_imports.sources.google_analytics.settings import (+ GOOGLE_ANALYTICS_INCREMENTAL_FIELD,+ GOOGLE_ANALYTICS_REPORT_SCHEMAS,+)from products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class GoogleAnalyticsSource(SimpleSource[GoogleAnalyticsSourceConfig]):+class GoogleAnalyticsSource(ResumableSource[GoogleAnalyticsSourceConfig, GoogleAnalyticsResumeConfig], OAuthMixin):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.GOOGLEANALYTICS+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your Google Analytics connection is invalid or expired. Please reconnect your account.",+ "403 Client Error": "PostHog is not authorized to read this Google Analytics property. Please make sure the connected Google account has access to the property.",+ "ACCESS_TOKEN_SCOPE_INSUFFICIENT": "Insufficient permissions. Please reconnect your Google Analytics account with the required scopes.",+ }++ def get_schemas(+ self,+ config: GoogleAnalyticsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=name,+ supports_incremental=True,+ supports_append=True,+ incremental_fields=[GOOGLE_ANALYTICS_INCREMENTAL_FIELD],+ description=schema["description"],+ should_sync_default=schema["should_sync_default"],+ )+ for name, schema in GOOGLE_ANALYTICS_REPORT_SCHEMAS.items()+ ]++ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]++ return schemas++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GoogleAnalyticsResumeConfig]:+ return ResumableSourceManager[GoogleAnalyticsResumeConfig](inputs, GoogleAnalyticsResumeConfig)++ def source_for_pipeline(+ self,+ config: GoogleAnalyticsSourceConfig,+ resumable_source_manager: ResumableSourceManager[GoogleAnalyticsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return google_analytics_source(+ config=config,+ resource_name=inputs.schema_name,+ team_id=inputs.team_id,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ )++ def validate_credentials(+ self,+ config: GoogleAnalyticsSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ ) -> tuple[bool, str | None]:+ property_id = normalize_property_id(config.property_id)+ if not property_id.isdigit():+ return (+ False,+ f"'{config.property_id}' is not a valid GA4 property ID. Use the numeric ID from "+ "Google Analytics admin settings (e.g. '123456789' or 'properties/123456789').",+ )++ try:+ session = google_analytics_session(config.google_analytics_integration_id, team_id)+ except Exception as e:+ return False, f"Could not load Google Analytics credentials: {e}"++ try:+ get_property_metadata(session, property_id)+ except requests.HTTPError as e:+ status = e.response.status_code if e.response is not None else None+ if status in (401, 403):+ return (+ False,+ f"Google Analytics rejected the credentials for property '{property_id}'. Please reconnect "+ "your account and ensure it has read access to the property.",+ )+ if status == 404:+ return (+ False,+ f"GA4 property '{property_id}' was not found. Verify the numeric property ID in "+ "Google Analytics admin settings.",+ )+ return False, f"Failed to read Google Analytics property metadata: {e}"+ except Exception as e:+ return False, f"Failed to read Google Analytics property metadata: {e}"++ return True, None+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(@@ -26,7 +141,37 @@ class GoogleAnalyticsSource(SimpleSource[GoogleAnalyticsSourceConfig]):category=DataWarehouseSourceCategory.ANALYTICS,keywords=["ga4", "ga"],label="Google Analytics",+ caption=(+ "Connect a Google Analytics 4 property to sync daily report data (users, sessions, page views, "+ "devices, locations, traffic sources, and events). Requires a Google account with read access "+ "to the GA4 property."+ ),+ releaseStatus=ReleaseStatus.ALPHA,+ featureFlag="dwh-google-analytics",iconPath="/static/services/google_analytics.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/google-analytics",+ fields=cast(+ list[FieldType],+ [+ SourceFieldOauthConfig(+ name="google_analytics_integration_id",+ label="Google Analytics account",+ required=True,+ kind="google-analytics",+ requiredScopes="https://www.googleapis.com/auth/analytics.readonly",+ ),+ SourceFieldInputConfig(+ name="property_id",+ label="Property ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="123456789",+ caption=(+ "The numeric GA4 property ID, found in Google Analytics under "+ "Admin → Property settings → Property details."+ ),+ secret=False,+ ),+ ],+ ),)diff --git a/posthog/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py b/posthog/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.pynew file mode 100644index 000000000000..cf533f8de1d0--- /dev/null+++ b/posthog/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py@@ -0,0 +1,527 @@+import datetime as dt+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest import mock++import requests++from posthog.temporal.data_imports.sources.generated_configs import GoogleAnalyticsSourceConfig+from posthog.temporal.data_imports.sources.google_analytics import google_analytics as ga+from posthog.temporal.data_imports.sources.google_analytics.google_analytics import (+ CHUNK_DAYS,+ HISTORY_DAYS,+ LOOKBACK_DAYS,+ QUOTA_MAX_RETRIES,+ GoogleAnalyticsQuotaExceededError,+ GoogleAnalyticsResumeConfig,+ _convert_metric_value,+ _credentials,+ _initial_start_date,+ _is_quota_error,+ _iter_chunks,+ _parse_ga4_date,+ _quota_backoff_seconds,+ _resolve_window,+ _rows_to_dicts,+ _run_report,+ google_analytics_source,+ normalize_property_id,+)++TODAY = dt.date(2026, 4, 30)+++ "raw,expected",+ [+ ("123456789", "123456789"),+ (" 123456789 ", "123456789"),+ ("properties/123456789", "123456789"),+ ("properties/123456789 ", "123456789"),+ ],+)+def test_normalize_property_id(raw, expected):+ assert normalize_property_id(raw) == expected+++ "last_value,expected_start",+ [+ # No last value → full history window from today backwards.+ (None, _initial_start_date(TODAY)),+ # Very old last value → clamped to the history floor.+ (TODAY - dt.timedelta(days=10_000), _initial_start_date(TODAY)),+ # Recent date → re-fetch from the lookback window before it.+ (TODAY - dt.timedelta(days=10), TODAY - dt.timedelta(days=10 + LOOKBACK_DAYS)),+ # ISO string is accepted and parsed.+ ("2026-04-15", dt.date(2026, 4, 15) - dt.timedelta(days=LOOKBACK_DAYS)),+ # Datetime is accepted and truncated to its date.+ (dt.datetime(2026, 4, 15, 12, 0, 0), dt.date(2026, 4, 15) - dt.timedelta(days=LOOKBACK_DAYS)),+ ],+)+def test_resolve_window_start(last_value, expected_start):+ start, end = _resolve_window(TODAY, last_value)+ assert start == expected_start+ # Today's aggregates are still accruing — the window always ends at yesterday.+ assert end == TODAY - dt.timedelta(days=1)+++def test_resolve_window_full_history_spans_history_days():+ start, _ = _resolve_window(TODAY, None)+ assert (TODAY - start).days == HISTORY_DAYS+++ "start,end,expected",+ [+ # Range smaller than one chunk → single chunk clamped to end.+ (dt.date(2026, 4, 1), dt.date(2026, 4, 3), [(dt.date(2026, 4, 1), dt.date(2026, 4, 3))]),+ # Exactly one chunk.+ (+ dt.date(2026, 4, 1),+ dt.date(2026, 4, 1) + dt.timedelta(days=CHUNK_DAYS - 1),+ [(dt.date(2026, 4, 1), dt.date(2026, 4, 1) + dt.timedelta(days=CHUNK_DAYS - 1))],+ ),+ # Spills into a second chunk.+ (+ dt.date(2026, 4, 1),+ dt.date(2026, 4, 1) + dt.timedelta(days=CHUNK_DAYS),+ [+ (dt.date(2026, 4, 1), dt.date(2026, 4, 1) + dt.timedelta(days=CHUNK_DAYS - 1)),+ (+ dt.date(2026, 4, 1) + dt.timedelta(days=CHUNK_DAYS),+ dt.date(2026, 4, 1) + dt.timedelta(days=CHUNK_DAYS),+ ),+ ],+ ),+ # start > end yields no chunks.+ (dt.date(2026, 4, 5), dt.date(2026, 4, 1), []),+ ],+)+def test_iter_chunks(start, end, expected):+ assert list(_iter_chunks(start, end)) == expected+++def test_iter_chunks_are_contiguous_and_cover_range():+ start, end = dt.date(2024, 5, 1), dt.date(2026, 4, 29)+ chunks = list(_iter_chunks(start, end))++ assert chunks[0][0] == start+ assert chunks[-1][1] == end+ for (_, prev_end), (next_start, _) in zip(chunks, chunks[1:]):+ assert next_start == prev_end + dt.timedelta(days=1)+++ "raw,expected",+ [+ ("20260415", dt.date(2026, 4, 15)),+ # Unparseable values pass through untouched rather than crashing the sync.+ ("(other)", "(other)"),+ ("2026-04-15", "2026-04-15"),+ ],+)+def test_parse_ga4_date(raw, expected):+ assert _parse_ga4_date(raw) == expected+++ "value,metric_type,expected",+ [+ ("123", "TYPE_INTEGER", 123),+ ("12.5", "TYPE_FLOAT", 12.5),+ ("88.2", "TYPE_SECONDS", 88.2),+ ("0.25", "TYPE_STANDARD", 0.25),+ # Integers parse as ints, everything else as floats.+ ("123", "", 123.0),+ # Garbage falls back to the raw value.+ ("not-a-number", "TYPE_INTEGER", "not-a-number"),+ (None, "TYPE_FLOAT", None),+ ],+)+def test_convert_metric_value(value, metric_type, expected):+ assert _convert_metric_value(value, metric_type) == expected+++def test_rows_to_dicts_flattens_headers_and_values():+ payload = {+ "dimensionHeaders": [{"name": "date"}, {"name": "deviceCategory"}],+ "metricHeaders": [+ {"name": "totalUsers", "type": "TYPE_INTEGER"},+ {"name": "bounceRate", "type": "TYPE_FLOAT"},+ ],+ "rows": [+ {+ "dimensionValues": [{"value": "20260415"}, {"value": "desktop"}],+ "metricValues": [{"value": "42"}, {"value": "0.35"}],+ },+ {+ "dimensionValues": [{"value": "20260416"}, {"value": "mobile"}],+ "metricValues": [{"value": "7"}, {"value": "0.5"}],+ },+ ],+ }++ rows = _rows_to_dicts(payload)++ assert rows == [+ {"date": dt.date(2026, 4, 15), "deviceCategory": "desktop", "totalUsers": 42, "bounceRate": 0.35},+ {"date": dt.date(2026, 4, 16), "deviceCategory": "mobile", "totalUsers": 7, "bounceRate": 0.5},+ ]+++def test_rows_to_dicts_handles_missing_rows():+ payload = {+ "dimensionHeaders": [{"name": "date"}],+ "metricHeaders": [{"name": "totalUsers", "type": "TYPE_INTEGER"}],+ }+ assert _rows_to_dicts(payload) == []+++def test_credentials_refreshes_stale_db_connection_before_query(monkeypatch):+ # The ORM read runs lazily inside `get_rows` on a worker thread whose pooled+ # Django connection may have been closed server-side. We must drop the stale+ # connection before querying, so the read happens on a fresh connection.+ calls: list[str] = []++ monkeypatch.setattr(ga, "close_old_connections", lambda: calls.append("close_old_connections"))++ integration = mock.MagicMock()+ integration.refresh_token = "refresh-token"++ def fake_get(*args, **kwargs):+ calls.append("Integration.objects.get")+ return integration++ monkeypatch.setattr(ga.Integration.objects, "get", fake_get)++ creds = _credentials(integration_id=1, team_id=1)++ assert calls == ["close_old_connections", "Integration.objects.get"]+ assert creds.refresh_token == "refresh-token"+++def _fake_response(status_code: int, json_body: dict | None = None, headers: dict | None = None):+ resp = mock.MagicMock(spec=requests.Response)+ resp.status_code = status_code+ resp.ok = status_code < 400+ resp.headers = headers or {}+ resp.text = "" if json_body is None else str(json_body)+ resp.json.return_value = json_body if json_body is not None else {}++ def raise_for_status():+ if not resp.ok:+ raise requests.HTTPError(f"{status_code} Client Error: oops for url: https://example", response=resp)++ resp.raise_for_status.side_effect = raise_for_status+ return resp+++ "status_code,expected",+ [+ (429, True),+ (403, False),+ (500, False),+ (200, False),+ ],+)+def test_is_quota_error(status_code, expected):+ assert _is_quota_error(_fake_response(status_code)) is expected+++def test_quota_backoff_honors_retry_after():+ response = _fake_response(429, headers={"Retry-After": "17"})+ assert _quota_backoff_seconds(response, attempt=0) == 17.0+++def test_quota_backoff_falls_back_to_exponential():+ response = _fake_response(429, headers={"Retry-After": "soon"})+ assert _quota_backoff_seconds(response, attempt=2) == ga.QUOTA_BACKOFF_BASE_SECONDS * 4+++def test_run_report_returns_payload_on_success():+ payload = {"rows": [], "rowCount": 0}+ session = mock.MagicMock()+ session.post.return_value = _fake_response(200, payload)++ result = _run_report(+ session=session,+ property_id="properties/123",+ start_date="2026-04-01",+ end_date="2026-04-30",+ dimensions=["date"],+ metrics=["totalUsers"],+ offset=0,+ )++ assert result == payload+ url = session.post.call_args[0][0]+ assert url == "https://analyticsdata.googleapis.com/v1beta/properties/123:runReport"+ body = session.post.call_args[1]["json"]+ assert body["dateRanges"] == [{"startDate": "2026-04-01", "endDate": "2026-04-30"}]+ assert body["dimensions"] == [{"name": "date"}]+ assert body["metrics"] == [{"name": "totalUsers"}]+ assert body["orderBys"] == [{"dimension": {"dimensionName": "date"}}]+++def test_run_report_retries_quota_errors_then_succeeds(monkeypatch):+ monkeypatch.setattr(ga.time, "sleep", lambda _: None)+ payload = {"rows": [], "rowCount": 0}+ session = mock.MagicMock()+ session.post.side_effect = [+ _fake_response(429),+ _fake_response(429),+ _fake_response(200, payload),+ ]++ result = _run_report(+ session=session,+ property_id="123",+ start_date="2026-04-01",+ end_date="2026-04-30",+ dimensions=["date"],+ metrics=["totalUsers"],+ offset=0,+ )++ assert result == payload+ assert session.post.call_count == 3+++def test_run_report_raises_after_exhausting_quota_retries(monkeypatch):+ monkeypatch.setattr(ga.time, "sleep", lambda _: None)+ session = mock.MagicMock()+ session.post.return_value = _fake_response(429)++ with pytest.raises(GoogleAnalyticsQuotaExceededError):+ _run_report(+ session=session,+ property_id="123",+ start_date="2026-04-01",+ end_date="2026-04-30",+ dimensions=["date"],+ metrics=["totalUsers"],+ offset=0,+ )++ assert session.post.call_count == QUOTA_MAX_RETRIES + 1++[email protected]("status_code", [400, 401, 403, 404])+def test_run_report_raises_http_error_for_non_quota_failures(status_code):+ session = mock.MagicMock()+ session.post.return_value = _fake_response(status_code)++ with pytest.raises(requests.HTTPError):+ _run_report(+ session=session,+ property_id="123",+ start_date="2026-04-01",+ end_date="2026-04-30",+ dimensions=["date"],+ metrics=["totalUsers"],+ offset=0,+ )++ assert session.post.call_count == 1+++def _report_payload(dates: list[str], users: list[int], row_count: int | None = None) -> dict:+ return {+ "dimensionHeaders": [{"name": "date"}],+ "metricHeaders": [{"name": "totalUsers", "type": "TYPE_INTEGER"}],+ "rows": [+ {"dimensionValues": [{"value": date}], "metricValues": [{"value": str(value)}]}+ for date, value in zip(dates, users)+ ],+ "rowCount": row_count if row_count is not None else len(dates),+ }+++def _patch_session(monkeypatch):+ monkeypatch.setattr(+ "posthog.temporal.data_imports.sources.google_analytics.google_analytics.google_analytics_session",+ lambda *a, **kw: mock.MagicMock(),+ )+++def _config() -> GoogleAnalyticsSourceConfig:+ return GoogleAnalyticsSourceConfig(property_id="123456789", google_analytics_integration_id=1)+++def test_source_yields_rows_and_advances_chunks(monkeypatch):+ fake_today = dt.date(2026, 4, 30)+ monkeypatch.setattr(ga, "_today", lambda: fake_today)+ _patch_session(monkeypatch)++ requests_made: list[tuple[str, str, int]] = []++ def fake_run_report(session, property_id, start_date, end_date, dimensions, metrics, offset, limit=50000):+ requests_made.append((start_date, end_date, offset))+ if start_date == "2026-04-23":+ return _report_payload(["20260423", "20260424"], [10, 20])+ return _report_payload([], [])++ monkeypatch.setattr(ga, "_run_report", fake_run_report)++ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ saved_states: list[GoogleAnalyticsResumeConfig] = []+ manager.save_state.side_effect = lambda state: saved_states.append(state)++ response = google_analytics_source(+ config=_config(),+ resource_name="website_overview",+ team_id=1,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=dt.date(2026, 4, 25),+ )++ batches = list(cast(Iterable[Any], response.items()))++ # Window: last value 2026-04-25 minus 2-day lookback → 2026-04-23 .. yesterday (2026-04-29); one chunk.+ assert requests_made == [("2026-04-23", "2026-04-29", 0)]+ assert len(batches) == 1+ assert batches[0] == [+ {"date": dt.date(2026, 4, 23), "totalUsers": 10},+ {"date": dt.date(2026, 4, 24), "totalUsers": 20},+ ]+ # Chunk exhausted → state advances to the next chunk with offset 0.+ assert len(saved_states) == 1+ assert saved_states[0].chunk_start == "2026-04-30"+ assert saved_states[0].offset == 0+++def test_source_paginates_within_chunk_and_saves_offsets(monkeypatch):+ fake_today = dt.date(2026, 4, 30)+ monkeypatch.setattr(ga, "_today", lambda: fake_today)+ _patch_session(monkeypatch)++ pages = {+ 0: _report_payload(["20260423", "20260424"], [1, 2], row_count=3),+ 2: _report_payload(["20260425"], [3], row_count=3),+ }++ def fake_run_report(session, property_id, start_date, end_date, dimensions, metrics, offset, limit=50000):+ return pages[offset]++ monkeypatch.setattr(ga, "_run_report", fake_run_report)++ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ saved_states: list[GoogleAnalyticsResumeConfig] = []+ manager.save_state.side_effect = lambda state: saved_states.append(state)++ response = google_analytics_source(+ config=_config(),+ resource_name="website_overview",+ team_id=1,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=dt.date(2026, 4, 25),+ )++ batches = list(cast(Iterable[Any], response.items()))++ assert len(batches) == 2+ # Mid-chunk state saves the in-progress chunk with the next offset; the final+ # page advances to the next chunk.+ assert [(s.chunk_start, s.offset) for s in saved_states] == [("2026-04-23", 2), ("2026-04-30", 0)]+++def test_source_resumes_from_saved_state(monkeypatch):+ fake_today = dt.date(2026, 4, 30)+ monkeypatch.setattr(ga, "_today", lambda: fake_today)+ _patch_session(monkeypatch)++ requests_made: list[tuple[str, int]] = []++ def fake_run_report(session, property_id, start_date, end_date, dimensions, metrics, offset, limit=50000):+ requests_made.append((start_date, offset))+ return _report_payload([], [])++ monkeypatch.setattr(ga, "_run_report", fake_run_report)++ manager = mock.MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = GoogleAnalyticsResumeConfig(chunk_start="2026-03-15", offset=500)++ response = google_analytics_source(+ config=_config(),+ resource_name="website_overview",+ team_id=1,+ resumable_source_manager=manager,+ )++ list(cast(Iterable[Any], response.items()))++ # Chunking restarts at the saved chunk start, with the saved offset applied+ # only to that first chunk.+ assert requests_made[0] == ("2026-03-15", 500)+ assert all(start >= "2026-03-15" for start, _ in requests_made)+ assert all(offset == 0 for _, offset in requests_made[1:])+++def test_source_resume_past_end_date_yields_nothing(monkeypatch):+ fake_today = dt.date(2026, 4, 30)+ monkeypatch.setattr(ga, "_today", lambda: fake_today)+ _patch_session(monkeypatch)++ fake_run_report = mock.MagicMock()+ monkeypatch.setattr(ga, "_run_report", fake_run_report)++ manager = mock.MagicMock()+ manager.can_resume.return_value = True+ # Saved state says everything up to the end of the window is already synced.+ manager.load_state.return_value = GoogleAnalyticsResumeConfig(chunk_start="2026-04-30", offset=0)++ response = google_analytics_source(+ config=_config(),+ resource_name="website_overview",+ team_id=1,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=dt.date(2026, 4, 25),+ )++ assert list(cast(Iterable[Any], response.items())) == []+ fake_run_report.assert_not_called()+++ "resource_name,expected_pk",+ [+ ("website_overview", ["date"]),+ ("devices", ["date", "deviceCategory", "operatingSystem", "browser"]),+ ("pages", ["date", "hostName", "pagePathPlusQueryString"]),+ ("traffic_sources", ["date", "sessionSource", "sessionMedium"]),+ ],+)+def test_source_response_has_partition_metadata(resource_name, expected_pk):+ response = google_analytics_source(+ config=_config(),+ resource_name=resource_name,+ team_id=1,+ resumable_source_manager=mock.MagicMock(),+ )++ assert response.primary_keys == expected_pk+ assert response.partition_keys == ["date"]+ assert response.partition_mode == "datetime"+ assert response.partition_format == "month"+ assert response.partition_count == 1+ assert response.partition_size == 1+++def test_unknown_resource_name_raises():+ with pytest.raises(ValueError, match="Unknown Google Analytics schema"):+ google_analytics_source(+ config=_config(),+ resource_name="not_a_real_schema",+ team_id=1,+ resumable_source_manager=mock.MagicMock(),+ )diff --git a/posthog/temporal/data_imports/sources/google_analytics/tests/test_google_analytics_source.py b/posthog/temporal/data_imports/sources/google_analytics/tests/test_google_analytics_source.pynew file mode 100644index 000000000000..e8953619849d--- /dev/null+++ b/posthog/temporal/data_imports/sources/google_analytics/tests/test_google_analytics_source.py@@ -0,0 +1,189 @@+import pytest+from unittest import mock++import requests++from posthog.schema import ReleaseStatus, SourceFieldOauthConfig++from posthog.temporal.data_imports.sources.generated_configs import GoogleAnalyticsSourceConfig+from posthog.temporal.data_imports.sources.google_analytics.google_analytics import GoogleAnalyticsResumeConfig+from posthog.temporal.data_imports.sources.google_analytics.settings import GOOGLE_ANALYTICS_REPORT_SCHEMAS+from posthog.temporal.data_imports.sources.google_analytics.source import GoogleAnalyticsSource++from products.data_warehouse.backend.types import ExternalDataSourceType, IncrementalFieldType+++def _config(property_id: str = "123456789") -> GoogleAnalyticsSourceConfig:+ return GoogleAnalyticsSourceConfig(property_id=property_id, google_analytics_integration_id=1)+++def test_source_type():+ assert GoogleAnalyticsSource().source_type == ExternalDataSourceType.GOOGLEANALYTICS+++def test_get_source_config_fields():+ cfg = GoogleAnalyticsSource().get_source_config++ field_names = {field.name for field in cfg.fields}+ assert field_names == {"google_analytics_integration_id", "property_id"}+ assert cfg.label == "Google Analytics"+ assert cfg.featureFlag == "dwh-google-analytics"+ assert cfg.releaseStatus == ReleaseStatus.ALPHA+ assert not cfg.unreleasedSource+++def test_get_source_config_oauth_field_declares_required_scope():+ cfg = GoogleAnalyticsSource().get_source_config+ oauth_field = next(field for field in cfg.fields if field.name == "google_analytics_integration_id")+ assert isinstance(oauth_field, SourceFieldOauthConfig)+ assert oauth_field.kind == "google-analytics"+ assert oauth_field.requiredScopes == "https://www.googleapis.com/auth/analytics.readonly"+++def test_get_schemas_returns_all_schemas_with_date_incremental():+ schemas = GoogleAnalyticsSource().get_schemas(_config(), team_id=1)++ assert {s.name for s in schemas} == set(GOOGLE_ANALYTICS_REPORT_SCHEMAS.keys())+ for schema in schemas:+ assert schema.supports_incremental is True+ assert schema.supports_append is True+ assert schema.incremental_fields == [+ {+ "label": "date",+ "field": "date",+ "type": IncrementalFieldType.Date,+ "field_type": IncrementalFieldType.Date,+ }+ ]+++def test_get_schemas_default_sync_set():+ schemas = GoogleAnalyticsSource().get_schemas(_config(), team_id=1)+ by_default_on = {s.name for s in schemas if s.should_sync_default}+ assert by_default_on == {"website_overview", "devices", "locations", "pages", "traffic_sources"}+++def test_get_schemas_filters_by_names():+ schemas = GoogleAnalyticsSource().get_schemas(_config(), team_id=1, names=["website_overview", "events"])+ assert {s.name for s in schemas} == {"website_overview", "events"}+++def test_all_schemas_have_date_dimension_and_in_primary_key():+ # Every report is day-grained: `date` must be requested and lead the primary key+ # so merge-mode dedupe and incremental syncs behave.+ for name, schema in GOOGLE_ANALYTICS_REPORT_SCHEMAS.items():+ assert schema["dimensions"][0] == "date", name+ assert schema["primary_key"] == schema["dimensions"], name+++def test_get_resumable_source_manager_uses_resume_config():+ inputs = mock.MagicMock()+ manager = GoogleAnalyticsSource().get_resumable_source_manager(inputs)+ assert manager._data_class is GoogleAnalyticsResumeConfig+++def test_source_for_pipeline_plumbs_arguments():+ inputs = mock.MagicMock()+ inputs.schema_name = "website_overview"+ inputs.team_id = 7+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-04-01"+ manager = mock.MagicMock()++ with mock.patch(+ "posthog.temporal.data_imports.sources.google_analytics.source.google_analytics_source"+ ) as mock_source:+ GoogleAnalyticsSource().source_for_pipeline(_config(), manager, inputs)++ mock_source.assert_called_once_with(+ config=mock.ANY,+ resource_name="website_overview",+ team_id=7,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-04-01",+ )+++def test_source_for_pipeline_drops_last_value_when_not_incremental():+ inputs = mock.MagicMock()+ inputs.schema_name = "website_overview"+ inputs.team_id = 7+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-04-01"++ with mock.patch(+ "posthog.temporal.data_imports.sources.google_analytics.source.google_analytics_source"+ ) as mock_source:+ GoogleAnalyticsSource().source_for_pipeline(_config(), mock.MagicMock(), inputs)++ assert mock_source.call_args[1]["db_incremental_field_last_value"] is None++[email protected]("bad_property_id", ["not-a-number", "properties/abc", "12 34", ""])+def test_validate_credentials_rejects_non_numeric_property_id(bad_property_id):+ ok, message = GoogleAnalyticsSource().validate_credentials(_config(bad_property_id), team_id=1)++ assert ok is False+ assert "not a valid GA4 property ID" in (message or "")+++def _http_error(status_code: int) -> requests.HTTPError:+ response = mock.MagicMock()+ response.status_code = status_code+ return requests.HTTPError(response=response)+++ "status_code,expected_substring",+ [+ (401, "rejected the credentials"),+ (403, "rejected the credentials"),+ (404, "was not found"),+ (500, "Failed to read Google Analytics property metadata"),+ ],+)+def test_validate_credentials_maps_http_errors(status_code, expected_substring):+ with (+ mock.patch("posthog.temporal.data_imports.sources.google_analytics.source.google_analytics_session"),+ mock.patch(+ "posthog.temporal.data_imports.sources.google_analytics.source.get_property_metadata",+ side_effect=_http_error(status_code),+ ),+ ):+ ok, message = GoogleAnalyticsSource().validate_credentials(_config(), team_id=1)++ assert ok is False+ assert expected_substring in (message or "")+++def test_validate_credentials_handles_session_failure():+ with mock.patch(+ "posthog.temporal.data_imports.sources.google_analytics.source.google_analytics_session",+ side_effect=Exception("no integration"),+ ):+ ok, message = GoogleAnalyticsSource().validate_credentials(_config(), team_id=1)++ assert ok is False+ assert "Could not load Google Analytics credentials" in (message or "")+++def test_validate_credentials_succeeds_when_metadata_readable():+ with (+ mock.patch("posthog.temporal.data_imports.sources.google_analytics.source.google_analytics_session"),+ mock.patch(+ "posthog.temporal.data_imports.sources.google_analytics.source.get_property_metadata",+ return_value={"dimensions": [], "metrics": []},+ ),+ ):+ ok, message = GoogleAnalyticsSource().validate_credentials(_config(), team_id=1)++ assert ok is True+ assert message is None+++def test_non_retryable_errors_cover_auth_failures():+ errors = GoogleAnalyticsSource().get_non_retryable_errors()+ assert "401 Client Error" in errors+ assert "403 Client Error" in errors+ assert "ACCESS_TOKEN_SCOPE_INSUFFICIENT" in errorsdiff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 2f6098a437ce..f78accf5db56 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -4094,6 +4094,7 @@ export const IntegrationKindApi = {GoogleCloudServiceAccount: 'google-cloud-service-account',GoogleCloudStorage: 'google-cloud-storage',GoogleAds: 'google-ads',+ GoogleAnalytics: 'google-analytics',GoogleSearchConsole: 'google-search-console',GoogleSheets: 'google-sheets',LinkedinAds: 'linkedin-ads',diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.tsindex 7f78129bc191..dfe714494dcd 100644--- a/products/integrations/frontend/generated/api.schemas.ts+++ b/products/integrations/frontend/generated/api.schemas.ts@@ -163,6 +163,7 @@ export interface RoleLookupResponseApi {* * `github` - Github* * `gitlab` - Gitlab* * `google-ads` - Google Ads+ * * `google-analytics` - Google Analytics* * `google-cloud-service-account` - Google Cloud Service Account* * `google-cloud-storage` - Google Cloud Storage* * `google-pubsub` - Google Pubsub@@ -203,6 +204,7 @@ export const IntegrationKindEnumApi = {Github: 'github',Gitlab: 'gitlab',GoogleAds: 'google-ads',+ GoogleAnalytics: 'google-analytics',GoogleCloudServiceAccount: 'google-cloud-service-account',GoogleCloudStorage: 'google-cloud-storage',GooglePubsub: 'google-pubsub',@@ -384,6 +386,7 @@ export type IntegrationsListParams = {* * `github` - Github* * `gitlab` - Gitlab* * `google-ads` - Google Ads+ * * `google-analytics` - Google Analytics* * `google-cloud-service-account` - Google Cloud Service Account* * `google-cloud-storage` - Google Cloud Storage* * `google-pubsub` - Google Pubsub@@ -435,6 +438,7 @@ export const IntegrationsListKind = {Github: 'github',Gitlab: 'gitlab',GoogleAds: 'google-ads',+ GoogleAnalytics: 'google-analytics',GoogleCloudServiceAccount: 'google-cloud-service-account',GoogleCloudStorage: 'google-cloud-storage',GooglePubsub: 'google-pubsub',diff --git a/products/integrations/frontend/generated/api.zod.ts b/products/integrations/frontend/generated/api.zod.tsindex 4ffbc789f171..69849da8e13c 100644--- a/products/integrations/frontend/generated/api.zod.ts+++ b/products/integrations/frontend/generated/api.zod.ts@@ -76,6 +76,7 @@ export const IntegrationsCreateBody = /* @__PURE__ */ zod'github','gitlab','google-ads',+ 'google-analytics','google-cloud-service-account','google-cloud-storage','google-pubsub',@@ -100,7 +101,7 @@ export const IntegrationsCreateBody = /* @__PURE__ */ zod'vercel',]).describe(- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'),config: zod.unknown().optional(),})@@ -124,6 +125,7 @@ export const IntegrationsEmailPartialUpdateBody = /* @__PURE__ */ zod'github','gitlab','google-ads',+ 'google-analytics','google-cloud-service-account','google-cloud-storage','google-pubsub',@@ -149,7 +151,7 @@ export const IntegrationsEmailPartialUpdateBody = /* @__PURE__ */ zod]).optional().describe(- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'),config: zod.unknown().optional(),})@@ -173,6 +175,7 @@ export const IntegrationsEmailVerifyCreateBody = /* @__PURE__ */ zod'github','gitlab','google-ads',+ 'google-analytics','google-cloud-service-account','google-cloud-storage','google-pubsub',@@ -197,7 +200,7 @@ export const IntegrationsEmailVerifyCreateBody = /* @__PURE__ */ zod'vercel',]).describe(- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'),config: zod.unknown().optional(),})@@ -228,6 +231,7 @@ export const IntegrationsDomainConnectApplyUrlCreateBody = /* @__PURE__ */ zod'github','gitlab','google-ads',+ 'google-analytics','google-cloud-service-account','google-cloud-storage','google-pubsub',@@ -252,7 +256,7 @@ export const IntegrationsDomainConnectApplyUrlCreateBody = /* @__PURE__ */ zod'vercel',]).describe(- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'),config: zod.unknown().optional(),})@@ -279,6 +283,7 @@ export const IntegrationsGithubLinkExistingCreateBody = /* @__PURE__ */ zod'github','gitlab','google-ads',+ 'google-analytics','google-cloud-service-account','google-cloud-storage','google-pubsub',@@ -303,7 +308,7 @@ export const IntegrationsGithubLinkExistingCreateBody = /* @__PURE__ */ zod'vercel',]).describe(- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'),config: zod.unknown().optional(),})@@ -330,6 +335,7 @@ export const IntegrationsGithubOauthAuthorizeCreateBody = /* @__PURE__ */ zod'github','gitlab','google-ads',+ 'google-analytics','google-cloud-service-account','google-cloud-storage','google-pubsub',@@ -354,7 +360,7 @@ export const IntegrationsGithubOauthAuthorizeCreateBody = /* @__PURE__ */ zod'vercel',]).describe(- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'),config: zod.unknown().optional(),})diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 2a55c928e4ba..0a68407abc4e 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -3629,6 +3629,7 @@ export const IntegrationKindApi = {GoogleCloudServiceAccount: 'google-cloud-service-account',GoogleCloudStorage: 'google-cloud-storage',GoogleAds: 'google-ads',+ GoogleAnalytics: 'google-analytics',GoogleSearchConsole: 'google-search-console',GoogleSheets: 'google-sheets',LinkedinAds: 'linkedin-ads',diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c43c8326efc9..400d4d5e44e9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -4689,6 +4689,7 @@ export namespace Schemas {GoogleCloudServiceAccount: 'google-cloud-service-account',GoogleCloudStorage: 'google-cloud-storage',GoogleAds: 'google-ads',+ GoogleAnalytics: 'google-analytics',GoogleSearchConsole: 'google-search-console',GoogleSheets: 'google-sheets',LinkedinAds: 'linkedin-ads',@@ -23083,6 +23084,7 @@ export namespace Schemas {* * `github` - Github* * `gitlab` - Gitlab* * `google-ads` - Google Ads+ * * `google-analytics` - Google Analytics* * `google-cloud-service-account` - Google Cloud Service Account* * `google-cloud-storage` - Google Cloud Storage* * `google-pubsub` - Google Pubsub@@ -23124,6 +23126,7 @@ export namespace Schemas {Github: 'github',Gitlab: 'gitlab',GoogleAds: 'google-ads',+ GoogleAnalytics: 'google-analytics',GoogleCloudServiceAccount: 'google-cloud-service-account',GoogleCloudStorage: 'google-cloud-storage',GooglePubsub: 'google-pubsub',@@ -48396,6 +48399,7 @@ export namespace Schemas {* * `github` - Github* * `gitlab` - Gitlab* * `google-ads` - Google Ads+ * * `google-analytics` - Google Analytics* * `google-cloud-service-account` - Google Cloud Service Account* * `google-cloud-storage` - Google Cloud Storage* * `google-pubsub` - Google Pubsub@@ -48448,6 +48452,7 @@ export namespace Schemas {Github: 'github',Gitlab: 'gitlab',GoogleAds: 'google-ads',+ GoogleAnalytics: 'google-analytics',GoogleCloudServiceAccount: 'google-cloud-service-account',GoogleCloudStorage: 'google-cloud-storage',GooglePubsub: 'google-pubsub',@@ -54508,6 +54513,7 @@ export namespace Schemas {* * `github` - Github* * `gitlab` - Gitlab* * `google-ads` - Google Ads+ * * `google-analytics` - Google Analytics* * `google-cloud-service-account` - Google Cloud Service Account* * `google-cloud-storage` - Google Cloud Storage* * `google-pubsub` - Google Pubsub@@ -54560,6 +54566,7 @@ export namespace Schemas {Github: 'github',Gitlab: 'gitlab',GoogleAds: 'google-ads',+ GoogleAnalytics: 'google-analytics',GoogleCloudServiceAccount: 'google-cloud-service-account',GoogleCloudStorage: 'google-cloud-storage',GooglePubsub: 'google-pubsub',diff --git a/services/mcp/src/generated/integrations/api.ts b/services/mcp/src/generated/integrations/api.tsindex 3ea242f3e933..8d6a528ee850 100644--- a/services/mcp/src/generated/integrations/api.ts+++ b/services/mcp/src/generated/integrations/api.ts@@ -33,6 +33,7 @@ export const IntegrationsListQueryParams = /* @__PURE__ */ zod.object({'github','gitlab','google-ads',+ 'google-analytics','google-cloud-service-account','google-cloud-storage','google-pubsub',@@ -58,7 +59,7 @@ export const IntegrationsListQueryParams = /* @__PURE__ */ zod.object({]).optional().describe(- '* `anthropic` - Anthropic\n* `apns` - Apple Push\n* `azure-blob` - Azure Blob\n* `bing-ads` - Bing Ads\n* `clickup` - Clickup\n* `customerio-app` - Customerio App\n* `customerio-track` - Customerio Track\n* `customerio-webhook` - Customerio Webhook\n* `databricks` - Databricks\n* `email` - Email\n* `firebase` - Firebase\n* `github` - Github\n* `gitlab` - Gitlab\n* `google-ads` - Google Ads\n* `google-cloud-service-account` - Google Cloud Service Account\n* `google-cloud-storage` - Google Cloud Storage\n* `google-pubsub` - Google Pubsub\n* `google-search-console` - Google Search Console\n* `google-sheets` - Google Sheets\n* `hubspot` - Hubspot\n* `intercom` - Intercom\n* `jira` - Jira\n* `linear` - Linear\n* `linkedin-ads` - Linkedin Ads\n* `meta-ads` - Meta Ads\n* `pinterest-ads` - Pinterest Ads\n* `postgresql` - Postgresql\n* `reddit-ads` - Reddit Ads\n* `salesforce` - Salesforce\n* `slack` - Slack\n* `slack-posthog-code` - Slack Posthog Code\n* `snapchat` - Snapchat\n* `stripe` - Stripe\n* `tiktok-ads` - Tiktok Ads\n* `twilio` - Twilio\n* `vercel` - Vercel'+ '* `anthropic` - Anthropic\n* `apns` - Apple Push\n* `azure-blob` - Azure Blob\n* `bing-ads` - Bing Ads\n* `clickup` - Clickup\n* `customerio-app` - Customerio App\n* `customerio-track` - Customerio Track\n* `customerio-webhook` - Customerio Webhook\n* `databricks` - Databricks\n* `email` - Email\n* `firebase` - Firebase\n* `github` - Github\n* `gitlab` - Gitlab\n* `google-ads` - Google Ads\n* `google-analytics` - Google Analytics\n* `google-cloud-service-account` - Google Cloud Service Account\n* `google-cloud-storage` - Google Cloud Storage\n* `google-pubsub` - Google Pubsub\n* `google-search-console` - Google Search Console\n* `google-sheets` - Google Sheets\n* `hubspot` - Hubspot\n* `intercom` - Intercom\n* `jira` - Jira\n* `linear` - Linear\n* `linkedin-ads` - Linkedin Ads\n* `meta-ads` - Meta Ads\n* `pinterest-ads` - Pinterest Ads\n* `postgresql` - Postgresql\n* `reddit-ads` - Reddit Ads\n* `salesforce` - Salesforce\n* `slack` - Slack\n* `slack-posthog-code` - Slack Posthog Code\n* `snapchat` - Snapchat\n* `stripe` - Stripe\n* `tiktok-ads` - Tiktok Ads\n* `twilio` - Twilio\n* `vercel` - Vercel'),limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.jsonindex ec30895495dd..852295d1cb47 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json@@ -2,7 +2,7 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"kind": {- "description": "* `anthropic` - Anthropic\n* `apns` - Apple Push\n* `azure-blob` - Azure Blob\n* `bing-ads` - Bing Ads\n* `clickup` - Clickup\n* `customerio-app` - Customerio App\n* `customerio-track` - Customerio Track\n* `customerio-webhook` - Customerio Webhook\n* `databricks` - Databricks\n* `email` - Email\n* `firebase` - Firebase\n* `github` - Github\n* `gitlab` - Gitlab\n* `google-ads` - Google Ads\n* `google-cloud-service-account` - Google Cloud Service Account\n* `google-cloud-storage` - Google Cloud Storage\n* `google-pubsub` - Google Pubsub\n* `google-search-console` - Google Search Console\n* `google-sheets` - Google Sheets\n* `hubspot` - Hubspot\n* `intercom` - Intercom\n* `jira` - Jira\n* `linear` - Linear\n* `linkedin-ads` - Linkedin Ads\n* `meta-ads` - Meta Ads\n* `pinterest-ads` - Pinterest Ads\n* `postgresql` - Postgresql\n* `reddit-ads` - Reddit Ads\n* `salesforce` - Salesforce\n* `slack` - Slack\n* `slack-posthog-code` - Slack Posthog Code\n* `snapchat` - Snapchat\n* `stripe` - Stripe\n* `tiktok-ads` - Tiktok Ads\n* `twilio` - Twilio\n* `vercel` - Vercel",+ "description": "* `anthropic` - Anthropic\n* `apns` - Apple Push\n* `azure-blob` - Azure Blob\n* `bing-ads` - Bing Ads\n* `clickup` - Clickup\n* `customerio-app` - Customerio App\n* `customerio-track` - Customerio Track\n* `customerio-webhook` - Customerio Webhook\n* `databricks` - Databricks\n* `email` - Email\n* `firebase` - Firebase\n* `github` - Github\n* `gitlab` - Gitlab\n* `google-ads` - Google Ads\n* `google-analytics` - Google Analytics\n* `google-cloud-service-account` - Google Cloud Service Account\n* `google-cloud-storage` - Google Cloud Storage\n* `google-pubsub` - Google Pubsub\n* `google-search-console` - Google Search Console\n* `google-sheets` - Google Sheets\n* `hubspot` - Hubspot\n* `intercom` - Intercom\n* `jira` - Jira\n* `linear` - Linear\n* `linkedin-ads` - Linkedin Ads\n* `meta-ads` - Meta Ads\n* `pinterest-ads` - Pinterest Ads\n* `postgresql` - Postgresql\n* `reddit-ads` - Reddit Ads\n* `salesforce` - Salesforce\n* `slack` - Slack\n* `slack-posthog-code` - Slack Posthog Code\n* `snapchat` - Snapchat\n* `stripe` - Stripe\n* `tiktok-ads` - Tiktok Ads\n* `twilio` - Twilio\n* `vercel` - Vercel","enum": ["anthropic","apns",@@ -18,6 +18,7 @@"github","gitlab","google-ads",+ "google-analytics","google-cloud-service-account","google-cloud-storage","google-pubsub",