Skip to content

: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.

fix(warehouse): sync Plausible entry and exit page tables (#81077)

Chris Shine3d4f0a6cc88f
diff --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.py
index 5058f87a8703..0b88a806a6c6 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,6 +1,7 @@
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
_DOCS_URL = "https://plausible.io/docs/stats-api"
@@ -15,6 +16,11 @@ _STANDARD_METRIC_COLUMNS = {
"events": "Number of events (pageviews plus custom events).",
}
+# Entry/exit page breakdowns are session-scoped, so they carry no event-scoped metric columns.
+_SESSION_METRIC_COLUMNS = {
+ name: description for name, description in _STANDARD_METRIC_COLUMNS.items() if name not in EVENT_SCOPED_METRICS
+}
+
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"timeseries": {
"description": "Site-wide traffic metrics aggregated per day.",
@@ -64,12 +70,12 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"entry_pages": {
"description": "Daily traffic metrics broken down by the first page of each visit.",
"docs_url": _DOCS_URL,
- "columns": {**_STANDARD_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."},
},
"exit_pages": {
"description": "Daily traffic metrics broken down by the last page of each visit.",
"docs_url": _DOCS_URL,
- "columns": {**_STANDARD_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."},
},
"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.py
index 284d9afea225..87bec1351ee0 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
@@ -8,11 +8,28 @@ REPORT_LOOKBACK_DAYS = 7
# History pulled on the first sync of a stream.
DEFAULT_BACKFILL_DAYS = 365
-# Metrics requested for every report. These are the standard Plausible Stats API v2 metrics that
-# are valid across visit and event dimensions. Goal/conversion-specific metrics live on their own
-# endpoints because they aren't valid for the generic breakdowns.
+# Metrics requested for every report. These are the standard Plausible Stats API v2 metrics.
+# Goal/conversion-specific metrics live on their own endpoints because they aren't valid for the
+# 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:
+# 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.
+SESSION_SCOPED_DIMENSIONS = frozenset(
+ {"visit:entry_page", "visit:entry_page_hostname", "visit:exit_page", "visit:exit_page_hostname"}
+)
+# Plausible Cloud exempts the two revenue metrics from that check and self-hosted does not, so both
+# are listed. Neither is in DEFAULT_METRICS today.
+EVENT_SCOPED_METRICS = frozenset(
+ {"pageviews", "events", "scroll_depth", "time_on_page", "total_revenue", "average_revenue"}
+)
+
# 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.
TIME_DIMENSION = "time:day"
@@ -47,6 +64,18 @@ class PlausibleEndpointConfig:
metrics: list[str] = field(default_factory=lambda: list(DEFAULT_METRICS))
should_sync_default: bool = True
+ def __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]
+ # 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
+
@property
def dimensions(self) -> list[str]:
return [TIME_DIMENSION, *self.breakdown_dimensions]
@@ -76,6 +105,7 @@ PLAUSIBLE_ENDPOINTS: dict[str, PlausibleEndpointConfig] = {
"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"]),
"countries": PlausibleEndpointConfig(name="countries", breakdown_dimensions=["visit:country"]),
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.py
index ded1b827989b..ac6aa92dd1cf 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
@@ -22,6 +22,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.plausible.
ENDPOINTS,
PLAUSIBLE_ENDPOINTS,
REPORT_LOOKBACK_DAYS,
+ SESSION_SCOPED_DIMENSIONS,
+ PlausibleEndpointConfig,
)
_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.plausible.plausible"
@@ -271,6 +273,39 @@ class TestGetRows:
_rows(_source(endpoint="timeseries"))
+# Pinned rather than derived from the scope constants, so tampering with those fails here.
+_SESSION_METRICS = ["visitors", "visits", "bounce_rate", "visit_duration"]
+_SESSION_SCOPED_ENDPOINT_METRICS = {"entry_pages": _SESSION_METRICS, "exit_pages": _SESSION_METRICS}
+
+
+class TestEndpointMetricScopes:
+ @pytest.mark.parametrize("endpoint, expected", sorted(_SESSION_SCOPED_ENDPOINT_METRICS.items()))
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_session_scoped_breakdown_requests_session_metrics_only(self, MockSession, endpoint, expected):
+ session = MockSession.return_value
+ bodies = _wire(session, [_response({"results": [], "meta": {"total_rows": 0}})])
+
+ _rows(_source(endpoint=endpoint))
+
+ assert bodies[0]["metrics"] == expected
+
+ def test_every_session_scoped_endpoint_is_covered(self):
+ # Forces a deliberate edit here when an endpoint is added on a session-scoped dimension,
+ # instead of the endpoint quietly dropping out of the parametrize list above.
+ covered = {
+ name
+ for name, config in PLAUSIBLE_ENDPOINTS.items()
+ if SESSION_SCOPED_DIMENSIONS.intersection(config.breakdown_dimensions)
+ }
+ assert covered == set(_SESSION_SCOPED_ENDPOINT_METRICS)
+
+ def test_endpoint_left_with_no_session_metrics_is_rejected(self):
+ with pytest.raises(ValueError, match="no session-scoped metrics"):
+ PlausibleEndpointConfig(
+ name="bad", breakdown_dimensions=["visit:exit_page"], metrics=["pageviews", "events"]
+ )
+
+
class TestPlausibleSourceResponse:
@pytest.mark.parametrize("endpoint", list(ENDPOINTS))
@mock.patch(CLIENT_SESSION_PATCH)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/plausible/tests/test_plausible_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/plausible/tests/test_plausible_source.py
index bcaa56e942f8..fcba0063b65c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/plausible/tests/test_plausible_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/plausible/tests/test_plausible_source.py
@@ -155,3 +155,12 @@ class TestCanonicalDescriptions:
for entry in descriptions.values():
assert entry.get("description")
assert "date" in entry.get("columns", {})
+
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_documented_columns_match_the_columns_the_endpoint_produces(self, endpoint):
+ # These descriptions are written per endpoint while the metric set is derived, so without
+ # this an endpoint can document metric columns its table never gets.
+ config = PLAUSIBLE_ENDPOINTS[endpoint]
+ columns = PlausibleSource().get_canonical_descriptions()[endpoint]["columns"]
+
+ assert set(columns) == {*config.column_names, *config.metrics}