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): compute email sending rates on the fly, retire reputation snapshots (#74762)

Meikel Ratza03b7b04c988
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index e7a6528df141..3762a31e1edb 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -586,8 +586,6 @@ SPECTACULAR_SETTINGS = {
"products.ai_observability.backend.models.evaluation_reports.EvaluationReport.Frequency"
),
"HogFlowStatusEnum": "products.workflows.backend.models.hog_flow.hog_flow.HogFlow.State",
- "EmailReputationScopeEnum": "products.workflows.backend.models.email_reputation.EmailReputationSnapshot.Scope",
- "EmailReputationStateEnum": "products.workflows.backend.models.email_reputation.EmailReputationSnapshot.State",
"MCPAuthTypeEnum": "products.mcp_store.backend.models.AUTH_TYPE_CHOICES",
"UtmIssueKindEnum": "products.marketing_analytics.backend.services.types.UTM_ISSUE_KIND_CHOICES",
# Shared by ConversionGoalSummary.kind and GoalExplanation.kind (same choice set).
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 40a6baf690ea..cf6d06ac4174 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -7,6 +7,7 @@ from copy import deepcopy
from datetime import timedelta
from typing import Any, Optional, cast
+from django.core.cache import cache
from django.core.exceptions import ValidationError as DjangoValidationError
from django.core.signing import BadSignature, SignatureExpired, TimestampSigner
from django.db import transaction
@@ -86,7 +87,6 @@ from products.workflows.backend.api.message_assets import (
fetch_message_assets,
)
from products.workflows.backend.api.publish_impact import build_publish_impact
-from products.workflows.backend.models.email_reputation import EmailReputationSnapshot
from products.workflows.backend.models.hog_flow.hog_flow import (
BILLABLE_ACTION_TYPES,
PERSON_DEPENDENT_ACTION_TYPES,
@@ -1139,87 +1139,62 @@ class HogFlowScheduleSerializer(serializers.ModelSerializer):
return super().update(instance, validated_data)
-class EmailReputationSnapshotSerializer(serializers.ModelSerializer):
- """One email deliverability reputation snapshot (per workflow or per team, per daily evaluation run)."""
+def _email_sending_rates(sent: int, bounced: int, complained: int) -> dict[str, float | int]:
+ # Sends are counted at send time but bounces/complaints at webhook time, so feedback arriving
+ # just inside the window for sends just outside it can push the ratio past 1 (worst case: a
+ # workflow that recently stopped sending, with trailing feedback from a prior blast). Clamp to
+ # 100% — the counter metrics can't attribute feedback to its send date, and past 100% the
+ # number stops meaning anything.
+ return {
+ "bounce_rate": min(1.0, bounced / sent) if sent else 0.0,
+ "complaint_rate": min(1.0, complained / sent) if sent else 0.0,
+ "emails_sent": sent,
+ }
- scope = serializers.ChoiceField(
- choices=EmailReputationSnapshot.Scope.choices,
- read_only=True,
- help_text="'workflow' for a single workflow's reputation, 'team' for the project-wide aggregate.",
- )
- state = serializers.ChoiceField(
- choices=EmailReputationSnapshot.State.choices,
+
+class EmailSendingRatesSerializer(serializers.Serializer):
+ """Bounce/complaint rates over the last 30 days of workflow email, computed on the fly from app metrics."""
+
+ bounce_rate = serializers.FloatField(
read_only=True,
help_text=(
- "'insufficient_data' (too few sends in the window to judge), 'healthy', 'warning' (over a "
- "warning threshold), or 'critical' (over a critical threshold)."
+ "Hard (permanent) bounces / emails sent over the last 30 days (0-1), matching how AWS "
+ "counts its bounce rate — transient bounces (greylisting, mailbox full) are excluded. "
+ "Bounces are counted when the feedback arrives, so the ratio is approximate at the "
+ "window boundary and capped at 1."
),
)
- bounce_rate = serializers.FloatField(
- read_only=True,
- help_text="Hard (permanent) bounces / emails sent over the evaluated volume (0-1), matching AWS's account bounce rate — transient bounces are excluded.",
- )
complaint_rate = serializers.FloatField(
- read_only=True, help_text="Spam complaints / emails sent over the evaluated volume (0-1)."
- )
- emails_sent = serializers.IntegerField(
read_only=True,
help_text=(
- "Emails in the evaluated window: at least the target's last day of sends and at least "
- "the configured representative volume (SES-style), whichever covers more. 0 means no "
- "recent sending."
+ "Spam complaints / emails sent over the last 30 days (0-1). Complaints are counted "
+ "when the feedback arrives, so the ratio is approximate at the window boundary and "
+ "capped at 1."
),
)
- evaluated_at = serializers.DateTimeField(
- read_only=True, help_text="When this snapshot was computed; one snapshot exists per target per run."
- )
-
- class Meta:
- model = EmailReputationSnapshot
- fields = [
- "scope",
- "state",
- "bounce_rate",
- "complaint_rate",
- "emails_sent",
- "evaluated_at",
- ]
- read_only_fields = fields
-
+ emails_sent = serializers.IntegerField(read_only=True, help_text="Emails sent in the last 30 days.")
-class WorkflowEmailReputationSnapshotSerializer(EmailReputationSnapshotSerializer):
- """A workflow-scoped reputation snapshot, annotated with the workflow it belongs to."""
- hog_flow_id = serializers.UUIDField(read_only=True, help_text="The workflow this snapshot is for.")
+class WorkflowEmailSendingRatesSerializer(EmailSendingRatesSerializer):
+ hog_flow_id = serializers.UUIDField(read_only=True, help_text="The workflow these rates are for.")
hog_flow_name = serializers.CharField(
- read_only=True, source="hog_flow.name", allow_null=True, help_text="Display name of the workflow."
+ read_only=True, allow_blank=True, help_text="Display name of the workflow; empty for unnamed workflows."
)
- history = serializers.SerializerMethodField(
- help_text="This workflow's snapshots from the last 7 days (oldest first, one per daily evaluation run), including the latest."
- )
-
- @extend_schema_field(EmailReputationSnapshotSerializer(many=True))
- def get_history(self, obj: EmailReputationSnapshot) -> list[dict]:
- rows = self.context.get("workflow_history", {}).get(obj.hog_flow_id, [])
- return list(EmailReputationSnapshotSerializer(rows, many=True).data)
-
- class Meta(EmailReputationSnapshotSerializer.Meta):
- fields = [*EmailReputationSnapshotSerializer.Meta.fields, "hog_flow_id", "hog_flow_name", "history"]
- read_only_fields = fields
class TeamEmailReputationResponseSerializer(serializers.Serializer):
- reputation = EmailReputationSnapshotSerializer(
+ reputation = EmailSendingRatesSerializer(
allow_null=True,
read_only=True,
- help_text="Latest project-wide email reputation snapshot across all workflows; null until first evaluated.",
+ help_text=(
+ "Project-wide rates across all workflow email in the last 30 days (including sends from "
+ "since-deleted workflows); null when nothing was sent."
+ ),
)
- workflows = WorkflowEmailReputationSnapshotSerializer(
+ workflows = WorkflowEmailSendingRatesSerializer(
many=True,
read_only=True,
- help_text=(
- "Latest snapshot per workflow, worst state and highest rates first, capped at the worst 50 workflows."
- ),
+ help_text="Rates per workflow, worst first (complaint rate, then bounce rate), capped at the worst 50.",
)
email_sending_suspended = serializers.BooleanField(
read_only=True,
@@ -3215,27 +3190,12 @@ class HogFlowViewSet(
return Response({"deleted": deleted_count})
- # Severity order for the worst-offender sort; complaint rate breaks ties first (it's the more
- # dangerous SES signal, with thresholds ~20x lower than bounce).
- _REPUTATION_STATE_SEVERITY = {
- EmailReputationSnapshot.State.CRITICAL: 0,
- EmailReputationSnapshot.State.WARNING: 1,
- EmailReputationSnapshot.State.HEALTHY: 2,
- EmailReputationSnapshot.State.INSUFFICIENT_DATA: 3,
- }
-
- # Cap the per-workflow breakdown: without it, hundreds of email workflows each carrying a
- # week of history make one unbounded response. Worst-first sorting means the cut tail is the
- # healthiest workflows.
+ # Cap the per-workflow breakdown to bound the response; worst-first sorting means the cut
+ # tail is the healthiest workflows, and search reaches past the cap.
WORKFLOW_REPUTATION_LIMIT = 50
- # Workflows drop off the breakdown once the evaluator stops producing snapshots for them
- # (i.e. no sends within its lookback), so a long-dead sender's last bad rate isn't pinned
- # to the top of the list forever.
- WORKFLOW_REPUTATION_RECENCY_DAYS = 7
- # How far back each listed workflow's per-day history reaches. Deliberately short: history
- # ships inline on the reputation endpoint (workflows x days rows per response), so widening
- # this fans out the payload for every workflow listed.
- WORKFLOW_REPUTATION_HISTORY_DAYS = 7
+ # Window for the on-the-fly rates. 30 days matches how the industry quotes bounce/complaint
+ # thresholds (e.g. "0.1% complaints per 30 days").
+ REPUTATION_WINDOW_DAYS = 30
@extend_schema(
parameters=[
@@ -3254,71 +3214,107 @@ class HogFlowViewSet(
@action(detail=False, methods=["GET"], pagination_class=None, filter_backends=[], url_path="reputation")
def team_reputation(self, request: Request, **kwargs) -> Response:
"""
- Email deliverability reputation for this project: the latest project-wide snapshot and the
- latest recent snapshot per workflow (worst first, capped). Written daily by the Node
- evaluator; everything is null/empty until the first run.
+ Bounce/complaint rates for this project's workflow email over the last 30 days, computed on
+ the fly from app metrics: a project-wide aggregate plus per-workflow rows (worst first,
+ capped). Display only — reputation judgment and enforcement live with AWS SES tenant
+ management, which attributes sends per team.
"""
# The project-wide aggregate pools ALL workflows' email (that's its point), so it can't be
# filtered per object grant — only members with project-wide workflow read access get it.
# Members holding just object-level grants still get their (filtered) per-workflow rows.
can_read_all_workflows = self.user_access_control.check_access_level_for_resource("hog_flow", "viewer")
- # for_team(canonical=True): rows are keyed by the raw team_id the Node evaluator writes,
- # which may be a child environment id that canonical resolution would rewrite and miss.
- latest = (
- EmailReputationSnapshot.objects.for_team(self.team_id, canonical=True)
- .filter(hog_flow__isnull=True)
- .order_by("-evaluated_at")
- .first()
- if can_read_all_workflows
+ # Cached briefly: the UI reloads per search keystroke, but search filters in Python — the
+ # ClickHouse totals are search-independent. Session-authenticated requests bypass the
+ # default (personal-API-key-only) ClickHouse throttles, so without this a member could
+ # re-run the 30-day aggregation on every request.
+ totals_cache_key = f"workflows_email_reputation_totals_{self.team_id}"
+ totals_by_source = cache.get(totals_cache_key)
+ if totals_by_source is None:
+ after = timezone.now() - timedelta(days=self.REPUTATION_WINDOW_DAYS)
+ totals_by_source = fetch_app_metric_totals_by_source(
+ team_id=self.team_id,
+ app_source="hog_flow",
+ after=after,
+ name=["email_sent", "email_bounced_hard", "email_blocked"],
+ )
+ cache.set(totals_cache_key, totals_by_source, 60)
+
+ # email_blocked is how SES complaint events are recorded (see the plugin server's SES
+ # webhook handler), hence "complained".
+ team_sent = sum(counts.get("email_sent", 0) for counts in totals_by_source.values())
+ team_bounced = sum(counts.get("email_bounced_hard", 0) for counts in totals_by_source.values())
+ team_complained = sum(counts.get("email_blocked", 0) for counts in totals_by_source.values())
+ reputation = (
+ _email_sending_rates(team_sent, team_bounced, team_complained)
+ if can_read_all_workflows and team_sent > 0
else None
)
- # One row per workflow per run over the history window, grouped in Python so each workflow
- # entry carries its recent history alongside the latest snapshot.
- now = timezone.now()
- workflow_rows = (
- EmailReputationSnapshot.objects.for_team(self.team_id, canonical=True)
- .filter(
- hog_flow__isnull=False,
- evaluated_at__gte=now - timedelta(days=self.WORKFLOW_REPUTATION_HISTORY_DAYS),
- )
- .order_by("hog_flow_id", "evaluated_at")
- .select_related("hog_flow")
+ # Attribute sources to workflows: metrics are recorded under the workflow id for
+ # event-triggered runs and under the batch job id for batch runs — resolve both and fold
+ # batch-job counts into the parent workflow. Sources matching neither (deleted workflows,
+ # non-UUID ids) still count toward the team aggregate above.
+ source_ids = [source_id for source_id in totals_by_source if _looks_like_uuid(source_id)]
+ team_queryset = self.get_queryset()
+ # Only names are needed and HogFlow rows are wide (full step graphs in edges/actions/draft),
+ # so don't hydrate model instances for an uncapped id list. Unnamed flows serialize as "" to
+ # keep hog_flow_name a plain string in the generated types.
+ names_by_flow_id = {
+ str(flow_id): name or ""
+ for flow_id, name in team_queryset.filter(id__in=source_ids).values_list("id", "name")
+ }
+ unmatched_ids = [source_id for source_id in source_ids if source_id not in names_by_flow_id]
+ batch_job_to_flow = {
+ str(batch_job_id): str(flow_id)
+ for batch_job_id, flow_id in HogFlowBatchJob.objects.filter(
+ team_id=self.team_id, id__in=unmatched_ids
+ ).values_list("id", "hog_flow_id")
+ }
+ missing_flow_ids = set(batch_job_to_flow.values()) - set(names_by_flow_id)
+ names_by_flow_id.update(
+ {
+ str(flow_id): name or ""
+ for flow_id, name in team_queryset.filter(id__in=missing_flow_ids).values_list("id", "name")
+ }
)
- # Server-side by necessity: the response is capped to the worst 50 workflows, so filtering
- # client-side could never find a healthy workflow beyond the cap.
- search = (request.query_params.get("search") or "").strip()
- if search:
- workflow_rows = workflow_rows.filter(hog_flow__name__icontains=search)
- history_by_flow: dict[uuid_mod.UUID, list[EmailReputationSnapshot]] = {}
- for row in workflow_rows:
- if row.hog_flow_id is None: # can't happen (hog_flow__isnull=False); narrows the nullable FK for mypy
+
+ counts_by_flow: dict[str, dict[str, int]] = {}
+ for source_id, counts in totals_by_source.items():
+ flow_id = source_id if source_id in names_by_flow_id else batch_job_to_flow.get(source_id)
+ if flow_id is None or flow_id not in names_by_flow_id:
continue
- history_by_flow.setdefault(row.hog_flow_id, []).append(row)
+ folded = counts_by_flow.setdefault(flow_id, {"sent": 0, "bounced": 0, "complained": 0})
+ folded["sent"] += counts.get("email_sent", 0)
+ folded["bounced"] += counts.get("email_bounced_hard", 0)
+ folded["complained"] += counts.get("email_blocked", 0)
# Mirror metrics_global: only surface workflows the caller can see, so reputation doesn't
# leak names/volumes of access-controlled workflows the list endpoint hides.
- accessible_ids = set(
- self.user_access_control.filter_queryset_by_access_level(self.get_queryset()).values_list("id", flat=True)
- )
- recency_cutoff = now - timedelta(days=self.WORKFLOW_REPUTATION_RECENCY_DAYS)
- workflow_snapshots = [
- rows[-1]
- for flow_id, rows in history_by_flow.items()
- if flow_id in accessible_ids and rows[-1].evaluated_at >= recency_cutoff
- ]
- # Sort by raw state string (not the State enum constructor, which raises on values a newer
- # evaluator may write before this code deploys); unknown states sort last.
- severity = {state.value: rank for state, rank in self._REPUTATION_STATE_SEVERITY.items()}
- workflow_snapshots.sort(
- key=lambda s: (
- severity.get(s.state, 99),
- -s.complaint_rate,
- -s.bounce_rate,
+ accessible_ids = {
+ str(flow_id)
+ for flow_id in self.user_access_control.filter_queryset_by_access_level(team_queryset).values_list(
+ "id", flat=True
)
- )
- workflow_snapshots = workflow_snapshots[: self.WORKFLOW_REPUTATION_LIMIT]
+ }
+ # Server-side by necessity: the response is capped to the worst 50 workflows, so filtering
+ # client-side could never find a healthy workflow beyond the cap.
+ search = (request.query_params.get("search") or "").strip().lower()
+ workflow_rows: list[dict[str, Any]] = [
+ {
+ "hog_flow_id": flow_id,
+ "hog_flow_name": names_by_flow_id[flow_id],
+ **_email_sending_rates(counts["sent"], counts["bounced"], counts["complained"]),
+ }
+ for flow_id, counts in counts_by_flow.items()
+ if flow_id in accessible_ids
+ and counts["sent"] > 0
+ and (not search or search in names_by_flow_id[flow_id].lower())
+ ]
+ # Complaint rate breaks ties first: it's the more dangerous SES signal, with thresholds
+ # ~20x lower than bounce.
+ workflow_rows.sort(key=lambda row: (-row["complaint_rate"], -row["bounce_rate"], -row["emails_sent"]))
+ workflow_rows = workflow_rows[: self.WORKFLOW_REPUTATION_LIMIT]
# Shown to every project member regardless of per-object grants: a suspension stops
# everyone's email, so hiding it would just leave silent send failures unexplained.
@@ -3333,13 +3329,12 @@ class HogFlowViewSet(
return Response(
TeamEmailReputationResponseSerializer(
{
- "reputation": latest,
- "workflows": workflow_snapshots,
+ "reputation": reputation,
+ "workflows": workflow_rows,
"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 "",
- },
- context={"workflow_history": history_by_flow},
+ }
).data
)
diff --git a/products/workflows/backend/api/test/test_email_reputation.py b/products/workflows/backend/api/test/test_email_reputation.py
index ec1515253b79..cae153d3a9b8 100644
--- a/products/workflows/backend/api/test/test_email_reputation.py
+++ b/products/workflows/backend/api/test/test_email_reputation.py
@@ -1,22 +1,24 @@
-from datetime import datetime, timedelta
-
from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+from django.core.cache import cache
from django.utils import timezone
from rest_framework import status
from posthog.models import Team
-from products.workflows.backend.models import EmailReputationSnapshot, HogFlow
+from products.workflows.backend.models import HogFlow, HogFlowBatchJob
from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig
-RUN_2 = timezone.now().replace(microsecond=0) - timedelta(days=1)
-RUN_1 = RUN_2 - timedelta(days=1)
-STALE_RUN = RUN_2 - timedelta(days=30)
-
class TestEmailReputationAPI(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ # Totals are cached per team and the team persists across this class's tests — clear so
+ # one test's mocked totals can't leak into the next.
+ cache.clear()
+
def _create_flow(self, name: str) -> HogFlow:
return HogFlow.objects.create(
team=self.team,
@@ -28,21 +30,17 @@ class TestEmailReputationAPI(APIBaseTest):
billable_action_types=["function_email"],
)
- def _create_snapshot(self, hog_flow: HogFlow | None, evaluated_at: datetime, **kwargs) -> EmailReputationSnapshot:
- snapshot = EmailReputationSnapshot(
- team=self.team,
- hog_flow=hog_flow,
- scope=EmailReputationSnapshot.Scope.WORKFLOW if hog_flow else EmailReputationSnapshot.Scope.TEAM,
- evaluated_at=evaluated_at,
- **kwargs,
- )
- snapshot.save()
- return snapshot
-
- def test_reputation_endpoint_returns_empty_shape_before_first_evaluation(self):
- response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/reputation")
+ def _get_reputation(self, totals_by_source: dict, query: str = "") -> dict:
+ with patch(
+ "products.workflows.backend.api.hog_flow.fetch_app_metric_totals_by_source",
+ return_value=totals_by_source,
+ ):
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/reputation{query}")
assert response.status_code == status.HTTP_200_OK
- assert response.json() == {
+ return response.json()
+
+ def test_reputation_endpoint_returns_empty_shape_when_nothing_was_sent(self):
+ assert self._get_reputation({}) == {
"reputation": None,
"workflows": [],
"email_sending_suspended": False,
@@ -50,73 +48,88 @@ class TestEmailReputationAPI(APIBaseTest):
"email_sending_suspension_reason": "",
}
- def test_reputation_endpoint_reports_email_sending_suspension(self):
- suspended_at = timezone.now().replace(microsecond=0)
- TeamWorkflowsConfig.objects.update_or_create(
+ # Creating a HogFlowBatchJob fires a post_save signal that dispatches to the plugin server —
+ # patched out like every other batch-job test, or CI fails on the outbound HTTP attempt.
+ @patch(
+ "products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation"
+ )
+ def test_reputation_endpoint_computes_rates_and_folds_batch_jobs_into_workflows(self, _mock_dispatch):
+ flow = self._create_flow("Newsletter")
+ batch_job = HogFlowBatchJob.objects.create(
+ team=self.team, hog_flow=flow, variables={}, filters={}, status="completed"
+ )
+ other_flow = self._create_flow("Onboarding drip")
+
+ data = self._get_reputation(
+ {
+ # Event-triggered sends recorded under the workflow id...
+ str(flow.id): {"email_sent": 600, "email_bounced_hard": 30},
+ # ...batch sends under the batch job id — folded into the same workflow row
+ str(batch_job.id): {"email_sent": 400, "email_bounced_hard": 20, "email_blocked": 1},
+ str(other_flow.id): {"email_sent": 1000},
+ # A source resolving to no workflow (deleted flow) counts only toward the team aggregate
+ "00000000-0000-0000-0000-00000000dead": {"email_sent": 500, "email_bounced_hard": 100},
+ # Non-UUID sources can't be workflows and also count team-level only
+ "not-a-uuid": {"email_sent": 100},
+ }
+ )
+
+ assert data["reputation"] == {
+ "bounce_rate": 150 / 2600,
+ "complaint_rate": 1 / 2600,
+ "emails_sent": 2600,
+ }
+ # Worst first: the folded Newsletter row (complaints beat bounces) before the clean flow
+ assert [(row["hog_flow_name"], row["emails_sent"]) for row in data["workflows"]] == [
+ ("Newsletter", 1000),
+ ("Onboarding drip", 1000),
+ ]
+ assert data["workflows"][0]["bounce_rate"] == 50 / 1000
+ assert data["workflows"][0]["complaint_rate"] == 1 / 1000
+ assert data["workflows"][0]["hog_flow_id"] == str(flow.id)
+
+ def test_reputation_endpoint_clamps_rates_when_trailing_feedback_exceeds_window_sends(self):
+ # Bounces/complaints are recorded at webhook time: a workflow that mostly stopped sending
+ # can have more feedback in the window than sends. The rate clamps at 100%.
+ flow = self._create_flow("Dormant blast")
+
+ data = self._get_reputation(
+ {str(flow.id): {"email_sent": 100, "email_bounced_hard": 500, "email_blocked": 150}}
+ )
+
+ assert data["workflows"][0]["bounce_rate"] == 1.0
+ assert data["workflows"][0]["complaint_rate"] == 1.0
+ assert data["reputation"]["bounce_rate"] == 1.0
+
+ def test_reputation_endpoint_serializes_unnamed_workflows_with_empty_name(self):
+ unnamed = HogFlow.objects.create(
team=self.team,
- defaults={
- "email_sending_suspended_at": suspended_at,
- "email_sending_suspension_reason": "critical bounce rate",
- },
+ name=None,
+ status="active",
+ trigger={"type": "event"},
+ edges=[],
+ actions=[],
+ billable_action_types=["function_email"],
)
- response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/reputation")
- assert response.status_code == status.HTTP_200_OK
- data = response.json()
- assert data["email_sending_suspended"] is True
- assert data["email_sending_suspended_at"] == suspended_at.isoformat().replace("+00:00", "Z")
- assert data["email_sending_suspension_reason"] == "critical bounce rate"
+ data = self._get_reputation({str(unnamed.id): {"email_sent": 10}})
+ assert [(row["hog_flow_id"], row["hog_flow_name"]) for row in data["workflows"]] == [(str(unnamed.id), "")]
def test_reputation_endpoint_search_filters_before_the_cap(self):
- # A healthy workflow pushed past the worst-50 cap must still be findable by name
needle = self._create_flow("Quarterly newsletter")
- self._create_snapshot(needle, RUN_2, state="healthy", bounce_rate=0.001)
+ totals = {str(needle.id): {"email_sent": 100}}
for i in range(55):
noisy = self._create_flow(f"Blast {i}")
- self._create_snapshot(noisy, RUN_2, state="critical", bounce_rate=0.2)
+ totals[str(noisy.id)] = {"email_sent": 1000, "email_bounced_hard": 200}
- unfiltered = self.client.get(f"/api/projects/{self.team.id}/hog_flows/reputation").json()
+ unfiltered = self._get_reputation(totals)
+ assert len(unfiltered["workflows"]) == 50
assert all(row["hog_flow_name"] != "Quarterly newsletter" for row in unfiltered["workflows"])
- searched = self.client.get(f"/api/projects/{self.team.id}/hog_flows/reputation?search=newsLETTER").json()
+ searched = self._get_reputation(totals, query="?search=newsLETTER")
assert [row["hog_flow_name"] for row in searched["workflows"]] == ["Quarterly newsletter"]
- # The team aggregate is unaffected by workflow search
- assert searched["reputation"] is None
-
- def test_reputation_endpoint_returns_latest_history_and_worst_first_workflows(self):
- ok_flow = self._create_flow("Fine workflow")
- bad_flow = self._create_flow("Toxic workflow")
- stale_flow = self._create_flow("Long-dead workflow")
-
- # Two daily team runs: latest must win regardless of insertion order
- self._create_snapshot(None, RUN_2, state="warning", bounce_rate=0.03)
- self._create_snapshot(None, RUN_1, state="healthy", bounce_rate=0.01)
-
- # Per-workflow: only the latest run's snapshot per flow, sorted worst first
- self._create_snapshot(ok_flow, RUN_1, state="critical", bounce_rate=0.09)
- self._create_snapshot(ok_flow, RUN_2, state="healthy", bounce_rate=0.005)
- self._create_snapshot(bad_flow, RUN_2, state="critical", bounce_rate=0.08)
- # A workflow whose last snapshot predates the recency cutoff drops off the breakdown
- self._create_snapshot(stale_flow, STALE_RUN, state="critical", bounce_rate=0.5)
-
- response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/reputation")
- assert response.status_code == status.HTTP_200_OK
- data = response.json()
-
- assert data["reputation"]["state"] == "warning"
- assert data["reputation"]["scope"] == "team"
- assert [(row["hog_flow_name"], row["state"]) for row in data["workflows"]] == [
- ("Toxic workflow", "critical"),
- ("Fine workflow", "healthy"),
- ]
- assert data["workflows"][0]["hog_flow_id"] == str(bad_flow.id)
-
- # Each workflow entry carries its own per-run history, oldest first
- assert [row["state"] for row in data["workflows"][1]["history"]] == ["critical", "healthy"]
- assert [row["state"] for row in data["workflows"][0]["history"]] == ["critical"]
-
- def test_reputation_endpoint_never_returns_other_teams_snapshots(self):
+ def test_reputation_endpoint_never_resolves_other_teams_workflows(self):
other_team = Team.objects.create(organization=self.organization, name="other team")
other_flow = HogFlow.objects.create(
team=other_team,
@@ -127,30 +140,24 @@ class TestEmailReputationAPI(APIBaseTest):
actions=[],
billable_action_types=["function_email"],
)
- EmailReputationSnapshot(
- team=other_team,
- hog_flow=None,
- scope=EmailReputationSnapshot.Scope.TEAM,
- state="critical",
- bounce_rate=0.5,
- evaluated_at=RUN_2,
- ).save()
- EmailReputationSnapshot(
- team=other_team,
- hog_flow=other_flow,
- scope=EmailReputationSnapshot.Scope.WORKFLOW,
- state="critical",
- bounce_rate=0.5,
- evaluated_at=RUN_2,
- ).save()
-
- response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/reputation")
- assert response.status_code == status.HTTP_200_OK
- # Nothing from the other team leaks: no aggregate, no workflow rows
- assert response.json() == {
- "reputation": None,
- "workflows": [],
- "email_sending_suspended": False,
- "email_sending_suspended_at": None,
- "email_sending_suspension_reason": "",
- }
+
+ # A cross-team app_source_id must not leak the other team's workflow name; its counts
+ # still land in this team's aggregate because the metrics query is team-scoped upstream.
+ data = self._get_reputation({str(other_flow.id): {"email_sent": 200, "email_bounced_hard": 10}})
+ assert data["workflows"] == []
+ assert data["reputation"]["emails_sent"] == 200
+
+ def test_reputation_endpoint_reports_email_sending_suspension(self):
+ suspended_at = timezone.now().replace(microsecond=0)
+ TeamWorkflowsConfig.objects.update_or_create(
+ team=self.team,
+ defaults={
+ "email_sending_suspended_at": suspended_at,
+ "email_sending_suspension_reason": "critical bounce rate",
+ },
+ )
+
+ data = self._get_reputation({})
+ assert data["email_sending_suspended"] is True
+ assert data["email_sending_suspended_at"] == suspended_at.isoformat().replace("+00:00", "Z")
+ assert data["email_sending_suspension_reason"] == "critical bounce rate"
diff --git a/products/workflows/backend/migrations/0015_delete_emailreputationsnapshot.py b/products/workflows/backend/migrations/0015_delete_emailreputationsnapshot.py
new file mode 100644
index 000000000000..25b2951b777a
--- /dev/null
+++ b/products/workflows/backend/migrations/0015_delete_emailreputationsnapshot.py
@@ -0,0 +1,24 @@
+# Generated by Django 5.2.14 on 2026-07-29 14:25
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("workflows", "0014_teamworkflowsconfig_email_sending_suspended_at_and_more"),
+ ]
+
+ # State-only removal: posthog_emailreputationsnapshot stays in the database (dropping tables
+ # rides a later dedicated RunSQL migration per the safe-migrations guide). The model is retired
+ # because reputation judgment moved to AWS SES tenant management and rates are computed on the
+ # fly from app metrics.
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.DeleteModel(
+ name="EmailReputationSnapshot",
+ ),
+ ],
+ database_operations=[],
+ ),
+ ]
diff --git a/products/workflows/backend/migrations/0016_drop_emailreputationsnapshot_fk.py b/products/workflows/backend/migrations/0016_drop_emailreputationsnapshot_fk.py
new file mode 100644
index 000000000000..550b31311998
--- /dev/null
+++ b/products/workflows/backend/migrations/0016_drop_emailreputationsnapshot_fk.py
@@ -0,0 +1,34 @@
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("workflows", "0015_delete_emailreputationsnapshot"),
+ ]
+
+ # 0015 removed EmailReputationSnapshot from Django state via SeparateDatabaseAndState but left
+ # the Postgres table and its FK to posthog_hogflow in place. Because the reverse relation is
+ # gone from state, HogFlow.delete() no longer cascade-cleans snapshot rows, and the FK blocks
+ # HogFlow deletion for any team that still has snapshot data. Drop the FK now so HogFlow
+ # deletes go through; the table itself is dropped in a follow-up migration once this one has
+ # finished rolling out (per the safe-migrations two-phase drop pattern).
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[],
+ database_operations=[
+ migrations.RunSQL(
+ sql=(
+ 'ALTER TABLE "posthog_emailreputationsnapshot" '
+ "DROP CONSTRAINT IF EXISTS "
+ '"posthog_emailreputat_hog_flow_id_bebb6dee_fk_posthog_h";'
+ ),
+ reverse_sql=(
+ 'ALTER TABLE "posthog_emailreputationsnapshot" '
+ 'ADD CONSTRAINT "posthog_emailreputat_hog_flow_id_bebb6dee_fk_posthog_h" '
+ 'FOREIGN KEY ("hog_flow_id") REFERENCES "posthog_hogflow" ("id") '
+ "DEFERRABLE INITIALLY DEFERRED;"
+ ),
+ ),
+ ],
+ ),
+ ]
diff --git a/products/workflows/backend/migrations/max_migration.txt b/products/workflows/backend/migrations/max_migration.txt
index 5eddbe3e2c82..92b4c0e3895c 100644
--- a/products/workflows/backend/migrations/max_migration.txt
+++ b/products/workflows/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0014_teamworkflowsconfig_email_sending_suspended_at_and_more
+0016_drop_emailreputationsnapshot_fk
diff --git a/products/workflows/backend/models/__init__.py b/products/workflows/backend/models/__init__.py
index 7c979faa1992..0d93b4114cf0 100644
--- a/products/workflows/backend/models/__init__.py
+++ b/products/workflows/backend/models/__init__.py
@@ -1,4 +1,3 @@
-from .email_reputation import EmailReputationSnapshot
from .hog_flow.hog_flow import HogFlow
from .hog_flow.hog_flow_template import HogFlowTemplate
from .hog_flow_batch_job import HogFlowBatchJob
@@ -7,7 +6,6 @@ from .hog_flow_schedule.hog_flow_schedule import HogFlowSchedule
from .team_workflows_config import TeamWorkflowsConfig
__all__ = [
- "EmailReputationSnapshot",
"HogFlow",
"HogFlowBatchJob",
"HogFlowRevision",
diff --git a/products/workflows/backend/models/email_reputation.py b/products/workflows/backend/models/email_reputation.py
deleted file mode 100644
index dff4eaa6ebdc..000000000000
--- a/products/workflows/backend/models/email_reputation.py
+++ /dev/null
@@ -1,81 +0,0 @@
-from django.db import models
-
-from posthog.models.scoping.root_mixin import TeamScopedRootMixin
-from posthog.models.utils import UUIDModel
-
-
-class EmailReputationSnapshot(TeamScopedRootMixin, UUIDModel):
- """
- Append-only daily snapshots of per-workflow and per-tenant email deliverability reputation
- (bounce/complaint rates from app_metrics2), written by the Node Temporal evaluator via raw SQL.
-
- Rates are volume-based, mirroring AWS SES: each snapshot covers the target's most recent sends
- up to a configured representative volume, not a fixed time window — ``emails_sent`` is that
- evaluated volume (0 for a carry-forward row written when a recently active team goes silent).
-
- One row per workflow (``hog_flow`` set, ``scope=WORKFLOW``) plus one aggregate row per team
- (``hog_flow`` null, ``scope=TEAM``) per evaluation run, so the table doubles as a time series
- for trend dashboards. Calculation only — enforcement (pausing bad senders) ships separately.
- """
-
- class Meta:
- db_table = "posthog_emailreputationsnapshot"
- constraints = [
- # One snapshot per target per run; the Node evaluator inserts ON CONFLICT DO NOTHING
- # against these so Temporal activity retries are idempotent.
- models.UniqueConstraint(
- fields=["team", "hog_flow", "evaluated_at"],
- condition=models.Q(hog_flow__isnull=False),
- name="unique_workflow_reputation_snapshot",
- ),
- models.UniqueConstraint(
- fields=["team", "evaluated_at"],
- condition=models.Q(hog_flow__isnull=True),
- name="unique_team_reputation_snapshot",
- ),
- # scope is denormalized from hog_flow nullability for readers; keep them coherent so
- # a row can't classify as one target by scope and the other by hog_flow.
- models.CheckConstraint(
- check=models.Q(scope="team", hog_flow__isnull=True)
- | models.Q(scope="workflow", hog_flow__isnull=False),
- name="email_rep_snapshot_scope_matches_target",
- ),
- ]
- indexes = [
- models.Index(fields=["team", "evaluated_at"], name="posthog_ema_team_id_a35f59_idx"),
- # Serves the evaluator's daily plan query (recent team rows with sends, no team filter).
- models.Index(
- fields=["evaluated_at"],
- condition=models.Q(hog_flow__isnull=True, emails_sent__gt=0),
- name="eml_rep_snapshot_plan_idx",
- ),
- ]
-
- class Scope(models.TextChoices):
- WORKFLOW = "workflow"
- TEAM = "team"
-
- class State(models.TextChoices):
- INSUFFICIENT_DATA = "insufficient_data"
- HEALTHY = "healthy"
- WARNING = "warning"
- CRITICAL = "critical"
-
- # db_constraint=False: posthog_team is a hot table; a real FK constraint would lock it on deploy.
- team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
- # Null hog_flow marks the team-level aggregate row.
- hog_flow = models.ForeignKey("workflows.HogFlow", on_delete=models.CASCADE, null=True, blank=True)
- scope = models.CharField(max_length=20, choices=Scope)
- state = models.CharField(max_length=20, choices=State)
-
- bounce_rate = models.FloatField(default=0.0)
- complaint_rate = models.FloatField(default=0.0)
- emails_sent = models.BigIntegerField(default=0)
-
- # End of the evaluated rolling window; shared by all rows of one evaluator run.
- evaluated_at = models.DateTimeField()
- created_at = models.DateTimeField(auto_now_add=True)
-
- def __str__(self) -> str:
- target = f"hog_flow {self.hog_flow_id}" if self.hog_flow_id else "team"
- return f"EmailReputationSnapshot({target}, {self.state}, {self.evaluated_at})"
diff --git a/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx b/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx
index 513ddf42e9e9..c3b8ffd096c1 100644
--- a/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx
+++ b/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx
@@ -1,65 +1,24 @@
import { useActions, useValues } from 'kea'
-import { LemonBanner, LemonInput, LemonTable, LemonTag, LemonTagType, Link, Tooltip } from '@posthog/lemon-ui'
+import { LemonBanner, LemonInput, LemonTable, Link, Tooltip } from '@posthog/lemon-ui'
-import { TZLabel } from 'lib/components/TZLabel'
import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
import { urls } from 'scenes/urls'
import type {
- EmailReputationSnapshotApi,
- EmailReputationStateEnumApi,
- WorkflowEmailReputationSnapshotApi,
+ EmailSendingRatesApi,
+ WorkflowEmailSendingRatesApi,
} from 'products/workflows/frontend/generated/api.schemas'
import { workflowsReputationLogic } from './workflowsReputationLogic'
-// Descriptions must match the evaluator's default thresholds
-// (nodejs/src/cdp/services/email-reputation/classifier.ts DEFAULT_THRESHOLDS).
-const STATE_CONFIG: Record<EmailReputationStateEnumApi, { label: string; type: LemonTagType; tooltip: string }> = {
- healthy: {
- label: 'Healthy',
- type: 'success',
- tooltip:
- 'Hard bounce rate below 2% and spam complaint rate below 0.1%. Transient bounces (greylisting, mailbox full) are not counted.',
- },
- warning: {
- label: 'Warning',
- type: 'warning',
- tooltip:
- 'Hard bounce rate at or above 2%, or spam complaint rate at or above 0.1%. Review your recipient list before rates climb further.',
- },
- critical: {
- label: 'Critical',
- type: 'danger',
- tooltip:
- 'Hard bounce rate at or above 5%, or spam complaint rate at or above 0.5%. Sending at these rates puts email deliverability at risk.',
- },
- insufficient_data: {
- label: 'Not enough data',
- type: 'muted',
- tooltip: 'Fewer than 100 emails in the evaluated window, which is too few to judge reliably.',
- },
-}
-
-function StateTag({ state }: { state: EmailReputationStateEnumApi }): JSX.Element {
- const config = STATE_CONFIG[state] ?? STATE_CONFIG.insufficient_data
- return (
- <Tooltip title={config.tooltip}>
- <LemonTag type={config.type}>{config.label}</LemonTag>
- </Tooltip>
- )
-}
-
function formatRate(rate: number): string {
return percentage(rate, 2, true)
}
-// Must match the evaluator's window config (nodejs/src/cdp/services/email-reputation: representative
-// volume = max(1,000, 3× the biggest sending day), min window 24h, 30d lookback) and the endpoint's
-// cap (HogFlowViewSet.WORKFLOW_REPUTATION_LIMIT).
-const EVALUATION_WINDOW_TOOLTIP =
- 'Rates are calculated over your most recent sending: roughly 3 times your biggest sending day of the last 30 days (at least 1,000 emails, and at least the last 24 hours), so a single campaign never dominates the score. The window looks back up to 30 days.'
+// Must match the endpoint's window (HogFlowViewSet.REPUTATION_WINDOW_DAYS) and cap
+// (HogFlowViewSet.WORKFLOW_REPUTATION_LIMIT).
+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 {
@@ -72,84 +31,34 @@ function MetricLabel({ label, tooltip }: { label: string; tooltip: string }): JS
)
}
-function TeamReputationCard({ reputation }: { reputation: EmailReputationSnapshotApi }): JSX.Element {
+function TeamRatesCard({ reputation }: { reputation: EmailSendingRatesApi }): JSX.Element {
return (
<div className="border rounded p-4 bg-surface-primary">
- <div className="flex items-center gap-2">
- <h3 className="mb-0">Project email reputation</h3>
- <StateTag state={reputation.state} />
- </div>
+ <h3 className="mb-0">Project email sending health</h3>
<div className="flex flex-wrap gap-8 mt-3">
<div>
<MetricLabel
label="Bounce rate"
- tooltip="Hard (permanent) bounces divided by emails evaluated. Transient bounces like a full mailbox are not counted."
+ tooltip={`Hard (permanent) bounces divided by emails sent. Transient bounces like a full mailbox are not counted. ${WINDOW_TOOLTIP}`}
/>
<div className="text-lg font-semibold">{formatRate(reputation.bounce_rate)}</div>
</div>
<div>
- <MetricLabel label="Spam complaint rate" tooltip="Spam complaints divided by emails evaluated." />
+ <MetricLabel
+ label="Spam complaint rate"
+ tooltip={`Spam complaints divided by emails sent. ${WINDOW_TOOLTIP}`}
+ />
<div className="text-lg font-semibold">{formatRate(reputation.complaint_rate)}</div>
</div>
<div>
- <MetricLabel label="Emails evaluated (recent volume)" tooltip={EVALUATION_WINDOW_TOOLTIP} />
+ <MetricLabel label="Emails sent (last 30 days)" tooltip={WINDOW_TOOLTIP} />
<div className="text-lg font-semibold">{humanFriendlyNumber(reputation.emails_sent)}</div>
</div>
- <div>
- <div className="text-secondary text-xs">Last evaluated</div>
- <div className="text-lg font-semibold">
- <TZLabel time={reputation.evaluated_at} />
- </div>
- </div>
</div>
</div>
)
}
-function WorkflowHistoryTable({ history }: { history: readonly EmailReputationSnapshotApi[] }): JSX.Element {
- return (
- <div className="py-1">
- <div className="text-secondary text-xs mb-1">Daily scores from the last 7 days</div>
- <LemonTable
- size="small"
- embedded
- dataSource={[...history].reverse()}
- rowKey={(snapshot) => snapshot.evaluated_at}
- columns={[
- {
- title: 'Evaluated',
- key: 'evaluated_at',
- render: (_, snapshot: EmailReputationSnapshotApi) => <TZLabel time={snapshot.evaluated_at} />,
- },
- {
- title: 'State',
- key: 'state',
- render: (_, snapshot: EmailReputationSnapshotApi) => <StateTag state={snapshot.state} />,
- },
- {
- title: 'Bounce rate',
- key: 'bounce_rate',
- align: 'right',
- render: (_, snapshot: EmailReputationSnapshotApi) => formatRate(snapshot.bounce_rate),
- },
- {
- title: 'Complaint rate',
- key: 'complaint_rate',
- align: 'right',
- render: (_, snapshot: EmailReputationSnapshotApi) => formatRate(snapshot.complaint_rate),
- },
- {
- title: 'Emails sent',
- key: 'emails_sent',
- align: 'right',
- render: (_, snapshot: EmailReputationSnapshotApi) => humanFriendlyNumber(snapshot.emails_sent),
- },
- ]}
- />
- </div>
- )
-}
-
export function WorkflowsReputation(): JSX.Element {
const { teamReputation, workflowSnapshots, reputationResponseLoading, search } = useValues(workflowsReputationLogic)
const { setSearch } = useActions(workflowsReputationLogic)
@@ -157,16 +66,15 @@ export function WorkflowsReputation(): JSX.Element {
return (
<div className="space-y-4" data-attr="workflows-reputation">
<LemonBanner type="info" data-attr="workflows-reputation-beta-banner">
- Reputation scores are surfaced here for transparency only. We don't take any enforcement action based on
- them right now. We're still actively developing the scoring calculation, so these values may change.
+ Sending health is shown for transparency: high bounce or spam complaint rates hurt email deliverability.
+ Reputation judgment and enforcement are handled per project by our email provider.
</LemonBanner>
{teamReputation ? (
- <TeamReputationCard reputation={teamReputation} />
+ <TeamRatesCard reputation={teamReputation} />
) : (
!reputationResponseLoading && (
<div className="border rounded p-4 text-secondary">
- No reputation data yet. Reputation is calculated daily from email bounces and spam complaints
- once your workflows start sending email.
+ No email sending data yet. Rates appear here once your workflows send email.
</div>
)
)}
@@ -181,8 +89,8 @@ export function WorkflowsReputation(): JSX.Element {
/>
{!search.trim() && workflowSnapshots.length >= WORKFLOW_LIMIT && (
<span className="text-secondary text-xs">
- Showing the {WORKFLOW_LIMIT} workflows with the worst reputation. Search to find any other
- evaluated workflow.
+ Showing the {WORKFLOW_LIMIT} workflows with the highest rates. Search to find any other sending
+ workflow.
</span>
)}
</div>
@@ -192,60 +100,39 @@ export function WorkflowsReputation(): JSX.Element {
rowKey={(snapshot) => snapshot.hog_flow_id}
emptyState={
search.trim()
- ? 'No evaluated workflows match your search.'
- : 'No workflows have sent enough email to be evaluated yet.'
+ ? 'No sending workflows match your search.'
+ : 'No workflows have sent email in the last 30 days.'
}
columns={[
{
title: 'Workflow',
key: 'workflow',
- render: (_, snapshot: WorkflowEmailReputationSnapshotApi) => (
+ render: (_, snapshot: WorkflowEmailSendingRatesApi) => (
<Link to={urls.workflow(snapshot.hog_flow_id, 'workflow')} className="font-semibold">
{snapshot.hog_flow_name || snapshot.hog_flow_id}
</Link>
),
},
- {
- title: 'State',
- key: 'state',
- render: (_, snapshot: WorkflowEmailReputationSnapshotApi) => (
- <StateTag state={snapshot.state} />
- ),
- },
{
title: 'Bounce rate',
key: 'bounce_rate',
align: 'right',
- render: (_, snapshot: WorkflowEmailReputationSnapshotApi) => formatRate(snapshot.bounce_rate),
+ render: (_, snapshot: WorkflowEmailSendingRatesApi) => formatRate(snapshot.bounce_rate),
},
{
title: 'Complaint rate',
key: 'complaint_rate',
align: 'right',
- render: (_, snapshot: WorkflowEmailReputationSnapshotApi) =>
- formatRate(snapshot.complaint_rate),
+ render: (_, snapshot: WorkflowEmailSendingRatesApi) => formatRate(snapshot.complaint_rate),
},
{
title: 'Emails sent',
key: 'emails_sent',
align: 'right',
- render: (_, snapshot: WorkflowEmailReputationSnapshotApi) =>
+ render: (_, snapshot: WorkflowEmailSendingRatesApi) =>
humanFriendlyNumber(snapshot.emails_sent),
},
- {
- title: 'Evaluated',
- key: 'evaluated_at',
- render: (_, snapshot: WorkflowEmailReputationSnapshotApi) => (
- <TZLabel time={snapshot.evaluated_at} />
- ),
- },
]}
- expandable={{
- rowExpandable: (snapshot: WorkflowEmailReputationSnapshotApi) => snapshot.history.length > 1,
- expandedRowRender: (snapshot: WorkflowEmailReputationSnapshotApi) => (
- <WorkflowHistoryTable history={snapshot.history} />
- ),
- }}
/>
</div>
)
diff --git a/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.ts b/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.ts
index d40da570d7c2..9f2a2241b5ed 100644
--- a/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.ts
+++ b/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.ts
@@ -5,9 +5,9 @@ import { projectLogic } from 'scenes/projectLogic'
import { hogFlowsReputationRetrieve } from 'products/workflows/frontend/generated/api'
import type {
- EmailReputationSnapshotApi,
+ EmailSendingRatesApi,
TeamEmailReputationResponseApi,
- WorkflowEmailReputationSnapshotApi,
+ WorkflowEmailSendingRatesApi,
} from 'products/workflows/frontend/generated/api.schemas'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -16,8 +16,8 @@ export interface workflowsReputationLogicValues {
reputationResponse: TeamEmailReputationResponseApi | null
reputationResponseLoading: boolean
search: string
- teamReputation: EmailReputationSnapshotApi | null
- workflowSnapshots: readonly WorkflowEmailReputationSnapshotApi[]
+ teamReputation: EmailSendingRatesApi | null
+ workflowSnapshots: readonly WorkflowEmailSendingRatesApi[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -51,10 +51,10 @@ export interface workflowsReputationLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface workflowsReputationLogicMeta {
__keaTypeGenInternalSelectorTypes: {
- teamReputation: (reputationResponse: TeamEmailReputationResponseApi | null) => EmailReputationSnapshotApi | null
+ teamReputation: (reputationResponse: TeamEmailReputationResponseApi | null) => EmailSendingRatesApi | null
workflowSnapshots: (
reputationResponse: TeamEmailReputationResponseApi | null
- ) => readonly WorkflowEmailReputationSnapshotApi[]
+ ) => readonly WorkflowEmailSendingRatesApi[]
}
}
@@ -114,12 +114,12 @@ export const workflowsReputationLogic = kea<workflowsReputationLogicType>([
selectors({
teamReputation: [
(s) => [s.reputationResponse],
- (response: TeamEmailReputationResponseApi | null): EmailReputationSnapshotApi | null =>
+ (response: TeamEmailReputationResponseApi | null): EmailSendingRatesApi | null =>
response?.reputation ?? null,
],
workflowSnapshots: [
(s) => [s.reputationResponse],
- (response: TeamEmailReputationResponseApi | null): readonly WorkflowEmailReputationSnapshotApi[] =>
+ (response: TeamEmailReputationResponseApi | null): readonly WorkflowEmailSendingRatesApi[] =>
response?.workflows ?? [],
],
}),
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index 2bf386b82dee..a8ec8b661ebb 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -1058,97 +1058,38 @@ export interface WorkflowStatsRowApi {
}
/**
- * * `workflow` - Workflow
- * * `team` - Team
+ * Bounce/complaint rates over the last 30 days of workflow email, computed on the fly from app metrics.
*/
-export type EmailReputationScopeEnumApi = (typeof EmailReputationScopeEnumApi)[keyof typeof EmailReputationScopeEnumApi]
-
-export const EmailReputationScopeEnumApi = {
- Workflow: 'workflow',
- Team: 'team',
-} as const
-
-/**
- * * `insufficient_data` - Insufficient Data
- * * `healthy` - Healthy
- * * `warning` - Warning
- * * `critical` - Critical
- */
-export type EmailReputationStateEnumApi = (typeof EmailReputationStateEnumApi)[keyof typeof EmailReputationStateEnumApi]
-
-export const EmailReputationStateEnumApi = {
- InsufficientData: 'insufficient_data',
- Healthy: 'healthy',
- Warning: 'warning',
- Critical: 'critical',
-} as const
-
-/**
- * One email deliverability reputation snapshot (per workflow or per team, per daily evaluation run).
- */
-export interface EmailReputationSnapshotApi {
- /** 'workflow' for a single workflow's reputation, 'team' for the project-wide aggregate.
- *
- * * `workflow` - Workflow
- * * `team` - Team */
- readonly scope: EmailReputationScopeEnumApi
- /** 'insufficient_data' (too few sends in the window to judge), 'healthy', 'warning' (over a warning threshold), or 'critical' (over a critical threshold).
- *
- * * `insufficient_data` - Insufficient Data
- * * `healthy` - Healthy
- * * `warning` - Warning
- * * `critical` - Critical */
- readonly state: EmailReputationStateEnumApi
- /** Hard (permanent) bounces / emails sent over the evaluated volume (0-1), matching AWS's account bounce rate — transient bounces are excluded. */
+export interface EmailSendingRatesApi {
+ /** Hard (permanent) bounces / emails sent over the last 30 days (0-1), matching how AWS counts its bounce rate — transient bounces (greylisting, mailbox full) are excluded. Bounces are counted when the feedback arrives, so the ratio is approximate at the window boundary and capped at 1. */
readonly bounce_rate: number
- /** Spam complaints / emails sent over the evaluated volume (0-1). */
+ /** Spam complaints / emails sent over the last 30 days (0-1). Complaints are counted when the feedback arrives, so the ratio is approximate at the window boundary and capped at 1. */
readonly complaint_rate: number
- /** Emails in the evaluated window: at least the target's last day of sends and at least the configured representative volume (SES-style), whichever covers more. 0 means no recent sending. */
+ /** Emails sent in the last 30 days. */
readonly emails_sent: number
- /** When this snapshot was computed; one snapshot exists per target per run. */
- readonly evaluated_at: string
}
/**
- * A workflow-scoped reputation snapshot, annotated with the workflow it belongs to.
+ * Bounce/complaint rates over the last 30 days of workflow email, computed on the fly from app metrics.
*/
-export interface WorkflowEmailReputationSnapshotApi {
- /** 'workflow' for a single workflow's reputation, 'team' for the project-wide aggregate.
- *
- * * `workflow` - Workflow
- * * `team` - Team */
- readonly scope: EmailReputationScopeEnumApi
- /** 'insufficient_data' (too few sends in the window to judge), 'healthy', 'warning' (over a warning threshold), or 'critical' (over a critical threshold).
- *
- * * `insufficient_data` - Insufficient Data
- * * `healthy` - Healthy
- * * `warning` - Warning
- * * `critical` - Critical */
- readonly state: EmailReputationStateEnumApi
- /** Hard (permanent) bounces / emails sent over the evaluated volume (0-1), matching AWS's account bounce rate — transient bounces are excluded. */
+export interface WorkflowEmailSendingRatesApi {
+ /** Hard (permanent) bounces / emails sent over the last 30 days (0-1), matching how AWS counts its bounce rate — transient bounces (greylisting, mailbox full) are excluded. Bounces are counted when the feedback arrives, so the ratio is approximate at the window boundary and capped at 1. */
readonly bounce_rate: number
- /** Spam complaints / emails sent over the evaluated volume (0-1). */
+ /** Spam complaints / emails sent over the last 30 days (0-1). Complaints are counted when the feedback arrives, so the ratio is approximate at the window boundary and capped at 1. */
readonly complaint_rate: number
- /** Emails in the evaluated window: at least the target's last day of sends and at least the configured representative volume (SES-style), whichever covers more. 0 means no recent sending. */
+ /** Emails sent in the last 30 days. */
readonly emails_sent: number
- /** When this snapshot was computed; one snapshot exists per target per run. */
- readonly evaluated_at: string
- /** The workflow this snapshot is for. */
+ /** The workflow these rates are for. */
readonly hog_flow_id: string
- /**
- * Display name of the workflow.
- * @nullable
- */
- readonly hog_flow_name: string | null
- /** This workflow's snapshots from the last 7 days (oldest first, one per daily evaluation run), including the latest. */
- readonly history: readonly EmailReputationSnapshotApi[]
+ /** Display name of the workflow; empty for unnamed workflows. */
+ readonly hog_flow_name: string
}
export interface TeamEmailReputationResponseApi {
- /** Latest project-wide email reputation snapshot across all workflows; null until first evaluated. */
- readonly reputation: EmailReputationSnapshotApi | null
- /** Latest snapshot per workflow, worst state and highest rates first, capped at the worst 50 workflows. */
- readonly workflows: readonly WorkflowEmailReputationSnapshotApi[]
+ /** Project-wide rates across all workflow email in the last 30 days (including sends from since-deleted workflows); null when nothing was sent. */
+ readonly reputation: EmailSendingRatesApi | null
+ /** Rates per workflow, worst first (complaint rate, then bounce rate), capped at the worst 50. */
+ readonly workflows: readonly WorkflowEmailSendingRatesApi[]
/** True while workflow email sending is suspended for this project to protect deliverability. */
readonly email_sending_suspended: boolean
/**
diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.ts
index 704caec5888e..29cc93ac6781 100644
--- a/products/workflows/frontend/generated/api.ts
+++ b/products/workflows/frontend/generated/api.ts
@@ -878,9 +878,10 @@ export const getHogFlowsReputationRetrieveUrl = (projectId: string, params?: Hog
}
/**
- * Email deliverability reputation for this project: the latest project-wide snapshot and the
- * latest recent snapshot per workflow (worst first, capped). Written daily by the Node
- * evaluator; everything is null/empty until the first run.
+ * Bounce/complaint rates for this project's workflow email over the last 30 days, computed on
+ * the fly from app metrics: a project-wide aggregate plus per-workflow rows (worst first,
+ * capped). Display only — reputation judgment and enforcement live with AWS SES tenant
+ * management, which attributes sends per team.
*/
export const hogFlowsReputationRetrieve = async (
projectId: string,
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 4199e1081922..86e0b5361bcc 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -23390,57 +23390,15 @@ export namespace Schemas {
}
/**
- * * `workflow` - Workflow
- * * `team` - Team
+ * Bounce/complaint rates over the last 30 days of workflow email, computed on the fly from app metrics.
*/
- export type EmailReputationScopeEnum = typeof EmailReputationScopeEnum[keyof typeof EmailReputationScopeEnum];
-
-
- export const EmailReputationScopeEnum = {
- Workflow: 'workflow',
- Team: 'team',
- } as const;
-
- /**
- * * `insufficient_data` - Insufficient Data
- * * `healthy` - Healthy
- * * `warning` - Warning
- * * `critical` - Critical
- */
- export type EmailReputationStateEnum = typeof EmailReputationStateEnum[keyof typeof EmailReputationStateEnum];
-
-
- export const EmailReputationStateEnum = {
- InsufficientData: 'insufficient_data',
- Healthy: 'healthy',
- Warning: 'warning',
- Critical: 'critical',
- } as const;
-
- /**
- * One email deliverability reputation snapshot (per workflow or per team, per daily evaluation run).
- */
- export interface EmailReputationSnapshot {
- /** 'workflow' for a single workflow's reputation, 'team' for the project-wide aggregate.
- *
- * * `workflow` - Workflow
- * * `team` - Team */
- readonly scope: EmailReputationScopeEnum;
- /** 'insufficient_data' (too few sends in the window to judge), 'healthy', 'warning' (over a warning threshold), or 'critical' (over a critical threshold).
- *
- * * `insufficient_data` - Insufficient Data
- * * `healthy` - Healthy
- * * `warning` - Warning
- * * `critical` - Critical */
- readonly state: EmailReputationStateEnum;
- /** Hard (permanent) bounces / emails sent over the evaluated volume (0-1), matching AWS's account bounce rate — transient bounces are excluded. */
+ export interface EmailSendingRates {
+ /** Hard (permanent) bounces / emails sent over the last 30 days (0-1), matching how AWS counts its bounce rate — transient bounces (greylisting, mailbox full) are excluded. Bounces are counted when the feedback arrives, so the ratio is approximate at the window boundary and capped at 1. */
readonly bounce_rate: number;
- /** Spam complaints / emails sent over the evaluated volume (0-1). */
+ /** Spam complaints / emails sent over the last 30 days (0-1). Complaints are counted when the feedback arrives, so the ratio is approximate at the window boundary and capped at 1. */
readonly complaint_rate: number;
- /** Emails in the evaluated window: at least the target's last day of sends and at least the configured representative volume (SES-style), whichever covers more. 0 means no recent sending. */
+ /** Emails sent in the last 30 days. */
readonly emails_sent: number;
- /** When this snapshot was computed; one snapshot exists per target per run. */
- readonly evaluated_at: string;
}
/**
@@ -69946,45 +69904,26 @@ export namespace Schemas {
}
/**
- * A workflow-scoped reputation snapshot, annotated with the workflow it belongs to.
+ * Bounce/complaint rates over the last 30 days of workflow email, computed on the fly from app metrics.
*/
- export interface WorkflowEmailReputationSnapshot {
- /** 'workflow' for a single workflow's reputation, 'team' for the project-wide aggregate.
- *
- * * `workflow` - Workflow
- * * `team` - Team */
- readonly scope: EmailReputationScopeEnum;
- /** 'insufficient_data' (too few sends in the window to judge), 'healthy', 'warning' (over a warning threshold), or 'critical' (over a critical threshold).
- *
- * * `insufficient_data` - Insufficient Data
- * * `healthy` - Healthy
- * * `warning` - Warning
- * * `critical` - Critical */
- readonly state: EmailReputationStateEnum;
- /** Hard (permanent) bounces / emails sent over the evaluated volume (0-1), matching AWS's account bounce rate — transient bounces are excluded. */
+ export interface WorkflowEmailSendingRates {
+ /** Hard (permanent) bounces / emails sent over the last 30 days (0-1), matching how AWS counts its bounce rate — transient bounces (greylisting, mailbox full) are excluded. Bounces are counted when the feedback arrives, so the ratio is approximate at the window boundary and capped at 1. */
readonly bounce_rate: number;
- /** Spam complaints / emails sent over the evaluated volume (0-1). */
+ /** Spam complaints / emails sent over the last 30 days (0-1). Complaints are counted when the feedback arrives, so the ratio is approximate at the window boundary and capped at 1. */
readonly complaint_rate: number;
- /** Emails in the evaluated window: at least the target's last day of sends and at least the configured representative volume (SES-style), whichever covers more. 0 means no recent sending. */
+ /** Emails sent in the last 30 days. */
readonly emails_sent: number;
- /** When this snapshot was computed; one snapshot exists per target per run. */
- readonly evaluated_at: string;
- /** The workflow this snapshot is for. */
+ /** The workflow these rates are for. */
readonly hog_flow_id: string;
- /**
- * Display name of the workflow.
- * @nullable
- */
- readonly hog_flow_name: string | null;
- /** This workflow's snapshots from the last 7 days (oldest first, one per daily evaluation run), including the latest. */
- readonly history: readonly EmailReputationSnapshot[];
+ /** Display name of the workflow; empty for unnamed workflows. */
+ readonly hog_flow_name: string;
}
export interface TeamEmailReputationResponse {
- /** Latest project-wide email reputation snapshot across all workflows; null until first evaluated. */
- readonly reputation: EmailReputationSnapshot | null;
- /** Latest snapshot per workflow, worst state and highest rates first, capped at the worst 50 workflows. */
- readonly workflows: readonly WorkflowEmailReputationSnapshot[];
+ /** Project-wide rates across all workflow email in the last 30 days (including sends from since-deleted workflows); null when nothing was sent. */
+ readonly reputation: EmailSendingRates | null;
+ /** Rates per workflow, worst first (complaint rate, then bounce rate), capped at the worst 50. */
+ readonly workflows: readonly WorkflowEmailSendingRates[];
/** True while workflow email sending is suspended for this project to protect deliverability. */
readonly email_sending_suspended: boolean;
/**