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.

feat(warehouse-sources): add Matomo pages, goals and events tables (#115046)

Tom Owers243243295ab1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index c9d791aa3f0b..06fd5f899b78 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -5464,10 +5464,10 @@ Today (5): `actions_summary`, `countries`, `referrers`, `visits`, `visits_summar
Diffed against: <https://demo.matomo.cloud/index.php?module=API&method=API.getReportMetadata&idSite=1&period=day&date=today&format=JSON&token_auth=anonymous>
-- [ ] `Actions.getPageUrls` — Page-level traffic report; actions_summary only carries site-wide totals (high)
-- [ ] `Goals.get` — Goal conversions and revenue, Matomo's headline conversion metric (high)
-- [ ] `Goals.getGoals` — Lookup table resolving the goal IDs that conversion reports key on (high)
-- [ ] `Events.getCategory / getAction / getName` — Custom event reports - the closest analogue to PostHog's own event model (high)
+- [x] `Actions.getPageUrls` — Page-level traffic report; actions_summary only carries site-wide totals (high)
+- [x] `Goals.get` — Goal conversions and revenue, Matomo's headline conversion metric (high)
+- [x] `Goals.getGoals` — Lookup table resolving the goal IDs that conversion reports key on (high)
+- [x] `Events.getCategory / getAction / getName` — Custom event reports - the closest analogue to PostHog's own event model (high)
- [ ] `Actions.getEntryPageUrls / getExitPageUrls` — Entry and exit page breakdowns for landing-page and drop-off analysis (medium)
- [ ] `Referrers.getReferrerType / getSearchEngines / getWebsites / getSocials` — Channel-level referrer breakdowns; referrers today is only the flat getAll roll-up (medium)
- [ ] `DevicesDetection.getType / getBrowsers / getOsFamilies` — Device, browser and OS breakdown dimensions (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/matomo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/matomo/canonical_descriptions.py
index 73ddeb9f4c01..34288f932023 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/matomo/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/matomo/canonical_descriptions.py
@@ -89,4 +89,101 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"nb_actions": "The number of actions from this country.",
},
},
+ "pages": {
+ "description": "Per-day page URL breakdown from Matomo's Actions API — one row per page URL.",
+ "docs_url": "https://developer.matomo.org/api-reference/reporting-api#Actions",
+ "columns": {
+ "_date": "The report day this row is for.",
+ "label": "The page path, flattened from Matomo's folder hierarchy.",
+ "url": "The full URL of the page.",
+ "nb_hits": "The number of page views of this page.",
+ "nb_visits": "The number of visits that viewed this page.",
+ "nb_uniq_visitors": "The number of unique visitors that viewed this page.",
+ "sum_time_spent": "The total time spent on this page in seconds.",
+ "avg_time_on_page": "The average time spent on this page in seconds.",
+ "entry_nb_visits": "The number of visits that started on this page.",
+ "exit_nb_visits": "The number of visits that ended on this page.",
+ "bounce_rate": "The percentage of visits that started on this page and left without another action.",
+ "exit_rate": "The percentage of this page's visits that ended on it.",
+ },
+ },
+ "goals_summary": {
+ "description": "Per-day aggregate goal conversion metrics across all goals from Matomo's Goals API.",
+ "docs_url": "https://developer.matomo.org/api-reference/reporting-api#Goals",
+ "columns": {
+ "_date": "The report day this aggregate row is for.",
+ "nb_conversions": "The total number of goal conversions in the period.",
+ "nb_visits_converted": "The number of visits that converted at least one goal.",
+ "revenue": "The total revenue from goal conversions.",
+ "conversion_rate": "The percentage of visits that converted at least one goal.",
+ "nb_conversions_new_visit": "The number of conversions by new visitors.",
+ "nb_conversions_returning_visit": "The number of conversions by returning visitors.",
+ "revenue_new_visit": "The revenue from conversions by new visitors.",
+ "revenue_returning_visit": "The revenue from conversions by returning visitors.",
+ },
+ },
+ "event_categories": {
+ "description": "Per-day custom event breakdown by event category from Matomo's Events API — one row per event category.",
+ "docs_url": "https://developer.matomo.org/api-reference/reporting-api#Events",
+ "columns": {
+ "_date": "The report day this row is for.",
+ "label": "The event category.",
+ "nb_events": "The number of events with this category.",
+ "nb_visits": "The number of visits that triggered an event with this category.",
+ "nb_uniq_visitors": "The number of unique visitors that triggered an event with this category.",
+ "nb_events_with_value": "The number of these events that carried a numeric value.",
+ "sum_event_value": "The sum of the values of these events.",
+ "avg_event_value": "The average value of these events.",
+ "min_event_value": "The smallest value among these events.",
+ "max_event_value": "The largest value among these events.",
+ },
+ },
+ "event_actions": {
+ "description": "Per-day custom event breakdown by event action from Matomo's Events API — one row per event action.",
+ "docs_url": "https://developer.matomo.org/api-reference/reporting-api#Events",
+ "columns": {
+ "_date": "The report day this row is for.",
+ "label": "The event action.",
+ "nb_events": "The number of events with this action.",
+ "nb_visits": "The number of visits that triggered an event with this action.",
+ "nb_uniq_visitors": "The number of unique visitors that triggered an event with this action.",
+ "nb_events_with_value": "The number of these events that carried a numeric value.",
+ "sum_event_value": "The sum of the values of these events.",
+ "avg_event_value": "The average value of these events.",
+ "min_event_value": "The smallest value among these events.",
+ "max_event_value": "The largest value among these events.",
+ },
+ },
+ "event_names": {
+ "description": "Per-day custom event breakdown by event name from Matomo's Events API — one row per event name.",
+ "docs_url": "https://developer.matomo.org/api-reference/reporting-api#Events",
+ "columns": {
+ "_date": "The report day this row is for.",
+ "label": "The event name.",
+ "nb_events": "The number of events with this name.",
+ "nb_visits": "The number of visits that triggered an event with this name.",
+ "nb_uniq_visitors": "The number of unique visitors that triggered an event with this name.",
+ "nb_events_with_value": "The number of these events that carried a numeric value.",
+ "sum_event_value": "The sum of the values of these events.",
+ "avg_event_value": "The average value of these events.",
+ "min_event_value": "The smallest value among these events.",
+ "max_event_value": "The largest value among these events.",
+ },
+ },
+ "goals": {
+ "description": "The goals configured for the site in Matomo — one row per goal.",
+ "docs_url": "https://developer.matomo.org/api-reference/reporting-api#Goals",
+ "columns": {
+ "idgoal": "The identifier of the goal, unique within the site.",
+ "idsite": "The identifier of the site the goal belongs to.",
+ "name": "The name of the goal.",
+ "description": "The description of the goal.",
+ "match_attribute": "What triggers the goal (e.g. url, title, event_category, manually).",
+ "pattern": "The pattern the match attribute is compared against.",
+ "pattern_type": "How the pattern is matched (contains, exact, or regex).",
+ "case_sensitive": "Whether the pattern match is case sensitive.",
+ "allow_multiple": "Whether the goal can convert more than once per visit.",
+ "revenue": "The default revenue credited for each conversion.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/matomo/matomo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/matomo/matomo.py
index 8486a0bc9e2c..2c83fd6997ce 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/matomo/matomo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/matomo/matomo.py
@@ -251,6 +251,15 @@ def get_rows(
)
return
+ if config.kind == "list":
+ body = call(config.method, dict(config.params))
+ # Current Matomo returns a list; older releases key the same rows by id in an object.
+ items = body.values() if isinstance(body, dict) else body if isinstance(body, list) else []
+ rows = [row for row in items if isinstance(row, dict)]
+ if rows:
+ yield rows
+ return
+
# Per-day report walk, oldest-first. Recent days re-archive, so
# incremental runs re-pull a trailing lookback window.
today = datetime.now(tz=UTC).date()
@@ -268,7 +277,7 @@ def get_rows(
day = start
while day <= today:
- body = call(config.method, {"period": "day", "date": day.isoformat(), "filter_limit": -1})
+ body = call(config.method, {"period": "day", "date": day.isoformat(), "filter_limit": -1, **config.params})
rows = body if isinstance(body, list) else ([body] if isinstance(body, dict) and body else [])
rows = [{**row, "_date": day.isoformat()} for row in rows if isinstance(row, dict)]
if rows:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/matomo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/matomo/settings.py
index 9089e70090f9..1c5272171eaf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/matomo/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/matomo/settings.py
@@ -1,5 +1,7 @@
-from dataclasses import dataclass, field
-from typing import Literal, Optional
+from dataclasses import field
+from typing import Any, Literal, Optional
+
+from posthog.dataclasses import frozen
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (
PartitionFormat,
@@ -16,7 +18,7 @@ DEFAULT_BACKFILL_DAYS = 365
# deferred to the next sync so their action list is complete when stored.
VISIT_FINALITY_WINDOW_SECONDS = 3600
-MatomoEndpointKind = Literal["visits", "report"]
+MatomoEndpointKind = Literal["visits", "report", "list"]
_DATE_INCREMENTAL_FIELDS: list[IncrementalField] = [
{
@@ -28,13 +30,15 @@ _DATE_INCREMENTAL_FIELDS: list[IncrementalField] = [
]
-@dataclass
+@frozen
class MatomoEndpointConfig:
name: str
kind: MatomoEndpointKind
# Matomo Reporting API method name (everything goes through one RPC-style
# endpoint: index.php?module=API&method=...).
method: str
+ # Extra request parameters sent alongside the method, e.g. `flat` for hierarchical reports.
+ params: dict[str, Any] = field(default_factory=dict)
primary_keys: list[str] = field(default_factory=lambda: ["id"])
incremental_fields: list[IncrementalField] = field(default_factory=list)
# Delta partitioning for this endpoint. Left unset (None) means the table is written
@@ -100,6 +104,51 @@ MATOMO_ENDPOINTS: dict[str, MatomoEndpointConfig] = {
primary_keys=["_date", "label"],
incremental_fields=list(_DATE_INCREMENTAL_FIELDS),
),
+ "pages": MatomoEndpointConfig(
+ name="pages",
+ kind="report",
+ method="Actions.getPageUrls",
+ # The report nests pages under folder rows; flattening yields one row per page URL
+ # with its full path as the label, so (_date, label) stays unique.
+ params={"flat": 1},
+ primary_keys=["_date", "label"],
+ incremental_fields=list(_DATE_INCREMENTAL_FIELDS),
+ ),
+ "goals_summary": MatomoEndpointConfig(
+ name="goals_summary",
+ kind="report",
+ method="Goals.get",
+ primary_keys=["_date"],
+ incremental_fields=list(_DATE_INCREMENTAL_FIELDS),
+ ),
+ "event_categories": MatomoEndpointConfig(
+ name="event_categories",
+ kind="report",
+ method="Events.getCategory",
+ primary_keys=["_date", "label"],
+ incremental_fields=list(_DATE_INCREMENTAL_FIELDS),
+ ),
+ "event_actions": MatomoEndpointConfig(
+ name="event_actions",
+ kind="report",
+ method="Events.getAction",
+ primary_keys=["_date", "label"],
+ incremental_fields=list(_DATE_INCREMENTAL_FIELDS),
+ ),
+ "event_names": MatomoEndpointConfig(
+ name="event_names",
+ kind="report",
+ method="Events.getName",
+ primary_keys=["_date", "label"],
+ incremental_fields=list(_DATE_INCREMENTAL_FIELDS),
+ ),
+ # Goal definitions: a small undated lookup, fetched whole each sync.
+ "goals": MatomoEndpointConfig(
+ name="goals",
+ kind="list",
+ method="Goals.getGoals",
+ primary_keys=["idgoal"],
+ ),
}
ENDPOINTS = tuple(MATOMO_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/matomo/tests/test_matomo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/matomo/tests/test_matomo.py
index bb0d821cf0c7..ad389769d0bf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/matomo/tests/test_matomo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/matomo/tests/test_matomo.py
@@ -1,9 +1,15 @@
from datetime import UTC, datetime
from typing import Any
+from urllib.parse import parse_qsl
import pytest
from unittest import mock
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.matomo import MatomoSourceConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.matomo.matomo import (
VISITS_PAGE_SIZE,
MatomoResumeConfig,
@@ -16,6 +22,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.matomo.set
REPORT_LOOKBACK_DAYS,
VISIT_FINALITY_WINDOW_SECONDS,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.matomo.source import MatomoSource
_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.matomo.matomo"
@@ -212,6 +219,62 @@ class TestReports:
)
[email protected](f"{_MODULE}.time.sleep")
[email protected](MatomoSource, "is_database_host_valid", return_value=(True, None))
+class TestDrivenEndpoints:
+ @staticmethod
+ def _driver() -> SourceDriver:
+ return SourceDriver(
+ MatomoSource(), MatomoSourceConfig(host="https://m.example.com", site_id="1", api_token="token")
+ )
+
+ @staticmethod
+ def _form(request: Any) -> dict[str, str]:
+ return dict(parse_qsl((request.body or b"").decode()))
+
+ @pytest.mark.parametrize(
+ "endpoint,method,expected_flat",
+ [
+ # Without flat=1 page URLs come back as folder rows whose pages hide in subtables.
+ ("pages", "Actions.getPageUrls", "1"),
+ ("event_names", "Events.getName", None),
+ ],
+ )
+ def test_report_request_params(self, mock_host_valid, mock_sleep, endpoint, method, expected_flat):
+ today = datetime.now(tz=UTC).date().isoformat()
+
+ result = self._driver().run(
+ endpoint,
+ [ScriptedResponse(json=[{"label": "/pricing"}])],
+ resume_state=MatomoResumeConfig(next_date=today),
+ )
+
+ assert result.raised is None
+ assert result.rows == [{"label": "/pricing", "_date": today}]
+ [request] = result.requests
+ body = self._form(request)
+ assert (body["method"], body["period"], body["date"], body["filter_limit"]) == (method, "day", today, "-1")
+ assert body.get("flat") == expected_flat
+
+ @pytest.mark.parametrize(
+ "goals",
+ [
+ [{"idgoal": 1, "name": "Signup"}, {"idgoal": 2, "name": "Purchase"}],
+ # Older Matomo releases key the goals by id instead of returning a list.
+ {"1": {"idgoal": "1", "name": "Signup"}, "2": {"idgoal": "2", "name": "Purchase"}},
+ ],
+ )
+ def test_goals_fetched_in_one_undated_call(self, mock_host_valid, mock_sleep, goals):
+ result = self._driver().run("goals", [ScriptedResponse(json=goals)])
+
+ assert result.raised is None
+ assert [row["name"] for row in result.rows] == ["Signup", "Purchase"]
+ [request] = result.requests
+ body = self._form(request)
+ assert body["method"] == "Goals.getGoals"
+ assert "period" not in body and "date" not in body
+
+
class TestMatomoSourceResponse:
@pytest.mark.parametrize(
"endpoint,expected_mode,expected_keys,expected_format",