: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): classify a truncated export and stop re-downloading the day (#95692)
posthog[bot]724f587d264c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.pyindex 060649d24198..73175bfa6e49 100644--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py@@ -257,6 +257,13 @@ Transient_Error_Messages: dict[str, str] = {"502 Server Error": TRANSIENT_VENDOR_UNAVAILABLE_MESSAGE,"503 Server Error": TRANSIENT_VENDOR_UNAVAILABLE_MESSAGE,"504 Server Error": TRANSIENT_VENDOR_UNAVAILABLE_MESSAGE,+ # Mixpanel signals a server-side abort inside an already-committed 200 body, so the export+ # stops part-way through a day (mixpanel.py `EXPORT_TRUNCATED_ERROR`). The day is re-fetched+ # in-process first; this copy is what the customer reads once those retries run out.+ "Mixpanel export: stream ended early": (+ "Mixpanel stopped sending a day of events before the export finished. This is on "+ "Mixpanel's side and usually clears on its own; the next sync runs on schedule."+ ),}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/mixpanel.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/mixpanel.pyindex ddeab8957db9..7fe89fc6b2c8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/mixpanel.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/mixpanel.py@@ -258,13 +258,21 @@ def _request(return _check_response(response, url, logger)+# Mixpanel commits a 200 before it starts streaming, so a server-side abort can only be+# signalled inside the body: it appends this plain-text marker after the JSONL rows instead+# of failing the request.+EXPORT_TERMINATED_MARKER = b"terminated early"++# Stable, date-free prefix of the raised message, so `get_retryable_errors` and the shared+# transient-message map can both match it.+EXPORT_TRUNCATED_ERROR = "Mixpanel export: stream ended early"++class MixpanelExportTruncatedError(Exception):- """The export stream ended in a line that isn't an event.+ """Mixpanel aborted the export part-way through a day.- Mixpanel commits a 200 before it starts streaming, so a server-side abort can only be- signalled inside the body: it appends a plain-text marker (`terminated early`) after the- JSONL rows instead of failing the request. That leaves a partial day, which is the same- situation as a dropped connection and is re-fetched the same way."""+ That leaves a partial day, which is the same situation as a dropped connection and is+ re-fetched the same way."""# The export body is read lazily while iterating `iter_lines`, i.e. outside `_request`'s@@ -307,9 +315,12 @@ def _stream_export_day(try:event = orjson.loads(line)except orjson.JSONDecodeError as e:- raise MixpanelExportTruncatedError(- f"Mixpanel export: stream for {from_date} ended with a line that is not an event"- ) from e+ # Only Mixpanel's abort marker means a partial day. Any other line the+ # parser rejects is an export shape we do not know, and re-downloading+ # the day cannot turn it into events, so let it surface instead.+ if EXPORT_TERMINATED_MARKER not in line.lower():+ raise+ raise MixpanelExportTruncatedError(f"{EXPORT_TRUNCATED_ERROR} for {from_date}") from ebatch.append(_flatten_event(event))if len(batch) >= CHUNK_SIZE:yield batchdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/source.pyindex 0682f6884abf..cd061d39b468 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/source.py@@ -23,6 +23,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_MixpanelSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.mixpanel.mixpanel import (+ EXPORT_TRUNCATED_ERROR,MixpanelResumeConfig,mixpanel_source,validate_credentials as validate_mixpanel_credentials,@@ -182,8 +183,9 @@ Authenticate with a [Mixpanel Service Account](https://developer.mixpanel.com/redef get_retryable_errors(self) -> set[str]:# A 429 (rate limit) or 5xx is retried internally honoring Retry-After; if those retries# still exhaust, the failure is transient and self-recovering, so let Temporal retry the- # activity without surfacing it as tracked exception noise.- return {"Mixpanel API error (retryable)"}+ # activity without surfacing it as tracked exception noise. An export Mixpanel aborts+ # mid-body reaches us on the same contract, after `_stream_export_day` re-fetches the day.+ return {"Mixpanel API error (retryable)", EXPORT_TRUNCATED_ERROR}def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MixpanelResumeConfig]:return ResumableSourceManager[MixpanelResumeConfig](inputs, MixpanelResumeConfig)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/test_mixpanel.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/test_mixpanel.pyindex 25265494784b..367242d33bbc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/test_mixpanel.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/test_mixpanel.py@@ -411,7 +411,7 @@ class TestExportStreamRetry:# Cursor only advances once the day finally completes.assert [s.from_date for s in manager.saved] == ["2024-01-02"]- def test_retries_day_when_stream_ends_in_a_non_event_line(self) -> None:+ def test_retries_day_when_the_stream_carries_the_abort_marker(self) -> None:manager = FakeManager()day = date(2024, 1, 1)truncated = FakeResponse(lines=[self._line("i1"), b"terminated early"])@@ -440,6 +440,32 @@ class TestExportStreamRetry:mock_sleep.assert_called_once()assert [s.from_date for s in manager.saved] == ["2024-01-02"]+ def test_does_not_retry_a_line_without_the_abort_marker(self) -> None:+ manager = FakeManager()+ day = date(2024, 1, 1)+ unparseable = FakeResponse(lines=[self._line("i1"), b"<html>gateway</html>"])+ with (+ patch.object(mp, "_request", side_effect=[unparseable]) as mock_request,+ patch.object(mp.time, "sleep") as mock_sleep,+ ):+ with pytest.raises(orjson.JSONDecodeError):+ list(+ mp._iter_export(+ "us",+ "u",+ "s",+ "123",+ LOGGER,+ manager, # type: ignore[arg-type]+ start_date=day,+ end_date=day,+ api_version=MIXPANEL_API_VERSION_V1,+ )+ )++ assert mock_request.call_count == 1+ mock_sleep.assert_not_called()+def test_gives_up_after_max_attempts(self) -> None:manager = FakeManager()day = date(2024, 1, 1)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/test_mixpanel_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/test_mixpanel_source.pyindex 253c5551add9..5e5420fb9816 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/test_mixpanel_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/test_mixpanel_source.py@@ -5,11 +5,13 @@ from unittest.mock import MagicMock, patchimport structlogfrom parameterized import parameterized+from products.warehouse_sources.backend.temporal.data_imports.external_data_job import Transient_Error_Messagesfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputsfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mixpanel import (MixpanelSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.mixpanel import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.mixpanel.mixpanel import EXPORT_TRUNCATED_ERRORfrom products.warehouse_sources.backend.temporal.data_imports.sources.mixpanel.source import MixpanelSourceLOGGER = structlog.get_logger()@@ -155,3 +157,12 @@ class TestNonRetryableErrors:)def test_transient_failures_stay_retryable(self, _name: str, other_error: str) -> None:assert not any(key in other_error for key in self.source.get_non_retryable_errors())++ def test_truncated_export_is_classified_retryable(self) -> None:+ observed_error = f"{EXPORT_TRUNCATED_ERROR} for 2024-01-01"+ assert not any(key in observed_error for key in self.source.get_non_retryable_errors())+ assert any(key in observed_error for key in self.source.get_retryable_errors())++ def test_truncated_export_has_customer_facing_copy(self) -> None:+ # The shared map keys on a literal, so a reworded error would silently lose its copy.+ assert EXPORT_TRUNCATED_ERROR in Transient_Error_Messages