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(workflows): show email sending health per mailbox provider (#89643)

Daniel Marchuk8785c53e0d34
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 159745e6bd97..6eec9d4b3738 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5668,6 +5668,26 @@ snapshots:
hash: v1.k794b7964.d553cecf3e544087316e1687404c8e2b3a6c19f618a05e09880e60e656054f23.hNkLLb04XLyd-PQJa59WwPhgRAxMbW5fSDzCnowJKBs
products-workflows-customerioimportmodal--step-4-track-not-configured--light:
hash: v1.k794b7964.0954891b73cdc0b1bce1275fa11a5fa4af2055b83b518bce82f3fde886097659.mgEq2W8sZg7x-vt8z2EpwEHPBGRzPI1GWtn-9tu-46o
+ products-workflows-reputation--domain-withheld-from-caller--dark:
+ hash: v1.k794b7964.b37b29c7894aedb7ca34c4976577e3aaed60f5e81a99d29c427ad4d5eeaf16ce.p2UYtjwRYsZEy_dF6JZTqzYZC8PD-WIUSALXCQGdpjM
+ products-workflows-reputation--domain-withheld-from-caller--light:
+ hash: v1.k794b7964.091ed3d12a75d2aff814c3ecc26ad7d35dc873a63c251610da3169c7e3c6b680.cFmrImD6HC6l6l-qkl5o_W89NUSW2NeK0PN6orswmZI
+ products-workflows-reputation--no-provider-data--dark:
+ hash: v1.k794b7964.fb4106e727cdaf881bb150dc59925f5259d21e78cb9efa7e452e3440c143c93b.JPlPndGIFWdaK3sS9Gh0YICf3ncO7E_jOxe5SII9hHM
+ products-workflows-reputation--no-provider-data--light:
+ hash: v1.k794b7964.dd0d5b8e28e1b9da35ac9aa7c0995b196e75006f4701c5ce2e32450e46b99359.vJQb1izatw_Q0naM9-YnUKg2ei7iujSXmDWR_DMOq00
+ products-workflows-reputation--one-provider-filtering--dark:
+ hash: v1.k794b7964.92b02e7b495e49fe4144e7460353bfe8d5796d20d9dd8cf48616072a535a89db.dWt1D72wV2hkJ8fmeTdQLYyM1BOykBmwO6HXykizg-E
+ products-workflows-reputation--one-provider-filtering--light:
+ hash: v1.k794b7964.3a0e798862115615854952e8305e9d560c2101e008ae3ae2facc0565a06019ce.ss-Ct9nK4UYLm-ZE7u9-T_NPIVLemYu_oJraUMjOczA
+ products-workflows-reputation--provider-data-without-workflow-rates--dark:
+ hash: v1.k794b7964.cc1ca040344e8041180a40b570f65d87f0528f74d08a4b8c7b41309efe404fc8.Niki9f84ric2-PTt-cjcgUIg0pIGS9KLodvHLAD6Pkc
+ products-workflows-reputation--provider-data-without-workflow-rates--light:
+ hash: v1.k794b7964.e111b58bcf61a72f106c04b7fd9085b9655b158f1ad3b7b022dbf18532b25858.zGZM4bwaoK7UN9LTuA-k9Vwv9DNrp0da9IytJTQCeeY
+ products-workflows-reputation--shared-sending-domain--dark:
+ hash: v1.k794b7964.08d8d17e823645bb6ebf7e2a6cb2cbb104a9f9048e8d99c01c134ce6b40306ae.MJQg25tB-WNOTBHJMyC7HVyPdzp1rgBB6YZz51ISpzU
+ products-workflows-reputation--shared-sending-domain--light:
+ hash: v1.k794b7964.d2215990d8282ab50a609d06cd15a1fb1de67cea1bc7a8acebef9b524c21b76d.0MlLPljZzWeXjETyXzX4JvaDP1ckpC-eXIjMQS43Dmg
products-workflows-steps-delay--date-not-chosen-yet--dark:
hash: v1.k794b7964.ec9c913ba6edb54c2b521e3b1913e45fe914dcd4fc5b45febacd543038865cd0.khqeV0deGQR_Ows3heRrRyvzw8fUBJ6KUNQbhb1asas
products-workflows-steps-delay--date-not-chosen-yet--light:
diff --git a/frontend/src/lib/components/Sparkline.tsx b/frontend/src/lib/components/Sparkline.tsx
index a3eae5514442..27037dc3789d 100644
--- a/frontend/src/lib/components/Sparkline.tsx
+++ b/frontend/src/lib/components/Sparkline.tsx
@@ -2,7 +2,7 @@ import clsx from 'clsx'
import { useCallback, useMemo } from 'react'
import { DefaultTooltip, Sparkline as QuillSparklineChart, useChartTheme } from '@posthog/quill-charts'
-import type { Series, TooltipContext } from '@posthog/quill-charts'
+import type { Series, TooltipContext, ValueDomain } from '@posthog/quill-charts'
import { getColorVar } from 'lib/colors'
import { humanFriendlyNumber } from 'lib/utils/numbers'
@@ -41,6 +41,9 @@ export interface SparklineProps {
sortTooltipByCount?: boolean
/** Format the per-series tooltip value. Defaults to `humanFriendlyNumber`. */
renderTooltipValue?: (value: number) => string
+ /** Pin the value axis instead of auto-scaling to the data, so sparklines in a column stay
+ * comparable to each other. */
+ valueDomain?: ValueDomain
}
function normalizeSparklineData(
@@ -112,6 +115,7 @@ export function Sparkline({
hideZerosInTooltip = false,
sortTooltipByCount = false,
renderTooltipValue,
+ valueDomain,
}: SparklineProps): JSX.Element {
const theme = useChartTheme()
@@ -156,6 +160,7 @@ export function Sparkline({
labels={chartLabels}
theme={theme}
type={type}
+ valueDomain={valueDomain}
fill
className="h-full"
tooltip={renderTooltip}
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index ba724f09451c..15f325929984 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -578,6 +578,7 @@ export const FEATURE_FLAGS = {
WORKFLOWS_EMAIL_REPUTATION: 'workflows-email-reputation', // owner: #team-workflows
WORKFLOWS_EMAIL_SENDER_ROTATION: 'workflows-email-sender-rotation', // owner: @arthurdedeus #team-workflows
WORKFLOWS_INTERNAL_EVENT_FILTERS: 'workflows-internal-event-filters', // owner: @haven #team-workflows
+ WORKFLOWS_ISP_SENDING_HEALTH: 'workflows-isp-sending-health', // owner: #team-workflows
WORKFLOWS_PUSH_NOTIFICATIONS: 'workflows-push-notifications', // owner: #team-workflows
XAA_AUTHENTICATION: 'xaa-authentication', // owner: @reecejones #team-platform-features
} as const
diff --git a/packages/quill/packages/charts/src/charts/Sparkline/Sparkline.tsx b/packages/quill/packages/charts/src/charts/Sparkline/Sparkline.tsx
index 06342cb5d714..344be4743713 100644
--- a/packages/quill/packages/charts/src/charts/Sparkline/Sparkline.tsx
+++ b/packages/quill/packages/charts/src/charts/Sparkline/Sparkline.tsx
@@ -3,7 +3,7 @@ import React, { useEffect, useMemo } from 'react'
import { useChartHover } from '../../core/chart-context'
import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
import { useLatest } from '../../core/hooks/useLatest'
-import type { BarChartConfig, ChartTheme, LineChartConfig, Series, TooltipContext } from '../../core/types'
+import type { BarChartConfig, ChartTheme, LineChartConfig, Series, TooltipContext, ValueDomain } from '../../core/types'
import { BarChart } from '../BarChart/BarChart'
import { LineChart } from '../LineChart/LineChart'
@@ -28,6 +28,9 @@ export interface SparklineProps {
fillOpacity?: number
/** Dash the line from this index onward (e.g. an in-progress trailing period). Omit for a fully solid line. */
dashedFromIndex?: number
+ /** Value-axis domain control — omit for data-derived auto-scaling. Pin both ends to keep
+ * separate sparklines comparable (e.g. a column of per-provider rates all read against 0–100). */
+ valueDomain?: ValueDomain
/** Fires the hovered index, or -1 when not hovering. */
onHoverIndexChange?: (index: number) => void
/** Tooltip content renderer. Sparkline tooltips are off by default; supplying this enables them. */
@@ -72,6 +75,7 @@ function SparklineInner({
fill = false,
fillOpacity = 0.35,
dashedFromIndex,
+ valueDomain,
onHoverIndexChange,
tooltip,
className,
@@ -111,8 +115,9 @@ function SparklineInner({
}
: { showCrosshair: true, margins: LINE_MARGINS }),
...(hasTooltip ? {} : { tooltip: { enabled: false } }),
+ ...(valueDomain ? { valueDomain } : {}),
}),
- [type, hasTooltip]
+ [type, hasTooltip, valueDomain]
)
const wrapperStyle = useMemo<React.CSSProperties | undefined>(() => (fill ? undefined : { height }), [fill, height])
diff --git a/posthog/settings/ses.py b/posthog/settings/ses.py
index 659ff307e428..7b606c760f8b 100644
--- a/posthog/settings/ses.py
+++ b/posthog/settings/ses.py
@@ -33,3 +33,20 @@ SES_TENANT_CONFIGURATION_SETS: list[str] = [
WORKFLOWS_SES_EVENTS_SNS_TOPIC_ARNS: list[str] = [
arn.strip() for arn in os.getenv("WORKFLOWS_SES_EVENTS_SNS_TOPIC_ARNS", "").split(",") if arn.strip()
]
+
+# SES ISP dimension values to break sending health down by. The only API that names providers is
+# GetDomainStatisticsReport, which needs the Deliverability dashboard subscription, so the list
+# comes from us, and SES gives no way to check a name up front: it validates the format only, and
+# accepts any well-formed word, inventions included. Two consequences.
+#
+# A name SES has no data for is harmless. It costs one query set and yields no row, because
+# providers with zero sends are dropped. That is why both spellings are listed for the two
+# families whose SES name is unconfirmed, Microsoft and Apple: the right one wins and the other
+# disappears. Prune the losers once VDM has collected.
+#
+# A name holding "." or "&" is not harmless. SES rejects "Mail.ru", "Web.de" and "AT&T" with
+# BadRequestException, which fails the whole BatchGetMetricData request and hides the entire
+# breakdown rather than one row. Those are plausible providers to reach for, so check a new value
+# against the API before adding it: query SEND for the name over a window VDM has data for, and
+# treat volume as the only proof the name is real.
+SES_ISP_DIMENSIONS: list[str] = ["Gmail", "Yahoo", "Outlook", "Hotmail", "Apple", "iCloud"]
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 2681c1eab6a0..8d4f2b6aed15 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -85,6 +85,8 @@ from posthog.dataclasses import frozen
from posthog.event_usage import AGENT_EVENT_SOURCES, EventSource, get_event_source, report_user_action
from posthog.models import Team
from posthog.models.filters import Filter
+from posthog.models.integration import Integration
+from posthog.permissions import posthog_feature_flag_enabled
from posthog.plugins.plugin_server_api import (
cancel_hog_flow_batch_job,
cancel_hog_flow_invocations,
@@ -94,9 +96,10 @@ from posthog.plugins.plugin_server_api import (
rerun_hog_invocations,
)
from posthog.synthetic_user import SyntheticUser
+from posthog.user_permissions import UserPermissions
from posthog.utils import relative_date_parse_with_delta_mapping
-from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.access_control.backend.facade.user_access_control import UserAccessControl, visible_teams_for_user
from products.access_control.backend.presentation.access_control import (
AccessControlViewSetMixin,
UserAccessControlSerializerMixin,
@@ -2210,6 +2213,167 @@ def _fetch_aws_tenant_reputation(team_id: int) -> dict[str, Any] | None:
return value
+# VDM aggregates by whole day and the window ends at the last UTC midnight, so these numbers move
+# at most once a day. A five-minute TTL bought nothing and cost a full fan-out on every expiry.
+# One refresh of five domains is 150 queries across 15 sequential BatchGetMetricData calls, and the
+# endpoint reloads on every search keystroke, so this is what keeps typing a workflow name from
+# costing a fan-out per character.
+ISP_METRICS_CACHE_SECONDS = 30 * 60
+# A failure is cached too, briefly: without it an unreachable SES is retried in full per keystroke.
+ISP_METRICS_ERROR_CACHE_SECONDS = 60
+# Held while one request does the fan-out so a cold key admits one, not all of them. Typing races
+# concurrent misses through the same key, and each miss can hold a worker for the whole query
+# budget. Longer than that budget, so the holder always outlives its own work.
+ISP_METRICS_REFRESH_LOCK_SECONDS = 30
+# Bounds the BatchGetMetricData fan-out: every extra domain costs one query per provider per
+# metric. A project with more sending domains gets a breakdown over its first few.
+ISP_METRICS_MAX_DOMAINS = 5
+# Shared with FEATURE_FLAGS in frontend/src/lib/constants.tsx.
+ISP_SENDING_HEALTH_FLAG = "workflows-isp-sending-health"
+
+
+def _isp_breakdown_enabled(team: Team) -> bool:
+ # The shared helper suppresses the $feature_flag_called exposure event (this gate runs on every
+ # reputation request, not once per person) and honors _FORCE_ENABLED_FLAGS like other internal
+ # gates. It does not catch, so the try/except stays to fail closed when a flag-eval errors.
+ try:
+ return posthog_feature_flag_enabled(
+ ISP_SENDING_HEALTH_FLAG,
+ str(team.uuid),
+ organization_id=team.organization_id,
+ team_id=team.id,
+ )
+ except Exception:
+ logger.warning(
+ "workflows.isp_sending_health_flag_check_failed_defaulting_off",
+ team_id=team.id,
+ exc_info=True,
+ )
+ return False
+
+
+@frozen
+class IspDomains:
+ """Which of this project's sending domains the breakdown may cover, and what to say about them."""
+
+ # Domains whose metrics the caller may read.
+ readable: tuple[str, ...]
+ # Domains hidden because a project behind them is one the caller cannot open.
+ withheld: tuple[str, ...]
+ # Readable domains another project also sends from, so their counts include its email.
+ shared: tuple[str, ...]
+
+
+def _isp_domains(team: Team, user_access_control: UserAccessControl, user_permissions: UserPermissions) -> IspDomains:
+ """
+ Resolve this project's verified sending domains against who else sends from them.
+
+ VDM keys its metrics on the domain, so a domain a second project also sends from returns both
+ projects' email. Reading that needs access to every project behind the domain: without it the
+ breakdown would hand a member the daily volume of a project they cannot open. A domain that
+ survives that check but is still shared gets said so, because its counts describe more email
+ than this project sent.
+ """
+ domains = list(
+ dict.fromkeys(
+ domain
+ for domain in Integration.objects.filter(team_id=team.id, kind="email", config__verified=True)
+ .order_by("id")
+ .values_list("config__domain", flat=True)
+ if domain
+ )
+ )
+ if not domains:
+ return IspDomains(readable=(), withheld=(), shared=())
+
+ sharers: dict[str, set[int]] = {domain: set() for domain in domains}
+ for domain, sharer_id in (
+ Integration.objects.filter(kind="email", config__verified=True, config__domain__in=domains)
+ .exclude(team_id=team.id)
+ .values_list("config__domain", "team_id")
+ ):
+ sharers[domain].add(sharer_id)
+
+ if not any(sharers.values()):
+ return IspDomains(readable=tuple(domains), withheld=(), shared=())
+
+ # A sharer outside this organization is never visible, so a cross-organization domain fails
+ # closed through the same subset test rather than needing a branch of its own. Not dead code:
+ # the guard in EmailIntegration.create_native_integration matches config__domain exactly, so a
+ # subdomain of a domain another organization verified is not blocked from being added.
+ visible = set(
+ visible_teams_for_user(team.organization, user_access_control, user_permissions).values_list("id", flat=True)
+ )
+ # Partitioned in one pass so the two lists stay complements. Set comparison is a partial order,
+ # not a total one, so a domain whose sharers are neither a subset nor a superset of the visible
+ # teams would fall through a pair of independent tests and be reported as neither.
+ readable: list[str] = []
+ withheld: list[str] = []
+ for domain in domains:
+ (readable if sharers[domain] <= visible else withheld).append(domain)
+ return IspDomains(
+ readable=tuple(readable),
+ withheld=tuple(withheld),
+ shared=tuple(domain for domain in readable if sharers[domain]),
+ )
+
+
+def _fetch_isp_metrics(team_id: int, window_days: int, domains: list[str]) -> list[dict[str, Any]]:
+ """
+ Per-mailbox-provider sending health for the given sending domains, cached like the tenant
+ reputation above and for the same reason: the endpoint reloads on every search keystroke.
+
+ Returns an empty list rather than raising when SES is unreachable or VDM is not collecting yet,
+ because the breakdown adds to the rates display and must not stop it loading.
+ """
+ if not domains:
+ return []
+ # The domain set depends on what the caller may see, so it belongs in the key: two members of
+ # one project can be entitled to different domains, and one must not be served the other's.
+ domain_key = hashlib.sha256("|".join(domains).encode()).hexdigest()[:12]
+ cache_key = f"workflows_ses_isp_metrics_{team_id}_{window_days}_{domain_key}"
+ cached = cache.get(cache_key)
+ if cached is not None:
+ return cached["value"]
+
+ # Losers show no breakdown rather than queueing behind the holder: the rates above are what the
+ # page is for, and a second fan-out would buy a number the next reload gets from cache anyway.
+ if not cache.add(f"{cache_key}_refreshing", True, ISP_METRICS_REFRESH_LOCK_SECONDS):
+ return []
+
+ try:
+ rows = SESProvider().get_identity_isp_metrics(
+ domains, window_days=window_days, max_domains=ISP_METRICS_MAX_DOMAINS
+ )
+ except Exception:
+ logger.exception("Failed to fetch SES per-ISP metrics", team_id=team_id)
+ cache.set(cache_key, {"value": []}, ISP_METRICS_ERROR_CACHE_SECONDS)
+ return []
+
+ value = [
+ {
+ "isp": row.isp,
+ "emails_sent": row.emails_sent,
+ "delivery_rate": row.delivery_rate,
+ "bounce_rate": row.bounce_rate,
+ "complaint_rate": row.complaint_rate,
+ "unavailable": list(row.unavailable),
+ "daily": [
+ {
+ "date": point.date,
+ "emails_sent": point.emails_sent,
+ "delivery_rate": point.delivery_rate,
+ "bounce_rate": point.bounce_rate,
+ }
+ for point in row.daily
+ ],
+ }
+ for row in rows
+ ]
+ cache.set(cache_key, {"value": value}, ISP_METRICS_CACHE_SECONDS)
+ return value
+
+
class EmailSendingRatesSerializer(serializers.Serializer):
"""Bounce/complaint rates over the last 30 days of workflow email, computed on the fly from app metrics."""
@@ -2295,6 +2459,71 @@ class AwsTenantReputationSerializer(serializers.Serializer):
)
+class IspDailyPointSerializer(serializers.Serializer):
+ """One bucket of a provider's sending history."""
+
+ date = serializers.CharField(read_only=True, help_text="Bucket date, as an ISO 8601 calendar date.")
+ emails_sent = serializers.IntegerField(read_only=True, help_text="Emails sent to this provider on this date.")
+ delivery_rate = serializers.FloatField(
+ read_only=True, help_text="Emails this provider accepted on this date, divided by emails sent to it (0-1)."
+ )
+ bounce_rate = serializers.FloatField(
+ read_only=True, help_text="Hard bounces at this provider on this date, divided by emails sent to it (0-1)."
+ )
+
+
+class IspSendingHealthSerializer(serializers.Serializer):
+ """How one mailbox provider treated this project's email, from AWS SES's own delivery data."""
+
+ isp = serializers.CharField(
+ read_only=True,
+ help_text="The recipient mailbox provider, as AWS names it — for example Gmail or Yahoo.",
+ )
+ emails_sent = serializers.IntegerField(read_only=True, help_text="Emails sent to this provider during the window.")
+ delivery_rate = serializers.FloatField(
+ read_only=True,
+ allow_null=True,
+ help_text=(
+ "Emails this provider accepted, divided by emails sent to it (0-1). Acceptance is not "
+ "inbox placement: a provider can accept a message and still file it as spam. Null when "
+ "the underlying metric could not be loaded from AWS, which is not the same as zero."
+ ),
+ )
+ bounce_rate = serializers.FloatField(
+ read_only=True,
+ allow_null=True,
+ help_text=(
+ "Hard (permanent) bounces at this provider, divided by emails sent to it (0-1). Null "
+ "when the underlying metric could not be loaded from AWS."
+ ),
+ )
+ complaint_rate = serializers.FloatField(
+ read_only=True,
+ allow_null=True,
+ help_text=(
+ "Spam complaints from this provider, divided by the deliveries it reports complaints "
+ "for (0-1). Null when there is no rate to state — the provider runs no feedback loop, "
+ "or nothing was delivered — and also when the metric could not be loaded from AWS."
+ ),
+ )
+ unavailable = serializers.ListField(
+ child=serializers.CharField(),
+ read_only=True,
+ help_text=(
+ "Rates AWS did not return for this provider, from `delivery`, `bounce` and `complaint`. "
+ "A rate named here is missing, not zero, and the UI says so rather than showing a number."
+ ),
+ )
+ daily = IspDailyPointSerializer(
+ many=True,
+ read_only=True,
+ help_text=(
+ "Sending history for this provider, oldest first, so a drop can be dated rather than "
+ "averaged into the window. Dates this provider received nothing are omitted."
+ ),
+ )
+
+
class EmailSendingAllowanceSerializer(serializers.Serializer):
"""How much workflow email this project may send, and how much of that it has used."""
@@ -2345,6 +2574,30 @@ class TeamEmailReputationResponseSerializer(serializers.Serializer):
read_only=True,
help_text="Rates per workflow, worst first (complaint rate, then bounce rate), capped at the worst 50.",
)
+ isps = IspSendingHealthSerializer(
+ many=True,
+ read_only=True,
+ help_text=(
+ "Sending health per mailbox provider, busiest first. Empty when the caller lacks "
+ "project-wide workflow access, no sending domain is verified, or AWS has no data yet."
+ ),
+ )
+ isp_shared_domains = serializers.ListField(
+ child=serializers.CharField(),
+ read_only=True,
+ help_text=(
+ "Sending domains behind the breakdown that another project also sends from, so its "
+ "counts include that project's email. Empty when every domain is this project's alone."
+ ),
+ )
+ isp_withheld_domains = serializers.ListField(
+ child=serializers.CharField(),
+ read_only=True,
+ help_text=(
+ "Sending domains left out of the breakdown because another project sends from them and "
+ "the caller cannot access that project. Empty when nothing is withheld."
+ ),
+ )
email_sending_suspended = serializers.BooleanField(
read_only=True,
help_text="True while workflow email sending is suspended for this project to protect deliverability.",
@@ -5001,6 +5254,14 @@ class HogFlowViewSet(
suspended_at = suspension["email_sending_suspended_at"] if suspension else None
suspension_reason = suspension["email_sending_suspension_reason"] if suspension else ""
+ # Same project-wide gate as `reputation`: the breakdown pools every workflow's email for a
+ # sending domain, so object-level grants alone don't earn it.
+ isp_domains = (
+ _isp_domains(self.team, self.user_access_control, self.user_permissions)
+ if can_read_all_workflows and _isp_breakdown_enabled(self.team)
+ else IspDomains(readable=(), withheld=(), shared=())
+ )
+
return Response(
TeamEmailReputationResponseSerializer(
{
@@ -5009,6 +5270,11 @@ class HogFlowViewSet(
"aws": _fetch_aws_tenant_reputation(self.team_id) if can_read_all_workflows else None,
"reputation": reputation,
"workflows": workflow_rows,
+ # Same project-wide gate as `reputation`: the breakdown pools every workflow's
+ # email for a sending domain, so object-level grants alone don't earn it.
+ "isps": _fetch_isp_metrics(self.team_id, self.REPUTATION_WINDOW_DAYS, list(isp_domains.readable)),
+ "isp_shared_domains": list(isp_domains.shared),
+ "isp_withheld_domains": list(isp_domains.withheld),
"email_sending_suspended": suspended_at is not None,
"email_sending_suspended_at": suspended_at,
"email_sending_suspension_reason": suspension_reason if suspended_at is not None else "",
diff --git a/products/workflows/backend/api/test/test_email_reputation.py b/products/workflows/backend/api/test/test_email_reputation.py
index 956f2fa5914e..9c0bbaf5fbec 100644
--- a/products/workflows/backend/api/test/test_email_reputation.py
+++ b/products/workflows/backend/api/test/test_email_reputation.py
@@ -10,12 +10,14 @@ from rest_framework import status
from posthog.constants import AvailableFeature
from posthog.models import Team
+from posthog.models.integration import Integration
from posthog.models.organization import OrganizationMembership
from posthog.models.user import User
from products.access_control.backend.models.access_control import AccessControl
from products.workflows.backend.models import HogFlow, HogFlowBatchJob
from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig
+from products.workflows.backend.providers.ses import IspDailyPoint, IspSendingMetrics
class TestEmailReputationAPI(APIBaseTest):
@@ -37,19 +39,32 @@ class TestEmailReputationAPI(APIBaseTest):
)
def _get_reputation(
- self, totals_by_source: dict, query: str = "", aws_tenant: dict | None | Exception = None
+ self,
+ totals_by_source: dict,
+ query: str = "",
+ aws_tenant: dict | None | Exception = None,
+ isp_metrics: list | Exception | None = None,
+ isp_flag_enabled: bool = True,
) -> dict:
provider = MagicMock()
if isinstance(aws_tenant, Exception):
provider.get_tenant_reputation.side_effect = aws_tenant
else:
provider.get_tenant_reputation.return_value = aws_tenant
+ if isinstance(isp_metrics, Exception):
+ provider.get_identity_isp_metrics.side_effect = isp_metrics
+ else:
+ provider.get_identity_isp_metrics.return_value = isp_metrics or []
with (
patch(
"products.workflows.backend.api.hog_flow.fetch_app_metric_totals_by_source",
return_value=totals_by_source,
),
patch("products.workflows.backend.api.hog_flow.SESProvider", return_value=provider),
+ patch(
+ "products.workflows.backend.api.hog_flow._isp_breakdown_enabled",
+ return_value=isp_flag_enabled,
+ ),
):
response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/reputation{query}")
assert response.status_code == status.HTTP_200_OK
@@ -68,6 +83,9 @@ class TestEmailReputationAPI(APIBaseTest):
"aws": None,
"reputation": None,
"workflows": [],
+ "isps": [],
+ "isp_shared_domains": [],
+ "isp_withheld_domains": [],
"email_sending_suspended": False,
"email_sending_suspended_at": None,
"email_sending_suspension_reason": "",
@@ -251,6 +269,204 @@ class TestEmailReputationAPI(APIBaseTest):
assert data["email_sending_suspended_at"] == suspended_at.isoformat().replace("+00:00", "Z")
assert data["email_sending_suspension_reason"] == "critical bounce rate"
+ def _verify_sending_domain(self, domain: str = "mail.example.com") -> None:
+ Integration.objects.create(
+ team=self.team,
+ kind="email",
+ integration_id=domain,
+ config={"domain": domain, "provider": "ses", "verified": True},
+ )
+
+ def test_reputation_endpoint_returns_the_per_provider_breakdown(self):
+ self._verify_sending_domain()
+
+ body = self._get_reputation(
+ {},
+ isp_metrics=[
+ IspSendingMetrics(
+ isp="Gmail",
+ emails_sent=900,
+ delivery_rate=0.97,
+ bounce_rate=0.01,
+ complaint_rate=None,
+ daily=(IspDailyPoint(date="2026-08-01", emails_sent=900, delivery_rate=0.97, bounce_rate=0.01),),
+ ),
+ IspSendingMetrics(
+ isp="Yahoo",
+ emails_sent=100,
+ delivery_rate=0.99,
+ bounce_rate=0.0,
+ complaint_rate=0.002,
+ daily=(),
+ ),
+ ],
+ )
+
+ assert body["isps"] == [
+ {
+ "isp": "Gmail",
+ "emails_sent": 900,
+ "delivery_rate": 0.97,
+ "bounce_rate": 0.01,
+ # Null rather than 0 — Gmail runs no feedback loop, so a complaint rate would be
+ # a number we can't actually measure.
+ "complaint_rate": None,
+ "unavailable": [],
+ "daily": [
+ {
+ "date": "2026-08-01",
+ "emails_sent": 900,
+ "delivery_rate": 0.97,
+ "bounce_rate": 0.01,
+ }
+ ],
+ },
+ {
+ "isp": "Yahoo",
+ "emails_sent": 100,
+ "delivery_rate": 0.99,
+ "bounce_rate": 0.0,
+ "complaint_rate": 0.002,
+ "unavailable": [],
+ "daily": [],
+ },
+ ]
+
+ @parameterized.expand(
+ [
+ ("sibling verified on the same domain", True, ["mail.example.com"]),
+ ("sibling not verified yet", False, []),
+ ]
+ )
+ def test_reputation_endpoint_names_domains_a_sibling_project_also_sends_from(
+ self, _name: str, sibling_verified: bool, expected: list[str]
+ ):
+ self._verify_sending_domain()
+ sibling = Team.objects.create(organization=self.organization, name="Sibling")
+ Integration.objects.create(
+ team=sibling,
+ kind="email",
+ integration_id="mail.example.com",
+ config={"domain": "mail.example.com", "provider": "ses", "verified": sibling_verified},
+ )
+
+ body = self._get_reputation({}, isp_metrics=[])
+
+ assert body["isp_shared_domains"] == expected
+
+ def test_reputation_endpoint_omits_domains_only_this_project_sends_from(self):
+ self._verify_sending_domain()
+ self._verify_sending_domain("solo.example.com")
+ sibling = Team.objects.create(organization=self.organization, name="Sibling")
+ Integration.objects.create(
+ team=sibling,
+ kind="email",
+ integration_id="mail.example.com",
+ config={"domain": "mail.example.com", "provider": "ses", "verified": True},
+ )
+
+ body = self._get_reputation({}, isp_metrics=[])
+
+ assert body["isp_shared_domains"] == ["mail.example.com"]
+
+ @parameterized.expand(
+ [
+ ("sibling project hidden from the caller", "none", [], ["mail.example.com"]),
+ ("sibling project the caller can open", "member", ["mail.example.com"], []),
+ ]
+ )
+ def test_reputation_endpoint_withholds_a_domain_a_hidden_project_also_sends_from(
+ self, _name: str, sibling_access: str, expected_shared: list[str], expected_withheld: list[str]
+ ):
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ self.organization.save()
+ self._verify_sending_domain()
+ sibling = Team.objects.create(organization=self.organization, name="Sibling")
+ Integration.objects.create(
+ team=sibling,
+ kind="email",
+ integration_id="mail.example.com",
+ config={"domain": "mail.example.com", "provider": "ses", "verified": True},
+ )
+ AccessControl.objects.create(
+ team=sibling, resource="project", resource_id=str(sibling.id), access_level=sibling_access
+ )
+ member = User.objects.create_and_join(self.organization, f"sibling-{sibling_access}@posthog.com", "testtest")
+ self.client.force_login(member)
+
+ body = self._get_reputation(
+ {},
+ isp_metrics=[
+ IspSendingMetrics(
+ isp="Gmail",
+ emails_sent=900,
+ delivery_rate=0.97,
+ bounce_rate=0.01,
+ complaint_rate=None,
+ daily=(),
+ )
+ ],
+ )
+
+ assert body["isp_shared_domains"] == expected_shared
+ assert body["isp_withheld_domains"] == expected_withheld
+ # A withheld domain is never queried, so the provider rows go with it.
+ assert [row["isp"] for row in body["isps"]] == ([] if expected_withheld else ["Gmail"])
+
+ def test_reputation_endpoint_still_loads_when_the_provider_breakdown_fails(self):
+ # The breakdown is an addition to the rates display; SES being unreachable must not take
+ # the whole reputation page down with it.
+ self._verify_sending_domain()
+
+ body = self._get_reputation(
+ {"src": {"email_sent": 100, "email_bounced_hard": 1}},
+ isp_metrics=Exception("SES timeout"),
+ )
+
+ assert body["isps"] == []
+ assert body["reputation"]["emails_sent"] == 100
+
+ def test_reputation_endpoint_shows_no_breakdown_while_another_request_is_refreshing_it(self):
+ # One refresh is 150 metric queries over 15 sequential SES calls, and the endpoint reloads on
+ # every search keystroke, so a cold key must admit one request rather than all of them.
+ self._verify_sending_domain()
+ provider = MagicMock()
+ provider.get_tenant_reputation.return_value = None
+ with (
+ patch("products.workflows.backend.api.hog_flow.fetch_app_metric_totals_by_source", return_value={}),
+ patch("products.workflows.backend.api.hog_flow.SESProvider", return_value=provider),
+ patch("products.workflows.backend.api.hog_flow._isp_breakdown_enabled", return_value=True),
+ patch("products.workflows.backend.api.hog_flow.cache.add", return_value=False),
+ ):
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/reputation")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["isps"] == []
+ assert provider.get_identity_isp_metrics.call_count == 0
+
+ def test_reputation_endpoint_withholds_the_breakdown_without_the_feature_flag(self):
+ self._verify_sending_domain()
+
+ body = self._get_reputation(
+ {"src": {"email_sent": 100, "email_bounced_hard": 1}},
+ isp_metrics=[
+ IspSendingMetrics(
+ isp="Gmail",
+ emails_sent=90,
+ delivery_rate=0.99,
+ bounce_rate=0.01,
+ complaint_rate=None,
+ daily=(),
+ )
+ ],
+ isp_flag_enabled=False,
+ )
+
+ assert body["isps"] == []
+ assert body["reputation"]["emails_sent"] == 100
+
@pytest.mark.ee
class TestEmailReputationAccessControl(APIBaseTest):
@@ -293,12 +509,24 @@ class TestEmailReputationAccessControl(APIBaseTest):
"reputation_impact": "HIGH",
"findings": [],
}
+ provider.get_identity_isp_metrics.return_value = [
+ IspSendingMetrics(
+ isp="Gmail",
+ emails_sent=100,
+ delivery_rate=0.9,
+ bounce_rate=0.05,
+ complaint_rate=None,
+ daily=(),
+ )
+ ]
with (
patch(
"products.workflows.backend.api.hog_flow.fetch_app_metric_totals_by_source",
return_value={str(flow.id): {"email_sent": 100, "email_bounced_hard": 5}},
),
patch("products.workflows.backend.api.hog_flow.SESProvider", return_value=provider),
+ # Enabled, so what the assertion below tests is the access-control gate, not the flag.
+ patch("products.workflows.backend.api.hog_flow._isp_breakdown_enabled", return_value=True),
):
response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/reputation")
@@ -306,4 +534,5 @@ class TestEmailReputationAccessControl(APIBaseTest):
data = response.json()
assert data["aws"] is None
assert data["reputation"] is None
+ assert data["isps"] == []
assert [row["hog_flow_id"] for row in data["workflows"]] == [str(flow.id)]
diff --git a/products/workflows/backend/providers/ses.py b/products/workflows/backend/providers/ses.py
index 311e47c8a153..219ee450a324 100644
--- a/products/workflows/backend/providers/ses.py
+++ b/products/workflows/backend/providers/ses.py
@@ -1,7 +1,11 @@
import re
import logging
-from collections.abc import Iterable, Iterator
+from collections import defaultdict
+from collections.abc import Iterable, Iterator, Mapping, Sequence
+from datetime import UTC, datetime, timedelta
from functools import cached_property
+from itertools import batched
+from time import monotonic
from typing import TYPE_CHECKING, Any
from django.conf import settings
@@ -9,9 +13,12 @@ from django.conf import settings
import boto3
import dns.name
import dns.resolver
+from botocore.config import Config
from botocore.exceptions import BotoCoreError, ClientError
from rest_framework import exceptions
+from posthog.dataclasses import frozen
+
if TYPE_CHECKING:
from types_boto3_ses.client import SESClient
from types_boto3_sesv2.client import SESV2Client
@@ -19,10 +26,179 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
+# DELIVERY_COMPLAINT is the complaint denominator rather than SEND, because AWS defines it as
+# deliveries excluding recipients at ISPs it has no feedback-loop agreement with.
+ISP_METRICS: tuple[str, ...] = ("SEND", "DELIVERY", "PERMANENT_BOUNCE", "COMPLAINT", "DELIVERY_COMPLAINT")
+
+# SES caps a BatchGetMetricData request at ten queries.
+METRIC_QUERY_BATCH_SIZE = 10
+
+# Bounds one metric call. Also the amount of budget a call needs before it may start, below.
+METRIC_CONNECT_TIMEOUT_SECONDS = 2
+METRIC_READ_TIMEOUT_SECONDS = 5
+METRIC_CALL_WORST_CASE_SECONDS = METRIC_CONNECT_TIMEOUT_SECONDS + METRIC_READ_TIMEOUT_SECONDS
+
+# The breakdown runs inside a web request, and the fan-out is one query per domain, provider and
+# metric, issued in sequence. Without a ceiling an unresponsive SES holds a worker for minutes on
+# boto3's 60 second default. Past the budget the caller gets no breakdown, which is the same
+# degradation as any other SES failure and better than partial counts, whose rates would be wrong.
+# The budget covers every call the breakdown makes, ranking included, and a call starts only with
+# its worst case still inside it — so the ceiling holds even when SES answers slowly.
+METRIC_QUERY_BUDGET_SECONDS = 20
+
+
+@frozen
+class IspDailyPoint:
+ date: str
+ emails_sent: int
+ delivery_rate: float
+ bounce_rate: float
+
+
+@frozen
+class IspSendingMetrics:
+ isp: str
+ emails_sent: int
+ # None when the metric behind the rate could not be loaded. A failed query returns an empty
+ # series, which is arithmetically indistinguishable from a real zero — and a 0% complaint rate
+ # reads as a healthy provider. Unknown is reported as unknown rather than as a number.
+ delivery_rate: float | None
+ bounce_rate: float | None
+ # Also None when the provider runs no feedback loop, or when nothing was delivered to measure
+ # complaints against: both are "no rate exists", as against "we could not load it".
+ complaint_rate: float | None
+ # Oldest bucket first. Buckets SES returned nothing for are absent rather than zero-filled.
+ daily: tuple[IspDailyPoint, ...]
+ # Rates whose metric AWS did not return, so the reader can be told the number is missing rather
+ # than shown one. A null rate that is not listed here has no value to state at all.
+ unavailable: tuple[str, ...] = ()
+
+
+@frozen
+class IspMetric:
+ """One SES metric for one mailbox provider: what a single query asks for, and what indexes its answer."""
+
+ isp: str
+ metric: str
+
+
+@frozen
+class IspQueryPlan:
+ """The queries for a breakdown, and the index from query id back to what each one asked."""
+
+ queries: list[dict[str, Any]]
+ subjects: dict[str, IspMetric]
+
+
+@frozen
+class IspMetricSeries:
+ """Daily counts per provider and metric, and the subjects SES returned no answer for."""
+
+ buckets: Mapping[IspMetric, Mapping[str, int]]
+ failed: frozenset[IspMetric]
+
+
+def _build_isp_queries(domains: Sequence[str], isps: Sequence[str], start: datetime, end: datetime) -> IspQueryPlan:
+ """
+ The BatchGetMetricData queries for a breakdown, and an index from query id to what it asked.
+
+ Dimensions filter rather than group, and the response echoes only the query id, so a
+ per-provider breakdown needs one query per (domain, provider, metric) and a local index back
+ to what each id asked for.
+ """
+ queries: list[dict[str, Any]] = []
+ subjects: dict[str, IspMetric] = {}
+ for domain in domains:
+ for isp in isps:
+ for metric in ISP_METRICS:
+ query_id = f"q{len(queries)}"
+ subjects[query_id] = IspMetric(isp=isp, metric=metric)
+ queries.append(
+ {
+ "Id": query_id,
+ "Namespace": "VDM",
+ "Metric": metric,
+ "Dimensions": {"EMAIL_IDENTITY": domain, "ISP": isp},
+ "StartDate": start,
+ "EndDate": end,
+ }
+ )
+ return IspQueryPlan(queries=queries, subjects=subjects)
+
+
+def _isp_rows_from_series(isps: Sequence[str], series: IspMetricSeries) -> list[IspSendingMetrics]:
+ """Per-provider rows derived from the collected series, busiest provider first."""
+ buckets, failed = series.buckets, series.failed
+ rows: list[IspSendingMetrics] = []
+ for isp in isps:
+ if IspMetric(isp=isp, metric="SEND") in failed:
+ # Without the denominator there is no row to build: volume is unknown and every
+ # rate divides by it. This is the one case where the provider is dropped.
+ continue
+ sent_by_date = buckets.get(IspMetric(isp=isp, metric="SEND"), {})
+ emails_sent = sum(sent_by_date.values())
+ if emails_sent == 0:
+ continue
+ delivered_by_date = buckets.get(IspMetric(isp=isp, metric="DELIVERY"), {})
+ bounced_by_date = buckets.get(IspMetric(isp=isp, metric="PERMANENT_BOUNCE"), {})
+ delivery_failed = IspMetric(isp=isp, metric="DELIVERY") in failed
+ bounce_failed = IspMetric(isp=isp, metric="PERMANENT_BOUNCE") in failed
+ complaint_failed = (
+ IspMetric(isp=isp, metric="COMPLAINT") in failed
+ or IspMetric(isp=isp, metric="DELIVERY_COMPLAINT") in failed
+ )
+ complaint_base = sum(buckets.get(IspMetric(isp=isp, metric="DELIVERY_COMPLAINT"), {}).values())
+ rows.append(
+ IspSendingMetrics(
+ isp=isp,
+ emails_sent=emails_sent,
+ # Feedback can arrive after the window closes, so a rate can exceed its
+ # denominator at the boundary. Clamp, as the project-wide rates do.
+ delivery_rate=None if delivery_failed else min(1.0, sum(delivered_by_date.values()) / emails_sent),
+ bounce_rate=None if bounce_failed else min(1.0, sum(bounced_by_date.values()) / emails_sent),
+ complaint_rate=(
+ None
+ if complaint_failed or not complaint_base
+ else min(
+ 1.0, sum(buckets.get(IspMetric(isp=isp, metric="COMPLAINT"), {}).values()) / complaint_base
+ )
+ ),
+ # The trend is a delivery-rate series, so a failed DELIVERY query leaves nothing
+ # to draw. An empty series renders no line rather than a flat one at zero.
+ unavailable=tuple(
+ name
+ for name, missing in (
+ ("delivery", delivery_failed),
+ ("bounce", bounce_failed),
+ ("complaint", complaint_failed),
+ )
+ if missing
+ ),
+ daily=()
+ if delivery_failed
+ else tuple(
+ IspDailyPoint(
+ date=date,
+ emails_sent=sent,
+ delivery_rate=min(1.0, delivered_by_date.get(date, 0) / sent),
+ bounce_rate=0.0 if bounce_failed else min(1.0, bounced_by_date.get(date, 0) / sent),
+ )
+ # A rate over zero sends is undefined, and zero-filling draws a cliff in
+ # the trend that never happened.
+ for date, sent in sorted(sent_by_date.items())
+ if sent > 0
+ ),
+ )
+ )
+
+ rows.sort(key=lambda row: -row.emails_sent)
+ return rows
+
class SESProvider:
ses_client: "SESClient"
ses_v2_client: "SESV2Client"
+ ses_v2_metrics_client: "SESV2Client"
def __init__(self):
# Initialize the boto3 clients
@@ -44,6 +220,19 @@ class SESProvider:
aws_secret_access_key=settings.SES_SECRET_ACCESS_KEY,
region_name=settings.SES_REGION,
)
+ # Separate client for the metric fan-out only, so bounding it cannot slow identity and
+ # tenant calls, which are allowed to take longer.
+ self.ses_v2_metrics_client = boto3.client(
+ "sesv2",
+ aws_access_key_id=settings.SES_ACCESS_KEY_ID,
+ aws_secret_access_key=settings.SES_SECRET_ACCESS_KEY,
+ region_name=settings.SES_REGION,
+ config=Config(
+ connect_timeout=METRIC_CONNECT_TIMEOUT_SECONDS,
+ read_timeout=METRIC_READ_TIMEOUT_SECONDS,
+ retries={"max_attempts": 1},
+ ),
+ )
def _tenant_name_for_team(self, team_id: int) -> str:
return f"team-{team_id}"
@@ -471,3 +660,134 @@ class SESProvider:
except (ClientError, BotoCoreError) as e:
logger.exception(f"SES API error deleting identity: {e}")
raise
+
+ def _busiest_domains(
+ self, domains: Sequence[str], *, start: datetime, end: datetime, limit: int, deadline: float
+ ) -> list[str]:
+ """The `limit` domains that sent the most over the window.
+
+ One SEND query per domain with no ISP dimension, which is a fraction of the per-provider
+ fan-out it decides. A domain whose query fails sorts last rather than raising: losing it is
+ the same outcome the unconditional slice already had, and this panel never fails the page.
+ Ranking shares the caller's deadline, and running out of it falls back to the first few
+ rather than spending the whole budget deciding what to spend it on.
+ """
+ totals: dict[str, int] = dict.fromkeys(domains, 0)
+ subjects = {f"d{index}": domain for index, domain in enumerate(domains)}
+ queries = [
+ {
+ "Id": query_id,
+ "Namespace": "VDM",
+ "Metric": "SEND",
+ "Dimensions": {"EMAIL_IDENTITY": domain},
+ "StartDate": start,
+ "EndDate": end,
+ }
+ for query_id, domain in subjects.items()
+ ]
+ try:
+ for batch in batched(queries, METRIC_QUERY_BATCH_SIZE, strict=False):
+ if monotonic() + METRIC_CALL_WORST_CASE_SECONDS > deadline:
+ logger.warning("Ran out of budget ranking sending domains; keeping the first few")
+ return list(domains)[:limit]
+ response = self.ses_v2_metrics_client.batch_get_metric_data(Queries=list(batch)) # type: ignore[arg-type]
+ for result in response.get("Results", []):
+ domain = subjects.get(result["Id"])
+ if domain is not None:
+ totals[domain] = sum(result.get("Values", []) or [])
+ except Exception:
+ logger.exception("Could not rank sending domains by volume; keeping the first few")
+ return list(domains)[:limit]
+
+ # Volume first, then the caller's order, so the choice is stable between refreshes when two
+ # domains sent the same amount.
+ order = {domain: index for index, domain in enumerate(domains)}
+ ranked = sorted(domains, key=lambda domain: (-totals[domain], order[domain]))
+ if ranked[limit:]:
+ logger.info(
+ "Capped the per-provider breakdown to the busiest sending domains",
+ extra={"kept": ranked[:limit], "dropped": ranked[limit:]},
+ )
+ return ranked[:limit]
+
+ def get_identity_isp_metrics(
+ self,
+ domains: Sequence[str],
+ window_days: int,
+ isps: Sequence[str] | None = None,
+ max_domains: int | None = None,
+ ) -> list[IspSendingMetrics]:
+ """
+ Sending health per mailbox provider, over the given sending domains.
+
+ Counts are summed across `domains` because VDM's EMAIL_IDENTITY dimension is per verified
+ domain, while a project's rates are project-wide. Providers that received nothing in the
+ window are omitted rather than shown as a row of zeros.
+ """
+ isps = list(isps) if isps is not None else list(settings.SES_ISP_DIMENSIONS)
+ # Several senders can share one domain. A duplicate would query the same series twice and
+ # sum it in twice, inflating volume.
+ domains = list(dict.fromkeys(domains))
+ if not domains or not isps:
+ return []
+
+ deadline = monotonic() + METRIC_QUERY_BUDGET_SECONDS
+
+ # VDM rejects the whole batch if either bound is a partial day, so the window is whole UTC
+ # days ending at the last midnight. Today is therefore excluded.
+ end = datetime.now(tz=UTC).replace(hour=0, minute=0, second=0, microsecond=0)
+ start = end - timedelta(days=window_days)
+
+ # Bounding the fan-out by taking an arbitrary slice drops whichever domains sort last, which
+ # can be the only one sending today. One cheap query each says which ones actually sent.
+ if max_domains is not None and len(domains) > max_domains:
+ domains = self._busiest_domains(domains, start=start, end=end, limit=max_domains, deadline=deadline)
+
+ plan = _build_isp_queries(domains, isps, start, end)
+ series = self._collect_isp_series(plan, deadline, len(domains))
+ return _isp_rows_from_series(isps, series)
+
+ def _collect_isp_series(self, plan: IspQueryPlan, deadline: float, domain_count: int) -> IspMetricSeries:
+ """
+ Run the queries in batches, returning the daily series and the subjects with no answer.
+
+ A subject in the failed set has an empty series for want of an answer, not because nothing
+ happened, so every rate derived from it is reported as unknown rather than as zero.
+ """
+ buckets_by_subject: dict[IspMetric, dict[str, int]] = defaultdict(lambda: defaultdict(int))
+ failed: set[IspMetric] = set()
+ for batch in batched(plan.queries, METRIC_QUERY_BATCH_SIZE, strict=False):
+ if monotonic() + METRIC_CALL_WORST_CASE_SECONDS > deadline:
+ # Raises rather than returning the batches that did answer: a rate built from a
+ # partial fan-out is wrong, not merely incomplete. The caller turns this into an
+ # absent breakdown, the same degradation as any other SES failure.
+ raise TimeoutError(
+ f"SES metric queries exceeded {METRIC_QUERY_BUDGET_SECONDS}s for {domain_count} domain(s)"
+ )
+ response = self.ses_v2_metrics_client.batch_get_metric_data(Queries=list(batch)) # type: ignore[arg-type]
+ for result in response.get("Results", []):
+ buckets = buckets_by_subject[plan.subjects[result["Id"]]]
+ # AWS documents Values as "cumulative / sum" without saying which, so this reads
+ # them as per-bucket counts. If they are running totals, summed deliveries overshoot
+ # sends and every provider pins to a 100% delivery rate against the clamp.
+ for timestamp, value in zip(result.get("Timestamps", []), result.get("Values", []), strict=False):
+ buckets[timestamp.date().isoformat()] += value
+ for error in response.get("Errors", []):
+ subject = plan.subjects.get(error.get("Id", ""))
+ if subject is not None:
+ failed.add(subject)
+ # A per-query failure leaves that metric at zero, which understates a rate rather
+ # than breaking the panel. Log it so a systematic failure stays visible. A
+ # malformed ISP name is different: SES fails the whole request, which the caller
+ # turns into an absent breakdown.
+ # "message" is reserved: LogRecord already has one, and passing it in `extra`
+ # raises KeyError inside makeRecord, turning a logged warning into a lost breakdown.
+ logger.warning(
+ "SES metric query failed",
+ extra={
+ "query": subject,
+ "code": error.get("Code"),
+ "error_message": error.get("Message"),
+ },
+ )
+ return IspMetricSeries(buckets=buckets_by_subject, failed=frozenset(failed))
diff --git a/products/workflows/backend/test/test_ses_provider.py b/products/workflows/backend/test/test_ses_provider.py
index efc7a71b2ccf..b464d97c2310 100644
--- a/products/workflows/backend/test/test_ses_provider.py
+++ b/products/workflows/backend/test/test_ses_provider.py
@@ -1,3 +1,5 @@
+from datetime import UTC, datetime
+from itertools import count
from typing import Optional
import pytest
@@ -12,7 +14,7 @@ import dns.resolver
from botocore.exceptions import ClientError
from parameterized import parameterized
-from products.workflows.backend.providers.ses import SESProvider
+from products.workflows.backend.providers.ses import METRIC_QUERY_BUDGET_SECONDS, SESProvider
TEST_DOMAIN = "test.posthog.com"
@@ -584,3 +586,266 @@ class TestGetAccountReputation(TestCase):
with pytest.raises(KeyError):
self.provider.get_account_reputation()
+
+
+class TestGetIdentityIspMetrics(TestCase):
+ def setUp(self):
+ patcher = patch("products.workflows.backend.providers.ses.boto3.client")
+ mock_boto3_client = patcher.start()
+ self.addCleanup(patcher.stop)
+ self.mock_client = mock_boto3_client.return_value
+ self.provider = SESProvider()
+
+ def _serve(self, values_by_subject: dict[tuple[str, str], int]) -> None:
+ """Answer each batch from a {(isp, metric): value} table, defaulting anything absent to 0."""
+
+ def respond(Queries):
+ return {
+ "Results": [
+ {
+ "Id": query["Id"],
+ "Timestamps": [datetime(2026, 8, 1, tzinfo=UTC)],
+ "Values": [values_by_subject.get((query["Dimensions"]["ISP"], query["Metric"]), 0)],
+ }
+ for query in Queries
+ ]
+ }
+
+ self.mock_client.batch_get_metric_data.side_effect = lambda Queries: respond(Queries)
+
+ def _serve_series(self, values_by_subject: dict[tuple[str, str], dict[str, int]]) -> None:
+ """Answer from a {(isp, metric): {date: value}} table, so a query spans several buckets."""
+
+ def respond(Queries):
+ results = []
+ for query in Queries:
+ buckets = values_by_subject.get((query["Dimensions"]["ISP"], query["Metric"]), {})
+ results.append(
+ {
+ "Id": query["Id"],
+ "Timestamps": [datetime.fromisoformat(date) for date in sorted(buckets)],
+ "Values": [buckets[date] for date in sorted(buckets)],
+ }
+ )
+ return {"Results": results}
+
+ self.mock_client.batch_get_metric_data.side_effect = lambda Queries: respond(Queries)
+
+ def test_daily_series_is_ordered_and_merged_across_domains(self):
+ # Two domains reporting the same days have to land in one bucket per day, or the trend
+ # draws each domain as its own point and every rate is computed against half the sends.
+ self._serve_series(
+ {
+ ("Gmail", "SEND"): {"2026-08-02": 50, "2026-08-01": 100},
+ ("Gmail", "DELIVERY"): {"2026-08-02": 10, "2026-08-01": 95},
+ }
+ )
+
+ rows = self.provider.get_identity_isp_metrics(
+ [TEST_DOMAIN, "other.posthog.com"], window_days=30, isps=["Gmail"]
+ )
+
+ assert [(point.date, point.emails_sent, point.delivery_rate) for point in rows[0].daily] == [
+ ("2026-08-01", 200, 0.95),
+ ("2026-08-02", 100, 0.2),
+ ]
+
+ def test_a_partial_query_failure_leaves_the_other_metrics_intact(self):
+ # SES reports per-query failures in Errors while still returning Results. Logging one used
+ # to raise KeyError, because "message" is reserved on LogRecord, so a single failed query
+ # took down the whole breakdown instead of understating one metric.
+ def respond(Queries):
+ return {
+ "Results": [
+ {"Id": q["Id"], "Timestamps": [datetime(2026, 8, 1, tzinfo=UTC)], "Values": [100]}
+ for q in Queries
+ if q["Metric"] == "SEND"
+ ],
+ "Errors": [
+ {"Id": q["Id"], "Code": "ACCESS_DENIED", "Message": "denied"}
+ for q in Queries
+ if q["Metric"] != "SEND"
+ ],
+ }
+
+ self.mock_client.batch_get_metric_data.side_effect = lambda Queries: respond(Queries)
+
+ # assertLogs raises the level so the record is actually built. Without it the warning is
+ # gated out under pytest and never reaches makeRecord, which is how the reserved-key crash
+ # stayed invisible in tests while failing in production, where WARNING is enabled.
+ with self.assertLogs("products.workflows.backend.providers.ses", level="WARNING") as logs:
+ rows = self.provider.get_identity_isp_metrics([TEST_DOMAIN], window_days=30, isps=["Gmail"])
+
+ assert any("SES metric query failed" in line for line in logs.output)
+ assert [row.isp for row in rows] == ["Gmail"]
+ assert rows[0].emails_sent == 100
+ # The provider stays, because SEND answered and its volume is known. The rates behind the
+ # failed queries are reported as missing: zero would read as a real measurement, and a 0%
+ # complaint rate is the most reassuring number this table can show.
+ assert rows[0].delivery_rate is None
+ assert rows[0].bounce_rate is None
+ assert rows[0].complaint_rate is None
+ assert set(rows[0].unavailable) == {"delivery", "bounce", "complaint"}
+ # No delivery series means no trend to draw, rather than a line flat at zero.
+ assert rows[0].daily == ()
+
+ def test_daily_series_skips_buckets_with_no_sends(self):
+ self._serve_series(
+ {
+ ("Gmail", "SEND"): {"2026-08-01": 10, "2026-08-02": 0},
+ ("Gmail", "DELIVERY"): {"2026-08-01": 9, "2026-08-02": 0},
+ }
+ )
+
+ rows = self.provider.get_identity_isp_metrics([TEST_DOMAIN], window_days=30, isps=["Gmail"])
+
+ assert [point.date for point in rows[0].daily] == ["2026-08-01"]
+
+ @parameterized.expand(
+ [
+ # A provider that reports complaints: the rate is complaints over the deliveries it
+ # reports them for, NOT over everything we sent it.
+ ("reporting_provider", 40, 4, 0.1),
+ # SES excludes recipients at providers it has no feedback-loop agreement with from
+ # DELIVERY_COMPLAINT. A zero base means unmeasurable, which must not read as 0%.
+ ("provider_without_a_feedback_loop", 0, 0, None),
+ ]
+ )
+ def test_complaint_rate_is_measured_against_delivery_complaint(
+ self, _name: str, delivery_complaint: int, complaints: int, expected: Optional[float]
+ ):
+ self._serve(
+ {
+ ("Gmail", "SEND"): 100,
+ ("Gmail", "DELIVERY"): 95,
+ ("Gmail", "DELIVERY_COMPLAINT"): delivery_complaint,
+ ("Gmail", "COMPLAINT"): complaints,
+ }
+ )
+
+ rows = self.provider.get_identity_isp_metrics([TEST_DOMAIN], window_days=30, isps=["Gmail"])
+
+ assert [row.complaint_rate for row in rows] == [expected]
+
+ def test_counts_are_summed_across_the_projects_sending_domains(self):
+ # Each domain is queried separately because EMAIL_IDENTITY is per verified domain, but a
+ # project's rates are project-wide, so the two domains' counts have to add up.
+ self._serve({("Gmail", "SEND"): 50, ("Gmail", "DELIVERY"): 40, ("Gmail", "PERMANENT_BOUNCE"): 5})
+
+ rows = self.provider.get_identity_isp_metrics(
+ [TEST_DOMAIN, "other.posthog.com"], window_days=30, isps=["Gmail"]
+ )
+
+ assert len(rows) == 1
+ assert rows[0].emails_sent == 100
+ assert rows[0].delivery_rate == 0.8
+ assert rows[0].bounce_rate == 0.1
+
+ def test_queries_are_batched_within_the_ses_ten_query_limit(self):
+ self._serve({("Gmail", "SEND"): 1, ("Yahoo", "SEND"): 1, ("Outlook", "SEND"): 1})
+
+ self.provider.get_identity_isp_metrics([TEST_DOMAIN], window_days=30, isps=["Gmail", "Yahoo", "Outlook"])
+
+ batches = [kwargs["Queries"] for _, kwargs in self.mock_client.batch_get_metric_data.call_args_list]
+ # 3 providers x 5 metrics = 15 queries, and SES rejects a batch of more than ten.
+ assert [len(batch) for batch in batches] == [10, 5]
+ sent = {(query["Dimensions"]["ISP"], query["Metric"]) for batch in batches for query in batch}
+ assert len(sent) == 15
+
+ def test_the_domain_cap_keeps_the_domains_that_actually_sent(self):
+ # The cap used to take the first few domains in id order, which is the order they were
+ # verified in — so a project that added its current sending domain last had the only domain
+ # with traffic dropped, while the breakdown still read as project-wide.
+ def respond(Queries):
+ results = []
+ for query in Queries:
+ dimensions = query["Dimensions"]
+ if "ISP" not in dimensions:
+ volume = 500 if dimensions["EMAIL_IDENTITY"] == "busy.test" else 0
+ else:
+ volume = 10
+ results.append(
+ {"Id": query["Id"], "Timestamps": [datetime(2026, 8, 1, tzinfo=UTC)], "Values": [volume]}
+ )
+ return {"Results": results, "Errors": []}
+
+ self.mock_client.batch_get_metric_data.side_effect = lambda Queries: respond(Queries)
+
+ self.provider.get_identity_isp_metrics(
+ ["quiet-a.test", "quiet-b.test", "busy.test"], window_days=30, isps=["Gmail"], max_domains=1
+ )
+
+ per_provider = [
+ query["Dimensions"]["EMAIL_IDENTITY"]
+ for _, kwargs in self.mock_client.batch_get_metric_data.call_args_list
+ for query in kwargs["Queries"]
+ if "ISP" in query["Dimensions"]
+ ]
+ assert set(per_provider) == {"busy.test"}
+
+ def test_slow_ses_cannot_hold_the_request_past_the_budget(self):
+ # The budget used to start after domain ranking and to be checked only against the clock,
+ # so ranking ran outside it and the last call could still start with the budget nearly
+ # spent — holding a web worker well past the ceiling the constant advertises.
+ clock = iter(count(start=0.0, step=6.0))
+
+ def respond(Queries):
+ return {
+ "Results": [
+ {"Id": query["Id"], "Timestamps": [datetime(2026, 8, 1, tzinfo=UTC)], "Values": [10]}
+ for query in Queries
+ ],
+ "Errors": [],
+ }
+
+ self.mock_client.batch_get_metric_data.side_effect = lambda Queries: respond(Queries)
+ with patch("products.workflows.backend.providers.ses.monotonic", lambda: next(clock)):
+ with pytest.raises(TimeoutError):
+ self.provider.get_identity_isp_metrics(
+ ["a.test", "b.test"], window_days=30, isps=["Gmail", "Yahoo", "Outlook"]
+ )
+
+ elapsed = 6.0 * self.mock_client.batch_get_metric_data.call_count
+ assert elapsed <= METRIC_QUERY_BUDGET_SECONDS
+
+ def test_ranking_that_runs_out_of_budget_keeps_the_first_domains(self):
+ # Ranking shares the budget, so it stops rather than spending all of it deciding which
+ # domains to spend it on. Losing the ranking is the old unconditional slice, not an error.
+ clock = iter(count(start=0.0, step=8.0))
+ self.mock_client.batch_get_metric_data.side_effect = lambda Queries: {
+ "Results": [
+ {"Id": query["Id"], "Timestamps": [datetime(2026, 8, 1, tzinfo=UTC)], "Values": [10]}
+ for query in Queries
+ ],
+ "Errors": [],
+ }
+ domains = [f"d{index}.test" for index in range(11)]
+
+ with patch("products.workflows.backend.providers.ses.monotonic", lambda: next(clock)):
+ with pytest.raises(TimeoutError):
+ self.provider.get_identity_isp_metrics(domains, window_days=30, isps=["Gmail"], max_domains=2)
+
+ ranking_calls = [
+ kwargs
+ for _, kwargs in self.mock_client.batch_get_metric_data.call_args_list
+ if all("ISP" not in query["Dimensions"] for query in kwargs["Queries"])
+ ]
+ # Eleven domains rank in two batches; the second would have started with less budget left
+ # than one call can take.
+ assert len(ranking_calls) == 1
+
+ def test_providers_that_received_nothing_are_omitted(self):
+ # Without this a silent provider divides by zero; a row of zeros would also read as a
+ # delivery problem rather than as "we never mailed anyone here".
+ self._serve({("Gmail", "SEND"): 10, ("Gmail", "DELIVERY"): 10})
+
+ rows = self.provider.get_identity_isp_metrics([TEST_DOMAIN], window_days=30, isps=["Gmail", "Yahoo"])
+
+ assert [row.isp for row in rows] == ["Gmail"]
+
+ def test_busiest_provider_is_reported_first(self):
+ self._serve({("Gmail", "SEND"): 10, ("Yahoo", "SEND"): 90})
+
+ rows = self.provider.get_identity_isp_metrics([TEST_DOMAIN], window_days=30, isps=["Gmail", "Yahoo"])
+
+ assert [row.isp for row in rows] == ["Yahoo", "Gmail"]
diff --git a/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.stories.tsx b/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.stories.tsx
new file mode 100644
index 000000000000..d83c0432289a
--- /dev/null
+++ b/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.stories.tsx
@@ -0,0 +1,140 @@
+import { Meta, StoryFn } from '@storybook/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+
+import { useStorybookMocks } from '~/mocks/browser'
+
+import type { TeamEmailReputationResponseApi } from 'products/workflows/frontend/generated/api.schemas'
+
+import { WorkflowsReputation } from './WorkflowsReputation'
+
+const reputationEndpoint = '/api/projects/:team_id/hog_flows/reputation'
+
+// A fortnight where Gmail starts filtering us halfway through while everyone else stays fine.
+// This is the shape the project-wide rates hide, so it's what the stories are built around.
+function gmailSeries(): TeamEmailReputationResponseApi['isps'][number]['daily'] {
+ return Array.from({ length: 14 }, (_, day) => {
+ const filtered = day >= 7
+ return {
+ date: `2026-08-${String(day + 1).padStart(2, '0')}`,
+ emails_sent: 6000,
+ delivery_rate: filtered ? 0.42 : 0.97,
+ bounce_rate: 0.008,
+ }
+ })
+}
+
+function steadySeries(deliveryRate: number): TeamEmailReputationResponseApi['isps'][number]['daily'] {
+ return Array.from({ length: 14 }, (_, day) => ({
+ date: `2026-08-${String(day + 1).padStart(2, '0')}`,
+ emails_sent: 900,
+ delivery_rate: deliveryRate,
+ bounce_rate: 0.004,
+ }))
+}
+
+const baseResponse: TeamEmailReputationResponseApi = {
+ aws: { health: 'healthy', sending_status: 'ENABLED', findings: [] },
+ reputation: { bounce_rate: 0.0062, complaint_rate: 0.0001, emails_sent: 115025 },
+ workflows: [],
+ isps: [
+ {
+ isp: 'Gmail',
+ emails_sent: 84000,
+ delivery_rate: 0.69,
+ bounce_rate: 0.008,
+ // Gmail runs no feedback loop, so a complaint rate here would be unmeasurable.
+ complaint_rate: null,
+ unavailable: [],
+ daily: gmailSeries(),
+ },
+ {
+ isp: 'Outlook',
+ emails_sent: 12600,
+ delivery_rate: 0.98,
+ bounce_rate: 0.004,
+ complaint_rate: 0.0004,
+ unavailable: [],
+ daily: steadySeries(0.98),
+ },
+ {
+ isp: 'Apple',
+ emails_sent: 8100,
+ // Steady, but steadily poor: the case an auto-scaled axis would draw as a flat line
+ // indistinguishable from a healthy provider.
+ delivery_rate: 0.45,
+ bounce_rate: 0.012,
+ complaint_rate: null,
+ unavailable: [],
+ daily: steadySeries(0.45),
+ },
+ {
+ isp: 'Yahoo',
+ emails_sent: 6300,
+ delivery_rate: 0.96,
+ bounce_rate: 0.006,
+ complaint_rate: 0.0011,
+ unavailable: [],
+ daily: steadySeries(0.96),
+ },
+ ],
+ isp_shared_domains: [],
+ isp_withheld_domains: [],
+ sending_allowance: {
+ tier: 2,
+ max_tier: 4,
+ emails_per_hour: 5000,
+ emails_per_day: 50000,
+ max_batch_audience: 25000,
+ emails_sent_last_hour: 1200,
+ emails_sent_last_day: 18400,
+ enforced: true,
+ },
+ email_sending_suspended: false,
+ email_sending_suspended_at: null,
+ email_sending_suspension_reason: '',
+}
+
+const meta: Meta<typeof WorkflowsReputation> = {
+ title: 'Products/Workflows/Reputation',
+ component: WorkflowsReputation,
+ parameters: {
+ layout: 'padded',
+ testOptions: { waitForLoadersToDisappear: true },
+ featureFlags: [FEATURE_FLAGS.WORKFLOWS_ISP_SENDING_HEALTH],
+ },
+}
+export default meta
+
+function mockReputation(response: TeamEmailReputationResponseApi): Record<string, any> {
+ return { get: { [reputationEndpoint]: response } }
+}
+
+export const OneProviderFiltering: StoryFn = () => {
+ useStorybookMocks(mockReputation(baseResponse))
+ return <WorkflowsReputation />
+}
+
+export const NoProviderData: StoryFn = () => {
+ // What every project sees until Virtual Deliverability Manager is collecting.
+ useStorybookMocks(mockReputation({ ...baseResponse, isps: [] }))
+ return <WorkflowsReputation />
+}
+
+export const ProviderDataWithoutWorkflowRates: StoryFn = () => {
+ // Domain-level sends with nothing from a workflow in the window: the card has to stay on screen
+ // and say what the table below counts, rather than claiming there is no data.
+ useStorybookMocks(mockReputation({ ...baseResponse, reputation: null, aws: null }))
+ return <WorkflowsReputation />
+}
+
+export const SharedSendingDomain: StoryFn = () => {
+ useStorybookMocks(mockReputation({ ...baseResponse, isp_shared_domains: ['mail.example.com'] }))
+ return <WorkflowsReputation />
+}
+
+export const DomainWithheldFromCaller: StoryFn = () => {
+ // A domain a project the viewer cannot open also sends from: excluded rather than blended in.
+ useStorybookMocks(mockReputation({ ...baseResponse, isps: [], isp_withheld_domains: ['mail.example.com'] }))
+ return <WorkflowsReputation />
+}
diff --git a/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx b/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx
index 2f84ccf336d8..f02fa8278555 100644
--- a/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx
+++ b/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx
@@ -2,6 +2,7 @@ import { useActions, useValues } from 'kea'
import { LemonBanner, LemonInput, LemonTable, LemonTag, LemonTagType, Link, Tooltip } from '@posthog/lemon-ui'
+import { Sparkline } from 'lib/components/Sparkline'
import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
import { urls } from 'scenes/urls'
@@ -11,6 +12,7 @@ import type {
AwsTenantReputationHealthEnumApi,
EmailSendingAllowanceApi,
EmailSendingRatesApi,
+ IspSendingHealthApi,
WorkflowEmailSendingRatesApi,
} from 'products/workflows/frontend/generated/api.schemas'
@@ -62,6 +64,23 @@ const RATE_LEVEL_TAG: Record<RateLevel, { label: string; type: LemonTagType }> =
high: { label: 'High', type: 'danger' },
}
+// AWS returning nothing for a metric is not the same as the metric being zero, and a 0.00% spam
+// complaint rate with a green tag is the most misleading thing this table could show. The API names
+// the rates it could not load, and those say so instead.
+function MissingRate({ reason }: { reason: 'unavailable' | 'no-rate' }): JSX.Element {
+ const tooltip =
+ reason === 'unavailable'
+ ? 'AWS did not return this metric, so there is no number to show. It usually reappears on the next refresh.'
+ : 'No complaints could be measured here: either this provider does not report them back to senders, or none of your email to it was delivered. Watch the delivery rate instead.'
+ return (
+ <Tooltip title={tooltip}>
+ <span className="text-secondary cursor-default">
+ {reason === 'unavailable' ? "Couldn't load" : 'No data'}
+ </span>
+ </Tooltip>
+ )
+}
+
function RateCell({ rate, kind }: { rate: number; kind: 'bounce' | 'complaint' }): JSX.Element {
const level = classifyRate(rate, kind)
const tag = RATE_LEVEL_TAG[level]
@@ -102,14 +121,31 @@ const FINDING_TYPE_LABELS: Record<string, string> = {
const WINDOW_TOOLTIP = 'Calculated over your workflow email from the last 30 days.'
const WORKFLOW_LIMIT = 50
-function MetricLabel({ label, tooltip }: { label: string; tooltip: string }): JSX.Element {
- return (
+function MetricLabel({
+ label,
+ tooltip,
+ description,
+}: {
+ label: string
+ tooltip: string
+ description?: string
+}): JSX.Element {
+ const labelNode = (
<Tooltip title={tooltip}>
<div className="text-secondary text-xs border-b border-dotted border-current inline-block cursor-default">
{label}
</div>
</Tooltip>
)
+ if (!description) {
+ return labelNode
+ }
+ return (
+ <div>
+ {labelNode}
+ <div className="text-secondary text-xs mt-1">{description}</div>
+ </div>
+ )
}
function AwsFindings({ aws }: { aws: AwsTenantReputationApi }): JSX.Element | null {
@@ -136,12 +172,147 @@ function AwsFindings({ aws }: { aws: AwsTenantReputationApi }): JSX.Element | nu
)
}
+// A single point is a reading, not a trend, so the column stays empty until there are two.
+const MIN_TREND_POINTS = 2
+
+// Every row is drawn against the same dates: the days any provider sent on. A provider only appears
+// on its own send days, so without this each row stretches its own handful of dates across the full
+// width — a provider whose last send was two weeks ago ends level with one that sent yesterday, and
+// a ten-day gap draws like a one-day gap.
+function trendDates(isps: readonly IspSendingHealthApi[]): string[] {
+ return [...new Set(isps.flatMap((isp) => isp.daily.map((point) => point.date)))].sort()
+}
+
+// NaN rather than 0 for a day with no sends to this provider: the renderer breaks the line at a
+// non-finite value, so the gap reads as "nothing sent" instead of as a drop to zero.
+function alignToDates(isp: IspSendingHealthApi, dates: string[]): number[] {
+ const byDate = new Map(isp.daily.map((point) => [point.date, point.delivery_rate * 100]))
+ return dates.map((date) => byDate.get(date) ?? Number.NaN)
+}
+
+function DeliveryTrend({ isp, dates }: { isp: IspSendingHealthApi; dates: string[] }): JSX.Element {
+ // An empty box of the same size rather than nothing: a provider with too few points to draw
+ // would otherwise collapse its row, and the table's rows would step up and down the column.
+ if (isp.daily.length < MIN_TREND_POINTS) {
+ return <div className="h-8 w-28" aria-hidden />
+ }
+ return (
+ <Sparkline
+ data={alignToDates(isp, dates)}
+ labels={dates}
+ name={`${isp.isp} delivery rate (%)`}
+ type="line"
+ renderTooltipValue={(value) => `${value.toFixed(1)}%`}
+ // Fixed 0-100 rather than auto-scaled per row: these are read against each other, and
+ // an auto-scaled axis draws a steady 40% provider identically to a steady 98% one.
+ valueDomain={{ min: 0, max: 100 }}
+ // Sizes Sparkline's own container: without a height it grows to fill the table cell
+ // and the chart bleeds across rows.
+ className="h-8 w-28"
+ />
+ )
+}
+
+function IspBreakdown({
+ isps,
+ sharedDomains,
+}: {
+ isps: readonly IspSendingHealthApi[]
+ sharedDomains: readonly string[]
+}): JSX.Element | null {
+ // The API returns [] unless the flag and access checks pass on its side, so gating on isps alone
+ // keeps one decision. A second client flag check can bucket differently and hide returned rows.
+ if (isps.length === 0) {
+ return null
+ }
+ const dates = trendDates(isps)
+ return (
+ <div className="mt-4 space-y-2" data-attr="workflows-reputation-isp-breakdown">
+ <MetricLabel
+ label="By mailbox provider"
+ description={
+ sharedDomains.length > 0
+ ? `Counts every email sent from ${sharedDomains.join(', ')}, including email from other projects using ${sharedDomains.length > 1 ? 'those domains' : 'that domain'}.`
+ : undefined
+ }
+ tooltip={`The project-wide rates above pool every provider together, so a struggling provider can be hidden by the others. This table splits the rates out per provider. A provider that accepts your mail and then files it as spam still reads as healthy here. ${WINDOW_TOOLTIP}`}
+ />
+ <LemonTable
+ dataSource={[...isps]}
+ rowKey={(row) => row.isp}
+ columns={[
+ {
+ title: 'Provider',
+ key: 'isp',
+ render: (_, row: IspSendingHealthApi) => <span className="font-semibold">{row.isp}</span>,
+ },
+ {
+ title: 'Delivery rate',
+ key: 'delivery_rate',
+ align: 'right',
+ render: (_, row: IspSendingHealthApi) =>
+ row.delivery_rate === null ? (
+ <MissingRate reason="unavailable" />
+ ) : (
+ <Tooltip title="Emails this provider accepted, divided by emails sent to it. Accepting a message is not the same as putting it in the inbox: a provider can accept your email and still file it as spam.">
+ <span className="tabular-nums cursor-default">{formatRate(row.delivery_rate)}</span>
+ </Tooltip>
+ ),
+ },
+ {
+ title: 'Delivery trend',
+ key: 'delivery_trend',
+ tooltip: 'Every provider is drawn on the same 0-100% axis, so rows can be compared by height.',
+ render: (_, row: IspSendingHealthApi) => <DeliveryTrend isp={row} dates={dates} />,
+ },
+ {
+ title: 'Bounce rate',
+ key: 'bounce_rate',
+ align: 'right',
+ render: (_, row: IspSendingHealthApi) =>
+ row.bounce_rate === null ? (
+ <MissingRate reason="unavailable" />
+ ) : (
+ <RateCell rate={row.bounce_rate} kind="bounce" />
+ ),
+ },
+ {
+ title: 'Complaint rate',
+ key: 'complaint_rate',
+ align: 'right',
+ render: (_, row: IspSendingHealthApi) =>
+ row.complaint_rate === null ? (
+ <MissingRate
+ reason={row.unavailable?.includes('complaint') ? 'unavailable' : 'no-rate'}
+ />
+ ) : (
+ <RateCell rate={row.complaint_rate} kind="complaint" />
+ ),
+ },
+ {
+ title: 'Emails sent',
+ key: 'emails_sent',
+ align: 'right',
+ render: (_, row: IspSendingHealthApi) => humanFriendlyNumber(row.emails_sent),
+ },
+ ]}
+ />
+ </div>
+ )
+}
+
function TeamRatesCard({
reputation,
aws,
+ isps,
+ sharedDomains,
+ withheldDomains,
}: {
reputation: EmailSendingRatesApi | null
aws: AwsTenantReputationApi | null
+ isps: readonly IspSendingHealthApi[]
+ sharedDomains: readonly string[]
+ withheldDomains: readonly string[]
}): JSX.Element {
return (
<div className="border rounded p-4 bg-surface-primary">
@@ -176,12 +347,25 @@ function TeamRatesCard({
<div className="text-lg font-semibold">{humanFriendlyNumber(reputation.emails_sent)}</div>
</div>
</div>
+ ) : isps.length > 0 ? (
+ <div className="text-secondary mt-3">
+ No workflow email in the last 30 days. The breakdown below covers all email sent from your verified
+ domains.
+ </div>
) : (
<div className="text-secondary mt-3">
No email sending data yet. Rates appear here once your workflows send email.
</div>
)}
{aws && <AwsFindings aws={aws} />}
+ <IspBreakdown isps={isps} sharedDomains={sharedDomains} />
+ {withheldDomains.length > 0 && (
+ <div className="text-secondary text-xs mt-3" data-attr="workflows-reputation-isp-withheld">
+ {withheldDomains.join(', ')} {withheldDomains.length > 1 ? 'are' : 'is'} left out of the provider
+ breakdown. Another project sends from {withheldDomains.length > 1 ? 'them' : 'it'}, and you do not
+ have access to that project.
+ </div>
+ )}
</div>
)
}
@@ -239,8 +423,17 @@ function SendingAllowanceCard({ allowance }: { allowance: EmailSendingAllowanceA
}
export function WorkflowsReputation(): JSX.Element {
- const { awsReputation, sendingAllowance, teamReputation, workflowSnapshots, reputationResponseLoading, search } =
- useValues(workflowsReputationLogic)
+ const {
+ awsReputation,
+ sendingAllowance,
+ teamReputation,
+ ispSendingHealth,
+ ispSharedDomains,
+ ispWithheldDomains,
+ workflowSnapshots,
+ reputationResponseLoading,
+ search,
+ } = useValues(workflowsReputationLogic)
const { setSearch } = useActions(workflowsReputationLogic)
return (
@@ -257,8 +450,14 @@ export function WorkflowsReputation(): JSX.Element {
We judge and enforce reputation per project.
</LemonBanner>
{sendingAllowance?.enforced && <SendingAllowanceCard allowance={sendingAllowance} />}
- {teamReputation || awsReputation ? (
- <TeamRatesCard reputation={teamReputation} aws={awsReputation} />
+ {teamReputation || awsReputation || ispSendingHealth.length > 0 || ispWithheldDomains.length > 0 ? (
+ <TeamRatesCard
+ reputation={teamReputation}
+ aws={awsReputation}
+ isps={ispSendingHealth}
+ sharedDomains={ispSharedDomains}
+ withheldDomains={ispWithheldDomains}
+ />
) : (
!reputationResponseLoading && (
<div className="border rounded p-4 text-secondary">
diff --git a/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.ts b/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.ts
index c0a92687bedf..31fae1f7b253 100644
--- a/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.ts
+++ b/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.ts
@@ -8,6 +8,7 @@ import type {
AwsTenantReputationApi,
EmailSendingAllowanceApi,
EmailSendingRatesApi,
+ IspSendingHealthApi,
TeamEmailReputationResponseApi,
WorkflowEmailSendingRatesApi,
} from 'products/workflows/frontend/generated/api.schemas'
@@ -16,6 +17,9 @@ import type {
export interface workflowsReputationLogicValues {
currentProjectId: number | null // projectLogic
awsReputation: AwsTenantReputationApi | null
+ ispSendingHealth: readonly IspSendingHealthApi[]
+ ispSharedDomains: readonly string[]
+ ispWithheldDomains: readonly string[]
reputationResponse: TeamEmailReputationResponseApi | null
reputationResponseLoading: boolean
search: string
@@ -58,6 +62,9 @@ export interface workflowsReputationLogicMeta {
awsReputation: (reputationResponse: TeamEmailReputationResponseApi | null) => AwsTenantReputationApi | null
sendingAllowance: (reputationResponse: TeamEmailReputationResponseApi | null) => EmailSendingAllowanceApi | null
teamReputation: (reputationResponse: TeamEmailReputationResponseApi | null) => EmailSendingRatesApi | null
+ ispSendingHealth: (reputationResponse: TeamEmailReputationResponseApi | null) => readonly IspSendingHealthApi[]
+ ispSharedDomains: (reputationResponse: TeamEmailReputationResponseApi | null) => readonly string[]
+ ispWithheldDomains: (reputationResponse: TeamEmailReputationResponseApi | null) => readonly string[]
workflowSnapshots: (
reputationResponse: TeamEmailReputationResponseApi | null
) => readonly WorkflowEmailSendingRatesApi[]
@@ -132,6 +139,19 @@ export const workflowsReputationLogic = kea<workflowsReputationLogicType>([
(response: TeamEmailReputationResponseApi | null): EmailSendingRatesApi | null =>
response?.reputation ?? null,
],
+ ispSendingHealth: [
+ (s) => [s.reputationResponse],
+ (response: TeamEmailReputationResponseApi | null): readonly IspSendingHealthApi[] => response?.isps ?? [],
+ ],
+ ispSharedDomains: [
+ (s) => [s.reputationResponse],
+ (response: TeamEmailReputationResponseApi | null): readonly string[] => response?.isp_shared_domains ?? [],
+ ],
+ ispWithheldDomains: [
+ (s) => [s.reputationResponse],
+ (response: TeamEmailReputationResponseApi | null): readonly string[] =>
+ response?.isp_withheld_domains ?? [],
+ ],
workflowSnapshots: [
(s) => [s.reputationResponse],
(response: TeamEmailReputationResponseApi | null): readonly WorkflowEmailSendingRatesApi[] =>
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index d649165e0759..4ec84cbf90fc 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -1518,6 +1518,49 @@ export interface WorkflowEmailSendingRatesApi {
readonly hog_flow_name: string
}
+/**
+ * One bucket of a provider's sending history.
+ */
+export interface IspDailyPointApi {
+ /** Bucket date, as an ISO 8601 calendar date. */
+ readonly date: string
+ /** Emails sent to this provider on this date. */
+ readonly emails_sent: number
+ /** Emails this provider accepted on this date, divided by emails sent to it (0-1). */
+ readonly delivery_rate: number
+ /** Hard bounces at this provider on this date, divided by emails sent to it (0-1). */
+ readonly bounce_rate: number
+}
+
+/**
+ * How one mailbox provider treated this project's email, from AWS SES's own delivery data.
+ */
+export interface IspSendingHealthApi {
+ /** The recipient mailbox provider, as AWS names it — for example Gmail or Yahoo. */
+ readonly isp: string
+ /** Emails sent to this provider during the window. */
+ readonly emails_sent: number
+ /**
+ * Emails this provider accepted, divided by emails sent to it (0-1). Acceptance is not inbox placement: a provider can accept a message and still file it as spam. Null when the underlying metric could not be loaded from AWS, which is not the same as zero.
+ * @nullable
+ */
+ readonly delivery_rate: number | null
+ /**
+ * Hard (permanent) bounces at this provider, divided by emails sent to it (0-1). Null when the underlying metric could not be loaded from AWS.
+ * @nullable
+ */
+ readonly bounce_rate: number | null
+ /**
+ * Spam complaints from this provider, divided by the deliveries it reports complaints for (0-1). Null when there is no rate to state — the provider runs no feedback loop, or nothing was delivered — and also when the metric could not be loaded from AWS.
+ * @nullable
+ */
+ readonly complaint_rate: number | null
+ /** Rates AWS did not return for this provider, from `delivery`, `bounce` and `complaint`. A rate named here is missing, not zero, and the UI says so rather than showing a number. */
+ readonly unavailable: readonly string[]
+ /** Sending history for this provider, oldest first, so a drop can be dated rather than averaged into the window. Dates this provider received nothing are omitted. */
+ readonly daily: readonly IspDailyPointApi[]
+}
+
/**
* How much workflow email this project may send, and how much of that it has used.
*/
@@ -1547,6 +1590,12 @@ export interface TeamEmailReputationResponseApi {
readonly reputation: EmailSendingRatesApi | null
/** Rates per workflow, worst first (complaint rate, then bounce rate), capped at the worst 50. */
readonly workflows: readonly WorkflowEmailSendingRatesApi[]
+ /** Sending health per mailbox provider, busiest first. Empty when the caller lacks project-wide workflow access, no sending domain is verified, or AWS has no data yet. */
+ readonly isps: readonly IspSendingHealthApi[]
+ /** Sending domains behind the breakdown that another project also sends from, so its counts include that project's email. Empty when every domain is this project's alone. */
+ readonly isp_shared_domains: readonly string[]
+ /** Sending domains left out of the breakdown because another project sends from them and the caller cannot access that project. Empty when nothing is withheld. */
+ readonly isp_withheld_domains: readonly string[]
/** True while workflow email sending is suspended for this project to protect deliverability. */
readonly email_sending_suspended: boolean
/**
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 47329fe3ef97..9c0511e913fb 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -46887,6 +46887,49 @@ export namespace Schemas {
identifier: string;
}
+ /**
+ * One bucket of a provider's sending history.
+ */
+ export interface IspDailyPoint {
+ /** Bucket date, as an ISO 8601 calendar date. */
+ readonly date: string;
+ /** Emails sent to this provider on this date. */
+ readonly emails_sent: number;
+ /** Emails this provider accepted on this date, divided by emails sent to it (0-1). */
+ readonly delivery_rate: number;
+ /** Hard bounces at this provider on this date, divided by emails sent to it (0-1). */
+ readonly bounce_rate: number;
+ }
+
+ /**
+ * How one mailbox provider treated this project's email, from AWS SES's own delivery data.
+ */
+ export interface IspSendingHealth {
+ /** The recipient mailbox provider, as AWS names it — for example Gmail or Yahoo. */
+ readonly isp: string;
+ /** Emails sent to this provider during the window. */
+ readonly emails_sent: number;
+ /**
+ * Emails this provider accepted, divided by emails sent to it (0-1). Acceptance is not inbox placement: a provider can accept a message and still file it as spam. Null when the underlying metric could not be loaded from AWS, which is not the same as zero.
+ * @nullable
+ */
+ readonly delivery_rate: number | null;
+ /**
+ * Hard (permanent) bounces at this provider, divided by emails sent to it (0-1). Null when the underlying metric could not be loaded from AWS.
+ * @nullable
+ */
+ readonly bounce_rate: number | null;
+ /**
+ * Spam complaints from this provider, divided by the deliveries it reports complaints for (0-1). Null when there is no rate to state — the provider runs no feedback loop, or nothing was delivered — and also when the metric could not be loaded from AWS.
+ * @nullable
+ */
+ readonly complaint_rate: number | null;
+ /** Rates AWS did not return for this provider, from `delivery`, `bounce` and `complaint`. A rate named here is missing, not zero, and the UI says so rather than showing a number. */
+ readonly unavailable: readonly string[];
+ /** Sending history for this provider, oldest first, so a drop can be dated rather than averaged into the window. Dates this provider received nothing are omitted. */
+ readonly daily: readonly IspDailyPoint[];
+ }
+
export interface JiraIssueSignalExtra {
key: string;
url: string | null;
@@ -85795,6 +85838,12 @@ export namespace Schemas {
readonly reputation: EmailSendingRates | null;
/** Rates per workflow, worst first (complaint rate, then bounce rate), capped at the worst 50. */
readonly workflows: readonly WorkflowEmailSendingRates[];
+ /** Sending health per mailbox provider, busiest first. Empty when the caller lacks project-wide workflow access, no sending domain is verified, or AWS has no data yet. */
+ readonly isps: readonly IspSendingHealth[];
+ /** Sending domains behind the breakdown that another project also sends from, so its counts include that project's email. Empty when every domain is this project's alone. */
+ readonly isp_shared_domains: readonly string[];
+ /** Sending domains left out of the breakdown because another project sends from them and the caller cannot access that project. Empty when nothing is withheld. */
+ readonly isp_withheld_domains: readonly string[];
/** True while workflow email sending is suspended for this project to protect deliverability. */
readonly email_sending_suspended: boolean;
/**