: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(mailgun): send a begin time for events and fail when every domain is skipped (#115942)
posthog[bot]b7b6279bb799
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/mailgun.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/mailgun.pyindex be1852516067..cd4cfede62ed 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/mailgun.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/mailgun.py@@ -58,6 +58,9 @@ MAX_RETRY_AFTER_SECONDS = 120# ~30 minutes as incomplete. Bounding `end` keeps the incremental watermark behind the# consistency horizon so late-arriving events aren't skipped on the next sync.EVENTS_CONSISTENCY_LAG_SECONDS = 30 * 60+# Mailgun keeps events for its plan's retention, at most 30 days on standard plans. A sync with no+# watermark starts there, because the Events API needs an explicit `begin` for an ascending range.+EVENTS_LOOKBACK_DAYS = 30# Backstop for a `paging.next` chain that never terminates and never repeats a URL, which the# seen-URL guard below can't catch. Sized far above any real page count (the largest paging# endpoint fetches 1000 rows a page) so it only trips on a runaway.@@ -194,8 +197,11 @@ def _initial_url(# Ascending creation order keeps fetched pages stable and lets the incremental# watermark advance monotonically.params["ascending"] = "yes"- end = int(time.time()) - EVENTS_CONSISTENCY_LAG_SECONDS- if begin is not None and begin >= end:+ now = int(time.time())+ end = now - EVENTS_CONSISTENCY_LAG_SECONDS+ if begin is None:+ begin = now - EVENTS_LOOKBACK_DAYS * 24 * 60 * 60+ elif begin >= end:# Watermark is already inside the consistency lag window; nothing safe to fetch.return Noneparams["begin"] = begin@@ -299,6 +305,10 @@ def _fetch_page(SKIPPABLE_DOMAIN_STATUS_CODES = frozenset({400, 401, 403})+class MailgunAllDomainsSkippedError(Exception):+ pass++def _is_skippable_domain_error(config: MailgunEndpointConfig, domain: Optional[str], error: requests.HTTPError) -> bool:"""Whether a failed domain-scoped request should skip that domain instead of failing the sync.@@ -425,6 +435,10 @@ def get_rows(# empty one. Without this guard the chain re-yields the same rows until the activity is killed,# and every re-yielded row is billed as a synced row even though the merge dedupes them away.seen_urls: set[str] = set()+ # A resumed run can't see the domains an earlier attempt already read, so it doesn't count.+ count_domains = resume_config is None and config.domain_scoped+ queried_domains = 0+ skipped_domains = 0while current_url is not None or pending_domains:if current_url is None:@@ -435,6 +449,7 @@ def get_rows(current_domain = Noneresumable_source_manager.save_state(MailgunResumeConfig(pending_domains=pending_domains))continue+ queried_domains += 1loop_reason: Optional[str] = Noneif current_url in seen_urls:@@ -464,6 +479,7 @@ def get_rows(f"request returned {error.response.status_code if error.response is not None else '?'}. "f"url={current_url}")+ skipped_domains += 1current_url = Nonecurrent_domain = Noneresumable_source_manager.save_state(MailgunResumeConfig(pending_domains=pending_domains))@@ -491,6 +507,13 @@ def get_rows(# A fan-out over many empty lists or domains yields nothing for a long stretch.resumable_source_manager.safe_point()+ if count_domains and queried_domains > 0 and skipped_domains == queried_domains:+ # Without this, a request Mailgun rejects for every domain ends as a successful sync of 0 rows.+ raise MailgunAllDomainsSkippedError(+ f"Mailgun rejected the {endpoint} request for every sending domain ({skipped_domains} domains). "+ "Check that your sending domains are active and that the API key can read them."+ )+def _to_date(value: Any) -> Optional[date]:if isinstance(value, datetime):diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun.pyindex f5033aa001fa..eab027656d9d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun.py@@ -3,7 +3,7 @@ from collections.abc import Iterablefrom datetime import UTC, date, datetime, timedeltafrom email.utils import parsedate_to_datetimefrom typing import Any, cast-from urllib.parse import parse_qs+from urllib.parse import parse_qs, urlparseimport pytestfrom unittest import mock@@ -24,11 +24,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_)from products.warehouse_sources.backend.temporal.data_imports.sources.mailgun import mailgun as mailgun_modulefrom products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun import (+ EVENTS_CONSISTENCY_LAG_SECONDS,+ EVENTS_LOOKBACK_DAYS,FORBIDDEN_ERROR,INVALID_KEY_ERROR,LOGS_LOOKBACK_DAYS,METRICS_PAGE_SIZE,UNREACHABLE_ERROR,+ MailgunAllDomainsSkippedError,MailgunResumeConfig,MailgunRetryableError,_epoch_to_datetime,@@ -136,6 +139,25 @@ class TestInitialUrl:with pytest.raises(ValueError):_initial_url(US_BASE, MAILGUN_ENDPOINTS["events"], None)+ @pytest.mark.parametrize(+ "watermark_seconds_ago, expected_begin_seconds_ago",+ [+ (None, EVENTS_LOOKBACK_DAYS * 24 * 60 * 60),+ (3 * 60 * 60, 3 * 60 * 60),+ ],+ )+ def test_events_query_always_sends_an_ascending_time_range(self, watermark_seconds_ago, expected_begin_seconds_ago):+ now = 1_800_000_000+ begin = None if watermark_seconds_ago is None else now - watermark_seconds_ago+ with mock.patch.object(mailgun_module.time, "time", return_value=now):+ url = _initial_url(US_BASE, MAILGUN_ENDPOINTS["events"], "example.com", begin)++ assert url is not None+ query = parse_qs(urlparse(url).query)+ assert query["ascending"] == ["yes"]+ assert query["begin"] == [str(now - expected_begin_seconds_ago)]+ assert query["end"] == [str(now - EVENTS_CONSISTENCY_LAG_SECONDS)]+class TestNormalizeRow:def test_injects_domain_for_domain_scoped_endpoints(self):@@ -292,6 +314,20 @@ class TestGetRows:assert result.saved_states[-1].next_url is Noneassert result.saved_states[-1].pending_domains == []+ def test_every_domain_skipped_fails_the_sync(self):+ domains_page = {"items": [{"name": "a.com"}, {"name": "b.com"}]}+ result = _driver().run(+ "events",+ [+ ScriptedResponse(json=domains_page),+ ScriptedResponse(status=400, json={}),+ ScriptedResponse(status=400, json={}),+ ],+ )++ assert isinstance(result.raised, MailgunAllDomainsSkippedError)+ assert "every sending domain" in str(result.raised)+def test_domain_listing_401_still_raises(self):# A 401 on the /v4/domains listing is a global credential failure, not a single bad# domain — it must surface (and stay non-retryable) rather than be skipped per-domain.