: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): let users define custom GA4 reports (#79894)
posthog[bot]0b9bf2c30762
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/googleanalytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/googleanalytics.pyindex 045b7d9379c0..183f6e6ffb50 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/googleanalytics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/googleanalytics.py@@ -8,3 +8,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common impclass GoogleAnalyticsSourceConfig(config.Config):property_id: strgoogle_analytics_integration_id: int = config.value(converter=config.str_to_int)+ custom_reports: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/canonical_descriptions.pyindex e00990abd0b5..e0189e5f7266 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/canonical_descriptions.py@@ -114,6 +114,45 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {firstUserMedium="Medium that first acquired the user.",),},+ "landing_pages": {+ "description": "Daily performance of the first page in each session (landing page, including query string).",+ "docs_url": "https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema",+ "columns": _date_columns(+ landingPagePlusQueryString="First page path (including query string) of the session.",+ sessions="Number of sessions that started on the page.",+ totalUsers="Number of unique users who landed on the page.",+ newUsers="Number of first-time users who landed on the page.",+ screenPageViews="Number of page views in those sessions.",+ averageSessionDuration="Average session duration, in seconds.",+ bounceRate="Share of sessions that were not engaged.",+ ),+ },+ "campaigns": {+ "description": "Daily traffic broken out by session campaign, default channel group, source, and medium.",+ "docs_url": "https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema",+ "columns": _date_columns(+ sessionCampaignName="Campaign that brought the user to the site for the session.",+ sessionDefaultChannelGroup="Rule-based channel grouping for the session (e.g. Paid Search, Organic Social).",+ sessionSource="The source that brought the user to the site for the session (e.g. google).",+ sessionMedium="The medium that brought the user for the session (e.g. organic, cpc, referral).",+ totalUsers="Number of unique users.",+ newUsers="Number of first-time users.",+ sessions="Number of sessions.",+ engagedSessions="Number of sessions that were engaged (lasted 10s+, had a conversion, or 2+ page views).",+ ),+ },+ "key_events": {+ "description": "Daily key events and purchase revenue broken out by session source and medium.",+ "docs_url": "https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema",+ "columns": _date_columns(+ sessionSource="The source that brought the user to the site for the session (e.g. google).",+ sessionMedium="The medium that brought the user for the session (e.g. organic, cpc, referral).",+ keyEvents="Number of key events (the GA4 successor to conversions).",+ purchaseRevenue="Total revenue from purchases.",+ sessions="Number of sessions.",+ totalUsers="Number of unique users.",+ ),+ },"events": {"description": "Daily event counts broken out by event name.","docs_url": "https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.pyindex d630e34e8f75..d08842d8c345 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py@@ -22,7 +22,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_GoogleAnalyticsSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.google_analytics.settings import (- GOOGLE_ANALYTICS_REPORT_SCHEMAS,+ build_report_schemas,)logger = structlog.get_logger(__name__)@@ -299,10 +299,11 @@ def google_analytics_source(should_use_incremental_field: bool = False,db_incremental_field_last_value: Any = None,) -> SourceResponse:- if resource_name not in GOOGLE_ANALYTICS_REPORT_SCHEMAS:+ report_schemas = build_report_schemas(config.custom_reports)+ if resource_name not in report_schemas:raise ValueError(f"Unknown Google Analytics schema: {resource_name}")- schema = GOOGLE_ANALYTICS_REPORT_SCHEMAS[resource_name]+ schema = report_schemas[resource_name]dimensions = schema["dimensions"]metrics = schema["metrics"]primary_keys = list(schema["primary_key"])diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/settings.pyindex ad2e54d8230b..5e4789b6d0d4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/settings.py@@ -1,3 +1,5 @@+import re+import jsonfrom typing import TypedDictfrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType@@ -121,6 +123,34 @@ GOOGLE_ANALYTICS_REPORT_SCHEMAS: dict[str, GoogleAnalyticsReportSchema] = {"should_sync_default": True,"description": "Daily acquisition broken out by the source and medium that first acquired each user.",},+ "landing_pages": {+ "dimensions": ["date", "landingPagePlusQueryString"],+ "metrics": [+ "sessions",+ "totalUsers",+ "newUsers",+ "screenPageViews",+ "averageSessionDuration",+ "bounceRate",+ ],+ "primary_key": ["date", "landingPagePlusQueryString"],+ "should_sync_default": False,+ "description": "Daily performance of the first page in each session (landing page, including query string).",+ },+ "campaigns": {+ "dimensions": ["date", "sessionCampaignName", "sessionDefaultChannelGroup", "sessionSource", "sessionMedium"],+ "metrics": ["totalUsers", "newUsers", "sessions", "engagedSessions"],+ "primary_key": ["date", "sessionCampaignName", "sessionDefaultChannelGroup", "sessionSource", "sessionMedium"],+ "should_sync_default": False,+ "description": "Daily traffic broken out by session campaign, default channel group, source, and medium.",+ },+ "key_events": {+ "dimensions": ["date", "sessionSource", "sessionMedium"],+ "metrics": ["keyEvents", "purchaseRevenue", "sessions", "totalUsers"],+ "primary_key": ["date", "sessionSource", "sessionMedium"],+ "should_sync_default": False,+ "description": "Daily key events and purchase revenue broken out by session source and medium.",+ },"events": {"dimensions": ["date", "eventName"],"metrics": ["eventCount", "totalUsers", "eventCountPerUser"],@@ -137,3 +167,110 @@ GOOGLE_ANALYTICS_INCREMENTAL_FIELD: IncrementalField = {"type": IncrementalFieldType.Date,"field_type": IncrementalFieldType.Date,}+++# GA4's runReport rejects requests over 9 dimensions or 10 metrics. `date` counts+# toward the dimension limit because it is always requested, so a user-defined+# report may name at most 8 dimensions of its own.+GA4_MAX_DIMENSIONS = 9+GA4_MAX_METRICS = 10++# GA4 dimension/metric API names are alphanumeric identifiers; custom dimensions and+# metrics carry a `customEvent:`/`customUser:` scope prefix. Reject anything else so a+# malformed name fails fast at config time instead of as an opaque runReport error.+_GA4_FIELD_NAME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(:[A-Za-z0-9_]+)?$")+++class CustomReportError(ValueError):+ """A user-defined custom report is malformed or exceeds GA4's request limits."""+++def _validated_field_names(raw: object, *, report_name: str, kind: str) -> list[str]:+ if not isinstance(raw, list):+ raise CustomReportError(f"Report '{report_name}': '{kind}' must be a list of GA4 {kind} names.")+ names: list[str] = []+ for value in raw:+ if not isinstance(value, str) or not value.strip():+ raise CustomReportError(f"Report '{report_name}': every {kind[:-1]} name must be a non-empty string.")+ name = value.strip()+ if not _GA4_FIELD_NAME_RE.match(name):+ raise CustomReportError(f"Report '{report_name}': '{name}' is not a valid GA4 {kind[:-1]} name.")+ if name not in names:+ names.append(name)+ return names+++def parse_custom_reports(custom_reports_json: str | None) -> dict[str, GoogleAnalyticsReportSchema]:+ """Turn the user's custom-report JSON into report schemas keyed by table name.++ Mirrors the conventions of the built-in schemas so custom reports flow through the+ same incremental/resumable sync unchanged: `date` always leads the dimensions and+ the primary key is date plus every dimension for merge-mode dedupe. Raises+ `CustomReportError` with an actionable message on any malformed or oversized report.+ """+ if not custom_reports_json or not custom_reports_json.strip():+ return {}++ try:+ parsed = json.loads(custom_reports_json)+ except json.JSONDecodeError as e:+ raise CustomReportError(f"Custom reports must be valid JSON: {e}.") from e++ if not isinstance(parsed, list):+ raise CustomReportError("Custom reports must be a JSON array of report objects.")++ reports: dict[str, GoogleAnalyticsReportSchema] = {}+ for entry in parsed:+ if not isinstance(entry, dict):+ raise CustomReportError(+ "Each custom report must be a JSON object with 'name', 'dimensions', and 'metrics'."+ )++ raw_name = entry.get("name")+ if not isinstance(raw_name, str) or not raw_name.strip():+ raise CustomReportError("Each custom report needs a non-empty 'name'.")+ name = raw_name.strip()++ if name in GOOGLE_ANALYTICS_REPORT_SCHEMAS:+ raise CustomReportError(+ f"'{name}' is a built-in report name. Choose a different name for your custom report."+ )+ if name in reports:+ raise CustomReportError(f"Duplicate custom report name '{name}'. Each report needs a unique name.")++ metrics = _validated_field_names(entry.get("metrics"), report_name=name, kind="metrics")+ if not metrics:+ raise CustomReportError(f"Report '{name}': add at least one metric.")++ # `date` is always day-grained and leads the dimensions; drop a user-supplied+ # duplicate so it is not requested twice.+ user_dimensions = _validated_field_names(entry.get("dimensions", []), report_name=name, kind="dimensions")+ dimensions = ["date", *(d for d in user_dimensions if d != "date")]++ if len(dimensions) > GA4_MAX_DIMENSIONS:+ raise CustomReportError(+ f"Report '{name}': GA4 allows at most {GA4_MAX_DIMENSIONS} dimensions per report "+ f"(date is always included), but this report has {len(dimensions)}."+ )+ if len(metrics) > GA4_MAX_METRICS:+ raise CustomReportError(+ f"Report '{name}': GA4 allows at most {GA4_MAX_METRICS} metrics per report, "+ f"but this report has {len(metrics)}."+ )++ reports[name] = {+ "dimensions": dimensions,+ "metrics": metrics,+ "primary_key": list(dimensions),+ "should_sync_default": True,+ "description": entry.get("description")+ if isinstance(entry.get("description"), str)+ else "User-defined GA4 report.",+ }++ return reports+++def build_report_schemas(custom_reports_json: str | None) -> dict[str, GoogleAnalyticsReportSchema]:+ """Built-in report schemas merged with any user-defined custom reports."""+ return {**GOOGLE_ANALYTICS_REPORT_SCHEMAS, **parse_custom_reports(custom_reports_json)}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/source.pyindex 3369b4f6d084..935e60826b5f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/source.py@@ -36,7 +36,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_ana)from products.warehouse_sources.backend.temporal.data_imports.sources.google_analytics.settings import (GOOGLE_ANALYTICS_INCREMENTAL_FIELD,- GOOGLE_ANALYTICS_REPORT_SCHEMAS,+ CustomReportError,+ build_report_schemas,)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -98,7 +99,7 @@ class GoogleAnalyticsSource(ResumableSource[GoogleAnalyticsSourceConfig, GoogleAdescription=schema["description"],should_sync_default=schema["should_sync_default"],)- for name, schema in GOOGLE_ANALYTICS_REPORT_SCHEMAS.items()+ for name, schema in build_report_schemas(config.custom_reports).items()]if names is not None:@@ -134,6 +135,11 @@ class GoogleAnalyticsSource(ResumableSource[GoogleAnalyticsSourceConfig, GoogleAschema_name: Optional[str] = None,api_version: str | None = None,) -> tuple[bool, str | None]:+ try:+ build_report_schemas(config.custom_reports)+ except CustomReportError as e:+ return False, str(e)+property_id = normalize_property_id(config.property_id)if not property_id.isdigit():# Name the two IDs users most often paste by mistake — both are non-numeric and@@ -242,6 +248,24 @@ class GoogleAnalyticsSource(ResumableSource[GoogleAnalyticsSourceConfig, GoogleA),secret=False,),+ SourceFieldInputConfig(+ name="custom_reports",+ label="Custom reports (optional)",+ type=SourceFieldInputConfigType.TEXTAREA,+ required=False,+ placeholder=(+ '[{"name": "paid_campaigns", '+ '"dimensions": ["sessionCampaignName", "sessionSource"], '+ '"metrics": ["sessions", "totalUsers", "purchaseRevenue"]}]'+ ),+ caption=(+ "Define your own report tables as a JSON array, on top of the built-in ones. "+ "Each report needs a name, GA4 dimensions, and GA4 metrics. PostHog always adds "+ "the date dimension and syncs each report daily. GA4 allows up to 9 dimensions "+ "(including date) and 10 metrics per report."+ ),+ secret=False,+ ),],),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.pyindex 29b11ba0fcc7..e5704bab9ca7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py@@ -476,8 +476,10 @@ def _patch_session(monkeypatch):)-def _config() -> GoogleAnalyticsSourceConfig:- return GoogleAnalyticsSourceConfig(property_id="123456789", google_analytics_integration_id=1)+def _config(custom_reports: str | None = None) -> GoogleAnalyticsSourceConfig:+ return GoogleAnalyticsSourceConfig(+ property_id="123456789", google_analytics_integration_id=1, custom_reports=custom_reports+ )def test_source_yields_rows_and_advances_chunks(monkeypatch):@@ -645,6 +647,35 @@ def test_source_response_has_partition_metadata(resource_name, expected_pk):assert response.partition_size == 1+def test_source_requests_user_defined_custom_report(monkeypatch):+ # A custom report drives the exact dimensions/metrics sent to runReport (date prepended),+ # proving user config reaches the generic fetch layer, and its primary key is date + dims.+ fake_today = dt.date(2026, 4, 30)+ monkeypatch.setattr(ga, "_today", lambda: fake_today)+ _patch_session(monkeypatch)++ seen: list[tuple[list[str], list[str]]] = []++ def fake_run_report(session, property_id, start_date, end_date, dimensions, metrics, offset, limit=50000):+ seen.append((dimensions, metrics))+ return _report_payload([], [])++ monkeypatch.setattr(ga, "_run_report", fake_run_report)++ custom = '[{"name": "paid_campaigns", "dimensions": ["sessionCampaignName", "sessionSource"], "metrics": ["sessions", "purchaseRevenue"]}]'+ response = google_analytics_source(+ config=_config(custom_reports=custom),+ resource_name="paid_campaigns",+ team_id=1,+ resumable_source_manager=mock.MagicMock(can_resume=mock.Mock(return_value=False)),+ )++ list(cast(Iterable[Any], response.items()))++ assert response.primary_keys == ["date", "sessionCampaignName", "sessionSource"]+ assert seen[0] == (["date", "sessionCampaignName", "sessionSource"], ["sessions", "purchaseRevenue"])++def test_unknown_resource_name_raises():with pytest.raises(ValueError, match="Unknown Google Analytics schema"):google_analytics_source(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics_source.pyindex 3a3172f2688e..cfa197ccbc81 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics_source.py@@ -17,6 +17,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_ana)from products.warehouse_sources.backend.temporal.data_imports.sources.google_analytics.settings import (GOOGLE_ANALYTICS_REPORT_SCHEMAS,+ CustomReportError,+ parse_custom_reports,)from products.warehouse_sources.backend.temporal.data_imports.sources.google_analytics.source import (GoogleAnalyticsSource,@@ -24,8 +26,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_anafrom products.warehouse_sources.backend.types import ExternalDataSourceType, IncrementalFieldType-def _config(property_id: str = "123456789") -> GoogleAnalyticsSourceConfig:- return GoogleAnalyticsSourceConfig(property_id=property_id, google_analytics_integration_id=1)+def _config(property_id: str = "123456789", custom_reports: str | None = None) -> GoogleAnalyticsSourceConfig:+ return GoogleAnalyticsSourceConfig(+ property_id=property_id, google_analytics_integration_id=1, custom_reports=custom_reports+ )def test_source_type():@@ -36,7 +40,7 @@ def test_get_source_config_fields():cfg = GoogleAnalyticsSource().get_source_configfield_names = {field.name for field in cfg.fields}- assert field_names == {"google_analytics_integration_id", "property_id"}+ assert field_names == {"google_analytics_integration_id", "property_id", "custom_reports"}assert cfg.label == "Google Analytics"assert cfg.featureFlag is Noneassert cfg.releaseStatus == ReleaseStatus.GA@@ -91,6 +95,76 @@ def test_get_schemas_filters_by_names():assert {s.name for s in schemas} == {"website_overview", "events"}+def test_get_schemas_includes_user_defined_custom_reports():+ # A configured custom report shows up alongside the built-ins, default-on (the user+ # explicitly asked for it) and incremental like every other report.+ custom = '[{"name": "paid_campaigns", "dimensions": ["sessionCampaignName"], "metrics": ["sessions"]}]'+ schemas = GoogleAnalyticsSource().get_schemas(_config(custom_reports=custom), team_id=1)++ by_name = {s.name: s for s in schemas}+ assert set(GOOGLE_ANALYTICS_REPORT_SCHEMAS.keys()) <= by_name.keys()+ assert "paid_campaigns" in by_name+ assert by_name["paid_campaigns"].should_sync_default is True+ assert by_name["paid_campaigns"].supports_incremental is True+++def test_parse_custom_reports_prepends_date_and_derives_primary_key():+ # `date` always leads the dimensions (day-grained) and the primary key is date + all+ # dimensions, matching the built-in convention that incremental/merge sync relies on.+ reports = parse_custom_reports(+ '[{"name": "campaign_grain", "dimensions": ["date", "sessionCampaignName"], "metrics": ["sessions"]}]'+ )+ schema = reports["campaign_grain"]+ assert schema["dimensions"] == ["date", "sessionCampaignName"]+ assert schema["primary_key"] == ["date", "sessionCampaignName"]+ assert schema["metrics"] == ["sessions"]+++def test_parse_custom_reports_empty_input_returns_no_reports():+ assert parse_custom_reports(None) == {}+ assert parse_custom_reports(" ") == {}+++ "custom_reports,expected_substring",+ [+ ("not json", "valid JSON"),+ ('{"name": "x"}', "JSON array"),+ ('[{"dimensions": ["a"], "metrics": ["sessions"]}]', "non-empty 'name'"),+ ('[{"name": "website_overview", "dimensions": [], "metrics": ["sessions"]}]', "built-in report name"),+ (+ '[{"name": "dup", "metrics": ["sessions"]}, {"name": "dup", "metrics": ["sessions"]}]',+ "Duplicate custom report name",+ ),+ ('[{"name": "no_metrics", "dimensions": ["country"], "metrics": []}]', "at least one metric"),+ ('[{"name": "bad_dim", "dimensions": ["not a dim!"], "metrics": ["sessions"]}]', "not a valid GA4"),+ (+ '[{"name": "too_many_dims", "dimensions": ["a","b","c","d","e","f","g","h","i"], "metrics": ["s"]}]',+ "at most 9 dimensions",+ ),+ (+ '[{"name": "too_many_metrics", "dimensions": ["a"], '+ '"metrics": ["m1","m2","m3","m4","m5","m6","m7","m8","m9","m10","m11"]}]',+ "at most 10 metrics",+ ),+ ],+)+def test_parse_custom_reports_rejects_invalid(custom_reports, expected_substring):+ with pytest.raises(CustomReportError) as exc:+ parse_custom_reports(custom_reports)+ assert expected_substring in str(exc.value)+++def test_validate_credentials_rejects_invalid_custom_reports():+ # A malformed custom-report config is surfaced at setup, before any GA4 call, so the+ # user fixes their JSON instead of hitting an opaque runReport failure mid-sync.+ ok, message = GoogleAnalyticsSource().validate_credentials(+ _config(custom_reports='[{"name": "x", "dimensions": ["country"], "metrics": []}]'), team_id=1+ )+ assert ok is False+ assert "at least one metric" in (message or "")++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.