: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(mixpanel): retry export stream drops in-process (#65049)
Tom Owersac40c0bc1ca1
diff --git a/posthog/temporal/data_imports/sources/mixpanel/mixpanel.py b/posthog/temporal/data_imports/sources/mixpanel/mixpanel.pyindex 612125915b10..aa73ff7c610c 100644--- a/posthog/temporal/data_imports/sources/mixpanel/mixpanel.py+++ b/posthog/temporal/data_imports/sources/mixpanel/mixpanel.py@@ -1,3 +1,5 @@+import time+import randomimport dataclassesfrom collections.abc import Iteratorfrom datetime import UTC, date, datetime, timedelta@@ -230,6 +232,64 @@ def _request(return _check_response(response, url, logger)+# The export body is read lazily while iterating `iter_lines`, i.e. outside `_request`'s+# retry. A connection dropped mid-day surfaces there (`requests` wraps the underlying+# `IncompleteRead` as `ChunkedEncodingError`), so it must be retried separately or a single+# truncated download fails the whole sync.+STREAM_MAX_ATTEMPTS = 5+_STREAM_RETRYABLE_ERRORS = (+ requests.exceptions.ChunkedEncodingError,+ requests.ConnectionError,+ requests.ReadTimeout,+)+++def _stream_export_day(+ url: str,+ *,+ username: str,+ secret: str,+ project_id: str,+ from_date: str,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Stream one UTC day of the raw export as `CHUNK_SIZE` batches.++ On a transient mid-stream drop the whole day is re-fetched from the start; already-yielded+ rows are re-emitted, but merge dedupes them on `$insert_id` (the same property the day-level+ resume relies on)."""+ params = {"from_date": from_date, "to_date": from_date, "project_id": project_id}+ for attempt in range(1, STREAM_MAX_ATTEMPTS + 1):+ try:+ with _request(+ "GET", url, username=username, secret=secret, logger=logger, params=params, stream=True+ ) as response:+ batch: list[dict[str, Any]] = []+ for line in response.iter_lines():+ if not line:+ continue+ batch.append(_flatten_event(orjson.loads(line)))+ if len(batch) >= CHUNK_SIZE:+ yield batch+ batch = []+ if batch:+ yield batch+ return+ except _STREAM_RETRYABLE_ERRORS as e:+ if attempt == STREAM_MAX_ATTEMPTS:+ logger.warning(+ f"Mixpanel export: stream for {from_date} dropped ({type(e).__name__}); "+ f"giving up after {STREAM_MAX_ATTEMPTS} attempts"+ )+ raise+ backoff = min(60.0, 2.0 * 2 ** (attempt - 1)) + random.uniform(0, 1)+ logger.warning(+ f"Mixpanel export: stream for {from_date} dropped ({type(e).__name__}); "+ f"re-fetching day (attempt {attempt}/{STREAM_MAX_ATTEMPTS})"+ )+ time.sleep(backoff)++def _iter_export(region: str,username: str,@@ -255,22 +315,14 @@ def _iter_export(logger.debug(f"Mixpanel export: resuming from {resumed_from.isoformat()}")while current <= end_date:- from_date = current.isoformat()- params = {"from_date": from_date, "to_date": from_date, "project_id": project_id}-- with _request(- "GET", url, username=username, secret=secret, logger=logger, params=params, stream=True- ) as response:- batch: list[dict[str, Any]] = []- for line in response.iter_lines():- if not line:- continue- batch.append(_flatten_event(orjson.loads(line)))- if len(batch) >= CHUNK_SIZE:- yield batch- batch = []- if batch:- yield batch+ yield from _stream_export_day(+ url,+ username=username,+ secret=secret,+ project_id=project_id,+ from_date=current.isoformat(),+ logger=logger,+ )# Day complete: advance the resume cursor so a restart skips finished days.next_day = current + timedelta(days=1)diff --git a/posthog/temporal/data_imports/sources/mixpanel/test_mixpanel.py b/posthog/temporal/data_imports/sources/mixpanel/test_mixpanel.pyindex 3d96381022db..81d500403eb9 100644--- a/posthog/temporal/data_imports/sources/mixpanel/test_mixpanel.py+++ b/posthog/temporal/data_imports/sources/mixpanel/test_mixpanel.py@@ -40,12 +40,16 @@ class FakeResponse:lines: Optional[list[bytes]] = None,text: str = "",headers: Optional[dict[str, str]] = None,+ error: Optional[BaseException] = None,) -> None:self.status_code = status_codeself._json = json_dataself._lines = lines or []self.text = textself.headers = headers or {}+ # Raised after the available lines are yielded, to simulate a connection dropped+ # mid-stream while reading the export body.+ self._error = error@propertydef ok(self) -> bool:@@ -55,7 +59,9 @@ class FakeResponse:return self._jsondef iter_lines(self):- return iter(self._lines)+ yield from self._lines+ if self._error is not None:+ raise self._errordef raise_for_status(self) -> None:if not self.ok:@@ -304,6 +310,73 @@ class TestExportIterator:assert [s.from_date for s in manager.saved] == ["2024-01-02"]+class TestExportStreamRetry:+ def _line(self, insert_id: str) -> bytes:+ return orjson.dumps({"event": "A", "properties": {"time": 1, "$insert_id": insert_id}})++ def test_retries_day_on_mid_stream_drop(self) -> None:+ manager = FakeManager()+ day = date(2024, 1, 1)+ incomplete_read = requests.exceptions.ChunkedEncodingError(+ "Connection broken: IncompleteRead(237 bytes read, 275 more expected)"+ )+ failing = FakeResponse(lines=[self._line("i1")], error=incomplete_read)+ succeeding = FakeResponse(lines=[self._line("i1")])+ with (+ patch.object(mp, "_request", side_effect=[failing, succeeding]) as mock_request,+ patch.object(mp.time, "sleep") as mock_sleep,+ ):+ batches = list(+ mp._iter_export("us", "u", "s", "123", LOGGER, manager, start_date=day, end_date=day) # type: ignore[arg-type]+ )++ rows = [row for batch in batches for row in batch]+ assert [r["$insert_id"] for r in rows] == ["i1"]+ # The same day is fetched twice; the dropped attempt yields nothing before the retry.+ assert mock_request.call_count == 2+ assert {c.kwargs["params"]["from_date"] for c in mock_request.call_args_list} == {"2024-01-01"}+ mock_sleep.assert_called_once()+ # Cursor only advances once the day finally completes.+ assert [s.from_date for s in manager.saved] == ["2024-01-02"]++ def test_gives_up_after_max_attempts(self) -> None:+ manager = FakeManager()+ day = date(2024, 1, 1)+ responses = [+ FakeResponse(lines=[], error=requests.exceptions.ChunkedEncodingError("Connection broken"))+ for _ in range(mp.STREAM_MAX_ATTEMPTS)+ ]+ with (+ patch.object(mp, "_request", side_effect=responses) as mock_request,+ patch.object(mp.time, "sleep") as mock_sleep,+ ):+ with pytest.raises(requests.exceptions.ChunkedEncodingError):+ list(+ mp._iter_export("us", "u", "s", "123", LOGGER, manager, start_date=day, end_date=day) # type: ignore[arg-type]+ )++ assert mock_request.call_count == mp.STREAM_MAX_ATTEMPTS+ assert mock_sleep.call_count == mp.STREAM_MAX_ATTEMPTS - 1+ # The failing day's cursor is never advanced.+ assert manager.saved == []++ def test_does_not_retry_unrelated_error(self) -> None:+ manager = FakeManager()+ day = date(2024, 1, 1)+ failing = FakeResponse(lines=[], error=ValueError("malformed payload"))+ with (+ patch.object(mp, "_request", side_effect=[failing]) as mock_request,+ patch.object(mp.time, "sleep") as mock_sleep,+ ):+ with pytest.raises(ValueError):+ list(+ mp._iter_export("us", "u", "s", "123", LOGGER, manager, start_date=day, end_date=day) # type: ignore[arg-type]+ )++ assert mock_request.call_count == 1+ mock_sleep.assert_not_called()++class TestEngageIterator:def test_paginates_with_session_id_and_saves_state(self) -> None:manager = FakeManager()