: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(warehouse): sync SendGrid global daily stats (#79949)
posthog[bot]17700c5e817f
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 56aca33d172d..801c3dd9573a 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,16 +16,17 @@ 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` |-| `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 |Notes:@@ -36,6 +37,13 @@ Notes:and paginate by following `_metadata.next`. `/templates` requires `generations=legacy,dynamic` to returnboth template types. Neither exposes a server-side timestamp filter, so both are full-refresh only.- `/asm/groups` returns the full set of unsubscribe groups in a single response with no pagination params.+- `/stats` returns global email statistics as a bare array of `{date, stats: [{metrics: {...}}]}`+ buckets. With `aggregated_by=day` (and no breakdown dimension) each bucket holds one `metrics`+ object, so it flattens to one flat row per day carrying `requests`, `delivered`, `opens`,+ `clicks`, `bounces`, `spam_reports`, etc. — the send-side denominators the suppression tables+ lack. `start_date` (YYYY-MM-DD) is a real server-side filter, so it syncs incrementally on the+ daily `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 notsynced here) is capped at ~6 req/min — webhook ingestion is the recommended path for per-event data andis left as a follow-up.diff --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 4a69eb42f8d8..3bd95d3ba186 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@@ -51,6 +51,29 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"created": "Time at which the address was added to the global unsubscribe list, as a Unix timestamp.",},},+ "stats": {+ "description": "Global email statistics aggregated per day — the send-side volume (requests, delivered, opens, clicks) that turns suppression counts into deliverability rates.",+ "docs_url": "https://www.twilio.com/docs/sendgrid/api-reference/stats/retrieve-global-email-statistics",+ "columns": {+ "date": "The day the statistics cover, as a YYYY-MM-DD date.",+ "requests": "Number of emails requested to be sent.",+ "processed": "Number of emails processed and handed off for delivery.",+ "delivered": "Number of emails successfully delivered to the recipient's mail server.",+ "deferred": "Number of emails temporarily rejected by the recipient's mail server.",+ "bounces": "Number of emails that bounced — permanently rejected by the receiving server.",+ "bounce_drops": "Number of emails dropped before sending because the address was on the bounce suppression list.",+ "blocks": "Number of emails blocked due to a temporary delivery issue such as a full mailbox.",+ "opens": "Total number of times delivered emails were opened, including repeat opens.",+ "unique_opens": "Number of unique recipients who opened a delivered email.",+ "clicks": "Total number of times links in delivered emails were clicked, including repeat clicks.",+ "unique_clicks": "Number of unique recipients who clicked a link in a delivered email.",+ "unsubscribes": "Number of recipients who unsubscribed.",+ "unsubscribe_drops": "Number of emails dropped because the address was on an unsubscribe suppression list.",+ "spam_reports": "Number of recipients who marked a delivered email as spam.",+ "spam_report_drops": "Number of emails dropped because the address had previously reported spam.",+ "invalid_emails": "Number of emails dropped because the recipient address was invalid.",+ },+ },"unsubscribe_groups": {"description": "Suppression (unsubscribe) groups used to let recipients opt out of specific categories of mail.","docs_url": "https://www.twilio.com/docs/sendgrid/api-reference/suppressions-unsubscribe-groups/retrieve-all-suppression-groups-associated-with-the-user",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 7e783e07e6b3..abedb68f4bd6 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,5 +1,5 @@import dataclasses-from datetime import UTC, date, datetime+from datetime import UTC, date, datetime, timedeltafrom typing import Any, Optionalfrom urllib.parse import parse_qs, urlencode, urlparse@@ -16,6 +16,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resOffsetPaginator,SinglePagePaginator,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom 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 SourceResponse@@ -58,6 +59,44 @@ def _to_epoch_seconds(value: Any) -> int:return int(value)+def _to_date_string(value: Any) -> str:+ """Coerce an incremental cursor value to a `YYYY-MM-DD` string for the `start_date` filter.++ The stats `date` field is a bare date string, but the pipeline may hand the cursor back as a+ datetime/date depending on how it round-tripped through storage.+ """+ if isinstance(value, datetime):+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return dt.date().isoformat()+ if isinstance(value, date):+ return value.isoformat()+ if isinstance(value, int | float):+ return datetime.fromtimestamp(value, tz=UTC).date().isoformat()+ # Already a string: trust the leading YYYY-MM-DD, tolerating a trailing time component.+ return str(value)[:10]+++def _format_cursor(value: Any, param_format: str) -> Any:+ return _to_date_string(value) if param_format == "date" else _to_epoch_seconds(value)+++def _default_backfill_value(config: SendGridEndpointConfig) -> Any:+ assert config.default_backfill_days is not None+ start = datetime.now(UTC) - timedelta(days=config.default_backfill_days)+ return _format_cursor(start, config.incremental_param_format)+++def _flatten_daily_stats(item: dict[str, Any]) -> list[dict[str, Any]]:+ """Flatten one `{date, stats: [{metrics: {...}}]}` bucket into a row per metrics entry, with the+ bucket `date` merged in. `aggregated_by=day` with no breakdown yields one row per date."""+ date_value = item.get("date")+ rows: list[dict[str, Any]] = []+ for entry in item.get("stats") or []:+ metrics = entry.get("metrics") or {}+ rows.append({"date": date_value, **metrics})+ return rows++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"])@@ -115,15 +154,20 @@ def _build_params(if config.pagination == "metadata":params["page_size"] = config.page_size- if (- should_use_incremental_field- and config.incremental_param- and incremental_field- and db_incremental_field_last_value is not None- ):- # start_time is inclusive (created >= start_time); the boundary row re-appears but merge- # dedupes it on the primary key.- params[config.incremental_param] = _to_epoch_seconds(db_incremental_field_last_value)+ if config.incremental_param:+ cursor = (+ db_incremental_field_last_value+ if (should_use_incremental_field and incremental_field and db_incremental_field_last_value is not None)+ else None+ )+ if cursor is not None:+ # The filter is inclusive (e.g. created >= start_time); the boundary row re-appears but+ # merge dedupes it on the primary key.+ params[config.incremental_param] = _format_cursor(cursor, config.incremental_param_format)+ elif config.default_backfill_days is not None:+ # No cursor, but the API requires the start param (stats). Backfill a fixed window rather+ # than sending a request the API would reject.+ params[config.incremental_param] = _default_backfill_value(config)return params@@ -168,6 +212,23 @@ def sendgrid_source(params = _build_params(config, should_use_incremental_field, db_incremental_field_last_value, incremental_field)+ resource_config: EndpointResource = {+ "name": endpoint,+ "endpoint": {+ "path": config.path,+ "params": params,+ # data_key wraps the array for metadata endpoints ("result"); None means the body+ # is the array itself (suppression/asm/stats). Fail loud on a shape change instead+ # of silently syncing 0 rows.+ "data_selector": config.data_key,+ "data_selector_required": True,+ },+ }++ if config.response_shape == "daily_stats":+ # stats rows are nested one level deeper than the bare array; flatten them into flat daily rows.+ resource_config["data_map"] = _flatten_daily_stats+rest_config: RESTAPIConfig = {"client": {"base_url": SENDGRID_BASE_URL,@@ -178,20 +239,7 @@ def sendgrid_source("paginator": _build_paginator(config),},"resource_defaults": {},- "resources": [- {- "name": endpoint,- "endpoint": {- "path": config.path,- "params": params,- # data_key wraps the array for metadata endpoints ("result"); None means the body- # is the array itself (suppression/asm). Fail loud on a shape change instead of- # silently syncing 0 rows.- "data_selector": config.data_key,- "data_selector_required": True,- },- }- ],+ "resources": [resource_config],}initial_paginator_state = _initial_paginator_state(config, resumable_source_manager)diff --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 e9a4cf5789c6..a9de9f619bf0 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@@ -9,6 +9,22 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment# - "single": one request returns the whole list, no pagination params.PaginationMode = Literal["offset", "metadata", "single"]+# How the incremental cursor is serialized into the `incremental_param` query value:+# - "epoch": Unix epoch seconds (suppression `start_time`).+# - "date": `YYYY-MM-DD` (stats `start_date`).+IncrementalParamFormat = Literal["epoch", "date"]++# Shape of a 200 response body, so the transport knows whether it needs flattening:+# - "array": the rows are the JSON body itself, or the array under `data_key`.+# - "daily_stats": nested `[{date, stats: [{metrics: {...}}]}]` that flattens to one row per+# metrics bucket with `date` merged in (the /stats family).+ResponseShape = Literal["array", "daily_stats"]++# /stats requires `start_date` on every request, so the first sync (no cursor yet) backfills this+# far back. Daily aggregation means one row per day, so a year is cheap and gives enough history to+# compare deliverability trends.+STATS_DEFAULT_BACKFILL_DAYS = 365+@dataclassclass SendGridEndpointConfig:@@ -23,8 +39,16 @@ class SendGridEndpointConfig:partition_key: Optional[str] = Nonepage_size: int = 500incremental_fields: list[IncrementalField] = field(default_factory=list)- # Server-side query param that filters by the incremental field (Unix epoch seconds).+ # Server-side query param that filters by the incremental field.incremental_param: Optional[str] = None+ # How the cursor value is written into `incremental_param`.+ incremental_param_format: IncrementalParamFormat = "epoch"+ # Number of days back to backfill when `incremental_param` is required by the API but there's no+ # cursor yet (first sync, or full refresh). None leaves the param off unless a cursor exists —+ # the right default for a genuinely optional filter like the suppression endpoints' `start_time`.+ default_backfill_days: Optional[int] = None+ # How the response body is shaped, so the transport can flatten nested stats responses.+ response_shape: ResponseShape = "array"# 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@@ -44,10 +68,20 @@ def _epoch_field(name: str) -> IncrementalField:}+def _date_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.Date,+ "field": name,+ "field_type": IncrementalFieldType.Date,+ }++# 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. Marketing/asm metadata endpoints offer no timestamp filter and ship as full-# refresh. See api_inventory.md for the per-endpoint research notes.+# incrementally. `stats` filters on `start_date` (YYYY-MM-DD) over its daily aggregate date and+# also syncs incrementally. Marketing/asm metadata endpoints offer no timestamp filter and ship as+# full refresh. See api_inventory.md for the per-endpoint research notes.SENDGRID_ENDPOINTS: dict[str, SendGridEndpointConfig] = {"bounces": SendGridEndpointConfig(name="bounces",@@ -99,6 +133,23 @@ SENDGRID_ENDPOINTS: dict[str, SendGridEndpointConfig] = {incremental_param="start_time",required_scope="suppression.unsubscribes.read",),+ "stats": SendGridEndpointConfig(+ name="stats",+ path="/stats",+ primary_keys=["date"],+ # /stats returns the whole date range in one bare-array response — no pagination params.+ pagination="single",+ partition_key="date",+ incremental_fields=[_date_field("date")],+ # start_date is a genuine server-side filter, so this endpoint syncs incrementally on the+ # daily aggregate date. start_date is required, so a cursorless sync backfills a fixed window.+ incremental_param="start_date",+ incremental_param_format="date",+ default_backfill_days=STATS_DEFAULT_BACKFILL_DAYS,+ response_shape="daily_stats",+ extra_params={"aggregated_by": "day"},+ required_scope="stats.read",+ ),"unsubscribe_groups": SendGridEndpointConfig(name="unsubscribe_groups",path="/asm/groups",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 661ec386ae88..978687918e88 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@@ -150,6 +150,7 @@ You can create an API key in your [SendGrid account settings](https://app.sendgrGrant the following read access (Restricted Access) so the key can reach the data you want to sync:- **Suppressions**: bounces, blocks, invalid emails, spam reports, global unsubscribes, unsubscribe groups+- **Stats**: global email statistics (daily requests, delivered, opens, clicks, bounces)- **Marketing**: marketing lists. This also needs an account with Marketing Campaigns enabled.- **Template Engine**: templatesdiff --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 381dd19d4770..32107c1b4c06 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@@ -11,6 +11,7 @@ from requests import Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.sendgrid.sendgrid import (SendGridResumeConfig,_offset_from_url,+ _to_date_string,_to_epoch_seconds,get_endpoint_permissions,get_status_code,@@ -84,6 +85,74 @@ class TestToEpochSeconds:assert _to_epoch_seconds(datetime(2023, 11, 14, 22, 13, 20)) == 1700000000+class TestToDateString:+ @pytest.mark.parametrize(+ ("value", "expected"),+ [+ ("2024-01-15", "2024-01-15"),+ ("2024-01-15T00:00:00", "2024-01-15"),+ (date(2024, 1, 15), "2024-01-15"),+ (datetime(2024, 1, 15, 22, 13, 20, tzinfo=UTC), "2024-01-15"),+ # Epoch seconds — the cursor may round-trip through storage as a number.+ (1705270400, "2024-01-14"),+ ],+ )+ def test_to_date_string(self, value: Any, expected: str) -> None:+ assert _to_date_string(value) == expected++ def test_naive_datetime_treated_as_utc(self) -> None:+ assert _to_date_string(datetime(2024, 1, 15, 22, 13, 20)) == "2024-01-15"+++class TestStats:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_flattens_nested_daily_metrics_into_one_row_per_day(self, MockSession) -> None:+ session = MockSession.return_value+ body = [+ {"date": "2024-01-01", "stats": [{"metrics": {"requests": 10, "delivered": 8, "bounces": 1}}]},+ {"date": "2024-01-02", "stats": [{"metrics": {"requests": 5, "delivered": 5, "bounces": 0}}]},+ ]+ params, _urls = _wire(session, [_response(body)])++ rows = _rows(_source("stats", _make_manager()))++ # The nested {date, stats:[{metrics}]} shape flattens to flat daily rows the denominator lives on.+ assert rows == [+ {"date": "2024-01-01", "requests": 10, "delivered": 8, "bounces": 1},+ {"date": "2024-01-02", "requests": 5, "delivered": 5, "bounces": 0},+ ]+ assert params[0]["aggregated_by"] == "day"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_first_sync_backfills_a_required_start_date(self, MockSession) -> None:+ session = MockSession.return_value+ params, _urls = _wire(session, [_response([])])++ # /stats rejects a request with no start_date, so a cursorless sync must still send one.+ _rows(_source("stats", _make_manager()))++ assert "start_date" in params[0]+ # A YYYY-MM-DD string, not epoch seconds — the format /stats requires.+ datetime.strptime(params[0]["start_date"], "%Y-%m-%d")++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_incremental_cursor_becomes_a_date_formatted_start_date(self, MockSession) -> None:+ session = MockSession.return_value+ params, _urls = _wire(session, [_response([])])++ _rows(+ _source(+ "stats",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-03-10",+ incremental_field="date",+ )+ )++ assert params[0]["start_date"] == "2024-03-10"++class TestOffsetFromUrl:@pytest.mark.parametrize(("url", "expected"),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 6402764e4217..899def3354b2 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@@ -24,11 +24,21 @@ ALL_ENDPOINTS = {"invalid_emails","spam_reports","global_unsubscribes",+ "stats","unsubscribe_groups","marketing_lists","templates",}-INCREMENTAL_ENDPOINTS = {"bounces", "blocks", "invalid_emails", "spam_reports", "global_unsubscribes"}+# Endpoints that sync incrementally, mapped to the cursor field they expose. Everything else is+# full refresh.+INCREMENTAL_FIELD_BY_ENDPOINT = {+ "bounces": "created",+ "blocks": "created",+ "invalid_emails": "created",+ "spam_reports": "created",+ "global_unsubscribes": "created",+ "stats": "date",+}def _config() -> SendGridSourceConfig:@@ -79,14 +89,16 @@ class TestSendGridSource:schemas = SendGridSource().get_schemas(_config(), team_id=1)assert {s.name for s in schemas} == ALL_ENDPOINTS- def test_only_suppression_endpoints_support_incremental(self) -> None:+ def test_incremental_endpoints_expose_their_cursor_field(self) -> None:schemas = {s.name: s for s in SendGridSource().get_schemas(_config(), team_id=1)}- for name in INCREMENTAL_ENDPOINTS:- assert schemas[name].supports_incremental is True- assert {f["field"] for f in schemas[name].incremental_fields} == {"created"}- for name in ALL_ENDPOINTS - INCREMENTAL_ENDPOINTS:- assert schemas[name].supports_incremental is False- assert schemas[name].incremental_fields == []+ for name in ALL_ENDPOINTS:+ expected_field = INCREMENTAL_FIELD_BY_ENDPOINT.get(name)+ if expected_field is None:+ assert schemas[name].supports_incremental is False+ assert schemas[name].incremental_fields == []+ else:+ assert schemas[name].supports_incremental is True+ assert {f["field"] for f in schemas[name].incremental_fields} == {expected_field}def test_get_schemas_filters_by_names(self) -> None:schemas = SendGridSource().get_schemas(_config(), team_id=1, names=["bounces", "templates"])