: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
feat(data-warehouse): implement mailjet import source (#61587)
Tom Owersa5aed9b2be00
diff --git a/posthog/temporal/data_imports/sources/mailjet/mailjet.py b/posthog/temporal/data_imports/sources/mailjet/mailjet.pyindex 9eeea42faf89..3c781f611410 100644--- a/posthog/temporal/data_imports/sources/mailjet/mailjet.py+++ b/posthog/temporal/data_imports/sources/mailjet/mailjet.py@@ -8,7 +8,6 @@ import requestsfrom structlog.types import FilteringBoundLoggerfrom tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter-from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcherfrom posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponsefrom posthog.temporal.data_imports.sources.common.http import make_tracked_sessionfrom posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager@@ -112,9 +111,8 @@ def get_rows(resumable_source_manager: ResumableSourceManager[MailjetResumeConfig],should_use_incremental_field: bool = False,db_incremental_field_last_value: Any = None,-) -> Iterator[Any]:+) -> Iterator[list[dict[str, Any]]]:config = MAILJET_ENDPOINTS[endpoint]- batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)# One tracked session for the whole sync — keeps urllib3's TLS connection warm# across pages, and every request inherits the basic-auth headers.@@ -138,16 +136,12 @@ def get_rows(total = data.get("Total")if rows:- batcher.batch(rows)+ # Yield the page as-is and let the pipeline batch it. Persist state only after the+ # yield so a crash re-yields the last page (deduped on the primary key via merge)+ # rather than skipping it.+ yield rowsoffset += len(rows)-- if batcher.should_yield():- yield batcher.get_table()- # The batcher flushes its whole buffer into the yielded table, so once we've- # yielded, `offset` covers exactly the rows emitted to the pipeline. Persisting- # state only after a yield avoids skipping buffered-but-unyielded rows if the- # process stops mid-sync (a re-yielded row is deduped on merge).- resumable_source_manager.save_state(MailjetResumeConfig(offset=offset, endpoint=endpoint))+ resumable_source_manager.save_state(MailjetResumeConfig(offset=offset, endpoint=endpoint))# Terminate on a short/empty page, or once Total is reached (guards the# exact-multiple-of-Limit case so we issue at most one extra empty request).@@ -156,10 +150,6 @@ def get_rows(if total is not None and offset >= total:break- if batcher.should_yield(include_incomplete_chunk=True):- yield batcher.get_table()- resumable_source_manager.save_state(MailjetResumeConfig(offset=offset, endpoint=endpoint))-def mailjet_source(api_key: str,diff --git a/posthog/temporal/data_imports/sources/mailjet/tests/test_mailjet.py b/posthog/temporal/data_imports/sources/mailjet/tests/test_mailjet.pyindex 118146ddc773..25f5ebe9fc7c 100644--- a/posthog/temporal/data_imports/sources/mailjet/tests/test_mailjet.py+++ b/posthog/temporal/data_imports/sources/mailjet/tests/test_mailjet.py@@ -98,9 +98,9 @@ class TestOffsetPagination:def test_single_short_page_stops(self, mock_session: MagicMock) -> None:mock_session.return_value.get.return_value = _mock_response(json_payload=_page(3))- tables = list(get_rows("key", "secret", "contact", MagicMock(), _mock_manager()))+ pages = list(get_rows("key", "secret", "contact", MagicMock(), _mock_manager()))- assert sum(t.num_rows for t in tables) == 3+ assert sum(len(t) for t in pages) == 3assert mock_session.return_value.get.call_count == 1@patch("posthog.temporal.data_imports.sources.mailjet.mailjet.make_tracked_session")@@ -111,9 +111,9 @@ class TestOffsetPagination:_mock_response(json_payload={"Data": [{"ID": i} for i in range(2)], "Total": limit + 2}),]- tables = list(get_rows("key", "secret", "contact", MagicMock(), _mock_manager()))+ pages = list(get_rows("key", "secret", "contact", MagicMock(), _mock_manager()))- assert sum(t.num_rows for t in tables) == limit + 2+ assert sum(len(t) for t in pages) == limit + 2assert mock_session.return_value.get.call_count == 2first_params = mock_session.return_value.get.call_args_list[0].kwargs["params"]second_params = mock_session.return_value.get.call_args_list[1].kwargs["params"]@@ -128,18 +128,18 @@ class TestOffsetPagination:json_payload={"Data": [{"ID": i} for i in range(limit)], "Total": limit})- tables = list(get_rows("key", "secret", "contact", MagicMock(), _mock_manager()))+ pages = list(get_rows("key", "secret", "contact", MagicMock(), _mock_manager()))- assert sum(t.num_rows for t in tables) == limit+ assert sum(len(t) for t in pages) == limitassert mock_session.return_value.get.call_count == 1@patch("posthog.temporal.data_imports.sources.mailjet.mailjet.make_tracked_session")def test_empty_first_page_yields_nothing(self, mock_session: MagicMock) -> None:mock_session.return_value.get.return_value = _mock_response(json_payload={"Data": [], "Total": 0})- tables = list(get_rows("key", "secret", "contact", MagicMock(), _mock_manager()))+ pages = list(get_rows("key", "secret", "contact", MagicMock(), _mock_manager()))- assert tables == []+ assert pages == []assert mock_session.return_value.get.call_count == 1@patch("posthog.temporal.data_imports.sources.mailjet.mailjet.make_tracked_session")@@ -183,21 +183,22 @@ class TestResume:assert saved.endpoint == "contact"@patch("posthog.temporal.data_imports.sources.mailjet.mailjet.make_tracked_session")- def test_state_saved_only_after_yield(self, mock_session: MagicMock) -> None:- # Three full pages (each == page_size) with chunk threshold 2000: the batcher yields a- # 2000-row chunk after page 2 and flushes the remaining 1000 at the end. State must only- # advance to offsets that have actually been yielded — never to a page still buffered.+ def test_state_saved_after_each_page_yield(self, mock_session: MagicMock) -> None:+ # Each page is yielded straight to the pipeline and state is persisted only after the+ # yield, so every saved offset equals the count of rows already emitted. A crash re-yields+ # the last page, which merge dedupes on the primary key.limit = MAILJET_ENDPOINTS["contact"].page_size- pages = [{"Data": [{"ID": i} for i in range(p * limit, (p + 1) * limit)], "Total": 3 * limit} for p in range(3)]- mock_session.return_value.get.side_effect = [_mock_response(json_payload=p) for p in pages]+ payloads = [+ {"Data": [{"ID": i} for i in range(p * limit, (p + 1) * limit)], "Total": 3 * limit} for p in range(3)+ ]+ mock_session.return_value.get.side_effect = [_mock_response(json_payload=p) for p in payloads]manager = _mock_manager()- tables = list(get_rows("key", "secret", "contact", MagicMock(), manager))+ pages = list(get_rows("key", "secret", "contact", MagicMock(), manager))- assert sum(t.num_rows for t in tables) == 3 * limit+ assert sum(len(t) for t in pages) == 3 * limitsaved_offsets = [call.args[0].offset for call in manager.save_state.call_args_list]- # Buffered-but-unyielded offset `limit` must never be persisted.- assert saved_offsets == [2 * limit, 3 * limit]+ assert saved_offsets == [limit, 2 * limit, 3 * limit]class TestIncremental:@@ -266,9 +267,9 @@ class TestRetryable:_mock_response(json_payload=_page(1)),]- tables = list(get_rows("key", "secret", "contact", MagicMock(), _mock_manager()))+ pages = list(get_rows("key", "secret", "contact", MagicMock(), _mock_manager()))- assert sum(t.num_rows for t in tables) == 1+ assert sum(len(t) for t in pages) == 1assert mock_session.return_value.get.call_count == 2@patch("posthog.temporal.data_imports.sources.mailjet.mailjet.make_tracked_session")