: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): add sendgrid message activity table (#80028)
jake sciotto4cae9e54fcfe
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.pyindex 05d301769cbd..39a5400c00b0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py@@ -131,6 +131,12 @@ _RATE_LIMIT_RESET_HEADERS: tuple[tuple[str, Callable[[str], Optional[float]]], .# Sentry signals its rate-limit window with a UNIX epoch timestamp rather than ``Retry-After``,# and Sentry's flat / fan-out endpoints (e.g. ``project_users``) sync through this client too.("X-Sentry-Rate-Limit-Reset", _seconds_from_epoch_reset),+ # The common ``X-RateLimit-*`` convention, spelled with a UNIX epoch reset and no+ # ``Retry-After`` — SendGrid answers every 429 this way, and its Email Activity endpoint is+ # capped at 6 requests/minute, so without honoring the reset a message-activity backfill+ # spends its whole attempt budget inside a single window. APIs that put delta-seconds in this+ # header parse to an elapsed instant and fall back to exponential backoff.+ ("X-RateLimit-Reset", _seconds_from_epoch_reset),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.pyindex 7acbe27115d8..463d43f41bf9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py@@ -637,6 +637,36 @@ class TestRESTClient:assert mock_session.send.call_count == 2mock_sleep.assert_called_once_with(45.0)+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.datetime")+ @patch("tenacity.nap.time.sleep")+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ )+ def test_send_request_respects_x_ratelimit_reset_header(self, MockSession, mock_sleep, mock_datetime) -> None:+ # SendGrid answers 429 with the common ``X-RateLimit-Reset`` epoch header and no+ # ``Retry-After``; its Email Activity endpoint allows 6 requests/minute, so falling back+ # to the short exponential backoff would exhaust the attempt budget inside one window.+ now = datetime(2026, 3, 6, 12, 0, 0, tzinfo=UTC)+ mock_datetime.now.return_value = now++ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.return_value = MagicMock()++ rate_limited = _make_response({"errors": [{"message": "too many requests"}]}, status_code=429)+ rate_limited.url = "https://api.sendgrid.com/v3/messages"+ rate_limited.headers["X-RateLimit-Reset"] = str(int(now.timestamp()) + 30)+ ok = _make_response({"results": [{"id": 1}]})++ mock_session.send.side_effect = [rate_limited, ok]++ client = RESTClient(base_url="https://api.sendgrid.com/v3")+ pages = list(client.paginate(path="/messages", data_selector="results", paginator=SinglePagePaginator()))++ assert pages == [[{"id": 1}]]+ assert mock_session.send.call_count == 2+ mock_sleep.assert_called_once_with(30.0)+@patch("tenacity.nap.time.sleep")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/api_inventory.md b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/api_inventory.mdindex 801c3dd9573a..bec3a2b92c0b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/api_inventory.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/api_inventory.md@@ -16,17 +16,18 @@ on the primary key — wasted API calls, not corrupted data.## Endpoints-| Schema | Path | Pagination | Data shape | Primary key | Incremental |-| --------------------- | ----------------------------- | ------------- | ------------------- | ----------- | ------------------------------------ |-| `bounces` | `/suppression/bounces` | limit/offset | bare array | `email` | `created` (epoch) via `start_time` |-| `blocks` | `/suppression/blocks` | limit/offset | bare array | `email` | `created` (epoch) via `start_time` |-| `invalid_emails` | `/suppression/invalid_emails` | limit/offset | bare array | `email` | `created` (epoch) via `start_time` |-| `spam_reports` | `/suppression/spam_reports` | limit/offset | bare array | `email` | `created` (epoch) via `start_time` |-| `global_unsubscribes` | `/suppression/unsubscribes` | limit/offset | bare array | `email` | `created` (epoch) via `start_time` |-| `stats` | `/stats` | none (single) | nested daily stats | `date` | `date` via `start_date` (YYYY-MM-DD) |-| `unsubscribe_groups` | `/asm/groups` | none (single) | bare array | `id` | full refresh |-| `marketing_lists` | `/marketing/lists` | `_metadata` | `{"result": [...]}` | `id` | full refresh |-| `templates` | `/templates` | `_metadata` | `{"result": [...]}` | `id` | full refresh |+| Schema | Path | Pagination | Data shape | Primary key | Incremental |+| --------------------- | ----------------------------- | ------------- | --------------------- | ----------- | ------------------------------------ |+| `bounces` | `/suppression/bounces` | limit/offset | bare array | `email` | `created` (epoch) via `start_time` |+| `blocks` | `/suppression/blocks` | limit/offset | bare array | `email` | `created` (epoch) via `start_time` |+| `invalid_emails` | `/suppression/invalid_emails` | limit/offset | bare array | `email` | `created` (epoch) via `start_time` |+| `spam_reports` | `/suppression/spam_reports` | limit/offset | bare array | `email` | `created` (epoch) via `start_time` |+| `global_unsubscribes` | `/suppression/unsubscribes` | limit/offset | bare array | `email` | `created` (epoch) via `start_time` |+| `stats` | `/stats` | none (single) | nested daily stats | `date` | `date` via `start_date` (YYYY-MM-DD) |+| `unsubscribe_groups` | `/asm/groups` | none (single) | bare array | `id` | full refresh |+| `marketing_lists` | `/marketing/lists` | `_metadata` | `{"result": [...]}` | `id` | full refresh |+| `templates` | `/templates` | `_metadata` | `{"result": [...]}` | `id` | full refresh |+| `message_activity` | `/messages` | query window | `{"messages": [...]}` | `msg_id` | `last_event_time` via `query` |Notes:@@ -44,9 +45,25 @@ Notes:lack. `start_date` (YYYY-MM-DD) is a real server-side filter, so it syncs incrementally on thedaily `date`; it is also required on every request, so the first sync backfills a fixed window.Free on every SendGrid plan (`stats.read`).-- Rate limits: most v3 endpoints are generous, but the Email Activity API (`/messages`, deliberately not- synced here) is capped at ~6 req/min — webhook ingestion is the recommended path for per-event data and- is left as a follow-up.+- `/messages` (Email Activity API) is the only per-recipient engagement record the API exposes, and it is+ synced as the opt-in `message_activity` table. It has no cursor or offset: `limit` (max 1000, default 10)+ only caps how many of the most recent matches come back, so the sync pages by narrowing the required+ `query=last_event_time BETWEEN TIMESTAMP "…" AND TIMESTAMP "…"` window newest to oldest until a short+ page (`sort_mode="desc"`; the pipeline defers the watermark to the end of a successful run). Grain is one+ row per message (`msg_id`), mutated in place as new events land (`status`, `opens_count`, `clicks_count`,+ `last_event_time`) — which makes the table merge-only, unpartitioned, and lets `last_event_time` double+ as the incremental cursor: an old message with a new event re-enters the window. Access requires the paid+ "additional email activity history" add-on (30 days of history, hence the 30-day first-sync backfill);+ accounts without it — including reseller accounts (Azure/GCP/Heroku), which cannot buy it — get 403+ however the key is scoped (`email_activity.read`), so the table ships `should_sync_default=False` with a+ `permission_note`. Rate limit is 6 requests/minute (429 + `X-RateLimit-Reset` epoch header, honored by+ the shared REST transport). Query syntax, `limit` cap, and the response shape were verified against the+ public docs only — no add-on credentials were available; the conservative failure mode of the inclusive+ window bounds is boundary re-fetches that merge dedupes on `msg_id`.+- The Event Webhook delivers the same event types at no extra cost and in near real time, but SendGrid+ allows a single webhook URL per account, so registering ours can silently break or replace a consumer the+ customer already runs. Webhook ingestion therefore stays parked as a separate product decision;+ `/messages` is the only per-event path wired here.- Scopes are per endpoint, so a key that reads one table often can't read another.`settings.py` records each endpoint's scope as `/v3/scopes` spells it (`suppression.bounces.read`,`asm.groups.read`, `marketing.read`, `templates.read`), and `get_endpoint_permissions` probes them so thediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/canonical_descriptions.pyindex 3bd95d3ba186..9c30c0b9e3b9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/canonical_descriptions.py@@ -105,4 +105,18 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"versions": "List of versions belonging to the template.",},},+ "message_activity": {+ "description": "Per-message activity from the Email Activity feed: one row per sent message with its latest delivery status and engagement counts. Requires SendGrid's paid additional email activity history add-on.",+ "docs_url": "https://www.twilio.com/docs/sendgrid/api-reference/email-activity/filter-all-messages",+ "columns": {+ "msg_id": "Unique identifier for the message.",+ "from_email": "Sender address of the message.",+ "to_email": "Recipient address of the message.",+ "subject": "Subject line of the message.",+ "status": "Latest delivery status of the message: processed, delivered, or not_delivered.",+ "opens_count": "Number of times the message was opened.",+ "clicks_count": "Number of times links in the message were clicked.",+ "last_event_time": "Time of the most recent event recorded for the message, in ISO 8601 format.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/sendgrid.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/sendgrid.pyindex abedb68f4bd6..f130e1bb69f4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/sendgrid.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/sendgrid.py@@ -1,9 +1,10 @@+import loggingimport dataclassesfrom datetime import UTC, date, datetime, timedeltafrom typing import Any, Optionalfrom urllib.parse import parse_qs, urlencode, urlparse-from requests import Response+from requests import Request, Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (@@ -21,10 +22,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.sendgrid.settings import (+ MESSAGE_ACTIVITY_BACKFILL_DAYS,SENDGRID_ENDPOINTS,SendGridEndpointConfig,)+logger = logging.getLogger(__name__)+SENDGRID_BASE_URL = "https://api.sendgrid.com/v3"@@ -36,6 +40,11 @@ class SendGridResumeConfig:next_url: Optional[str] = None# Row offset of the next unfetched page (offset pagination).offset: Optional[int] = None+ # Remaining unfetched Email Activity window (activity pagination), both bounds as normalized+ # UTC ISO timestamps. Saved together so a resumed sync keeps walking the original window+ # instead of recomputing it from "now" and losing the oldest slice of a first backfill.+ activity_window_start: Optional[str] = None+ activity_window_end: Optional[str] = Nonedef _get_headers(api_key: str) -> dict[str, str]:@@ -97,6 +106,42 @@ def _flatten_daily_stats(item: dict[str, Any]) -> list[dict[str, Any]]:return rows+_ACTIVITY_TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%SZ"+++def _to_activity_timestamp(value: Any) -> str:+ """Normalize a cursor, resume, or response timestamp to the UTC second-precision form the+ Email Activity query's TIMESTAMP literal takes.++ Flooring sub-second parts is safe: both window bounds are inclusive, so a floored bound only+ re-fetches boundary rows and merge dedupes them on the primary key.+ """+ if isinstance(value, datetime):+ dt = value+ elif isinstance(value, date):+ dt = datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ elif isinstance(value, int | float):+ dt = datetime.fromtimestamp(value, tz=UTC)+ else:+ dt = datetime.fromisoformat(str(value).replace("Z", "+00:00"))+ dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)+ return dt.strftime(_ACTIVITY_TIMESTAMP_FORMAT)+++def _require_activity_timestamp(value: Any) -> str:+ # Re-normalizing rejects a tampered Redis value before it can smuggle arbitrary syntax into+ # the Email Activity query.+ try:+ return _to_activity_timestamp(value)+ except (TypeError, ValueError, OverflowError, OSError):+ raise ValueError(f"SendGrid resume state contains an unexpected timestamp: {value!r}")+++def _activity_query(window_start: str, window_end: str) -> str:+ # Both bounds are inclusive; `requests` URL-encodes the spaces and quotes.+ return f'last_event_time BETWEEN TIMESTAMP "{window_start}" AND TIMESTAMP "{window_end}"'++def _offset_from_url(url: str) -> int:"""Recover the `offset` query param so a resumed offset-paginated sync keeps advancing."""values = parse_qs(urlparse(url).query).get("offset", ["0"])@@ -132,6 +177,83 @@ class SendGridMetadataPaginator(JSONResponsePaginator):self._has_next_page = False+class SendGridMessagesPaginator(BasePaginator):+ """Page the Email Activity API by narrowing its query window newest to oldest.++ `GET /v3/messages` exposes no cursor or offset — `limit` (max 1000) just caps how many of the+ most recent matches come back. Each full page therefore moves the window end back to the+ oldest `last_event_time` on the page (inclusive, so boundary rows re-appear and merge dedupes+ them on `msg_id`); a short page means the window is drained.+ """++ def __init__(self, window_start: str, window_end: str, limit: int) -> None:+ super().__init__()+ self._window_start = window_start+ self._window_end = window_end+ self._limit = limit++ def _apply_window(self, request: Request) -> None:+ if request.params is None:+ request.params = {}+ request.params["query"] = _activity_query(self._window_start, self._window_end)+ request.params["limit"] = self._limit++ def init_request(self, request: Request) -> None:+ self._apply_window(request)++ def update_request(self, request: Request) -> None:+ self._apply_window(request)++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ rows = data or []+ if len(rows) < self._limit:+ self._has_next_page = False+ return++ oldest: Optional[str] = None+ for row in rows:+ raw = row.get("last_event_time") if isinstance(row, dict) else None+ if not raw:+ continue+ try:+ normalized = _to_activity_timestamp(raw)+ except (TypeError, ValueError):+ continue+ if oldest is None or normalized < oldest:+ oldest = normalized++ if oldest is None or oldest >= self._window_end:+ # A full page that can't narrow the window: more than `limit` messages share the+ # window-end second, or no row carried a parseable last_event_time. Stop instead of+ # refetching the same page until the activity times out; anything older is skipped.+ logger.warning(+ "SendGrid message activity window cannot advance; stopping pagination",+ extra={"window_start": self._window_start, "window_end": self._window_end},+ )+ self._has_next_page = False+ return++ self._window_end = oldest+ self._has_next_page = True++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ if not self._has_next_page:+ return None+ return {"activity_window_start": self._window_start, "activity_window_end": self._window_end}++ def set_resume_state(self, state: dict[str, Any]) -> None:+ window_start = state.get("activity_window_start")+ window_end = state.get("activity_window_end")+ if window_start is None or window_end is None:+ return+ self._window_start = _require_activity_timestamp(window_start)+ self._window_end = _require_activity_timestamp(window_end)+ self._has_next_page = True++ def __str__(self) -> str:+ return f"SendGridMessagesPaginator(window_start={self._window_start}, window_end={self._window_end})"++def _build_paginator(config: SendGridEndpointConfig) -> BasePaginator:if config.pagination == "offset":# No top-level `total`; termination is a short/empty page (OffsetPaginator default).@@ -141,6 +263,27 @@ def _build_paginator(config: SendGridEndpointConfig) -> BasePaginator:return SinglePagePaginator()+def _build_activity_paginator(+ config: SendGridEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: Optional[str],+) -> SendGridMessagesPaginator:+ now = datetime.now(UTC)+ if should_use_incremental_field and incremental_field and db_incremental_field_last_value is not None:+ # The window is inclusive of the watermark, so the boundary message re-appears and merge+ # updates it. Because the filter rides every request, pagination terminates at the+ # watermark by construction.+ window_start = _to_activity_timestamp(db_incremental_field_last_value)+ else:+ window_start = _to_activity_timestamp(now - timedelta(days=MESSAGE_ACTIVITY_BACKFILL_DAYS))+ return SendGridMessagesPaginator(+ window_start=window_start,+ window_end=_to_activity_timestamp(now),+ limit=config.page_size,+ )++def _build_params(config: SendGridEndpointConfig,should_use_incremental_field: bool,@@ -195,6 +338,17 @@ def _initial_paginator_state(_require_sendgrid_url(resume.next_url)return {"next_url": resume.next_url}+ if (+ config.pagination == "activity"+ and resume.activity_window_start is not None+ and resume.activity_window_end is not None+ ):+ # The paginator re-normalizes both bounds when seeded, rejecting tampered state.+ return {+ "activity_window_start": resume.activity_window_start,+ "activity_window_end": resume.activity_window_end,+ }+return None@@ -229,6 +383,16 @@ def sendgrid_source(# stats rows are nested one level deeper than the bare array; flatten them into flat daily rows.resource_config["data_map"] = _flatten_daily_stats+ # Activity pagination owns its own request params (`query` window + `limit`), including the+ # server-side incremental filter, so it is built with the cursor instead of via `params`.+ paginator: BasePaginator = (+ _build_activity_paginator(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )+ if config.pagination == "activity"+ else _build_paginator(config)+ )+rest_config: RESTAPIConfig = {"client": {"base_url": SENDGRID_BASE_URL,@@ -236,7 +400,7 @@ def sendgrid_source(# and raised errors; only the non-secret Accept header is set here."headers": {"Accept": "application/json"},"auth": {"type": "bearer", "token": api_key},- "paginator": _build_paginator(config),+ "paginator": paginator,},"resource_defaults": {},"resources": [resource_config],@@ -251,6 +415,13 @@ def sendgrid_source(returnif state.get("offset") is not None:resumable_source_manager.save_state(SendGridResumeConfig(offset=int(state["offset"])))+ elif state.get("activity_window_end") is not None:+ resumable_source_manager.save_state(+ SendGridResumeConfig(+ activity_window_start=state.get("activity_window_start"),+ activity_window_end=state["activity_window_end"],+ )+ )elif state.get("next_url"):resumable_source_manager.save_state(SendGridResumeConfig(next_url=state["next_url"]))@@ -272,7 +443,7 @@ def sendgrid_source(partition_mode="datetime" if config.partition_key else None,partition_format="week" if config.partition_key else None,partition_keys=[config.partition_key] if config.partition_key else None,- sort_mode="asc",+ sort_mode=config.sort_mode,)@@ -296,6 +467,12 @@ def _probe_params(config: SendGridEndpointConfig) -> dict[str, Any]:params["limit"] = 1elif config.pagination == "metadata":params["page_size"] = 1+ elif config.pagination == "activity":+ # `query` is required on /messages, so probe a one-day window for one row. The 403 for a+ # missing add-on or scope fires regardless of the window.+ now = datetime.now(UTC)+ params["limit"] = 1+ params["query"] = _activity_query(_to_activity_timestamp(now - timedelta(days=1)), _to_activity_timestamp(now))return paramsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/settings.pyindex a9de9f619bf0..a853871767f7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/settings.py@@ -7,7 +7,13 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment# - "offset": `limit`/`offset` query params over a bare JSON array (suppression endpoints).# - "metadata": follow the absolute `_metadata.next` URL the API returns (marketing endpoints).# - "single": one request returns the whole list, no pagination params.-PaginationMode = Literal["offset", "metadata", "single"]+# - "activity": no cursor at all — the Email Activity `query` time window is narrowed newest to+# oldest until a short page (message_activity).+PaginationMode = Literal["offset", "metadata", "single", "activity"]++# The Email Activity add-on stores 30 days of history, so a message_activity sync with no+# incremental cursor yet starts its query window this far back.+MESSAGE_ACTIVITY_BACKFILL_DAYS = 30# How the incremental cursor is serialized into the `incremental_param` query value:# - "epoch": Unix epoch seconds (suppression `start_time`).@@ -49,6 +55,13 @@ class SendGridEndpointConfig:default_backfill_days: Optional[int] = None# How the response body is shaped, so the transport can flatten nested stats responses.response_shape: ResponseShape = "array"+ # Order rows arrive in across the whole sync. The Email Activity walk pages newest to oldest,+ # so it declares "desc" and the pipeline defers the incremental watermark to the end of a+ # successful run instead of checkpointing it per batch.+ sort_mode: Literal["asc", "desc"] = "asc"+ # False for tables whose sync needs grants beyond what source creation validated: the schema+ # picker and one-shot source creation leave them unselected until the user opts in.+ should_sync_default: bool = True# Static query params always sent (e.g. templates' `generations`).extra_params: dict[str, str] = field(default_factory=dict)# SendGrid scope this endpoint reads, spelled as `/scopes` reports it. Surfaced per table in the@@ -77,6 +90,15 @@ def _date_field(name: str) -> IncrementalField:}+def _datetime_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }++# SendGrid (v3) endpoint catalog. The suppression endpoints expose a genuine server-side# `start_time` filter (Unix epoch seconds) over their immutable `created` field, so they sync# incrementally. `stats` filters on `start_date` (YYYY-MM-DD) over its daily aggregate date and@@ -179,6 +201,25 @@ SENDGRID_ENDPOINTS: dict[str, SendGridEndpointConfig] = {extra_params={"generations": "legacy,dynamic"},required_scope="templates.read",),+ "message_activity": SendGridEndpointConfig(+ name="message_activity",+ path="/messages",+ primary_keys=["msg_id"],+ pagination="activity",+ data_key="messages",+ # /messages caps `limit` at 1000. No partition key: a message's only timestamp,+ # last_event_time, advances whenever a new event lands, so partitions would rewrite.+ page_size=1000,+ incremental_fields=[_datetime_field("last_event_time")],+ sort_mode="desc",+ # Gated behind a paid add-on most accounts don't have, so it must be an explicit opt-in.+ should_sync_default=False,+ required_scope="email_activity.read",+ permission_note=(+ "Accounts without SendGrid's paid additional email activity history add-on cannot sync "+ "this table, even with the Email Activity scope granted."+ ),+ ),}ENDPOINTS = tuple(SENDGRID_ENDPOINTS.keys())@@ -186,3 +227,5 @@ ENDPOINTS = tuple(SENDGRID_ENDPOINTS.keys())INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: config.incremental_fields for name, config in SENDGRID_ENDPOINTS.items() if config.incremental_fields}++SHOULD_SYNC_DEFAULT: dict[str, bool] = {name: config.should_sync_default for name, config in SENDGRID_ENDPOINTS.items()}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/source.pyindex 978687918e88..20b47a0312a6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/source.py@@ -35,6 +35,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.sendgrid.sENDPOINTS,INCREMENTAL_FIELDS,SENDGRID_ENDPOINTS,+ SHOULD_SYNC_DEFAULT,)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -59,8 +60,11 @@ class SendGridSource(ResumableSource[SendGridSourceConfig, SendGridResumeConfig]return CANONICAL_DESCRIPTIONSdef get_non_retryable_errors(self) -> dict[str, str | None]:+ # Insertion order matters: the job finalizer surfaces the message of the first matching+ # key, and the bare-host 403 key below also matches /v3/messages error text.return {"401 Client Error: Unauthorized for url: https://api.sendgrid.com": "Your SendGrid API key is invalid or expired. Please generate a new key and reconnect.",+ "403 Client Error: Forbidden for url: https://api.sendgrid.com/v3/messages": "Message activity needs SendGrid's paid additional email activity history add-on and an API key with Email Activity access. Add both in SendGrid, then resume this sync. Other SendGrid tables are not affected.",# Keyed on the error text, so this covers every endpoint and can't name the one scope.# `get_endpoint_permissions` does that per table before a sync is ever queued."403 Client Error: Forbidden for url: https://api.sendgrid.com": "Your SendGrid API key cannot read this table. Add that table's read access to the key in SendGrid under Settings > API Keys, then resume this sync. Marketing lists also need an account with Marketing Campaigns.",@@ -75,7 +79,16 @@ class SendGridSource(ResumableSource[SendGridSourceConfig, SendGridResumeConfig]force_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ return build_endpoint_schemas(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names,+ # message_activity rows mutate in place as events land (status, opens_count,+ # last_event_time), so append mode would pile up stale copies; merge on msg_id is+ # the only safe incremental mode.+ merge_only=("message_activity",),+ should_sync_default=SHOULD_SYNC_DEFAULT,+ )def validate_credentials(self,@@ -153,6 +166,7 @@ Grant the following read access (Restricted Access) so the key can reach the dat- **Stats**: global email statistics (daily requests, delivered, opens, clicks, bounces)- **Marketing**: marketing lists. This also needs an account with Marketing Campaigns enabled.- **Template Engine**: templates+- **Email Activity**: message activity. This table is off by default and also needs SendGrid's paid additional email activity history add-on.Tables your key cannot read are flagged in the next step and left unselected.""",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid.pyindex 32107c1b4c06..ae0594e69272 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid.py@@ -4,9 +4,10 @@ from typing import Anyfrom urllib.parse import parse_qs, urlparseimport pytest+from freezegun import freeze_timefrom unittest import mock-from requests import Response+from requests import HTTPError, Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.sendgrid.sendgrid import (SendGridResumeConfig,@@ -341,6 +342,143 @@ class TestSinglePagination:manager.save_state.assert_not_called()+def _messages_page(count: int, last_event_time: str) -> list[dict[str, Any]]:+ return [{"msg_id": f"m{last_event_time}-{i}", "last_event_time": last_event_time} for i in range(count)]+++class TestActivityPagination:+ @freeze_time("2026-08-07T12:00:00Z")+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_walks_query_window_backwards_until_short_page(self, MockSession) -> None:+ session = MockSession.return_value+ # Sub-second precision on the oldest row exercises the flooring of window bounds.+ page1 = [+ *_messages_page(999, "2026-08-01T05:00:00Z"),+ {"msg_id": "old", "last_event_time": "2026-07-20T09:00:00.500Z"},+ ]+ page2 = [{"msg_id": "oldest", "last_event_time": "2026-07-10T00:00:00Z"}]+ params, _urls = _wire(session, [_response({"messages": page1}), _response({"messages": page2})])++ manager = _make_manager()+ rows = _rows(_source("message_activity", manager))++ assert rows == [*page1, *page2]+ assert params[0]["limit"] == 1000+ assert (+ params[0]["query"]+ == 'last_event_time BETWEEN TIMESTAMP "2026-07-08T12:00:00Z" AND TIMESTAMP "2026-08-07T12:00:00Z"'+ )+ # The second request narrows the window end to the oldest timestamp of the full page.+ assert (+ params[1]["query"]+ == 'last_event_time BETWEEN TIMESTAMP "2026-07-08T12:00:00Z" AND TIMESTAMP "2026-07-20T09:00:00Z"'+ )+ assert session.send.call_count == 2+ # Checkpoint saved once (after the full first page); the terminal short page saves nothing.+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0] == SendGridResumeConfig(+ activity_window_start="2026-07-08T12:00:00Z", activity_window_end="2026-07-20T09:00:00Z"+ )++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_window(self, MockSession) -> None:+ session = MockSession.return_value+ params, _urls = _wire(session, [_response({"messages": [{"msg_id": "m1"}]})])++ manager = _make_manager(+ SendGridResumeConfig(+ activity_window_start="2026-07-08T12:00:00Z", activity_window_end="2026-07-20T09:00:00Z"+ )+ )+ _rows(_source("message_activity", manager))++ # Both bounds come from the saved state, so a resumed first backfill keeps its+ # original window instead of recomputing it from "now".+ assert (+ params[0]["query"]+ == 'last_event_time BETWEEN TIMESTAMP "2026-07-08T12:00:00Z" AND TIMESTAMP "2026-07-20T09:00:00Z"'+ )++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_tampered_resume_window_raises(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [])++ manager = _make_manager(+ SendGridResumeConfig(+ activity_window_start='" OR to_email LIKE "%', activity_window_end="2026-07-20T09:00:00Z"+ )+ )+ with pytest.raises(ValueError, match="unexpected timestamp"):+ _rows(_source("message_activity", manager))++ @pytest.mark.parametrize(+ "cursor",+ [+ datetime(2026, 8, 1, 3, 4, 5, tzinfo=UTC),+ "2026-08-01T03:04:05Z",+ "2026-08-01T03:04:05.123456+00:00",+ int(datetime(2026, 8, 1, 3, 4, 5, tzinfo=UTC).timestamp()),+ ],+ )+ @freeze_time("2026-08-07T12:00:00Z")+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_incremental_window_starts_at_watermark(self, MockSession, cursor: Any) -> None:+ # The cursor round-trips through storage in several shapes; all must produce the same+ # server-side window, otherwise every incremental sync silently refetches 30 days.+ session = MockSession.return_value+ params, _urls = _wire(session, [_response({"messages": [{"msg_id": "m1"}]})])++ _rows(+ _source(+ "message_activity",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=cursor,+ incremental_field="last_event_time",+ )+ )++ assert (+ params[0]["query"]+ == 'last_event_time BETWEEN TIMESTAMP "2026-08-01T03:04:05Z" AND TIMESTAMP "2026-08-07T12:00:00Z"'+ )++ @freeze_time("2026-08-07T12:00:00Z")+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_full_page_that_cannot_narrow_the_window_stops(self, MockSession) -> None:+ # More than `limit` messages sharing the window-end second would otherwise refetch the+ # same page until the activity times out.+ session = MockSession.return_value+ page = _messages_page(1000, "2026-08-07T12:00:00Z")+ _wire(session, [_response({"messages": page})])++ manager = _make_manager()+ rows = _rows(_source("message_activity", manager))++ assert rows == page+ assert session.send.call_count == 1+ manager.save_state.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_403_error_text_matches_the_non_retryable_key(self, MockSession) -> None:+ # The add-on gate surfaces per table through `get_non_retryable_errors`, whose /v3/messages+ # key is a substring match on this exact error text — if the phrasing drifts, the 403+ # retries forever instead of failing with the add-on message.+ session = MockSession.return_value+ response = Response()+ response.status_code = 403+ response.reason = "Forbidden"+ response.url = "https://api.sendgrid.com/v3/messages?limit=1000&query=..."+ response._content = json.dumps({"errors": [{"message": "access forbidden"}]}).encode()+ _wire(session, [response])++ with pytest.raises(HTTPError) as excinfo:+ _rows(_source("message_activity", _make_manager()))++ assert "403 Client Error: Forbidden for url: https://api.sendgrid.com/v3/messages" in str(excinfo.value)++class TestSourceResponse:@mock.patch(CLIENT_SESSION_PATCH)def test_suppression_endpoint_partitioning_and_keys(self, MockSession) -> None:@@ -358,6 +496,17 @@ class TestSourceResponse:assert response.partition_mode is Noneassert response.partition_keys is None+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_message_activity_is_desc_keyed_on_msg_id_and_unpartitioned(self, MockSession) -> None:+ response = _source("message_activity", _make_manager())+ assert response.primary_keys == ["msg_id"]+ # Newest-first walk: declaring "asc" would checkpoint the watermark at ≈now after the+ # first batch and skip everything older on the next incremental sync.+ assert response.sort_mode == "desc"+ # last_event_time advances whenever a new event lands, so it can't be a partition key.+ assert response.partition_mode is None+ assert response.partition_keys is None+class TestGetStatusCode:@pytest.mark.parametrize("status", [200, 401, 403, 404])@@ -402,11 +551,18 @@ class TestGetEndpointPermissions:permissions = self._probe(status, ["marketing_lists"])assert (permissions["marketing_lists"] is not None) is expect_blocked- def test_403_names_the_scope_and_the_marketing_campaigns_caveat(self) -> None:- reason = self._probe(403, ["marketing_lists"])["marketing_lists"]+ @pytest.mark.parametrize(+ ("endpoint", "fragments"),+ [+ ("marketing_lists", ["marketing.read", "Marketing Campaigns"]),+ ("message_activity", ["email_activity.read", "additional email activity history"]),+ ],+ )+ def test_403_names_the_scope_and_its_account_caveat(self, endpoint: str, fragments: list[str]) -> None:+ reason = self._probe(403, [endpoint])[endpoint]assert reason is not None- assert "marketing.read" in reason- assert "Marketing Campaigns" in reason+ for fragment in fragments:+ assert fragment in reasondef test_unknown_endpoint_is_treated_as_reachable(self) -> None:assert self._probe(403, ["not_an_endpoint"]) == {"not_an_endpoint": None}@@ -420,8 +576,17 @@ class TestGetEndpointPermissions:("marketing_lists", {"page_size": "1"}),("templates", {"page_size": "1", "generations": "legacy,dynamic"}),("unsubscribe_groups", {}),+ # /messages requires `query`, so a probe without one risks the same masking 400.+ (+ "message_activity",+ {+ "limit": "1",+ "query": 'last_event_time BETWEEN TIMESTAMP "2026-08-06T12:00:00Z" AND TIMESTAMP "2026-08-07T12:00:00Z"',+ },+ ),],)+ @freeze_time("2026-08-07T12:00:00Z")def test_probe_uses_the_endpoints_own_pagination_params(self, endpoint: str, expected_params: dict[str, str]) -> None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid_source.pyindex 899def3354b2..27e2aac334b0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid_source.py@@ -6,6 +6,7 @@ from unittest.mock import MagicMock, patchfrom posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigTypefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import build_default_schemasfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.sendgrid import (SendGridSourceConfig,@@ -28,6 +29,7 @@ ALL_ENDPOINTS = {"unsubscribe_groups","marketing_lists","templates",+ "message_activity",}# Endpoints that sync incrementally, mapped to the cursor field they expose. Everything else is# full refresh.@@ -38,6 +40,7 @@ INCREMENTAL_FIELD_BY_ENDPOINT = {"spam_reports": "created","global_unsubscribes": "created","stats": "date",+ "message_activity": "last_event_time",}@@ -99,6 +102,24 @@ class TestSendGridSource:else:assert schemas[name].supports_incremental is Trueassert {f["field"] for f in schemas[name].incremental_fields} == {expected_field}+ # message_activity rows mutate in place as events land, so it syncs incrementally on+ # last_event_time but must never be offered as append (stale copies would pile up).+ assert schemas["message_activity"].supports_append is False+ for name in INCREMENTAL_FIELD_BY_ENDPOINT.keys() - {"message_activity"}:+ assert schemas[name].supports_append is True++ def test_message_activity_is_opt_in(self) -> None:+ # The add-on gate means most accounts 403 on this table: force-enabling it would fail+ # their first sync, so both the schema picker default and one-shot source creation must+ # leave it unselected.+ schemas = SendGridSource().get_schemas(_config(), team_id=1)+ defaults = {s.name: s.should_sync_default for s in schemas}+ assert defaults.pop("message_activity") is False+ assert all(defaults.values())++ by_name = {schema["name"]: schema for schema in build_default_schemas(schemas)}+ assert by_name["message_activity"] == {"name": "message_activity", "should_sync": False}+ assert by_name["bounces"]["should_sync"] is Truedef test_get_schemas_filters_by_names(self) -> None:schemas = SendGridSource().get_schemas(_config(), team_id=1, names=["bounces", "templates"])@@ -129,25 +150,43 @@ class TestSendGridSource:assert ok is expected_okassert (msg is not None) is expected_has_msg- def test_per_schema_403_names_the_missing_scope(self) -> None:+ @pytest.mark.parametrize(+ ("schema_name", "fragments"),+ [+ ("marketing_lists", ["marketing.read"]),+ ("message_activity", ["email_activity.read", "additional email activity history"]),+ ],+ )+ def test_per_schema_403_names_the_missing_scope(self, schema_name: str, fragments: list[str]) -> None:with patch(f"{_SOURCE_MODULE}.get_endpoint_status_code", return_value=403):- _ok, msg = SendGridSource().validate_credentials(_config(), team_id=1, schema_name="marketing_lists")+ _ok, msg = SendGridSource().validate_credentials(_config(), team_id=1, schema_name=schema_name)assert msg is not None- assert "marketing.read" in msg+ for fragment in fragments:+ assert fragment in msg- def test_get_endpoint_permissions_flags_only_the_unreadable_table(self) -> None:+ @pytest.mark.parametrize(+ ("gated_endpoint", "scope"),+ [+ ("marketing_lists", "marketing.read"),+ # The add-on gate must stay per-table: a 403 on message_activity cannot make the+ # picker (or a sync) treat any other table as unreachable.+ ("message_activity", "email_activity.read"),+ ],+ )+ def test_get_endpoint_permissions_flags_only_the_unreadable_table(self, gated_endpoint: str, scope: str) -> None:# The bug this guards: with no per-table probe every table looked reachable, so a key without- # `marketing.read` still got marketing_lists enabled, and the first sync hard-failed.+ # the scope still got the gated table enabled, and the first sync hard-failed.def status_for(_api_key: str, config: Any) -> int:- return 403 if config.name == "marketing_lists" else 200+ return 403 if config.name == gated_endpoint else 200with patch(f"{_TRANSPORT_MODULE}.get_endpoint_status_code", side_effect=status_for):permissions = SendGridSource().get_endpoint_permissions(_config(), team_id=1, endpoints=list(ALL_ENDPOINTS))- assert permissions["marketing_lists"] is not None- assert "marketing.read" in permissions["marketing_lists"]+ gated_reason = permissions[gated_endpoint]+ assert gated_reason is not None+ assert scope in gated_reasonassert {name: reason for name, reason in permissions.items() if reason is not None} == {- "marketing_lists": permissions["marketing_lists"]+ gated_endpoint: gated_reason}@pytest.mark.parametrize("name", sorted(ALL_ENDPOINTS))@@ -165,6 +204,23 @@ class TestSendGridSource:assert any("401" in key for key in errors)assert any("403" in key for key in errors)+ @pytest.mark.parametrize(+ ("error_url", "expected_fragment"),+ [+ # A /v3/messages 403 also matches the bare-host key, so the add-on entry must come+ # first in insertion order or users get the generic scope advice for a paid add-on gap.+ ("https://api.sendgrid.com/v3/messages?limit=1000", "additional email activity history"),+ ("https://api.sendgrid.com/v3/suppression/bounces?limit=500", "cannot read this table"),+ ],+ )+ def test_403_friendly_message_matches_the_failing_endpoint(self, error_url: str, expected_fragment: str) -> None:+ # Mirrors the job finalizer: the first matching key in insertion order supplies the message.+ error = f"403 Client Error: Forbidden for url: {error_url}"+ errors = SendGridSource().get_non_retryable_errors()+ matches = [message for key, message in errors.items() if key.lower() in error.lower()]+ assert matches and matches[0] is not None+ assert expected_fragment in matches[0]+def test_source_for_pipeline_plumbs_arguments(self) -> None:manager = MagicMock(spec=ResumableSourceManager)inputs = _source_inputs(