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 mailjet statcounters and bouncestatistics tables (#114905)

Tom Owersb7c46fd60728
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 e0876016b1e1..c16cf6292a52 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
@@ -5394,10 +5394,10 @@ Today (10): `campaign`, `campaigndraft`, `clickstatistics`, `contact`, `contactm
Diffed against: <https://dev.mailjet.com/email/reference/messages/>
-- [ ] `statcounters` — Mailjet's unified stats endpoint - sent/open/click/bounce counters sliced by campaign, list or sender (high)
-- [ ] `messagesentstatistics` — Per-message delivery outcome metrics, the base fact table for deliverability analysis (high)
-- [ ] `messagehistory` — Per-message event/state transition log (sent, opened, clicked, bounced, spam) (high)
-- [ ] `bouncestatistics` — Bounce events with reason codes; we sync clicks and opens but not bounces (high)
+- [x] `statcounters` — Mailjet's unified stats endpoint - sent/open/click/bounce counters sliced by campaign, list or sender (high). Added as `statcounters`: daily, event-timed counters for the whole API key.
+- [ ] `messagesentstatistics` — skipped: Mailjet lists it as a deprecated legacy statistics resource replaced by `/statcounters`.
+- [ ] `messagehistory` — skipped: only exposed as `/messagehistory/{message_ID}`, so it would take one request per message ever sent. The webhook-fed `messageevent` table already carries this event stream.
+- [x] `bouncestatistics` — Bounce events with reason codes; we sync clicks and opens but not bounces (high)
- [ ] `campaignstatistics` — Aggregate performance per campaign, resolving the campaign rows we already sync (high)
- [ ] `contactdata` — Actual custom property values per contact - we sync contactmetadata (the schema) but not the values (high)
- [ ] `openstatistics` — Open events aggregated per message/campaign, complementing the openinformation rows we sync (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/canonical_descriptions.py
index d08d3b9d83a9..737e3f4aea7d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/canonical_descriptions.py
@@ -148,6 +148,50 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"UserAgent": "The user agent of the device that clicked the link.",
},
},
+ "bouncestatistics": {
+ "description": "A bounce event recording that a message could not be delivered to a recipient in Mailjet.",
+ "docs_url": "https://dev.mailjet.com/openapi/openapi-mailjet/message-events/get_v3_bouncestatistics",
+ "columns": {
+ "ID": "Unique identifier of the bounced message.",
+ "ContactID": "The identifier of the recipient contact the bounce is linked to.",
+ "CampaignID": "The identifier of the campaign the bounce is linked to.",
+ "BouncedAt": "Time the bounce occurred.",
+ "IsBlocked": "Whether the contact was blocked as a result of this bounce.",
+ "IsStatePermanent": "Whether this is a permanent (hard) bounce.",
+ "StateID": "The bounce reason code, such as 1 for an unknown user or 4 for an invalid domain.",
+ },
+ },
+ "statcounters": {
+ "description": (
+ "Daily delivery and engagement counters for the whole Mailjet API key, counted by the "
+ "day each event happened."
+ ),
+ "docs_url": "https://dev.mailjet.com/openapi/openapi-mailjet/statistics/get_v3_statcounters",
+ "columns": {
+ "Timeslice": "Start of the day the counters cover.",
+ "APIKeyID": "The identifier of the API key the counters belong to.",
+ "SourceID": "The identifier of the aggregation source. For API key counters, the API key.",
+ "Total": "Total number of processed messages.",
+ "MessageSentCount": "Number of sent messages.",
+ "MessageQueuedCount": "Number of queued messages.",
+ "MessageDeferredCount": "Number of deferred messages.",
+ "MessageBlockedCount": "Number of blocked messages.",
+ "MessageSoftBouncedCount": "Number of soft-bounced messages.",
+ "MessageHardBouncedCount": "Number of hard-bounced messages.",
+ "MessageOpenedCount": "Number of opened messages.",
+ "MessageClickedCount": "Number of clicked messages.",
+ "MessageSpamCount": "Number of messages marked as spam.",
+ "MessageUnsubscribedCount": "Number of messages with unsubscribe requests.",
+ "MessageWorkFlowExitedCount": "Number of contacts that exited a workflow.",
+ "EventOpenedCount": "Total number of open events.",
+ "EventClickedCount": "Total number of click events.",
+ "EventSpamCount": "Total number of spam reports.",
+ "EventUnsubscribedCount": "Total number of unsubscriptions.",
+ "EventWorkflowExitedCount": "Total number of workflow exits.",
+ "EventOpenDelay": "Sum of the delays in seconds between sending and the first open, over all opened messages.",
+ "EventClickDelay": "Sum of the delays in seconds between sending and the first click, over all clicked messages.",
+ },
+ },
"messageevent": {
"description": (
"A delivery or engagement event pushed by the Mailjet Event API: sent, open, click, "
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/mailjet.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/mailjet.py
index 4407da4c16c3..4a9c1fc3971e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/mailjet.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/mailjet.py
@@ -1,6 +1,7 @@
import base64
import secrets
import dataclasses
+from collections.abc import Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional
from urllib.parse import urlsplit, urlunsplit
@@ -32,6 +33,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.web
from products.warehouse_sources.backend.temporal.data_imports.sources.mailjet.settings import (
MAILJET_ENDPOINTS,
MAILJET_WEBHOOK_EVENTS,
+ STATCOUNTERS_EARLIEST_UNIX_TS,
+ STATCOUNTERS_ENDPOINT,
+ STATCOUNTERS_PARAMS,
+ STATCOUNTERS_WINDOW_DAYS,
WEBHOOK_PRIMARY_KEY,
WEBHOOK_TABLE_NAME,
MailjetEndpointConfig,
@@ -40,6 +45,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mailjet.se
MAILJET_BASE_URL = "https://api.mailjet.com/v3/REST"
WEBHOOK_PATH = "/eventcallbackurl"
REQUEST_TIMEOUT_SECONDS = 30
+DAY_SECONDS = 24 * 60 * 60
# Mailjet does not sign deliveries. Its documented way to prove a delivery came from Mailjet is
# HTTP basic credentials embedded in the registered callback URL, which Mailjet then sends as an
@@ -50,12 +56,14 @@ WEBHOOK_BASIC_AUTH_USERNAME = "posthog"
LOGGER = structlog.get_logger(__name__)
[email protected](frozen=True)
class MailjetResumeConfig:
offset: int = 0
# The schema this offset belongs to. A single job can sync multiple schemas, so we
# guard against applying one endpoint's offset to another on resume.
endpoint: Optional[str] = None
+ # Start of the next `/statcounters` window to fetch (Unix timestamp).
+ from_ts: Optional[int] = None
def _get_headers(api_key: str, secret_key: str) -> dict[str, str]:
@@ -154,6 +162,73 @@ def _webhook_source(endpoint: str, webhook_source_manager: WebhookSourceManager)
)
+def _statcounters_start(db_incremental_field_last_value: Any) -> int:
+ value = db_incremental_field_last_value
+ if isinstance(value, str):
+ try:
+ value = datetime.fromisoformat(value)
+ except ValueError:
+ value = None
+ last_ts = _to_unix_ts(value)
+ if last_ts is None:
+ return STATCOUNTERS_EARLIEST_UNIX_TS
+ # Re-read the last synced day: it was probably still in progress when it was synced.
+ return max(last_ts - last_ts % DAY_SECONDS, STATCOUNTERS_EARLIEST_UNIX_TS)
+
+
+def _statcounters_source(
+ api_key: str,
+ secret_key: str,
+ endpoint: str,
+ resumable_source_manager: ResumableSourceManager[MailjetResumeConfig],
+ db_incremental_field_last_value: Any,
+) -> SourceResponse:
+ config = MAILJET_ENDPOINTS[endpoint]
+ start = _statcounters_start(db_incremental_field_last_value)
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None and resume.endpoint == endpoint and resume.from_ts:
+ start = resume.from_ts
+
+ def items() -> Iterator[list[dict[str, Any]]]:
+ session = make_tracked_session(headers=_get_headers(api_key, secret_key), redact_values=(secret_key,))
+ now = int(datetime.now(UTC).timestamp())
+ window_start = start
+ while window_start <= now:
+ window_end = window_start + STATCOUNTERS_WINDOW_DAYS * DAY_SECONDS
+ params: dict[str, str | int] = {
+ **STATCOUNTERS_PARAMS,
+ "FromTS": window_start,
+ # Windows must not overlap, or a full refresh writes the boundary day twice.
+ "ToTS": min(window_end - 1, now),
+ "Limit": config.page_size,
+ }
+ response = session.get(f"{MAILJET_BASE_URL}/{config.path}", params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+ response.raise_for_status()
+ rows = sorted(
+ (row for row in response.json().get("Data") or [] if isinstance(row, dict)),
+ key=lambda row: str(row.get("Timeslice") or ""),
+ )
+ resumable_source_manager.save_state(MailjetResumeConfig(endpoint=endpoint, from_ts=window_end))
+ if rows:
+ yield rows
+ else:
+ resumable_source_manager.safe_point()
+ window_start = window_end
+
+ return SourceResponse(
+ name=endpoint,
+ items=items,
+ primary_keys=[config.primary_key],
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ sort_mode="asc",
+ )
+
+
def mailjet_source(
api_key: str,
secret_key: str,
@@ -168,6 +243,15 @@ def mailjet_source(
if endpoint == WEBHOOK_TABLE_NAME:
return _webhook_source(endpoint, webhook_source_manager)
+ if endpoint == STATCOUNTERS_ENDPOINT:
+ return _statcounters_source(
+ api_key,
+ secret_key,
+ endpoint,
+ resumable_source_manager,
+ db_incremental_field_last_value if should_use_incremental_field else None,
+ )
+
config = MAILJET_ENDPOINTS[endpoint]
limit = config.page_size
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/settings.py
index c161b3364c4e..c4d47d2db1a9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/settings.py
@@ -94,7 +94,39 @@ MAILJET_ENDPOINTS: dict[str, MailjetEndpointConfig] = {
from_ts_field="ClickedAt",
incremental_fields=[_datetime_incremental_field("ClickedAt")],
),
+ "bouncestatistics": MailjetEndpointConfig(
+ name="bouncestatistics",
+ path="bouncestatistics",
+ partition_key="BouncedAt",
+ sort="BouncedAt",
+ from_ts_field="BouncedAt",
+ incremental_fields=[_datetime_incremental_field("BouncedAt")],
+ ),
+ # Not offset-paginated like the rest: `/statcounters` takes a mandatory FromTS/ToTS window per
+ # request, so `mailjet.py` walks it window by window. One row per day for the whole API key.
+ "statcounters": MailjetEndpointConfig(
+ name="statcounters",
+ path="statcounters",
+ primary_key="Timeslice",
+ partition_key="Timeslice",
+ sort=None,
+ incremental_fields=[_datetime_incremental_field("Timeslice")],
+ ),
+}
+
+STATCOUNTERS_ENDPOINT = "statcounters"
+# Event timing makes each day's counters final once the day ends, so an incremental sync only has
+# to re-read the last synced day. Message timing would keep changing old days as late opens and
+# clicks arrive.
+STATCOUNTERS_PARAMS: dict[str, str] = {
+ "CounterSource": "APIKey",
+ "CounterTiming": "Event",
+ "CounterResolution": "Day",
}
+# Mailjet caps a Day-resolution window at 100 days; stay under it.
+STATCOUNTERS_WINDOW_DAYS = 90
+# Mailjet's current statistics system holds no data from before its April 2018 launch.
+STATCOUNTERS_EARLIEST_UNIX_TS = 1522540800 # 2018-04-01T00:00:00Z
# The Event API pushes per-recipient engagement and delivery events. Mailjet exposes no list
# endpoint for that stream — `/openinformation` and `/clickstatistics` cover opens and clicks
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/tests/test_mailjet.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/tests/test_mailjet.py
index 26448a51a154..e9df74005bb7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/tests/test_mailjet.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/tests/test_mailjet.py
@@ -4,6 +4,7 @@ from datetime import UTC, datetime
from typing import Any
import pytest
+import time_machine
from unittest import mock
from parameterized import parameterized
@@ -26,6 +27,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mailjet.ma
from products.warehouse_sources.backend.temporal.data_imports.sources.mailjet.settings import (
MAILJET_ENDPOINTS,
MAILJET_WEBHOOK_EVENTS,
+ STATCOUNTERS_EARLIEST_UNIX_TS,
+ STATCOUNTERS_ENDPOINT,
WEBHOOK_TABLE_NAME,
)
@@ -92,6 +95,7 @@ def _rows(source_response) -> list[dict[str, Any]]:
LIMIT = MAILJET_ENDPOINTS["contact"].page_size
+OFFSET_PAGINATED_ENDPOINTS = [name for name in MAILJET_ENDPOINTS if name != STATCOUNTERS_ENDPOINT]
class TestToUnixTs:
@@ -128,7 +132,7 @@ class TestOffsetPagination:
assert params[0]["Limit"] == LIMIT
assert params[1]["Offset"] == LIMIT
- @parameterized.expand([(name,) for name in MAILJET_ENDPOINTS])
+ @parameterized.expand([(name,) for name in OFFSET_PAGINATED_ENDPOINTS])
@mock.patch(CLIENT_SESSION_PATCH)
def test_sort_param_sent(self, endpoint: str, MockSession) -> None:
session = MockSession.return_value
@@ -173,6 +177,101 @@ class TestIncremental:
assert params[0]["FromTS"] == 1767225600
+DAY = 24 * 60 * 60
+WINDOW = 90 * DAY
+
+
+class TestStatcounters:
+ def _session(self, mock_session: mock.MagicMock, pages: list[list[dict[str, Any]]]) -> mock.MagicMock:
+ session = mock_session.return_value
+ session.get.side_effect = [_json_response({"Data": rows, "Count": len(rows)}) for rows in pages]
+ return session
+
+ @time_machine.travel(datetime.fromtimestamp(STATCOUNTERS_EARLIEST_UNIX_TS + WINDOW + 5 * DAY, tz=UTC), tick=False)
+ @mock.patch(MAILJET_SESSION_PATCH)
+ def test_full_refresh_walks_non_overlapping_windows_up_to_now(self, mock_session) -> None:
+ session = self._session(
+ mock_session,
+ [
+ [{"Timeslice": "2018-04-02T00:00:00Z"}, {"Timeslice": "2018-04-01T00:00:00Z"}],
+ [],
+ ],
+ )
+ manager = _make_manager()
+
+ rows = _rows(_source(STATCOUNTERS_ENDPOINT, manager))
+
+ now = STATCOUNTERS_EARLIEST_UNIX_TS + WINDOW + 5 * DAY
+ windows = [
+ (call.kwargs["params"]["FromTS"], call.kwargs["params"]["ToTS"]) for call in session.get.call_args_list
+ ]
+ assert windows == [
+ (STATCOUNTERS_EARLIEST_UNIX_TS, STATCOUNTERS_EARLIEST_UNIX_TS + WINDOW - 1),
+ (STATCOUNTERS_EARLIEST_UNIX_TS + WINDOW, now),
+ ]
+ params = session.get.call_args.kwargs["params"]
+ assert (params["CounterSource"], params["CounterTiming"], params["CounterResolution"]) == (
+ "APIKey",
+ "Event",
+ "Day",
+ )
+ # sort_mode="asc" relies on rows arriving oldest first.
+ assert [row["Timeslice"] for row in rows] == ["2018-04-01T00:00:00Z", "2018-04-02T00:00:00Z"]
+ assert [call.args[0].from_ts for call in manager.save_state.call_args_list] == [
+ STATCOUNTERS_EARLIEST_UNIX_TS + WINDOW,
+ STATCOUNTERS_EARLIEST_UNIX_TS + 2 * WINDOW,
+ ]
+ # The empty window yields nothing, so it has to give the pipeline a chance to hand off.
+ manager.safe_point.assert_called_once()
+
+ @parameterized.expand(
+ [
+ ("full_refresh", False, None, None, STATCOUNTERS_EARLIEST_UNIX_TS),
+ ("watermark_rereads_its_day", True, datetime(2026, 1, 1, 15, 30, tzinfo=UTC), None, 1767225600),
+ ("iso_string_watermark", True, "2026-01-01T15:30:00Z", None, 1767225600),
+ ("watermark_before_earliest", True, datetime(2010, 1, 1, tzinfo=UTC), None, STATCOUNTERS_EARLIEST_UNIX_TS),
+ (
+ "resume_wins_over_watermark",
+ True,
+ datetime(2026, 1, 1, tzinfo=UTC),
+ MailjetResumeConfig(endpoint=STATCOUNTERS_ENDPOINT, from_ts=1767312000),
+ 1767312000,
+ ),
+ (
+ "resume_of_another_endpoint_ignored",
+ False,
+ None,
+ MailjetResumeConfig(endpoint="contact", from_ts=1767312000),
+ STATCOUNTERS_EARLIEST_UNIX_TS,
+ ),
+ ]
+ )
+ @time_machine.travel("2026-01-03T00:00:00Z", tick=False)
+ @mock.patch(MAILJET_SESSION_PATCH)
+ def test_first_window_start(
+ self,
+ _name: str,
+ incremental: bool,
+ last_value: object,
+ resume: MailjetResumeConfig | None,
+ expected_from_ts: int,
+ mock_session,
+ ) -> None:
+ session = mock_session.return_value
+ session.get.return_value = _json_response({"Data": []})
+
+ _rows(
+ _source(
+ STATCOUNTERS_ENDPOINT,
+ _make_manager(resume),
+ should_use_incremental_field=incremental,
+ db_incremental_field_last_value=last_value,
+ )
+ )
+
+ assert session.get.call_args_list[0].kwargs["params"]["FromTS"] == expected_from_ts
+
+
class TestSourceResponseShape:
@parameterized.expand([(name,) for name in MAILJET_ENDPOINTS])
def test_source_response_shape(self, endpoint: str) -> None: