: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(data-warehouse): fetch matomo visits one day at a time (#104167)
Tom Owersa93bcca23ab6
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.pyindex 5fd36b9a794d..8486a0bc9e2c 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@@ -1,5 +1,4 @@import time-import dataclassesfrom collections.abc import Iteratorfrom datetime import UTC, date, datetime, timedeltafrom typing import Any, Optional@@ -9,6 +8,8 @@ import requestsfrom structlog.types import FilteringBoundLoggerfrom tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@@ -30,10 +31,10 @@ class MatomoRetryableError(Exception):pass+@frozenclass MatomoResumeConfig:- # Visits: the serverTimestamp cursor of the next minTimestamp request.- # Reports: the next unfetched day (yyyy-mm-dd).+ # The next unfetched day (yyyy-mm-dd), for both streams. Visits additionally carry the+ # serverTimestamp cursor that pages within that day.min_timestamp: Optional[int] = Nonenext_date: Optional[str] = None@@ -158,9 +159,6 @@ def get_rows(min_timestamp = int(float(db_incremental_field_last_value))except (TypeError, ValueError):min_timestamp = 0- if resume_config is not None and resume_config.min_timestamp is not None:- min_timestamp = max(min_timestamp, resume_config.min_timestamp)- logger.debug(f"Matomo: resuming visits from minTimestamp {min_timestamp}")# Defer visits that may still be in progress so their action list is# complete when stored; they're picked up by the next sync instead.@@ -168,57 +166,90 @@ def get_rows(today = datetime.now(tz=UTC).date()if min_timestamp > 0:- range_start = datetime.fromtimestamp(min_timestamp, tz=UTC).date()+ # `period=day` resolves in the site's timezone while minTimestamp is UTC, so start a+ # day early: the watermark's UTC date can sit a site-day ahead of visits we still owe.+ # The extra day costs one request and merge dedupes its rows on idVisit.+ day = datetime.fromtimestamp(min_timestamp, tz=UTC).date() - timedelta(days=1)else:- range_start = today - timedelta(days=DEFAULT_BACKFILL_DAYS)-- while True:- batch = call(- config.method,- {- "period": "range",- "date": f"{range_start.isoformat()},{today.isoformat()}",- "filter_limit": VISITS_PAGE_SIZE,- "filter_sort_order": "asc",- "minTimestamp": min_timestamp,- },- )- if not isinstance(batch, list):- return- visits = [row for row in batch if isinstance(row, dict)]-- final_visits = []- for visit in visits:- ts = visit.get("serverTimestamp")- if isinstance(ts, (int, float)) and ts > finality_cutoff:- continue- final_visits.append(visit)-- if final_visits:- yield final_visits-- if len(visits) < VISITS_PAGE_SIZE or not final_visits:- return-- timestamps = [- int(v["serverTimestamp"]) for v in final_visits if isinstance(v.get("serverTimestamp"), (int, float))- ]- if not timestamps:- return- next_min_timestamp = max(timestamps)- # minTimestamp is inclusive: boundary visits at the max second get- # refetched next page and deduped on idVisit (fine). But if a full- # page's visits all fall in a single second, advancing to that- # second returns the same page forever, so step one second past it- # to guarantee progress. The only loss is overflow beyond- # VISITS_PAGE_SIZE visits within that one second — an accepted- # tradeoff against stalling the sync indefinitely.- if next_min_timestamp <= min_timestamp or min(timestamps) == next_min_timestamp:- next_min_timestamp = next_min_timestamp + 1- min_timestamp = next_min_timestamp- # Save state AFTER yielding so a crash re-yields the in-flight- # batch (merge dedupes on idVisit).- resumable_source_manager.save_state(MatomoResumeConfig(min_timestamp=min_timestamp))+ day = today - timedelta(days=DEFAULT_BACKFILL_DAYS)++ if resume_config is not None:+ if resume_config.min_timestamp is not None:+ min_timestamp = max(min_timestamp, resume_config.min_timestamp)+ resumed_day = _to_date(resume_config.next_date) if resume_config.next_date else None+ if resumed_day is not None and resumed_day > day:+ day = resumed_day+ logger.debug(f"Matomo: resuming visits from {day.isoformat()} at minTimestamp {min_timestamp}")++ # One day per request. Matomo reads the raw visit log with every visit's actions+ # attached, so a request spanning months of history can run long enough for the+ # instance's gateway to answer 502 instead (matomo-org/matomo#11592). The same request+ # times out the same way on every retry, so the backfill never gets past it.+ # minTimestamp still pages within a day that holds more than one page.+ while day <= today:+ while True:+ batch = call(+ config.method,+ {+ "period": "day",+ "date": day.isoformat(),+ "filter_limit": VISITS_PAGE_SIZE,+ "filter_sort_order": "asc",+ "minTimestamp": min_timestamp,+ },+ )+ if not isinstance(batch, list):+ return+ visits = [row for row in batch if isinstance(row, dict)]++ final_visits = []+ for visit in visits:+ ts = visit.get("serverTimestamp")+ if isinstance(ts, (int, float)) and ts > finality_cutoff:+ continue+ final_visits.append(visit)++ if final_visits:+ yield final_visits++ if len(visits) < VISITS_PAGE_SIZE:+ break++ if not final_visits:+ # Visits arrive oldest-first, so a full page holding nothing but in-progress+ # visits means every later day is in progress too.+ return++ timestamps = [+ int(v["serverTimestamp"])+ for v in final_visits+ if isinstance(v.get("serverTimestamp"), (int, float))+ ]+ if not timestamps:+ return+ next_min_timestamp = max(timestamps)+ # minTimestamp is inclusive: boundary visits at the max second get+ # refetched next page and deduped on idVisit (fine). But if a full+ # page's visits all fall in a single second, advancing to that+ # second returns the same page forever, so step one second past it+ # to guarantee progress. The only loss is overflow beyond+ # VISITS_PAGE_SIZE visits within that one second — an accepted+ # tradeoff against stalling the sync indefinitely.+ if next_min_timestamp <= min_timestamp or min(timestamps) == next_min_timestamp:+ next_min_timestamp = next_min_timestamp + 1+ min_timestamp = next_min_timestamp+ # Save state AFTER yielding so a crash re-yields the in-flight+ # batch (merge dedupes on idVisit).+ resumable_source_manager.save_state(+ MatomoResumeConfig(min_timestamp=min_timestamp, next_date=day.isoformat())+ )++ day = day + timedelta(days=1)+ if day <= today:+ resumable_source_manager.save_state(+ MatomoResumeConfig(min_timestamp=min_timestamp, next_date=day.isoformat())+ )+ return# Per-day report walk, oldest-first. Recent days re-archive, so# incremental runs re-pull a trailing lookback window.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.pyindex f1d0e87d6856..833f0c76aa17 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,4 +1,4 @@-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom typing import Anyimport pytest@@ -14,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.matomo.matvalidate_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.matomo.settings import (+ DEFAULT_BACKFILL_DAYS,ENDPOINTS,MATOMO_ENDPOINTS,REPORT_LOOKBACK_DAYS,@@ -38,6 +39,10 @@ def _response(body: Any, status_code: int = 200) -> mock.MagicMock:return resp+def _now_ts() -> int:+ return int(datetime.now(tz=UTC).timestamp())++def _final_ts(offset_seconds: int = 0) -> int:# A timestamp safely older than the finality window.return int(datetime.now(tz=UTC).timestamp()) - VISIT_FINALITY_WINDOW_SECONDS - 100 - offset_seconds@@ -91,38 +96,84 @@ class TestValidateCredentials:@mock.patch(f"{_MODULE}.time.sleep")class TestVisits:@mock.patch(f"{_MODULE}.make_tracked_session")- def test_short_batch_yields_and_stops(self, mock_session, mock_sleep):+ def test_backfill_walks_the_default_window_day_by_day(self, mock_session, mock_sleep):+ # Asking for the whole backfill window in one request is what the instance's gateway+ # answers 502 to, identically on every retry, so the backfill never gets past it.+ mock_session.return_value.post.return_value = _response([])++ list(get_rows("https://m.example.com", "1", "token", "visits", mock.MagicMock(), _make_manager()))++ bodies = [call.kwargs["data"] for call in mock_session.return_value.post.call_args_list]+ today = datetime.now(tz=UTC).date()+ assert {body["period"] for body in bodies} == {"day"}+ assert [body["date"] for body in bodies] == [+ (today - timedelta(days=DEFAULT_BACKFILL_DAYS - offset)).isoformat()+ for offset in range(DEFAULT_BACKFILL_DAYS + 1)+ ]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_short_batch_yields_and_moves_to_the_next_day(self, mock_session, mock_sleep):ts = _final_ts()+ watermark = _now_ts()mock_session.return_value.post.return_value = _response([{"idVisit": "1", "serverTimestamp": ts}, {"idVisit": "2", "serverTimestamp": ts + 1}])manager = _make_manager()- batches = list(get_rows("https://m.example.com", "1", "token", "visits", mock.MagicMock(), manager))+ batches = list(+ get_rows(+ "https://m.example.com",+ "1",+ "token",+ "visits",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )+ )- assert [row["idVisit"] for batch in batches for row in batch] == ["1", "2"]- body = mock_session.return_value.post.call_args.kwargs["data"]+ assert [len(batch) for batch in batches] == [2, 2]+ body = mock_session.return_value.post.call_args_list[0].kwargs["data"]assert body["method"] == "Live.getLastVisitsDetails"assert body["filter_sort_order"] == "asc"- assert body["minTimestamp"] == 0+ assert body["minTimestamp"] == watermarkassert body["token_auth"] == "token"@mock.patch(f"{_MODULE}.make_tracked_session")- def test_full_page_advances_min_timestamp_cursor(self, mock_session, mock_sleep):+ def test_full_page_advances_min_timestamp_cursor_within_the_day(self, mock_session, mock_sleep):base = _final_ts(10_000)first_page = [{"idVisit": str(i), "serverTimestamp": base + i} for i in range(VISITS_PAGE_SIZE)]second_page = [{"idVisit": "last", "serverTimestamp": base + VISITS_PAGE_SIZE}]- mock_session.return_value.post.side_effect = [_response(first_page), _response(second_page)]+ mock_session.return_value.post.side_effect = [+ _response(first_page),+ _response(second_page),+ *[_response([]) for _ in range(10)],+ ]manager = _make_manager()- batches = list(get_rows("https://m.example.com", "1", "token", "visits", mock.MagicMock(), manager))+ batches = list(+ get_rows(+ "https://m.example.com",+ "1",+ "token",+ "visits",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=base - 60,+ )+ )assert [len(batch) for batch in batches] == [VISITS_PAGE_SIZE, 1]- second_body = mock_session.return_value.post.call_args_list[1].kwargs["data"]- assert second_body["minTimestamp"] == base + VISITS_PAGE_SIZE - 1- assert [call.args[0].min_timestamp for call in manager.save_state.call_args_list] == [- base + VISITS_PAGE_SIZE - 1- ]+ bodies = [call.kwargs["data"] for call in mock_session.return_value.post.call_args_list]+ # The second request pages within the same day; the third has moved on.+ assert bodies[1]["date"] == bodies[0]["date"]+ assert bodies[1]["minTimestamp"] == base + VISITS_PAGE_SIZE - 1+ assert bodies[2]["date"] > bodies[0]["date"]+ assert manager.save_state.call_args_list[0].args[0] == MatomoResumeConfig(+ min_timestamp=base + VISITS_PAGE_SIZE - 1, next_date=bodies[0]["date"]+ )@mock.patch(f"{_MODULE}.make_tracked_session")def test_full_page_at_one_timestamp_steps_past_cursor(self, mock_session, mock_sleep):@@ -131,15 +182,28 @@ class TestVisits:ts = _final_ts(10_000)first_page = [{"idVisit": str(i), "serverTimestamp": ts} for i in range(VISITS_PAGE_SIZE)]second_page = [{"idVisit": "last", "serverTimestamp": ts + 5}]- mock_session.return_value.post.side_effect = [_response(first_page), _response(second_page)]+ mock_session.return_value.post.side_effect = [+ _response(first_page),+ _response(second_page),+ *[_response([]) for _ in range(10)],+ ]manager = _make_manager()- batches = list(get_rows("https://m.example.com", "1", "token", "visits", mock.MagicMock(), manager))+ batches = list(+ get_rows(+ "https://m.example.com",+ "1",+ "token",+ "visits",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=ts - 60,+ )+ )assert [len(batch) for batch in batches] == [VISITS_PAGE_SIZE, 1]- second_body = mock_session.return_value.post.call_args_list[1].kwargs["data"]- assert second_body["minTimestamp"] == ts + 1- assert [call.args[0].min_timestamp for call in manager.save_state.call_args_list] == [ts + 1]+ assert mock_session.return_value.post.call_args_list[1].kwargs["data"]["minTimestamp"] == ts + 1@mock.patch(f"{_MODULE}.make_tracked_session")def test_still_active_visits_are_deferred(self, mock_session, mock_sleep):@@ -151,13 +215,25 @@ class TestVisits:])- batches = list(get_rows("https://m.example.com", "1", "token", "visits", mock.MagicMock(), _make_manager()))+ batches = list(+ get_rows(+ "https://m.example.com",+ "1",+ "token",+ "visits",+ mock.MagicMock(),+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=_now_ts(),+ )+ )- assert [row["idVisit"] for batch in batches for row in batch] == ["done"]+ assert {row["idVisit"] for batch in batches for row in batch} == {"done"}@mock.patch(f"{_MODULE}.make_tracked_session")- def test_incremental_watermark_sets_min_timestamp(self, mock_session, mock_sleep):+ def test_incremental_watermark_sets_min_timestamp_and_start_day(self, mock_session, mock_sleep):mock_session.return_value.post.return_value = _response([])+ watermark = _now_ts()list(get_rows(@@ -168,18 +244,21 @@ class TestVisits:mock.MagicMock(),_make_manager(),should_use_incremental_field=True,- db_incremental_field_last_value=1700000000,+ db_incremental_field_last_value=watermark,))- body = mock_session.return_value.post.call_args.kwargs["data"]- assert body["minTimestamp"] == 1700000000+ body = mock_session.return_value.post.call_args_list[0].kwargs["data"]+ assert body["minTimestamp"] == watermark+ # A day earlier than the watermark, because `period=day` resolves in the site's timezone.+ assert body["date"] == (datetime.now(tz=UTC).date() - timedelta(days=1)).isoformat()@mock.patch(f"{_MODULE}.make_tracked_session")def test_resume_state_supersedes_older_watermark(self, mock_session, mock_sleep):mock_session.return_value.post.return_value = _response([])+ resumed = _now_ts()- manager = _make_manager(MatomoResumeConfig(min_timestamp=1800000000))+ manager = _make_manager(MatomoResumeConfig(min_timestamp=resumed))list(get_rows("https://m.example.com",@@ -189,12 +268,22 @@ class TestVisits:mock.MagicMock(),manager,should_use_incremental_field=True,- db_incremental_field_last_value=1700000000,+ db_incremental_field_last_value=resumed - 86_400,))- body = mock_session.return_value.post.call_args.kwargs["data"]- assert body["minTimestamp"] == 1800000000+ assert mock_session.return_value.post.call_args_list[0].kwargs["data"]["minTimestamp"] == resumed++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resume_day_restarts_the_walk_where_it_stopped(self, mock_session, mock_sleep):+ mock_session.return_value.post.return_value = _response([])+ today = datetime.now(tz=UTC).date()++ manager = _make_manager(MatomoResumeConfig(min_timestamp=1, next_date=today.isoformat()))+ list(get_rows("https://m.example.com", "1", "token", "visits", mock.MagicMock(), manager))++ assert mock_session.return_value.post.call_count == 1+ assert mock_session.return_value.post.call_args.kwargs["data"]["date"] == today.isoformat()@mock.patch(f"{_MODULE}.time.sleep")