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(data-warehouse): add resend suppressions, email metrics and clicked links tables (#113867)

Tom Owersd9eda270722c
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index a10deb327116..4ea19872e562 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -1011,8 +1011,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/replicate/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/reply_io.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/reply_io/settings.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/resend/resend.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/resend/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/retently/retently.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/retently/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/revenuecat.py
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 44f8c774f47e..5493f12851c8 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
@@ -7270,6 +7270,16 @@ Diffed against: <https://docs.reply.io/llms.txt>
- [ ] `sequence-folders/list-all-sequence-folders` — lookup grouping sequences into folders for team-level rollups (medium)
- [ ] `linkedin-accounts/list-linkedin-accounts` — sending-account dimension for LinkedIn, mirroring email_accounts which is already synced (medium)
+## Resend — gaps
+
+Today (8): `audiences`, `broadcast_clicked_links`, `broadcasts`, `contacts`, `domains`, `email_metrics`, `emails`, `suppressions`
+
+Diffed against: <https://resend.com/docs/llms.txt>
+
+- [x] `/suppressions` — suppressed recipients with their origin (bounce, complaint, manual), which explain delivery gaps (medium) — synced as `suppressions`
+- [x] `/emails/metrics` — the account's delivery and engagement metrics per day, the headline numbers for sending health (high) — synced as `email_metrics`
+- [x] `/broadcasts/{broadcast_id}/clicked-links` — per-link click counts for each broadcast (medium) — synced as `broadcast_clicked_links`
+
## Retently — gaps
Today (7): `campaigns`, `companies`, `customers`, `feedback`, `outbox`, `reports`, `templates`
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/resend/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/resend/canonical_descriptions.py
index 685504b04320..9adcbf461046 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/resend/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/resend/canonical_descriptions.py
@@ -78,4 +78,55 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"created_at": "Time at which the contact was created.",
},
},
+ "suppressions": {
+ "description": "An email address on the team's suppression list, which Resend skips when sending.",
+ "docs_url": "https://resend.com/docs/api-reference/suppressions/list-suppressions",
+ "columns": {
+ "id": "Unique identifier for the suppression.",
+ "email": "The suppressed email address.",
+ "origin": "Why the address was suppressed: bounce, complaint, or manual.",
+ "source_id": "ID of the email that triggered the suppression. Null for manual suppressions.",
+ "created_at": "Time at which the address was suppressed.",
+ },
+ },
+ "email_metrics": {
+ "description": "Account-level email delivery and engagement metrics, one row per UTC day.",
+ "docs_url": "https://resend.com/docs/api-reference/emails/get-metrics",
+ "columns": {
+ "period": "The UTC day the metrics cover.",
+ "received": "Emails Resend accepted for processing.",
+ "sent": "Emails sent to the recipient's mail server.",
+ "delivered": "Emails the recipient's mail server accepted.",
+ "delivery_delayed": "Deliveries postponed by a temporary issue.",
+ "failed": "Emails that never reached a mail server.",
+ "suppressed": "Emails skipped because the recipient is suppressed.",
+ "bounced": "All bounces: transient, permanent, and undetermined.",
+ "bounced_transient": "Soft bounces. A later send can succeed.",
+ "bounced_permanent": "Hard bounces. The address is suppressed.",
+ "bounced_undetermined": "Bounces with no classifiable reason.",
+ "opened": "Open events, including repeats.",
+ "unique_opened": "Emails opened at least once.",
+ "clicked": "Link click events, including repeats.",
+ "unique_clicked": "Emails clicked at least once.",
+ "complained": "Delivered emails marked as spam.",
+ "unsubscribed": "Recipients who unsubscribed.",
+ "delivery_rate": "delivered / sent.",
+ "open_rate": "unique_opened / delivered.",
+ "click_rate": "unique_clicked / delivered.",
+ "bounce_rate": "bounced / sent.",
+ "complaint_rate": "complained / delivered.",
+ "unsubscribe_rate": "unsubscribed / delivered.",
+ },
+ },
+ "broadcast_clicked_links": {
+ "description": "A link clicked in a broadcast, with its total and unique click counts.",
+ "docs_url": "https://resend.com/docs/api-reference/broadcasts/list-broadcast-clicked-links",
+ "columns": {
+ "id": "Opaque pagination cursor for the row. It does not identify any entity in Resend.",
+ "url": "The URL that was clicked.",
+ "clicks": "Total clicks on the link, including repeat clicks by the same recipient.",
+ "unique_clicks": "Number of distinct recipients who clicked the link.",
+ "_broadcast_id": "ID of the broadcast the link belongs to.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/resend/resend.py b/products/warehouse_sources/backend/temporal/data_imports/sources/resend/resend.py
index 147dd88b146b..74b981db3785 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/resend/resend.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/resend/resend.py
@@ -1,8 +1,11 @@
-import dataclasses
+from collections.abc import Callable
+from datetime import UTC, datetime, timedelta
from typing import Any, Optional
from requests import Request, Response
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
@@ -28,12 +31,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.resend.set
)
RESEND_BASE_URL = "https://api.resend.com"
-_EMAILS_DEFAULT_PAGE_SIZE = 100
+# Resend caps a metrics range at 10,000 periods and clamps the start to the plan's retention window,
+# so ten years of daily periods asks for everything the account still retains.
+_METRICS_LOOKBACK_DAYS = 3650
+@frozen
class ResendResumeConfig:
- # Cursor for the /emails endpoint (Resend's `after` parameter).
+ # Cursor for the cursor-paginated endpoints (Resend's `after` parameter).
next_cursor: Optional[str] = None
# Pre-framework fan-out bookmark. Kept (with a default) so previously saved state still parses;
# no longer written — fan-out resume now lives in fanout_state.
@@ -43,9 +48,10 @@ class ResendResumeConfig:
fanout_state: Optional[dict] = None
-class ResendEmailsPaginator(BasePaginator):
- """Keyset pagination for /emails: Resend pages with `limit` + `after`, where `after` is the id
- of the last row on the previous page and `has_more` in the body signals whether more remain."""
+class ResendCursorPaginator(BasePaginator):
+ """Keyset pagination for Resend's cursor lists (/emails, /suppressions, clicked links): Resend
+ pages with `limit` + `after`, where `after` is the id of the last row on the previous page and
+ `has_more` in the body signals whether more remain."""
def __init__(self) -> None:
super().__init__()
@@ -113,20 +119,16 @@ def _simple_resource(
manager: ResumableSourceManager[ResendResumeConfig],
) -> Resource:
"""A single top-level list endpoint: flat (one page) or cursor-paginated (/emails)."""
- is_emails = config.name == "emails"
+ is_cursor_paginated = config.page_size is not None
- params: dict[str, Any] = {}
- paginator: BasePaginator
- if is_emails:
- params["limit"] = config.page_size or _EMAILS_DEFAULT_PAGE_SIZE
- paginator = ResendEmailsPaginator()
- else:
- paginator = SinglePagePaginator()
+ params = _endpoint_params(config)
+ if config.name == "email_metrics":
+ params["start_date"] = (datetime.now(UTC) - timedelta(days=_METRICS_LOOKBACK_DAYS)).date().isoformat()
endpoint: Endpoint = {
"path": config.path,
"params": params,
- "paginator": paginator,
+ "paginator": _paginator(config),
# A missing `data` key yields a zero-row page (the API returns {"data": [...]}); tolerant,
# matching the previous implementation's `data.get("data") or []`.
"data_selector": "data",
@@ -138,7 +140,7 @@ def _simple_resource(
}
initial_paginator_state: Optional[dict[str, Any]] = None
- if is_emails and manager.can_resume():
+ if is_cursor_paginated and manager.can_resume():
resume = manager.load_state()
if resume is not None and resume.next_cursor is not None:
initial_paginator_state = {"next_cursor": resume.next_cursor}
@@ -159,13 +161,31 @@ def _simple_resource(
)
-def _inject_audience_id(row: dict[str, Any]) -> dict[str, Any]:
- # include_from_parent lands the parent id as `_audiences_id`; rename it to the `_audience_id`
- # column the previous implementation injected onto every contact row.
- audience_id = row.pop("_audiences_id", None)
- if audience_id is not None:
- row["_audience_id"] = audience_id
- return row
+def _endpoint_params(config: ResendEndpointConfig) -> dict[str, Any]:
+ params = dict(config.params)
+ if config.page_size is not None:
+ params["limit"] = config.page_size
+ return params
+
+
+def _paginator(config: ResendEndpointConfig) -> BasePaginator:
+ return ResendCursorPaginator() if config.page_size is not None else SinglePagePaginator()
+
+
+def _parent_id_renamer(parent: str, resolve_param: str) -> Callable[[dict[str, Any]], dict[str, Any]]:
+ # include_from_parent lands the parent id as `_<parent>_id` (e.g. `_audiences_id`); rename it to
+ # `_<resolve_param>` (e.g. the `_audience_id` column the previous implementation injected onto
+ # every contact row).
+ source_key = f"_{parent}_id"
+ target_key = f"_{resolve_param}"
+
+ def rename(row: dict[str, Any]) -> dict[str, Any]:
+ parent_id = row.pop(source_key, None)
+ if parent_id is not None:
+ row[target_key] = parent_id
+ return row
+
+ return rename
def _fan_out_resource(
@@ -175,16 +195,25 @@ def _fan_out_resource(
job_id: str,
manager: ResumableSourceManager[ResendResumeConfig],
) -> Resource:
- """Fan the contacts endpoint out over every audience via a dependent resource: the framework
- fetches audiences, then GETs each audience's contacts and injects the audience id per row."""
- if config.parent is None:
+ """Fan a child endpoint out over every parent row via a dependent resource: the framework
+ fetches the parent list, then GETs each parent's children and injects the parent id per row."""
+ if config.parent is None or config.resolve_param is None:
raise ValueError(f"Resend endpoint {config.name} has no parent configured")
parent_config = RESEND_ENDPOINTS[config.parent]
child_params: dict[str, Any] = {
- "audience_id": {"type": "resolve", "resource": config.parent, "field": "id"},
+ **_endpoint_params(config),
+ config.resolve_param: {"type": "resolve", "resource": config.parent, "field": "id"},
}
+ child_endpoint: Endpoint = {
+ "path": config.path,
+ "params": child_params,
+ "paginator": _paginator(config),
+ "data_selector": "data",
+ }
+ if config.ignore_child_404:
+ child_endpoint["response_actions"] = [{"status_code": 404, "action": "ignore"}]
rest_config: RESTAPIConfig = {
"client": _client_config(auth),
@@ -199,14 +228,9 @@ def _fan_out_resource(
},
{
"name": config.name,
- "endpoint": {
- "path": config.path,
- "params": child_params,
- "paginator": SinglePagePaginator(),
- "data_selector": "data",
- },
+ "endpoint": child_endpoint,
"include_from_parent": ["id"],
- "data_map": _inject_audience_id,
+ "data_map": _parent_id_renamer(config.parent, config.resolve_param),
},
],
}
@@ -252,7 +276,7 @@ def resend_source(
return SourceResponse(
name=endpoint,
items=lambda: resource,
- primary_keys=[config.primary_key],
+ primary_keys=config.primary_keys,
partition_count=1,
partition_size=1,
partition_mode="datetime" if config.partition_key else None,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/resend/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/resend/settings.py
index aea48153926b..eeacf071bfab 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/resend/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/resend/settings.py
@@ -1,19 +1,26 @@
-from dataclasses import dataclass
-from typing import Optional
+from dataclasses import field
+from typing import Any, Optional
+from posthog.dataclasses import frozen
-@dataclass
+
+@frozen
class ResendEndpointConfig:
name: str
path: str
- primary_key: str = "id"
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
partition_key: Optional[str] = None
# Cursor-paginated endpoints (e.g. /emails) use `limit` + `after`. Flat endpoints
# return the full list in a single response, so page_size is None.
page_size: Optional[int] = None
+ # Static query params sent on every request.
+ params: dict[str, Any] = field(default_factory=dict)
# For fan-out endpoints like `contacts`, names the parent endpoint we iterate to
- # resolve the path parameter.
+ # resolve the path parameter, and the path parameter the parent id fills.
parent: Optional[str] = None
+ resolve_param: Optional[str] = None
+ # Skip a parent whose child request 404s instead of failing the sync.
+ ignore_child_404: bool = False
RESEND_ENDPOINTS: dict[str, ResendEndpointConfig] = {
@@ -43,6 +50,32 @@ RESEND_ENDPOINTS: dict[str, ResendEndpointConfig] = {
path="/audiences/{audience_id}/contacts",
partition_key="created_at",
parent="audiences",
+ resolve_param="audience_id",
+ ),
+ "suppressions": ResendEndpointConfig(
+ name="suppressions",
+ path="/suppressions",
+ partition_key="created_at",
+ page_size=100,
+ ),
+ # One row per UTC day. The start date is set at request time; Resend clamps it to the plan's
+ # retention window.
+ "email_metrics": ResendEndpointConfig(
+ name="email_metrics",
+ path="/emails/metrics",
+ primary_keys=["period"],
+ params={"dimensions": "period", "granularity": "daily", "timezone": "UTC"},
+ ),
+ # The row `id` is an opaque pagination cursor, not a stable identifier, so key on the URL
+ # within its broadcast.
+ "broadcast_clicked_links": ResendEndpointConfig(
+ name="broadcast_clicked_links",
+ path="/broadcasts/{broadcast_id}/clicked-links",
+ primary_keys=["_broadcast_id", "url"],
+ page_size=100,
+ parent="broadcasts",
+ resolve_param="broadcast_id",
+ ignore_child_404=True,
),
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/resend/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/resend/source.py
index 3c757c77d57f..d84328b54e84 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/resend/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/resend/source.py
@@ -57,10 +57,11 @@ class ResendSource(ResumableSource[ResendSourceConfig, ResendResumeConfig], OAut
Either way, the connection needs **full access** so the following resources can be read:
- Audiences
-- Broadcasts
+- Broadcasts and their clicked links
- Contacts
- Domains
-- Emails
+- Emails and email metrics
+- Suppressions
""",
iconPath="/static/services/resend.png",
docsUrl="https://posthog.com/docs/cdp/sources/resend",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/resend/tests/test_resend.py b/products/warehouse_sources/backend/temporal/data_imports/sources/resend/tests/test_resend.py
index f58528237750..8574b3d7d53a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/resend/tests/test_resend.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/resend/tests/test_resend.py
@@ -3,6 +3,7 @@ from collections.abc import Iterable
from typing import Any, cast
import pytest
+import time_machine
from unittest import mock
from requests import Response
@@ -176,6 +177,67 @@ class TestContactsFanOut:
assert sorted(r["_audience_id"] for r in rows) == ["aud_1", "aud_2"]
+class TestBroadcastClickedLinksFanOut:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_pages_each_broadcast_and_skips_missing_broadcast(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response({"data": [{"id": "b_1"}, {"id": "b_gone"}, {"id": "b_2"}]}), # broadcasts
+ _response({"data": [{"id": "o0", "url": "https://example.com/a", "clicks": 3}], "has_more": True}),
+ _response({"data": [{"id": "o1", "url": "https://example.com/b", "clicks": 1}], "has_more": False}),
+ _response({"message": "not found"}, status_code=404),
+ _response({"data": [{"id": "o0", "url": "https://example.com/a", "clicks": 7}], "has_more": False}),
+ ],
+ )
+
+ rows = _rows(_source("broadcast_clicked_links"))
+
+ assert [(r["_broadcast_id"], r["url"], r["clicks"]) for r in rows] == [
+ ("b_1", "https://example.com/a", 3),
+ ("b_1", "https://example.com/b", 1),
+ ("b_2", "https://example.com/a", 7),
+ ]
+ assert all("_broadcasts_id" not in r for r in rows)
+ assert [(url, params.get("after")) for url, params in snapshots[1:]] == [
+ (f"{RESEND_BASE_URL}/broadcasts/b_1/clicked-links", None),
+ (f"{RESEND_BASE_URL}/broadcasts/b_1/clicked-links", "o0"),
+ (f"{RESEND_BASE_URL}/broadcasts/b_gone/clicked-links", None),
+ (f"{RESEND_BASE_URL}/broadcasts/b_2/clicked-links", None),
+ ]
+ assert snapshots[1][1]["limit"] == 100
+
+
+class TestEmailMetrics:
+ @time_machine.travel("2026-10-08T12:00:00Z", tick=False)
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_requests_daily_breakdown_and_yields_one_row_per_day(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response(
+ {
+ "object": "metrics",
+ "totals": {"sent": 5},
+ "data": [{"period": "2026-10-07", "sent": 2}, {"period": "2026-10-08", "sent": 3}],
+ }
+ )
+ ],
+ )
+
+ rows = _rows(_source("email_metrics"))
+
+ assert rows == [{"period": "2026-10-07", "sent": 2}, {"period": "2026-10-08", "sent": 3}]
+ assert snapshots == [
+ (
+ f"{RESEND_BASE_URL}/emails/metrics",
+ {"dimensions": "period", "granularity": "daily", "timezone": "UTC", "start_date": "2016-10-10"},
+ )
+ ]
+
+
class TestRetryable:
@mock.patch(CLIENT_SESSION_PATCH)
def test_401_does_not_retry_and_raises(self, MockSession) -> None:
@@ -205,10 +267,14 @@ class TestSourceResponseShape:
config = RESEND_ENDPOINTS[endpoint]
assert response.name == endpoint
- assert response.primary_keys == [config.primary_key]
- assert response.partition_mode == "datetime"
- assert response.partition_format == "month"
- assert response.partition_keys == [config.partition_key]
+ assert response.primary_keys == config.primary_keys
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_format == "month"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
class TestValidateCredentials: