:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(warehouse): import hostname on Plausible page breakdowns (#87133)
posthog[bot]ed176e79e41f
diff --git a/products/warehouse_sources/backend/migrations/0157_reset_plausible_page_breakdowns.py b/products/warehouse_sources/backend/migrations/0157_reset_plausible_page_breakdowns.pynew file mode 100644index 000000000000..20acf5e51692--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0157_reset_plausible_page_breakdowns.py@@ -0,0 +1,51 @@+from django.db import migrations++# The Plausible `pages`, `entry_pages`, and `exit_pages` breakdowns gained a hostname dimension,+# which widens their composite primary key. Existing schemas are stuck on the old key two ways:+# `resolve_primary_keys` gives the persisted `sync_type_config["primary_key_columns"]` absolute+# precedence over the source's keys, and existing Delta rows carry no hostname column, so a merge+# on the widened key would leave old hostname-less rows beside the new per-hostname rows and+# double-count. Rewrite the persisted key to the widened one and stamp `reset_pipeline`, so the+# next scheduled sync wipes the table and rebuilds it keyed on hostname+# (`handle_reset_or_full_refresh`).++AFFECTED_PRIMARY_KEYS = {+ "pages": (["date", "page"], ["date", "page", "hostname"]),+ "entry_pages": (["date", "entry_page"], ["date", "entry_page", "entry_page_hostname"]),+ "exit_pages": (["date", "exit_page"], ["date", "exit_page", "exit_page_hostname"]),+}+++def forwards(apps, schema_editor):+ ExternalDataSchema = apps.get_model("warehouse_sources", "ExternalDataSchema")++ # One row per configured Plausible page table (the source is Alpha) — a per-row loop is fine.+ schemas = ExternalDataSchema.objects.filter(+ source__source_type="Plausible",+ deleted=False,+ name__in=AFFECTED_PRIMARY_KEYS.keys(),+ ).iterator()++ for schema in schemas:+ config = schema.sync_type_config or {}+ stale_key, widened_key = AFFECTED_PRIMARY_KEYS[schema.name]+ # Only replace the exact stale key. A different persisted value is a deliberate user+ # override, which the reset below rebuilds the table under unchanged.+ if config.get("primary_key_columns") == stale_key:+ config["primary_key_columns"] = widened_key+ # Stamp every affected schema, keyed or not: a schema without a persisted key still holds+ # hostname-less rows the merge can never update or delete. Full-refresh schemas wipe on+ # every run anyway, so the stamp is a no-op difference there.+ config["reset_pipeline"] = True+ schema.sync_type_config = config+ schema.save(update_fields=["sync_type_config"])+++class Migration(migrations.Migration):+ dependencies = [("warehouse_sources", "0156_externaldatajob_pipeline_status_finished_idx")]++ operations = [+ # Reverse is a no-op: the reset consumes itself on the next sync, and restoring the stale+ # narrow key would recreate the subdomain collision this repairs.+ migrations.RunPython(forwards, migrations.RunPython.noop, elidable=True),+ ]diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txtindex 857ff21228bf..04fda7ca10df 100644--- a/products/warehouse_sources/backend/migrations/max_migration.txt+++ b/products/warehouse_sources/backend/migrations/max_migration.txt@@ -1 +1 @@-0156_externaldatajob_pipeline_status_finished_idx+0157_reset_plausible_page_breakdownsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/plausible/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/plausible/canonical_descriptions.pyindex 0b88a806a6c6..09f6d1d20c27 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/plausible/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/plausible/canonical_descriptions.py@@ -1,7 +1,10 @@from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)-from products.warehouse_sources.backend.temporal.data_imports.sources.plausible.settings import EVENT_SCOPED_METRICS+from products.warehouse_sources.backend.temporal.data_imports.sources.plausible.settings import (+ EVENT_SCOPED_METRICS,+ SESSION_SCOPED_METRICS,+)_DOCS_URL = "https://plausible.io/docs/stats-api"@@ -21,6 +24,13 @@ _SESSION_METRIC_COLUMNS = {name: description for name, description in _STANDARD_METRIC_COLUMNS.items() if name not in EVENT_SCOPED_METRICS}+# The page breakdown is event-scoped (it carries `event:hostname`), so it drops the session metrics.+_EVENT_METRIC_COLUMNS = {+ name: description for name, description in _STANDARD_METRIC_COLUMNS.items() if name not in SESSION_SCOPED_METRICS+}++_HOSTNAME_DESCRIPTION = "The hostname the page was served on, so paths on different subdomains stay distinct."+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"timeseries": {"description": "Site-wide traffic metrics aggregated per day.",@@ -63,19 +73,31 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"columns": {**_STANDARD_METRIC_COLUMNS, "utm_content": "Value of the utm_content query parameter."},},"pages": {- "description": "Daily traffic metrics broken down by page path.",+ "description": "Daily traffic metrics broken down by page path and hostname.","docs_url": _DOCS_URL,- "columns": {**_STANDARD_METRIC_COLUMNS, "page": "The page path of the pageview."},+ "columns": {+ **_EVENT_METRIC_COLUMNS,+ "page": "The page path of the pageview.",+ "hostname": _HOSTNAME_DESCRIPTION,+ },},"entry_pages": {- "description": "Daily traffic metrics broken down by the first page of each visit.",+ "description": "Daily traffic metrics broken down by the first page of each visit and its hostname.","docs_url": _DOCS_URL,- "columns": {**_SESSION_METRIC_COLUMNS, "entry_page": "The first page path visited in a session."},+ "columns": {+ **_SESSION_METRIC_COLUMNS,+ "entry_page": "The first page path visited in a session.",+ "entry_page_hostname": _HOSTNAME_DESCRIPTION,+ },},"exit_pages": {- "description": "Daily traffic metrics broken down by the last page of each visit.",+ "description": "Daily traffic metrics broken down by the last page of each visit and its hostname.","docs_url": _DOCS_URL,- "columns": {**_SESSION_METRIC_COLUMNS, "exit_page": "The last page path visited in a session."},+ "columns": {+ **_SESSION_METRIC_COLUMNS,+ "exit_page": "The last page path visited in a session.",+ "exit_page_hostname": _HOSTNAME_DESCRIPTION,+ },},"countries": {"description": "Daily traffic metrics broken down by visitor country.",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/plausible/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/plausible/settings.pyindex 87bec1351ee0..91a95d771958 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/plausible/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/plausible/settings.py@@ -13,14 +13,14 @@ DEFAULT_BACKFILL_DAYS = 365# generic breakdowns.DEFAULT_METRICS = ["visitors", "visits", "pageviews", "bounce_rate", "visit_duration", "events"]-# Plausible resolves these dimensions against its sessions table and these metrics against its-# events table, and answers 400 when one of these metrics is requested alongside one of these-# dimensions. Both sets are complete as transcribed from Plausible v3.2.1:+# Plausible resolves each dimension and metric against either its sessions table or its events+# table, and answers 400 when a report pairs a metric from one scope with a dimension from the+# other. `__post_init__` enforces both directions. These sets are transcribed from Plausible v3.2.1:# https://github.com/plausible/analytics/blob/v3.2.1/lib/plausible/stats/table_decider.ex#-# Only this direction is enforced below. Plausible rejects the mirror case too — a session metric-# such as `bounce_rate` alongside an `event:*` dimension — and exempts only `event:page`, which is-# why `pages` works on the shared metric set. A new `event:*` breakdown needs its own metrics.+# `event:page` alone is exempted — Plausible splits the session query downstream — so `pages` can+# keep the session metrics on that lone dimension. Pairing it with any other `event:*` dimension+# (e.g. `event:hostname`) loses the exemption, so those session metrics get dropped.SESSION_SCOPED_DIMENSIONS = frozenset({"visit:entry_page", "visit:entry_page_hostname", "visit:exit_page", "visit:exit_page_hostname"})@@ -29,6 +29,10 @@ SESSION_SCOPED_DIMENSIONS = frozenset(EVENT_SCOPED_METRICS = frozenset({"pageviews", "events", "scroll_depth", "time_on_page", "total_revenue", "average_revenue"})+# Metrics Plausible resolves only against its sessions table, rejected alongside an event dimension.+# `bounce_rate` and `visit_duration` are the two in DEFAULT_METRICS; the rest are listed for future+# metric sets.+SESSION_SCOPED_METRICS = frozenset({"bounce_rate", "visit_duration", "views_per_visit", "exit_rate"})# The day bucket every report is grouped by — must be the first dimension so `order_by` can sort# on it and the pipeline can slide the date window incrementally.@@ -55,7 +59,8 @@ def dimension_to_column(dimension: str) -> str:return dimension.split(":", 1)[-1]-@dataclass+# Mutable: `__post_init__` narrows `metrics` in place to the scope Plausible accepts.+@dataclass(frozen=False)class PlausibleEndpointConfig:name: str# Plausible Stats API v2 query dimensions. `time:day` is prepended automatically, so list only@@ -65,16 +70,24 @@ class PlausibleEndpointConfig:should_sync_default: bool = Truedef __post_init__(self) -> None:- # Drop the metrics Plausible would reject here rather than relying on every session-scoped- # endpoint to remember to exclude them.- if not SESSION_SCOPED_DIMENSIONS.intersection(self.breakdown_dimensions):- return- session_metrics = [metric for metric in self.metrics if metric not in EVENT_SCOPED_METRICS]+ # Drop the metrics Plausible would reject for this breakdown rather than relying on every+ # endpoint to remember the scope rule.+ if SESSION_SCOPED_DIMENSIONS.intersection(self.breakdown_dimensions):+ self._drop_metrics(EVENT_SCOPED_METRICS, scope="session-scoped")+ elif self._breaks_event_page_exemption():+ self._drop_metrics(SESSION_SCOPED_METRICS, scope="event-scoped")++ def _breaks_event_page_exemption(self) -> bool:+ event_dimensions = [d for d in self.breakdown_dimensions if d.startswith("event:")]+ return bool(event_dimensions) and event_dimensions != ["event:page"]++ def _drop_metrics(self, excluded: frozenset[str], scope: str) -> None:+ remaining = [metric for metric in self.metrics if metric not in excluded]# Plausible rejects an empty `metrics`. This raise reaches the source loader, which skips the# whole connector rather than failing the deploy, so a test pins it instead.- if not session_metrics:- raise ValueError(f"{self.name}: no session-scoped metrics remain out of {self.metrics}")- self.metrics = session_metrics+ if not remaining:+ raise ValueError(f"{self.name}: no {scope} metrics remain out of {self.metrics}")+ self.metrics = remaining@propertydef dimensions(self) -> list[str]:@@ -104,10 +117,16 @@ PLAUSIBLE_ENDPOINTS: dict[str, PlausibleEndpointConfig] = {"utm_campaigns": PlausibleEndpointConfig(name="utm_campaigns", breakdown_dimensions=["visit:utm_campaign"]),"utm_terms": PlausibleEndpointConfig(name="utm_terms", breakdown_dimensions=["visit:utm_term"]),"utm_contents": PlausibleEndpointConfig(name="utm_contents", breakdown_dimensions=["visit:utm_content"]),- "pages": PlausibleEndpointConfig(name="pages", breakdown_dimensions=["event:page"]),- # Session-scoped, so `__post_init__` narrows these two to the session metrics.- "entry_pages": PlausibleEndpointConfig(name="entry_pages", breakdown_dimensions=["visit:entry_page"]),- "exit_pages": PlausibleEndpointConfig(name="exit_pages", breakdown_dimensions=["visit:exit_page"]),+ # Hostname pairs with the path so rows from different subdomains stay distinct in the composite+ # primary key. It makes these breakdowns event-scoped, so `__post_init__` drops the session+ # metrics from `pages` and keeps the session metrics on the two visit-scoped page breakdowns.+ "pages": PlausibleEndpointConfig(name="pages", breakdown_dimensions=["event:page", "event:hostname"]),+ "entry_pages": PlausibleEndpointConfig(+ name="entry_pages", breakdown_dimensions=["visit:entry_page", "visit:entry_page_hostname"]+ ),+ "exit_pages": PlausibleEndpointConfig(+ name="exit_pages", breakdown_dimensions=["visit:exit_page", "visit:exit_page_hostname"]+ ),"countries": PlausibleEndpointConfig(name="countries", breakdown_dimensions=["visit:country"]),"regions": PlausibleEndpointConfig(name="regions", breakdown_dimensions=["visit:region"]),"cities": PlausibleEndpointConfig(name="cities", breakdown_dimensions=["visit:city"]),diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/plausible/tests/test_plausible.py b/products/warehouse_sources/backend/temporal/data_imports/sources/plausible/tests/test_plausible.pyindex ac6aa92dd1cf..56d541191ad2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/plausible/tests/test_plausible.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/plausible/tests/test_plausible.py@@ -305,6 +305,26 @@ class TestEndpointMetricScopes:name="bad", breakdown_dimensions=["visit:exit_page"], metrics=["pageviews", "events"])+ def test_event_page_exemption_keeps_session_metrics_only_when_page_is_alone(self):+ # `event:page` alone is exempt, so it keeps the session metrics; pairing it with another+ # `event:*` dimension loses the exemption and drops them, or Plausible would 400.+ alone = PlausibleEndpointConfig(name="alone", breakdown_dimensions=["event:page"])+ assert "bounce_rate" in alone.metrics and "visit_duration" in alone.metrics++ paired = PlausibleEndpointConfig(name="paired", breakdown_dimensions=["event:page", "event:hostname"])+ assert "bounce_rate" not in paired.metrics and "visit_duration" not in paired.metrics+ assert paired.metrics == ["visitors", "visits", "pageviews", "events"]++ @pytest.mark.parametrize(+ "endpoint, hostname_column",+ [("pages", "hostname"), ("entry_pages", "entry_page_hostname"), ("exit_pages", "exit_page_hostname")],+ )+ def test_page_breakdowns_key_on_hostname(self, endpoint, hostname_column):+ # Without hostname in the composite key, paths on different subdomains merge into one row.+ config = PLAUSIBLE_ENDPOINTS[endpoint]+ assert hostname_column in config.column_names+ assert hostname_column in config.primary_keys+class TestPlausibleSourceResponse:@pytest.mark.parametrize("endpoint", list(ENDPOINTS))