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): move teams between email sending tiers on their own record (#89924)

Meikel Ratz86eee9800ff7
diff --git a/posthog/admin/admins/team_admin.py b/posthog/admin/admins/team_admin.py
index a35fef73f474..7414131cb65f 100644
--- a/posthog/admin/admins/team_admin.py
+++ b/posthog/admin/admins/team_admin.py
@@ -16,7 +16,7 @@ from django.core.exceptions import PermissionDenied
from django.core.files.uploadedfile import UploadedFile
from django.db import IntegrityError, transaction
from django.forms import ModelForm, ValidationError
-from django.http import HttpResponse, HttpResponseNotAllowed, JsonResponse
+from django.http import HttpRequest, HttpResponse, HttpResponseNotAllowed, JsonResponse
from django.shortcuts import redirect, render
from django.template.loader import render_to_string
from django.urls import NoReverseMatch, path, reverse
@@ -69,6 +69,12 @@ from products.notifications.backend.facade.api import (
create_notification,
)
from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig
+from products.workflows.backend.services.email_sending_tier import recompute_email_sending_tier_for_team
+from products.workflows.backend.utils.email_sending_tiers import (
+ MIN_EMAIL_SENDING_TIER,
+ get_email_sending_tier_limits,
+ max_email_sending_tier,
+)
logger = get_logger()
@@ -180,6 +186,8 @@ class TeamAdmin(admin.ModelAdmin):
"group_type_mappings_display",
"email_sending_suspension_state",
"email_sending_suspension_actions",
+ "email_sending_tier_state",
+ "email_sending_tier_actions",
]
exclude = DEPRECATED_ATTRS
@@ -336,12 +344,16 @@ class TeamAdmin(admin.ModelAdmin):
"fields": [
"email_sending_suspension_state",
"email_sending_suspension_actions",
+ "email_sending_tier_state",
+ "email_sending_tier_actions",
],
"description": mark_safe(
"Kill switch for all workflow email from this team, used when its sender reputation "
"(hard bounce / spam complaint rates) endangers shared SES deliverability. Suspending "
"notifies the team by email and in-app; the CDP email worker picks the flag up within "
- "a few minutes."
+ "a few minutes.<br><br>The trust tier below sets how fast this team may send. Teams "
+ "earn tiers automatically by sending cleanly over time; pinning holds a team at a tier "
+ "and stops both automatic promotion and automatic demotion."
),
},
),
@@ -788,7 +800,22 @@ class TeamAdmin(admin.ModelAdmin):
suspended_at = timezone.now()
config.email_sending_suspended_at = suspended_at
config.email_sending_suspension_reason = reason
- config.save(update_fields=["email_sending_suspended_at", "email_sending_suspension_reason"])
+ # Drop the trust tier now, in the same locked transaction, rather than at the next
+ # daily sweep: a suspension is the strongest signal there is, and the tier sets how
+ # fast the team may send once reinstated. A suspension always maps to the lowest
+ # tier, and that mapping needs no metrics, so write it here instead of through the
+ # recompute. This does not depend on ClickHouse and it also covers pinned teams,
+ # which the periodic sweep skips.
+ config.email_sending_tier = MIN_EMAIL_SENDING_TIER
+ config.email_sending_tier_updated_at = suspended_at
+ config.save(
+ update_fields=[
+ "email_sending_suspended_at",
+ "email_sending_suspension_reason",
+ "email_sending_tier",
+ "email_sending_tier_updated_at",
+ ]
+ )
if already_suspended_at is not None:
self.message_user(
@@ -916,6 +943,173 @@ class TeamAdmin(admin.ModelAdmin):
)
)
+ @admin.display(description="Email sending tier")
+ def email_sending_tier_state(self, team: Team) -> str:
+ if not team.pk:
+ return "-"
+ config = TeamWorkflowsConfig.objects.filter(team_id=team.pk).first()
+ tier = config.email_sending_tier if config else 0
+ limits = get_email_sending_tier_limits(tier)
+ updated_at = config.email_sending_tier_updated_at if config else None
+ allowlist_note = ""
+ if team.pk in settings.HOGFLOW_BATCH_TRIGGER_ELEVATED_TEAM_IDS:
+ # A saved tier changes nothing while the team sits on the legacy allowlist, which the
+ # limit resolution checks first. Say so here rather than letting a staff tier write
+ # look effective when it is not.
+ allowlist_note = (
+ "<br><strong>Note:</strong> this team is on the legacy elevated allowlist "
+ "(HOGFLOW_BATCH_TRIGGER_ELEVATED_TEAM_IDS), which overrides the tier until the "
+ "team is removed from it."
+ )
+ return format_html(
+ "<strong>Tier {}</strong> of {} — {} emails/hour, {} emails/day, "
+ "{} max batch audience<br>Set at: {}<br>Pinned: {}<br>Rollout mode: <code>{}</code>{}",
+ tier,
+ max_email_sending_tier(),
+ f"{limits.per_hour:,}",
+ f"{limits.per_day:,}",
+ f"{limits.max_batch_audience:,}",
+ updated_at.isoformat() if updated_at else "never (team has not been evaluated yet)",
+ "yes" if config and config.email_sending_tier_pinned else "no",
+ settings.WORKFLOWS_EMAIL_TIER_MODE,
+ mark_safe(allowlist_note), # noqa: S308 - static admin-only string, no user input
+ )
+
+ @admin.display(description="Email sending tier actions")
+ def email_sending_tier_actions(self, team: Team) -> str:
+ if not team.pk:
+ return "-"
+ config = TeamWorkflowsConfig.objects.filter(team_id=team.pk).first()
+ tiers = [
+ {
+ "tier": tier,
+ "per_hour": f"{get_email_sending_tier_limits(tier).per_hour:,}",
+ "per_day": f"{get_email_sending_tier_limits(tier).per_day:,}",
+ "selected": tier == (config.email_sending_tier if config else 0),
+ }
+ for tier in range(max_email_sending_tier() + 1)
+ ]
+ # nosemgrep: python.django.security.audit.avoid-mark-safe.avoid-mark-safe (admin-only, renders trusted template)
+ return mark_safe(
+ render_to_string(
+ "admin/posthog/team/email_sending_tier_actions.html",
+ {
+ "tiers": tiers,
+ "pinned": bool(config and config.email_sending_tier_pinned),
+ "set_tier_url": reverse("admin:posthog_team_set_email_sending_tier", args=[team.pk]),
+ "recompute_url": reverse("admin:posthog_team_recompute_email_sending_tier", args=[team.pk]),
+ },
+ request=getattr(self, "_current_request", None),
+ )
+ )
+
+ def set_email_sending_tier_view(self, request: HttpRequest, object_id: str) -> HttpResponse:
+ if request.method != "POST":
+ return HttpResponseNotAllowed(["POST"])
+
+ team = Team.objects.get(pk=object_id)
+ if not self.has_change_permission(request, team):
+ raise PermissionDenied
+
+ team_url = reverse("admin:posthog_team_change", args=[object_id])
+ top_tier = max_email_sending_tier()
+ try:
+ tier = int(request.POST.get("tier", ""))
+ except ValueError:
+ messages.error(request, "Tier must be a whole number.")
+ return redirect(team_url)
+ if tier < 0 or tier > top_tier:
+ messages.error(request, f"Tier must be between 0 and {top_tier}.")
+ return redirect(team_url)
+ pinned = request.POST.get("pinned") == "on"
+
+ get_or_create_team_extension(team, TeamWorkflowsConfig)
+ with transaction.atomic():
+ config = TeamWorkflowsConfig.objects.select_for_update().get(team_id=team.pk)
+ previous_tier = config.email_sending_tier
+ config.email_sending_tier = tier
+ config.email_sending_tier_pinned = pinned
+ if tier != previous_tier:
+ # Only a real tier change restarts the dwell clock. Toggling the pin alone must not
+ # push the next earned promotion out by the full dwell.
+ config.email_sending_tier_updated_at = timezone.now()
+ config.save(
+ update_fields=[
+ "email_sending_tier",
+ "email_sending_tier_pinned",
+ "email_sending_tier_updated_at",
+ ]
+ )
+
+ logger.info(
+ "admin_set_email_sending_tier",
+ team_id=team.id,
+ previous_tier=previous_tier,
+ new_tier=tier,
+ pinned=pinned,
+ # The admin guarantees an authenticated staff user, but the typed request carries
+ # User | AnonymousUser.
+ triggered_by=getattr(request.user, "email", ""),
+ )
+ self.message_user(
+ request,
+ f"Set team '{team.name}' to email sending tier {tier}"
+ f"{' and pinned it there' if pinned else ' (unpinned, so it can move automatically)'}.",
+ level=messages.SUCCESS,
+ )
+ return redirect(team_url)
+
+ def recompute_email_sending_tier_view(self, request: HttpRequest, object_id: str) -> HttpResponse:
+ if request.method != "POST":
+ return HttpResponseNotAllowed(["POST"])
+
+ team = Team.objects.get(pk=object_id)
+ if not self.has_change_permission(request, team):
+ raise PermissionDenied
+
+ team_url = reverse("admin:posthog_team_change", args=[object_id])
+ # A team that only sent through the API may have no config row yet, and the sweep skips a
+ # rowless team. Create the row first so the recompute can move it off tier 0, matching the
+ # suspend and set-tier actions.
+ get_or_create_team_extension(team, TeamWorkflowsConfig)
+ try:
+ decision = recompute_email_sending_tier_for_team(team.id)
+ except Exception:
+ logger.exception("admin_recompute_email_sending_tier_failed", team_id=team.id)
+ self.message_user(request, "Could not recompute the tier. Check the logs.", level=messages.ERROR)
+ return redirect(team_url)
+
+ if decision is None:
+ self.message_user(
+ request,
+ f"Team '{team.name}' was not evaluated: it is pinned, or its config changed while recomputing.",
+ level=messages.INFO,
+ )
+ elif not decision.changed:
+ hold_reasons = {
+ "too_soon": "it has not held its current tier for the required number of days yet",
+ "tier_not_used_enough": "it has not used enough of its current tier's daily allowance "
+ "on enough separate days since the tier was set",
+ "demotion_cooldown": "a recent demotion's cooldown is still active",
+ "rates_recovering": "its complaint or bounce rate over the promotion window is not clean yet",
+ "ses_reputation_not_clean": "AWS currently flags its SES tenant reputation",
+ "already_top_tier": "it is already at the top tier",
+ }
+ explanation = hold_reasons.get(decision.reason, f"decision reason: {decision.reason}")
+ self.message_user(
+ request,
+ f"Team '{team.name}' keeps tier {decision.previous_tier}: {explanation}.",
+ level=messages.INFO,
+ )
+ else:
+ self.message_user(
+ request,
+ f"Team '{team.name}' moved from tier {decision.previous_tier} to tier {decision.new_tier} "
+ f"({decision.reason}).",
+ level=messages.SUCCESS,
+ )
+ return redirect(team_url)
+
def add_ai_gateway_credit_view(self, request, object_id):
team = Team.objects.get(pk=object_id)
if not self.has_change_permission(request, team):
@@ -1229,6 +1423,16 @@ class TeamAdmin(admin.ModelAdmin):
self.admin_site.admin_view(self.unsuspend_email_sending_view),
name="posthog_team_unsuspend_email_sending",
),
+ path(
+ "<path:object_id>/set-email-sending-tier/",
+ self.admin_site.admin_view(self.set_email_sending_tier_view),
+ name="posthog_team_set_email_sending_tier",
+ ),
+ path(
+ "<path:object_id>/recompute-email-sending-tier/",
+ self.admin_site.admin_view(self.recompute_email_sending_tier_view),
+ name="posthog_team_recompute_email_sending_tier",
+ ),
]
return custom_urls + urls
diff --git a/posthog/admin/inlines/team_inline.py b/posthog/admin/inlines/team_inline.py
index 4bc16b7354ba..de7f1af3fe9c 100644
--- a/posthog/admin/inlines/team_inline.py
+++ b/posthog/admin/inlines/team_inline.py
@@ -57,6 +57,8 @@ class TeamInline(TabularInlinePaginated):
"group_type_mappings_display",
"email_sending_suspension_state",
"email_sending_suspension_actions",
+ "email_sending_tier_state",
+ "email_sending_tier_actions",
)
] + ["displayed_name"]
diff --git a/posthog/admin/test_team_admin.py b/posthog/admin/test_team_admin.py
index 6002c6052293..a6dee7a8d7c2 100644
--- a/posthog/admin/test_team_admin.py
+++ b/posthog/admin/test_team_admin.py
@@ -25,11 +25,13 @@ from posthog.llm.gateway_internal_client import (
)
from posthog.models import Organization
from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.team.team import Team
from posthog.personhog_client.fake_client import FakePersonHogClient
from posthog.personhog_client.proto import GetGroupTypeMappingsByProjectIdRequest
from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig
+from products.workflows.backend.services.email_sending_tier import TierDecision
def _attach_messages(request) -> None:
@@ -677,6 +679,70 @@ class TestTeamAdminEmailSendingSuspension(BaseTest):
assert self.mock_suspend_email.delay.call_args.kwargs["reason"] == "Hard bounce rate above 5%"
assert self.mock_notification.call_count == 1
+ def test_suspend_drops_the_tier_to_zero_even_when_pinned(self) -> None:
+ config = get_or_create_team_extension(
+ self.team, TeamWorkflowsConfig, defaults={"email_sending_tier": 3, "email_sending_tier_pinned": True}
+ )
+
+ response = self.admin.suspend_email_sending_view(self._post({"reason": "spam complaints"}), str(self.team.pk))
+ assert response.status_code == 302
+
+ config.refresh_from_db()
+ assert config.email_sending_suspended_at is not None
+ assert config.email_sending_tier == 0
+ assert config.email_sending_tier_updated_at is not None
+
+ def test_tier_actions_render_without_a_nested_form(self) -> None:
+ # The field renders inside the admin's team change form. A nested <form> would break the page,
+ # so the actions must submit the surrounding form through formaction instead.
+ html = self.admin.email_sending_tier_actions(self.team)
+ assert "<form" not in html
+ assert html.count('formmethod="post"') == 2
+ assert "Save tier" in html
+ assert "Recompute now" in html
+
+ def test_tier_actions_use_a_nonce_script_not_inline_handlers(self) -> None:
+ # Admin pages serve a CSP with no unsafe-inline/unsafe-hashes on script-src, so inline
+ # onclick/onsubmit attributes are dropped. The recompute confirm must run from a nonce'd
+ # script, which needs the request in the render context.
+ request = self.factory.get(f"/admin/posthog/team/{self.team.pk}/change/")
+ request.user = self.user
+ request.csp_nonce = "test-nonce-value" # type: ignore[attr-defined] # ty: ignore[invalid-assignment]
+ _attach_messages(request)
+ self.admin._current_request = request
+
+ html = self.admin.email_sending_tier_actions(self.team)
+
+ assert "onclick=" not in html
+ assert "onsubmit=" not in html
+ assert 'nonce="test-nonce-value"' in html
+
+ def test_recompute_message_names_the_hold_reason(self) -> None:
+ # A held recompute used to report a canned guess ("pinned or does not meet the promotion
+ # bar"), which misled staff when the real reason was the dwell or a cooldown.
+ request = self._post()
+ with patch(
+ "posthog.admin.admins.team_admin.recompute_email_sending_tier_for_team",
+ return_value=TierDecision(team_id=self.team.id, previous_tier=4, new_tier=4, reason="too_soon"),
+ ):
+ response = self.admin.recompute_email_sending_tier_view(request, str(self.team.pk))
+ assert response.status_code == 302
+ rendered = [str(message) for message in request._messages]
+ assert any("keeps tier 4" in message and "has not held its current tier" in message for message in rendered)
+
+ def test_recompute_creates_a_missing_workflows_config(self) -> None:
+ # A team that predates the extension signal can have no config row, and the sweep skips a
+ # rowless team, so the recompute action must create the row before it runs.
+ TeamWorkflowsConfig.objects.filter(team_id=self.team.pk).delete()
+ assert self._config() is None
+ with patch(
+ "posthog.admin.admins.team_admin.recompute_email_sending_tier_for_team", return_value=None
+ ) as mock_recompute:
+ response = self.admin.recompute_email_sending_tier_view(self._post(), str(self.team.pk))
+ assert response.status_code == 302
+ mock_recompute.assert_called_once_with(self.team.id)
+ assert self._config() is not None
+
def test_suspend_is_idempotent(self) -> None:
self.admin.suspend_email_sending_view(self._post({"reason": "first"}), str(self.team.pk))
response = self.admin.suspend_email_sending_view(self._post({"reason": "second"}), str(self.team.pk))
diff --git a/posthog/api/app_metrics2.py b/posthog/api/app_metrics2.py
index c893ef0a4244..df9f4f85281c 100644
--- a/posthog/api/app_metrics2.py
+++ b/posthog/api/app_metrics2.py
@@ -10,6 +10,7 @@ from rest_framework.response import Response
from rest_framework_dataclasses.serializers import DataclassSerializer
from posthog.api.utils import action
+from posthog.clickhouse.client.connection import Workload
from posthog.clickhouse.client.execute import sync_execute
from posthog.clickhouse.query_tagging import Feature, tag_queries
from posthog.models.team.team import Team
@@ -291,6 +292,142 @@ def fetch_app_metric_totals_by_source(
return totals
+def fetch_app_metric_totals_by_team_and_source(
+ app_source: str,
+ name: list[str],
+ after: Optional[datetime] = None,
+ before: Optional[datetime] = None,
+ team_ids: Optional[list[int]] = None,
+ min_totals: Optional[dict[str, int]] = None,
+ any_min_totals: Optional[dict[str, int]] = None,
+) -> dict[int, dict[str, dict[str, int]]]:
+ """Per-`app_source_id` metric totals across many teams in one grouped query.
+
+ Unlike `fetch_app_metric_totals_by_source` (one team), this groups by `team_id` as
+ well, so a background sweep gets the whole fleet from a single query instead of a
+ query per team. Returns `{team_id: {app_source_id: {metric_name: count}}}`.
+
+ Each requested metric name becomes its own `sumIf` column, which is what lets the
+ thresholds be pushed down: `min_totals` requires every named metric to reach its
+ value and `any_min_totals` requires at least one to, both evaluated in `HAVING`. Use
+ a pushdown, a `team_ids` list, or both. Unfiltered, the result set grows with the
+ fleet, and a sweep that has to stream every object's counts back to Python stops
+ being affordable.
+ """
+ if not name:
+ raise ValueError("At least one metric name is required")
+
+ # Convert to UTC before formatting — the naive string is read as UTC by toDateTime64, so a
+ # team-timezone-aware bound would otherwise shift the window by the team's offset.
+ clickhouse_kwargs: dict[str, Any] = {
+ "app_source": app_source,
+ "after": after.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S") if after else None,
+ "before": before.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S") if before else None,
+ "name": name,
+ "team_ids": team_ids,
+ }
+
+ # Alias per metric rather than the metric name itself: metric names are caller-supplied and
+ # would have to be interpolated raw into the SQL to be usable as identifiers.
+ aliases = {metric_name: f"metric_{index}" for index, metric_name in enumerate(name)}
+ for metric_name, alias in aliases.items():
+ clickhouse_kwargs[f"{alias}_name"] = metric_name
+
+ selects = ", ".join(f"sumIf(count, metric_name = %({alias}_name)s) AS {alias}" for alias in aliases.values())
+
+ having_clauses: list[str] = []
+ for metric_name, minimum in (min_totals or {}).items():
+ alias = aliases[metric_name]
+ clickhouse_kwargs[f"{alias}_min"] = minimum
+ having_clauses.append(f"{alias} >= %({alias}_min)s")
+ any_clauses: list[str] = []
+ for metric_name, minimum in (any_min_totals or {}).items():
+ alias = aliases[metric_name]
+ clickhouse_kwargs[f"{alias}_any_min"] = minimum
+ any_clauses.append(f"{alias} >= %({alias}_any_min)s")
+ if any_clauses:
+ having_clauses.append(f"({' OR '.join(any_clauses)})")
+
+ clickhouse_query = f"""
+ SELECT
+ team_id,
+ app_source_id,
+ {selects}
+ FROM app_metrics2
+ WHERE app_source = %(app_source)s
+ {"AND team_id IN %(team_ids)s" if team_ids else ""}
+ {"AND timestamp >= toDateTime64(%(after)s, 6)" if after else ""}
+ {"AND timestamp <= toDateTime64(%(before)s, 6)" if before else ""}
+ AND metric_name IN %(name)s
+ GROUP BY team_id, app_source_id
+ {f"HAVING {' AND '.join(having_clauses)}" if having_clauses else ""}
+ """
+
+ results = sync_execute(clickhouse_query, clickhouse_kwargs)
+
+ if not isinstance(results, list):
+ raise ValueError("Unexpected results from ClickHouse")
+
+ totals: dict[int, dict[str, dict[str, int]]] = {}
+ for row in results:
+ team_id, app_source_id = row[0], row[1]
+ totals.setdefault(team_id, {})[app_source_id] = dict(zip(name, (int(value) for value in row[2:])))
+ return totals
+
+
+def fetch_app_metric_daily_totals_by_team(
+ app_source: str,
+ name: list[str],
+ after: datetime,
+ before: Optional[datetime] = None,
+ team_ids: Optional[list[int]] = None,
+ workload: Workload = Workload.DEFAULT,
+) -> dict[int, dict[str, dict[str, int]]]:
+ """Daily metric totals per team, keyed `{team_id: {"YYYY-MM-DD": {metric_name: count}}}`.
+
+ Days rather than a single total, because "sent at least X on each of N days" cannot be told
+ apart from one burst of the same size once the window is summed.
+
+ Called without team_ids, the daily tier sweep scans the whole fleet. The result is bounded per
+ team, at most one row per metric name per day, but it grows linearly with the number of sending
+ teams because app_source alone does not prune the app_metrics2 primary key. This is affordable at
+ the current scale and runs on the LONG_RUNNING queue. If the sending fleet grows large, batch by
+ team or aggregate to one row per team here.
+ """
+ clickhouse_kwargs: dict[str, Any] = {
+ "app_source": app_source,
+ "after": after.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S"),
+ "before": before.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S") if before else None,
+ "name": name,
+ "team_ids": team_ids,
+ }
+
+ clickhouse_query = f"""
+ SELECT
+ team_id,
+ toDate(timestamp) as day,
+ metric_name,
+ sum(count) as count
+ FROM app_metrics2
+ WHERE app_source = %(app_source)s
+ {"AND team_id IN %(team_ids)s" if team_ids else ""}
+ AND timestamp >= toDateTime64(%(after)s, 6)
+ {"AND timestamp <= toDateTime64(%(before)s, 6)" if before else ""}
+ AND metric_name IN %(name)s
+ GROUP BY team_id, day, metric_name
+ """
+
+ results = sync_execute(clickhouse_query, clickhouse_kwargs, workload=workload)
+
+ if not isinstance(results, list):
+ raise ValueError("Unexpected results from ClickHouse")
+
+ totals: dict[int, dict[str, dict[str, int]]] = {}
+ for team_id, day, metric_name, count in results:
+ totals.setdefault(team_id, {}).setdefault(day.strftime("%Y-%m-%d"), {})[metric_name] = count
+ return totals
+
+
class AppMetricsMixin(viewsets.GenericViewSet):
app_source: str # Should be set by the inheriting class
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index ed2fb951dc90..947ef977c1de 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -1283,6 +1283,9 @@ WORKFLOWS_EMAIL_TIER_DEMOTION_COOLDOWN_DAYS = int(get_from_env("WORKFLOWS_EMAIL_
# A team above the lowest tier that sends nothing for this long drops one tier per period. Mailbox
# providers keep about 30 days of reputation history, so a long-dormant allowance is unearned and a
# comeback blast from a stale list is exactly what the caps exist to prevent. 0 disables decay.
+# The sweep tests inactivity as zero sends over WORKFLOWS_EMAIL_TIER_RATE_WINDOW_DAYS, not over this
+# value, so keep the two equal. A larger value decays teams that still sent inside the rate window,
+# and a smaller one waits for the rate window to clear before it decays.
WORKFLOWS_EMAIL_TIER_INACTIVITY_DECAY_DAYS = int(get_from_env("WORKFLOWS_EMAIL_TIER_INACTIVITY_DECAY_DAYS", 30))
WORKFLOWS_EMAIL_TIER_MAX_COMPLAINT_RATE = float(get_from_env("WORKFLOWS_EMAIL_TIER_MAX_COMPLAINT_RATE", 0.001))
WORKFLOWS_EMAIL_TIER_MAX_BOUNCE_RATE = float(get_from_env("WORKFLOWS_EMAIL_TIER_MAX_BOUNCE_RATE", 0.02))
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index cb909db75679..201ede0d2a50 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -126,6 +126,7 @@ from products.web_analytics.backend.tasks.heatmap_screenshot import (
reap_stale_prewarm_heatmaps,
report_stuck_heatmap_screenshots,
)
+from products.workflows.backend.tasks.email_sending_tiers import recompute_workflows_email_sending_tiers
from products.workflows.backend.tasks.ses_account_reputation import poll_ses_account_reputation
from products.workflows.backend.tasks.ses_tenant_state import reconcile_ses_tenant_states
@@ -257,6 +258,15 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="ses tenant reputation reconciliation",
)
+ # Workflow email trust tiers - daily at 7:15 AM UTC, after the tenant reconciliation above.
+ # Promotion is intentionally slow (a team must hold a tier for days), so a daily pass is enough.
+ # Demotions do not wait for it: the staff suspension action recomputes the team directly.
+ sender.add_periodic_task(
+ crontab(hour="7", minute="15"),
+ recompute_workflows_email_sending_tiers.s(),
+ name="workflows email sending tier recomputation",
+ )
+
# LLM gateway policy cache sync - hourly at :05 to stagger from team_metadata at :00
sender.add_periodic_task(
crontab(hour="*", minute="5"),
diff --git a/posthog/templates/admin/posthog/team/email_sending_tier_actions.html b/posthog/templates/admin/posthog/team/email_sending_tier_actions.html
new file mode 100644
index 000000000000..e4a21882f289
--- /dev/null
+++ b/posthog/templates/admin/posthog/team/email_sending_tier_actions.html
@@ -0,0 +1,43 @@
+{% comment %}
+Rendered as a readonly field inside the admin's team change form, so the controls sit in that
+outer form (no <form> of their own, which the browser would drop) and submit through formaction.
+Admin pages serve a CSP with no 'unsafe-inline'/'unsafe-hashes' on script-src, which silently
+drops inline onclick/onsubmit attributes, so the recompute confirmation lives in the nonce'd
+<script> block below. Include with request=request so {{ request.csp_nonce }} resolves.
+{% endcomment %}
+<div class="email-sending-tier-widget" style="margin: 10px 0;">
+ <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
+ <label for="email_sending_tier">Tier</label>
+ <select id="email_sending_tier" name="tier">
+ {% for option in tiers %}
+ <option value="{{ option.tier }}" {% if option.selected %}selected{% endif %}>
+ {{ option.tier }} — {{ option.per_hour }}/hour, {{ option.per_day }}/day
+ </option>
+ {% endfor %}
+ </select>
+ <label for="email_sending_tier_pinned">
+ <input type="checkbox" id="email_sending_tier_pinned" name="pinned" {% if pinned %}checked{% endif %} />
+ Pin (stops automatic promotion and demotion)
+ </label>
+ <button type="submit" class="default" formmethod="post" formaction="{{ set_tier_url }}" formnovalidate>Save tier</button>
+ </div>
+ <div style="margin-top: 8px;">
+ <button type="submit" class="button recompute-tier-button" formmethod="post" formaction="{{ recompute_url }}" formnovalidate>
+ Recompute now from sending history</button>
+ </div>
+ <p style="margin-top: 8px; color: #666; font-size: 12px;">
+ Saving a tier writes <code>email_sending_tier</code> on the team's workflows config and stamps
+ <code>email_sending_tier_updated_at</code>, which restarts the clock the promotion bar measures.
+ Recomputing applies the same rules the daily sweep uses and moves the team at most one tier.
+ </p>
+</div>
+<script nonce="{{ request.csp_nonce }}">
+(function () {
+ var widget = document.currentScript.previousElementSibling;
+ widget.querySelector(".recompute-tier-button").addEventListener("click", function (event) {
+ if (!confirm("Recompute the email sending tier for this team from its recent sending history?")) {
+ event.preventDefault();
+ }
+ });
+})();
+</script>
diff --git a/products/workflows/backend/management/commands/backfill_workflows_email_sending_tiers.py b/products/workflows/backend/management/commands/backfill_workflows_email_sending_tiers.py
new file mode 100644
index 000000000000..40433416a3d3
--- /dev/null
+++ b/products/workflows/backend/management/commands/backfill_workflows_email_sending_tiers.py
@@ -0,0 +1,217 @@
+from collections import Counter
+from collections.abc import Iterable
+from datetime import timedelta
+from typing import Any, Optional
+
+from django.core.management.base import BaseCommand
+from django.utils import timezone
+
+import structlog
+
+from posthog.clickhouse.client.connection import Workload
+from posthog.models.team import Team
+from posthog.models.team.extensions import get_or_create_team_extension
+
+from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig
+from products.workflows.backend.services.email_sending_tier import (
+ SesTenantState,
+ TeamSendingHistory,
+ TierDecision,
+ build_sending_histories,
+ decide_tier,
+)
+from products.workflows.backend.utils.email_sending_tiers import (
+ MIN_EMAIL_SENDING_TIER,
+ get_email_sending_tier_limits,
+ max_email_sending_tier,
+)
+
+logger = structlog.get_logger(__name__)
+
+DEFAULT_HISTORY_DAYS = 90
+
+
+class Command(BaseCommand):
+ help = (
+ "Assign every team an initial workflow email sending tier from its recent sending history. "
+ "Uses the same promotion rules as the periodic task, minus the time-at-tier requirement and "
+ "the one-tier-per-run step, so an established high-volume sender lands at the top tier at "
+ "once instead of climbing for weeks. Teams with no sending history stay at tier 0. Prints a "
+ "tier distribution so the tier boundaries can be checked against reality before enforcement "
+ "is switched on. Read-only unless --apply is passed."
+ )
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument(
+ "--days",
+ type=int,
+ default=DEFAULT_HISTORY_DAYS,
+ help=f"How many days of sending history to read. Defaults to {DEFAULT_HISTORY_DAYS}.",
+ )
+ parser.add_argument(
+ "--apply",
+ action="store_true",
+ help="Write the computed tiers. Without this the command only reports what it would do.",
+ )
+ parser.add_argument(
+ "--team-id",
+ type=int,
+ action="append",
+ dest="team_ids",
+ help="Restrict the backfill to this team. Repeatable.",
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ days: int = options["days"]
+ apply_changes: bool = options["apply"]
+ team_ids: Optional[list[int]] = options.get("team_ids")
+
+ after = timezone.now() - timedelta(days=days)
+ # A management command inherits the online workload, but this fleet-wide 90-day scan belongs
+ # on the offline pool, away from customer queries. The daily Celery sweep already runs offline.
+ histories = self._without_deleted_teams(
+ build_sending_histories(after=after, team_ids=team_ids, workload=Workload.OFFLINE)
+ )
+ decisions = self._decide(histories=histories, team_ids=team_ids)
+
+ written = self._apply(decisions) if apply_changes else 0
+
+ self._report(decisions=decisions, histories=histories, days=days, applied=apply_changes, written=written)
+
+ def _without_deleted_teams(self, histories: dict[int, TeamSendingHistory]) -> dict[int, TeamSendingHistory]:
+ # app_metrics2 lives in ClickHouse and is not cleared when a team is deleted from Postgres,
+ # so its history can name teams that no longer exist. Drop them so a defunct team_id does not
+ # inflate the distribution, the denominator, or the written count.
+ existing = set(Team.objects.filter(id__in=list(histories)).values_list("id", flat=True))
+ return {team_id: history for team_id, history in histories.items() if team_id in existing}
+
+ def _decide(self, *, histories: dict[int, TeamSendingHistory], team_ids: Optional[list[int]]) -> list[TierDecision]:
+ configs = TeamWorkflowsConfig.objects.all()
+ if team_ids is not None:
+ configs = configs.filter(team_id__in=team_ids)
+ state_by_team = {
+ row["team_id"]: row
+ for row in configs.values(
+ "team_id",
+ "email_sending_tier",
+ "email_sending_tier_pinned",
+ "email_sending_suspended_at",
+ "ses_tenant_sending_status",
+ "ses_tenant_reputation_impact",
+ )
+ }
+
+ decisions: list[TierDecision] = []
+ for team_id in sorted(set(histories) | set(state_by_team)):
+ state = state_by_team.get(team_id)
+ if state and state["email_sending_tier_pinned"]:
+ continue
+ history = histories.get(team_id)
+ if history is None:
+ if state is None or state["email_sending_suspended_at"] is None:
+ # No sending in the window and no suspension owed, so there is nothing to earn a
+ # tier with. Tier 0 is right for a new team and harmless for a dormant one,
+ # which will not hit a cap anyway.
+ continue
+ # A suspended team must land on tier 0 even with no sends in the window, or the
+ # backfill would leave its elevated allowance in place for reinstatement.
+ history = TeamSendingHistory(
+ team_id=team_id, sent=0, hard_bounced=0, complained=0, auto_paused=False, daily_sends={}
+ )
+ decision = decide_tier(
+ history=history,
+ current_tier=state["email_sending_tier"] if state else MIN_EMAIL_SENDING_TIER,
+ tier_updated_at=None,
+ suspended=state is not None and state["email_sending_suspended_at"] is not None,
+ tenant_state=SesTenantState(
+ sending_status=state["ses_tenant_sending_status"] if state else "",
+ reputation_impact=state["ses_tenant_reputation_impact"] if state else "",
+ ),
+ require_time_at_tier=False,
+ single_step=False,
+ )
+ if decision.changed:
+ decisions.append(decision)
+ return decisions
+
+ def _apply(self, decisions: list[TierDecision]) -> int:
+ teams = {team.id: team for team in Team.objects.filter(id__in=[d.team_id for d in decisions])}
+ now = timezone.now()
+ written = 0
+ for decision in decisions:
+ team = teams.get(decision.team_id)
+ if team is None:
+ continue
+ get_or_create_team_extension(team, TeamWorkflowsConfig)
+ # Compare-and-set against the state the decision was computed from, like the daily
+ # sweep's write: a staff pin, suspension, or manual tier set landing during the fleet
+ # scan must not be overwritten by a stale decision. A no-op here is left for the next
+ # sweep, which recomputes from the new state.
+ updated = TeamWorkflowsConfig.objects.filter(
+ team_id=decision.team_id,
+ email_sending_tier=decision.previous_tier,
+ email_sending_tier_pinned=False,
+ email_sending_suspended_at__isnull=decision.reason != "staff_suspension",
+ ).update(
+ email_sending_tier=decision.new_tier,
+ email_sending_tier_updated_at=now,
+ )
+ if not updated:
+ continue
+ written += 1
+ logger.info(
+ "workflows_email_sending_tier_backfilled",
+ team_id=decision.team_id,
+ previous_tier=decision.previous_tier,
+ new_tier=decision.new_tier,
+ reason=decision.reason,
+ )
+ return written
+
+ def _current_tiers(self, team_ids: Iterable[int]) -> dict[int, int]:
+ return {
+ row["team_id"]: row["email_sending_tier"]
+ for row in TeamWorkflowsConfig.objects.filter(team_id__in=team_ids).values("team_id", "email_sending_tier")
+ }
+
+ def _report(
+ self,
+ *,
+ decisions: list[TierDecision],
+ histories: dict[int, TeamSendingHistory],
+ days: int,
+ applied: bool,
+ written: int,
+ ) -> None:
+ moved_to = {decision.team_id: decision.new_tier for decision in decisions}
+ current_tiers = self._current_tiers(histories.keys())
+ distribution: Counter[int] = Counter()
+ for team_id in histories:
+ # Report the tier the team would actually hold: the new tier if it moved, otherwise its
+ # stored tier, or the default 0 when it has no stored row yet. An unchanged or pinned
+ # team keeps its stored tier, so a re-run must not count it back down to tier 0.
+ effective_tier = moved_to.get(team_id, current_tiers.get(team_id, MIN_EMAIL_SENDING_TIER))
+ distribution[effective_tier] += 1
+
+ sending_teams = len(histories)
+ self.stdout.write(f"Read {days} days of history for {sending_teams} teams that sent workflow email.")
+ self.stdout.write("")
+ self.stdout.write("Tier distribution across those teams:")
+ for tier in range(max_email_sending_tier() + 1):
+ limits = get_email_sending_tier_limits(tier)
+ count = distribution.get(tier, 0)
+ share = (count / sending_teams * 100) if sending_teams else 0.0
+ self.stdout.write(
+ f" tier {tier}: {count:>6} teams ({share:5.1f}%) "
+ f"{limits.per_hour:>9,}/hour {limits.per_day:>10,}/day {limits.max_batch_audience:>10,} batch"
+ )
+ self.stdout.write("")
+
+ dirty = [team_id for team_id, history in histories.items() if not history.rates_are_clean]
+ self.stdout.write(f"Teams with complaint or bounce rates above the threshold: {len(dirty)}")
+ self.stdout.write(f"Teams whose tier would change: {len(decisions)}")
+
+ if applied:
+ self.stdout.write(self.style.SUCCESS(f"Wrote {written} tier changes."))
+ else:
+ self.stdout.write(self.style.WARNING("Nothing written. Re-run with --apply to write these tiers."))
diff --git a/products/workflows/backend/services/email_sending_tier.py b/products/workflows/backend/services/email_sending_tier.py
new file mode 100644
index 000000000000..42b8b7175298
--- /dev/null
+++ b/products/workflows/backend/services/email_sending_tier.py
@@ -0,0 +1,499 @@
+from datetime import datetime, timedelta
+from typing import Any, Optional
+
+from django.conf import settings
+from django.utils import timezone
+
+import structlog
+
+from posthog.api.app_metrics2 import fetch_app_metric_daily_totals_by_team
+from posthog.clickhouse.client.connection import Workload
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.dataclasses import frozen
+
+from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig
+from products.workflows.backend.utils.email_sending_tiers import (
+ MIN_EMAIL_SENDING_TIER,
+ get_email_sending_tier_limits,
+ max_email_sending_tier,
+ min_days_at_tier,
+)
+
+logger = structlog.get_logger(__name__)
+
+APP_SOURCE = "hog_flow"
+
+SENT_METRIC = "email_sent"
+HARD_BOUNCE_METRIC = "email_bounced_hard"
+# SES complaint events are recorded under this name (see the SES webhook handler in the email
+# worker), so a complaint rate reads `email_blocked`, not a metric called "complaint".
+COMPLAINT_METRIC = "email_blocked"
+
+# Decision reasons that count as a rate-driven demotion and therefore arm the demotion cooldown.
+RATE_DEMOTION_REASONS = frozenset({"rates_above_threshold", "workflow_auto_paused", "ses_reputation_high"})
+
+
+@frozen
+class TeamSendingHistory:
+ """What a team's workflow email metrics say over the trailing rate window."""
+
+ team_id: int
+ sent: int
+ hard_bounced: int
+ complained: int
+ auto_paused: bool
+ # Sends per calendar day, keyed "YYYY-MM-DD". Used to tell steady use of a tier apart from one
+ # burst of the same total.
+ daily_sends: dict[str, int]
+
+ @property
+ def complaint_rate(self) -> float:
+ return min(1.0, self.complained / self.sent) if self.sent else 0.0
+
+ @property
+ def hard_bounce_rate(self) -> float:
+ return min(1.0, self.hard_bounced / self.sent) if self.sent else 0.0
+
+ @property
+ def rates_are_clean(self) -> bool:
+ if self.sent == 0:
+ # Nothing sent means no rate to measure, and callers pair this with the volume bar,
+ # which a team that sent nothing cannot clear. Complaints still count through the
+ # absolute backstop: feedback lags sends by hours or days, so a window can hold the
+ # complaints from sends that happened just before it opened.
+ return self.complained < settings.WORKFLOWS_EMAIL_TIER_COMPLAINT_COUNT_BACKSTOP
+ # A rate needs a denominator to mean anything: at the 0.1% complaint threshold, one
+ # complaint per 1,000 sends is exactly the line, so on a smaller window a single complaint
+ # would read as dirty. Below the floor, complaints only count through the absolute
+ # backstop, and the bounce rate does not count at all.
+ complaints_are_dirty = self.complaint_rate > settings.WORKFLOWS_EMAIL_TIER_MAX_COMPLAINT_RATE and (
+ self.sent >= settings.WORKFLOWS_EMAIL_TIER_COMPLAINT_RATE_MIN_SENDS
+ or self.complained >= settings.WORKFLOWS_EMAIL_TIER_COMPLAINT_COUNT_BACKSTOP
+ )
+ bounces_are_dirty = (
+ self.hard_bounce_rate > settings.WORKFLOWS_EMAIL_TIER_MAX_BOUNCE_RATE
+ and self.sent >= settings.WORKFLOWS_EMAIL_TIER_BOUNCE_RATE_MIN_SENDS
+ )
+ return not (complaints_are_dirty or bounces_are_dirty)
+
+
+@frozen
+class TierDecision:
+ team_id: int
+ previous_tier: int
+ new_tier: int
+ reason: str
+
+ @property
+ def changed(self) -> bool:
+ return self.previous_tier != self.new_tier
+
+
+@frozen
+class SesTenantState:
+ """AWS's own view of the team's SES tenant, synced by the tenant-state tasks.
+
+ This complements our internal rates rather than duplicating them: AWS measures the complaint
+ rate against mail sent to FBL-providing domains only, while our rate divides by all sends, so
+ ours reads systematically lower for teams whose audience skews toward non-FBL domains. A team
+ can look clean to us while AWS is about to pause its tenant.
+ """
+
+ sending_status: str = ""
+ reputation_impact: str = ""
+
+ @property
+ def is_paused(self) -> bool:
+ # SendingStatusAggregate folds AWS-managed and customer-managed pauses; REINSTATED is a
+ # re-enabled grace state and must not read as paused.
+ return self.sending_status.strip().upper() == "DISABLED"
+
+ @property
+ def impact(self) -> str:
+ # Empty string means never synced, which reads the same as NONE.
+ return self.reputation_impact.strip().upper()
+
+
+def highest_qualifying_tier(daily_sends: dict[str, int], *, since: Optional[datetime] = None) -> int:
+ """
+ Highest tier the team's send volume has earned.
+
+ Clearing a tier's use bar earns the tier above it, so the walk stops at the first tier whose bar
+ the team did not meet on enough separate days. It never returns more than the top tier.
+ """
+ min_days = settings.WORKFLOWS_EMAIL_TIER_MIN_ACTIVE_DAYS
+ ratio = settings.WORKFLOWS_EMAIL_TIER_MIN_DAILY_USE_RATIO
+ # Exclude the whole anchor day, not only the change moment. Metrics are day-grained, so the
+ # anchor day holds sends made both before and after the tier change. Keeping it would count
+ # pre-change volume as evidence for the new tier, which lets a demoted team re-promote on one
+ # real day at the new tier plus the day it was demoted on.
+ since_key = since.strftime("%Y-%m-%d") if since else None
+ counted = {day: sent for day, sent in daily_sends.items() if since_key is None or day > since_key}
+
+ tier = MIN_EMAIL_SENDING_TIER
+ top = max_email_sending_tier()
+ while tier < top:
+ bar = get_email_sending_tier_limits(tier).per_day * ratio
+ days_at_bar = sum(1 for sent in counted.values() if sent >= bar)
+ if days_at_bar < min_days:
+ break
+ tier += 1
+ return tier
+
+
+def decide_tier(
+ *,
+ history: TeamSendingHistory,
+ current_tier: int,
+ tier_updated_at: Optional[datetime],
+ suspended: bool,
+ recent_history: Optional[TeamSendingHistory] = None,
+ tenant_state: Optional[SesTenantState] = None,
+ last_rate_demotion_at: Optional[datetime] = None,
+ now: Optional[datetime] = None,
+ require_time_at_tier: bool = True,
+ single_step: bool = True,
+) -> TierDecision:
+ """
+ The tier a team should hold, given its sending history.
+
+ `history` covers the promotion window and `recent_history` the shorter demotion window, so an
+ incident demotes while it is fresh but stops holding the team down once it ages out of the
+ short window, while promotion still requires the full window to be clean. Callers with a
+ single window (the backfill) omit `recent_history`.
+
+ `tenant_state` carries AWS's per-tenant verdict, which sees the FBL-correct complaint rate
+ our internal metrics dilute (see SesTenantState). A paused tenant drops to the bottom, a
+ HIGH reputation impact demotes, and any non-clean impact blocks promotion.
+
+ `require_time_at_tier` and `single_step` are both off for the backfill, which reads a long
+ history at once and must land an established sender on its real tier immediately instead of
+ walking it up one step per run.
+ """
+ now = now or timezone.now()
+ top = max_email_sending_tier()
+ recent = recent_history or history
+ tenant = tenant_state or SesTenantState()
+
+ if suspended:
+ return TierDecision(
+ team_id=history.team_id,
+ previous_tier=current_tier,
+ new_tier=MIN_EMAIL_SENDING_TIER,
+ reason="staff_suspension",
+ )
+
+ if tenant.is_paused:
+ # AWS stopped this tenant's sends over its reputation, which is a stronger verdict than
+ # anything our internal rates can produce. The tier sets how fast the team may send once
+ # the tenant is re-enabled, so it must restart from the bottom.
+ return TierDecision(
+ team_id=history.team_id,
+ previous_tier=current_tier,
+ new_tier=MIN_EMAIL_SENDING_TIER,
+ reason="ses_tenant_paused",
+ )
+
+ if recent.auto_paused or not recent.rates_are_clean or tenant.impact == "HIGH":
+ # One incident stays inside the demotion window for days and the sweep runs daily, so
+ # without a cooldown the same incident would demote the team again on every run and
+ # cascade it to the bottom. The anchor is the last rate demotion, not the last tier write:
+ # a promotion or staff change must not shield a team from its first real demotion. With the
+ # cooldown at least as long as the demotion window, the evidence behind the last demotion
+ # has aged out by the time demotions resume, so a second step needs new evidence.
+ cooldown = timedelta(days=settings.WORKFLOWS_EMAIL_TIER_DEMOTION_COOLDOWN_DAYS)
+ if last_rate_demotion_at is not None and now - last_rate_demotion_at < cooldown:
+ return TierDecision(
+ team_id=history.team_id,
+ previous_tier=current_tier,
+ new_tier=current_tier,
+ reason="demotion_cooldown",
+ )
+ if recent.auto_paused:
+ demotion_reason = "workflow_auto_paused"
+ elif not recent.rates_are_clean:
+ demotion_reason = "rates_above_threshold"
+ else:
+ demotion_reason = "ses_reputation_high"
+ return TierDecision(
+ team_id=history.team_id,
+ previous_tier=current_tier,
+ new_tier=max(MIN_EMAIL_SENDING_TIER, current_tier - 1),
+ reason=demotion_reason,
+ )
+
+ decay_days = settings.WORKFLOWS_EMAIL_TIER_INACTIVITY_DECAY_DAYS
+ if (
+ decay_days > 0
+ and current_tier > MIN_EMAIL_SENDING_TIER
+ and history.sent == 0
+ and tier_updated_at is not None
+ and now - tier_updated_at >= timedelta(days=decay_days)
+ ):
+ # Mailbox providers keep roughly 30 days of reputation history, so a long-dormant
+ # allowance is no longer earned, and a comeback blast from a stale list is exactly what
+ # the caps exist to prevent. Each decay step resets tier_updated_at, so a dormant team
+ # steps down one tier per decay period rather than dropping at once.
+ return TierDecision(
+ team_id=history.team_id,
+ previous_tier=current_tier,
+ new_tier=current_tier - 1,
+ reason="inactive",
+ )
+
+ if current_tier >= top:
+ return TierDecision(
+ team_id=history.team_id, previous_tier=current_tier, new_tier=current_tier, reason="already_top_tier"
+ )
+
+ if not history.rates_are_clean:
+ # The recent window recovered but the promotion window has not. Hold rather than promote,
+ # so a team does not climb while its long-run rates are still over the threshold.
+ return TierDecision(
+ team_id=history.team_id, previous_tier=current_tier, new_tier=current_tier, reason="rates_recovering"
+ )
+
+ if tenant.impact not in ("", "NONE"):
+ # AWS sees a reputation problem our diluted internal rates may not. LOW is not worth a
+ # demotion, but a team must not climb while AWS flags its tenant.
+ return TierDecision(
+ team_id=history.team_id,
+ previous_tier=current_tier,
+ new_tier=current_tier,
+ reason="ses_reputation_not_clean",
+ )
+
+ if require_time_at_tier:
+ anchor = tier_updated_at
+ if anchor is not None and now - anchor < timedelta(days=min_days_at_tier(current_tier)):
+ return TierDecision(
+ team_id=history.team_id, previous_tier=current_tier, new_tier=current_tier, reason="too_soon"
+ )
+
+ # Only days spent at the current tier count toward its use bar, so a demotion does not carry the
+ # previous tier's volume forward as evidence. The backfill has no tier anchor, but its long
+ # history must still qualify on recent days: without the cutoff, two high-volume days months ago
+ # would grant a dormant team a tier the inactivity decay exists to remove, and the write would
+ # restart the decay clock on top.
+ if require_time_at_tier:
+ since = tier_updated_at
+ else:
+ decay_days = settings.WORKFLOWS_EMAIL_TIER_INACTIVITY_DECAY_DAYS
+ since = now - timedelta(days=decay_days) if decay_days > 0 else None
+ earned = highest_qualifying_tier(history.daily_sends, since=since)
+ if earned <= current_tier:
+ return TierDecision(
+ team_id=history.team_id, previous_tier=current_tier, new_tier=current_tier, reason="tier_not_used_enough"
+ )
+
+ new_tier = min(current_tier + 1, top) if single_step else min(earned, top)
+ return TierDecision(team_id=history.team_id, previous_tier=current_tier, new_tier=new_tier, reason="clean_and_used")
+
+
+def build_sending_histories(
+ *,
+ after: datetime,
+ before: Optional[datetime] = None,
+ team_ids: Optional[list[int]] = None,
+ workload: Workload = Workload.DEFAULT,
+) -> dict[int, TeamSendingHistory]:
+ """Read every team's workflow email metrics for the window in one grouped query."""
+ daily_by_team = _fetch_daily_metrics(after=after, before=before, team_ids=team_ids, workload=workload)
+ return {team_id: _history_from_daily(team_id, days) for team_id, days in daily_by_team.items()}
+
+
+@frozen
+class SendingHistoryWindows:
+ """Per-team sending histories over the promotion window and the shorter demotion window."""
+
+ window: dict[int, TeamSendingHistory]
+ recent: dict[int, TeamSendingHistory]
+
+
+def build_sending_history_windows(
+ *,
+ after: datetime,
+ recent_after: datetime,
+ before: Optional[datetime] = None,
+ team_ids: Optional[list[int]] = None,
+) -> SendingHistoryWindows:
+ """The full promotion window and the shorter demotion window, from one query.
+
+ The recent window is cut on calendar days (UTC), matching the day granularity the metrics are
+ fetched at, so its edge can be up to a day coarser than `recent_after`.
+ """
+ daily_by_team = _fetch_daily_metrics(after=after, before=before, team_ids=team_ids)
+ recent_key = recent_after.strftime("%Y-%m-%d")
+ return SendingHistoryWindows(
+ window={team_id: _history_from_daily(team_id, days) for team_id, days in daily_by_team.items()},
+ recent={
+ team_id: _history_from_daily(team_id, {day: counts for day, counts in days.items() if day >= recent_key})
+ for team_id, days in daily_by_team.items()
+ },
+ )
+
+
+def _fetch_daily_metrics(
+ *,
+ after: datetime,
+ before: Optional[datetime],
+ team_ids: Optional[list[int]],
+ workload: Workload = Workload.DEFAULT,
+) -> dict[int, dict[str, dict[str, int]]]:
+ auto_pause_metrics = [name for name in settings.WORKFLOWS_EMAIL_TIER_AUTO_PAUSE_METRIC_NAMES if name]
+ metric_names = [SENT_METRIC, HARD_BOUNCE_METRIC, COMPLAINT_METRIC, *auto_pause_metrics]
+ # Tag the query so it is attributable in query-cost analysis and does not trip the untagged-query
+ # guard in local dev. Celery adds only task identity, not a product or feature. This derives tier
+ # state in the background, so it is enrichment, not a customer-facing query. One context here
+ # covers the daily sweep, the admin recompute, and the backfill command.
+ with tags_context(product=Product.WORKFLOWS, feature=Feature.ENRICHMENT):
+ return fetch_app_metric_daily_totals_by_team(
+ app_source=APP_SOURCE,
+ name=metric_names,
+ after=after,
+ before=before,
+ team_ids=team_ids,
+ workload=workload,
+ )
+
+
+def _history_from_daily(team_id: int, days: dict[str, dict[str, int]]) -> TeamSendingHistory:
+ # The tier decision only reads team totals, so metrics recorded under a batch job id and under
+ # its parent workflow id sum the same either way and need no per-source resolution.
+ auto_pause_metrics = [name for name in settings.WORKFLOWS_EMAIL_TIER_AUTO_PAUSE_METRIC_NAMES if name]
+ return TeamSendingHistory(
+ team_id=team_id,
+ sent=sum(counts.get(SENT_METRIC, 0) for counts in days.values()),
+ hard_bounced=sum(counts.get(HARD_BOUNCE_METRIC, 0) for counts in days.values()),
+ complained=sum(counts.get(COMPLAINT_METRIC, 0) for counts in days.values()),
+ auto_paused=any(counts.get(metric, 0) > 0 for counts in days.values() for metric in auto_pause_metrics),
+ daily_sends={day: counts.get(SENT_METRIC, 0) for day, counts in days.items() if counts.get(SENT_METRIC, 0)},
+ )
+
+
+def _empty_history(team_id: int) -> TeamSendingHistory:
+ return TeamSendingHistory(team_id=team_id, sent=0, hard_bounced=0, complained=0, auto_paused=False, daily_sends={})
+
+
+def apply_tier_decision(config: TeamWorkflowsConfig, decision: TierDecision) -> bool:
+ """Persist a tier change. Returns whether anything was written."""
+ if not decision.changed:
+ return False
+
+ # Compare-and-set against the state the decision was read from. The fleet sweep loads every
+ # config in one snapshot and writes later in the loop, so a staff pin, suspension, or manual
+ # tier set that lands in that gap must not be clobbered by a stale computed value. Every admin
+ # writer of this row locks it; the sweep instead conditions the write, so it no-ops when the
+ # row moved underneath and the next run recomputes from the new state.
+ fields: dict[str, Any] = {
+ "email_sending_tier": decision.new_tier,
+ "email_sending_tier_updated_at": timezone.now(),
+ }
+ if decision.reason in RATE_DEMOTION_REASONS:
+ # Only rate-driven demotions arm the demotion cooldown. Promotions, decay, suspensions,
+ # and staff writes share the dwell anchor above but must not delay a real demotion.
+ fields["email_sending_tier_demoted_at"] = timezone.now()
+
+ updated = TeamWorkflowsConfig.objects.filter(
+ team_id=decision.team_id,
+ email_sending_tier=decision.previous_tier,
+ email_sending_tier_pinned=False,
+ email_sending_suspended_at__isnull=config.email_sending_suspended_at is None,
+ ).update(**fields)
+ if not updated:
+ return False
+
+ logger.info(
+ "workflows_email_sending_tier_changed",
+ team_id=decision.team_id,
+ previous_tier=decision.previous_tier,
+ new_tier=decision.new_tier,
+ reason=decision.reason,
+ )
+ return True
+
+
+def recompute_email_sending_tiers(team_ids: Optional[list[int]] = None) -> list[TierDecision]:
+ """
+ Move every candidate team at most one tier, up or down.
+
+ Candidates are teams that sent workflow email in the window plus teams whose stored state can
+ only be corrected by a run: a suspended team owed a demotion, and any team already above tier 0.
+ A pinned team is skipped in both directions.
+
+ Returns every decision, including holds (`changed` False, with the reason), so callers like the
+ admin recompute action can say why a team did not move. A changed decision whose write lost to
+ a concurrent staff change is dropped: the stored state moved underneath it, so neither the
+ change nor its reason describes the row anymore.
+ """
+ now = timezone.now()
+ after = now - timedelta(days=settings.WORKFLOWS_EMAIL_TIER_RATE_WINDOW_DAYS)
+ recent_after = now - timedelta(days=settings.WORKFLOWS_EMAIL_TIER_DEMOTION_WINDOW_DAYS)
+ windows = build_sending_history_windows(after=after, recent_after=recent_after, team_ids=team_ids)
+ histories = windows.window
+
+ stateful_teams = TeamWorkflowsConfig.objects.filter(email_sending_tier_pinned=False).exclude(
+ email_sending_tier=MIN_EMAIL_SENDING_TIER, email_sending_suspended_at__isnull=True
+ )
+ if team_ids is not None:
+ stateful_teams = stateful_teams.filter(team_id__in=team_ids)
+
+ candidate_ids = set(histories) | set(stateful_teams.values_list("team_id", flat=True))
+ if not candidate_ids:
+ return []
+
+ # select_related bypasses TeamManager's defer, so without only() the join pulls every wide Team
+ # column, including the deprecated taxonomy blobs, for every candidate. The decision reads only
+ # created_at from Team, so restrict the load to that plus the config fields it uses.
+ configs = {
+ config.team_id: config
+ for config in TeamWorkflowsConfig.objects.filter(team_id__in=candidate_ids)
+ .select_related("team")
+ .only(
+ "email_sending_tier",
+ "email_sending_tier_pinned",
+ "email_sending_tier_updated_at",
+ "email_sending_tier_demoted_at",
+ "email_sending_suspended_at",
+ "ses_tenant_sending_status",
+ "ses_tenant_reputation_impact",
+ "team__created_at",
+ )
+ }
+
+ decisions: list[TierDecision] = []
+ for team_id in sorted(candidate_ids):
+ config = configs.get(team_id)
+ if config is None:
+ # No row means tier 0 with no history worth acting on: a promotion needs volume the
+ # metrics sweep would have surfaced, and there is nothing stored to demote.
+ continue
+ if config.email_sending_tier_pinned:
+ continue
+
+ decision = decide_tier(
+ history=histories.get(team_id) or _empty_history(team_id),
+ recent_history=windows.recent.get(team_id) or _empty_history(team_id),
+ current_tier=config.email_sending_tier,
+ tier_updated_at=config.email_sending_tier_updated_at or config.team.created_at,
+ suspended=config.email_sending_suspended_at is not None,
+ tenant_state=SesTenantState(
+ sending_status=config.ses_tenant_sending_status,
+ reputation_impact=config.ses_tenant_reputation_impact,
+ ),
+ last_rate_demotion_at=config.email_sending_tier_demoted_at,
+ )
+ if not decision.changed or apply_tier_decision(config, decision):
+ decisions.append(decision)
+ return decisions
+
+
+def recompute_email_sending_tier_for_team(team_id: int) -> Optional[TierDecision]:
+ """
+ Recompute one team now, so a staff suspension takes its tier down without waiting for the
+ next periodic run. Returns the decision, held or applied, so the caller can say why a team
+ did not move. None means the team was not evaluated at all: it is pinned, it has no config
+ row, or its state changed while recomputing.
+ """
+ decisions = recompute_email_sending_tiers(team_ids=[team_id])
+ return decisions[0] if decisions else None
diff --git a/products/workflows/backend/tasks/__init__.py b/products/workflows/backend/tasks/__init__.py
index 919bab02c9ad..90f47c6d753f 100644
--- a/products/workflows/backend/tasks/__init__.py
+++ b/products/workflows/backend/tasks/__init__.py
@@ -1,3 +1,3 @@
-from . import hog_flows, ses_account_reputation
+from . import email_sending_tiers, hog_flows, ses_account_reputation
-__all__ = ["hog_flows", "ses_account_reputation"]
+__all__ = ["email_sending_tiers", "hog_flows", "ses_account_reputation"]
diff --git a/products/workflows/backend/tasks/email_sending_tiers.py b/products/workflows/backend/tasks/email_sending_tiers.py
new file mode 100644
index 000000000000..c1fe5f0a3779
--- /dev/null
+++ b/products/workflows/backend/tasks/email_sending_tiers.py
@@ -0,0 +1,23 @@
+import structlog
+from celery import shared_task
+
+from posthog.tasks.utils import CeleryQueue
+
+from products.workflows.backend.services.email_sending_tier import recompute_email_sending_tiers
+
+logger = structlog.get_logger(__name__)
+
+
+@shared_task(ignore_result=True, queue=CeleryQueue.LONG_RUNNING.value)
+def recompute_workflows_email_sending_tiers() -> None:
+ """Move each team at most one trust tier, based on how much workflow email it sent and how
+ clean the sending was. Runs in every rollout mode: tiers are stored before anything reads them,
+ so enforcement can be switched on against a settled distribution."""
+ decisions = recompute_email_sending_tiers()
+ logger.info(
+ "workflows_email_sending_tier_sweep_finished",
+ evaluated_teams=len(decisions),
+ changed_teams=sum(1 for decision in decisions if decision.changed),
+ promoted=sum(1 for decision in decisions if decision.new_tier > decision.previous_tier),
+ demoted=sum(1 for decision in decisions if decision.new_tier < decision.previous_tier),
+ )
diff --git a/products/workflows/backend/test/test_email_sending_tier.py b/products/workflows/backend/test/test_email_sending_tier.py
new file mode 100644
index 000000000000..8cddd7634a7b
--- /dev/null
+++ b/products/workflows/backend/test/test_email_sending_tier.py
@@ -0,0 +1,491 @@
+from datetime import timedelta
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.test import override_settings
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from products.workflows.backend.management.commands.backfill_workflows_email_sending_tiers import (
+ Command as BackfillCommand,
+)
+from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig
+from products.workflows.backend.services.email_sending_tier import (
+ SendingHistoryWindows,
+ SesTenantState,
+ TeamSendingHistory,
+ TierDecision,
+ apply_tier_decision,
+ decide_tier,
+ highest_qualifying_tier,
+ recompute_email_sending_tiers,
+)
+from products.workflows.backend.utils.email_sending_tiers import get_email_sending_tier_limits
+
+TIER_HOURLY_CAPS = [200, 600, 2000, 6000, 20000, 60000, 200000]
+TIER_DAILY_CAPS = [1000, 3000, 10000, 30000, 100000, 300000, 1000000]
+TIER_BATCH_CAPS = [1000, 3000, 10000, 30000, 100000, 300000, 1000000]
+
+TIER_SETTINGS = {
+ "WORKFLOWS_EMAIL_TIER_HOURLY_CAPS": TIER_HOURLY_CAPS,
+ "WORKFLOWS_EMAIL_TIER_DAILY_CAPS": TIER_DAILY_CAPS,
+ "WORKFLOWS_EMAIL_TIER_BATCH_AUDIENCE_CAPS": TIER_BATCH_CAPS,
+ "WORKFLOWS_EMAIL_TIER_MIN_DAYS_AT_TIER": [3],
+ "WORKFLOWS_EMAIL_TIER_MIN_ACTIVE_DAYS": 2,
+ "WORKFLOWS_EMAIL_TIER_MIN_DAILY_USE_RATIO": 0.5,
+ "WORKFLOWS_EMAIL_TIER_MAX_COMPLAINT_RATE": 0.001,
+ "WORKFLOWS_EMAIL_TIER_MAX_BOUNCE_RATE": 0.02,
+ "WORKFLOWS_EMAIL_TIER_COMPLAINT_RATE_MIN_SENDS": 1000,
+ "WORKFLOWS_EMAIL_TIER_COMPLAINT_COUNT_BACKSTOP": 3,
+ "WORKFLOWS_EMAIL_TIER_BOUNCE_RATE_MIN_SENDS": 200,
+ "WORKFLOWS_EMAIL_TIER_DEMOTION_WINDOW_DAYS": 7,
+ "WORKFLOWS_EMAIL_TIER_DEMOTION_COOLDOWN_DAYS": 7,
+ "WORKFLOWS_EMAIL_TIER_INACTIVITY_DECAY_DAYS": 30,
+ "WORKFLOWS_EMAIL_TIER_AUTO_PAUSE_METRIC_NAMES": [],
+}
+
+
+def history(
+ *,
+ team_id: int = 1,
+ sent: int = 0,
+ hard_bounced: int = 0,
+ complained: int = 0,
+ auto_paused: bool = False,
+ daily_sends: dict[str, int] | None = None,
+) -> TeamSendingHistory:
+ return TeamSendingHistory(
+ team_id=team_id,
+ sent=sent,
+ hard_bounced=hard_bounced,
+ complained=complained,
+ auto_paused=auto_paused,
+ daily_sends=daily_sends or {},
+ )
+
+
+def clean_days(count: int, sent_per_day: int, *, days_ago: int = 0) -> dict[str, int]:
+ # Relative to today, because only days after the team's tier_updated_at count toward the use
+ # bar. Absolute dates would drift out of every window as wall-clock time moves past them.
+ today = timezone.now().date()
+ return {(today - timedelta(days=offset + days_ago)).strftime("%Y-%m-%d"): sent_per_day for offset in range(count)}
+
+
+@override_settings(**TIER_SETTINGS)
+class TestEmailSendingTierDecision(BaseTest):
+ @parameterized.expand([(tier, caps) for tier, caps in enumerate(zip(TIER_HOURLY_CAPS, TIER_DAILY_CAPS))])
+ def test_tier_maps_to_its_caps(self, tier: int, caps: tuple[int, int]) -> None:
+ limits = get_email_sending_tier_limits(tier)
+ assert (limits.per_hour, limits.per_day) == caps
+
+ @parameterized.expand([(tier,) for tier in range(len(TIER_DAILY_CAPS) - 1)])
+ def test_promotes_one_tier_when_every_criterion_is_met(self, tier: int) -> None:
+ used = clean_days(2, TIER_DAILY_CAPS[tier])
+ decision = decide_tier(
+ history=history(sent=sum(used.values()), daily_sends=used),
+ current_tier=tier,
+ tier_updated_at=timezone.now() - timedelta(days=30),
+ suspended=False,
+ )
+ assert decision.new_tier == tier + 1
+ assert decision.reason == "clean_and_used"
+
+ def test_does_not_promote_before_the_minimum_time_at_tier(self) -> None:
+ used = clean_days(2, TIER_DAILY_CAPS[0])
+ decision = decide_tier(
+ history=history(sent=sum(used.values()), daily_sends=used),
+ current_tier=0,
+ tier_updated_at=timezone.now() - timedelta(hours=1),
+ suspended=False,
+ )
+ assert decision.new_tier == 0
+ assert decision.reason == "too_soon"
+
+ # Tier 0 allows 1,000/day and the bar is half of it, so 900 clears the volume but one day is
+ # short of the two-day minimum, and 400 misses the volume however many days it runs for.
+ @parameterized.expand(
+ [
+ ("nothing sent", 0, 0),
+ ("only one qualifying day", 1, 900),
+ ("volume below half the daily cap on every day", 2, 400),
+ ]
+ )
+ def test_does_not_promote_without_real_use_of_the_tier(self, _name: str, days: int, sent_per_day: int) -> None:
+ daily_sends = clean_days(days, sent_per_day)
+ decision = decide_tier(
+ history=history(sent=sum(daily_sends.values()), daily_sends=daily_sends),
+ current_tier=0,
+ tier_updated_at=timezone.now() - timedelta(days=30),
+ suspended=False,
+ )
+ assert decision.new_tier == 0
+ assert decision.reason == "tier_not_used_enough"
+
+ @parameterized.expand(
+ [
+ ("complaint rate above the bar", 10_000, 0, 50),
+ ("hard bounce rate above the bar", 10_000, 500, 0),
+ ]
+ )
+ def test_demotes_one_tier_on_dirty_rates(self, _name: str, sent: int, bounced: int, complained: int) -> None:
+ used = clean_days(5, TIER_DAILY_CAPS[1])
+ decision = decide_tier(
+ history=history(sent=sent, hard_bounced=bounced, complained=complained, daily_sends=used),
+ current_tier=2,
+ tier_updated_at=timezone.now() - timedelta(days=30),
+ suspended=False,
+ )
+ assert decision.new_tier == 1
+ assert decision.reason == "rates_above_threshold"
+
+ def test_demotion_stops_at_tier_zero(self) -> None:
+ decision = decide_tier(
+ history=history(sent=1000, complained=500),
+ current_tier=0,
+ tier_updated_at=timezone.now() - timedelta(days=30),
+ suspended=False,
+ )
+ assert decision.new_tier == 0
+
+ # The cooldown must be armed only by a prior rate demotion: with the cooldown at the window
+ # length, one incident demotes exactly once, and a fresh promotion must not shield a team from
+ # its first real demotion.
+ @parameterized.expand(
+ [
+ ("a recent rate demotion holds further demotion", 1, 2, "demotion_cooldown"),
+ ("an expired cooldown lets new evidence demote", 8, 1, "rates_above_threshold"),
+ ("no prior rate demotion demotes immediately", None, 1, "rates_above_threshold"),
+ ]
+ )
+ def test_the_demotion_cooldown_is_armed_by_rate_demotions_only(
+ self, _name: str, demoted_days_ago: int | None, expected_tier: int, expected_reason: str
+ ) -> None:
+ decision = decide_tier(
+ history=history(sent=10_000, complained=50),
+ current_tier=2,
+ # A fresh tier write (a promotion or a staff change) must not block the demotion.
+ tier_updated_at=timezone.now() - timedelta(days=1),
+ last_rate_demotion_at=(
+ timezone.now() - timedelta(days=demoted_days_ago) if demoted_days_ago is not None else None
+ ),
+ suspended=False,
+ )
+ assert decision.new_tier == expected_tier
+ assert decision.reason == expected_reason
+
+ @parameterized.expand(
+ [
+ ("complaints at the backstop demote a silent window", 3, 1, "rates_above_threshold"),
+ ("fewer complaints than the backstop stay clean", 2, 2, "tier_not_used_enough"),
+ ]
+ )
+ def test_delayed_complaints_count_even_when_the_window_has_no_sends(
+ self, _name: str, complained: int, expected_tier: int, expected_reason: str
+ ) -> None:
+ # Feedback lags sends, so a window can hold the complaints from sends made just before it
+ # opened. Zero sends must not make those complaints invisible. The anchor stays inside the
+ # inactivity decay period so the clean case is not demoted for dormancy instead.
+ decision = decide_tier(
+ history=history(sent=0, complained=complained),
+ current_tier=2,
+ tier_updated_at=timezone.now() - timedelta(days=10),
+ suspended=False,
+ )
+ assert decision.new_tier == expected_tier
+ assert decision.reason == expected_reason
+
+ # Demotion reads the short recent window and promotion the full window, so an aged-out
+ # incident stops demoting but still blocks the climb until the full window is clean.
+ @parameterized.expand(
+ [
+ ("recent incident demotes despite a clean full window", 50, 0, 1, "rates_above_threshold"),
+ ("aged-out incident blocks promotion but stops demoting", 0, 200, 2, "rates_recovering"),
+ ]
+ )
+ def test_demotion_and_promotion_read_different_windows(
+ self, _name: str, recent_complaints: int, older_complaints: int, expected_tier: int, expected_reason: str
+ ) -> None:
+ used = clean_days(5, TIER_DAILY_CAPS[2])
+ decision = decide_tier(
+ history=history(sent=100_000, complained=recent_complaints + older_complaints, daily_sends=used),
+ recent_history=history(sent=10_000, complained=recent_complaints),
+ current_tier=2,
+ tier_updated_at=timezone.now() - timedelta(days=30),
+ suspended=False,
+ )
+ assert decision.new_tier == expected_tier
+ assert decision.reason == expected_reason
+
+ # AWS measures the complaint rate against FBL-domain sends only, while our rate divides by all
+ # sends and reads lower. The tenant verdict must therefore override a clean internal history:
+ # a paused tenant restarts at the bottom, HIGH impact demotes, LOW blocks the climb.
+ @parameterized.expand(
+ [
+ ("aws paused tenant drops to the bottom", "DISABLED", "", 0, "ses_tenant_paused"),
+ ("high impact demotes despite clean internal rates", "ENABLED", "HIGH", 1, "ses_reputation_high"),
+ ("low impact blocks promotion but does not demote", "ENABLED", "LOW", 2, "ses_reputation_not_clean"),
+ ("reinstated tenant with no impact still promotes", "REINSTATED", "NONE", 3, "clean_and_used"),
+ ]
+ )
+ def test_the_ses_tenant_verdict_overrides_clean_internal_rates(
+ self, _name: str, sending_status: str, impact: str, expected_tier: int, expected_reason: str
+ ) -> None:
+ used = clean_days(5, TIER_DAILY_CAPS[2])
+ decision = decide_tier(
+ history=history(sent=sum(used.values()), daily_sends=used),
+ current_tier=2,
+ tier_updated_at=timezone.now() - timedelta(days=30),
+ suspended=False,
+ tenant_state=SesTenantState(sending_status=sending_status, reputation_impact=impact),
+ )
+ assert decision.new_tier == expected_tier
+ assert decision.reason == expected_reason
+
+ # At the 0.1% threshold one complaint per 1,000 sends is exactly the line, so a small window
+ # must not turn a single complaint into a demotion, while the absolute backstop still catches
+ # an egregious small sender.
+ @parameterized.expand(
+ [
+ ("one complaint under the denominator floor stays clean", 900, 0, 1, 2),
+ ("complaints at the backstop demote despite the floor", 900, 0, 3, 1),
+ ("high bounce rate under the denominator floor stays clean", 150, 20, 0, 2),
+ ]
+ )
+ def test_rates_only_count_on_a_meaningful_denominator(
+ self, _name: str, sent: int, bounced: int, complained: int, expected_tier: int
+ ) -> None:
+ decision = decide_tier(
+ history=history(sent=sent, hard_bounced=bounced, complained=complained),
+ current_tier=2,
+ tier_updated_at=timezone.now() - timedelta(days=30),
+ suspended=False,
+ )
+ assert decision.new_tier == expected_tier
+
+ # A dormant allowance is no longer earned: mailbox providers keep about 30 days of reputation
+ # history, and a comeback blast from a stale list is what the caps exist to prevent.
+ @parameterized.expand(
+ [
+ ("dormant past the decay period drops one tier", 3, 40, 2, "inactive"),
+ ("dormant but inside the decay period holds", 3, 10, 3, "tier_not_used_enough"),
+ ("the lowest tier never decays", 0, 40, 0, "tier_not_used_enough"),
+ ]
+ )
+ def test_inactivity_decays_one_tier_per_period(
+ self, _name: str, current_tier: int, days_since_update: int, expected_tier: int, expected_reason: str
+ ) -> None:
+ decision = decide_tier(
+ history=history(sent=0),
+ current_tier=current_tier,
+ tier_updated_at=timezone.now() - timedelta(days=days_since_update),
+ suspended=False,
+ )
+ assert decision.new_tier == expected_tier
+ assert decision.reason == expected_reason
+
+ @parameterized.expand([("dwell met at the low tier", 0, 1), ("dwell not met at the high tier", 2, 2)])
+ @override_settings(WORKFLOWS_EMAIL_TIER_MIN_DAYS_AT_TIER=[3, 3, 5])
+ def test_the_promotion_dwell_is_indexed_by_tier(self, _name: str, current_tier: int, expected_tier: int) -> None:
+ used = clean_days(4, TIER_DAILY_CAPS[current_tier])
+ decision = decide_tier(
+ history=history(sent=sum(used.values()), daily_sends=used),
+ current_tier=current_tier,
+ tier_updated_at=timezone.now() - timedelta(days=4),
+ suspended=False,
+ )
+ assert decision.new_tier == expected_tier
+
+ def test_suspension_drops_straight_to_tier_zero(self) -> None:
+ decision = decide_tier(
+ history=history(sent=100_000, daily_sends=clean_days(10, TIER_DAILY_CAPS[3])),
+ current_tier=4,
+ tier_updated_at=timezone.now() - timedelta(days=30),
+ suspended=True,
+ )
+ assert decision.new_tier == 0
+ assert decision.reason == "staff_suspension"
+
+ @override_settings(WORKFLOWS_EMAIL_TIER_AUTO_PAUSE_METRIC_NAMES=["email_auto_paused"])
+ def test_auto_pause_demotes_one_tier(self) -> None:
+ decision = decide_tier(
+ history=history(sent=10_000, auto_paused=True, daily_sends=clean_days(5, TIER_DAILY_CAPS[2])),
+ current_tier=3,
+ tier_updated_at=timezone.now() - timedelta(days=30),
+ suspended=False,
+ )
+ assert decision.new_tier == 2
+ assert decision.reason == "workflow_auto_paused"
+
+ # An established sender must land on its real tier at once, but only recent volume counts:
+ # two high-volume days months ago must not grant a dormant team an allowance the inactivity
+ # decay exists to remove, with a freshly stamped decay clock on top.
+ @parameterized.expand(
+ [
+ ("recent volume earns the real tier", 0, 4),
+ ("volume older than the decay period earns nothing", 60, 0),
+ ]
+ )
+ def test_backfill_mode_jumps_straight_to_the_recently_earned_tier(
+ self, _name: str, days_ago: int, expected_tier: int
+ ) -> None:
+ used = clean_days(5, TIER_DAILY_CAPS[3], days_ago=days_ago)
+ decision = decide_tier(
+ history=history(sent=sum(used.values()), daily_sends=used),
+ current_tier=0,
+ tier_updated_at=None,
+ suspended=False,
+ require_time_at_tier=False,
+ single_step=False,
+ )
+ assert decision.new_tier == expected_tier
+
+ def test_sends_before_a_midday_tier_change_do_not_count(self) -> None:
+ # The tier change stamps a mid-day anchor, but metrics are day-grained. The anchor day's
+ # pre-change volume must not count toward the new tier, so a team demoted mid-day cannot
+ # re-promote on one real day at the new tier plus the anchor day it was demoted on.
+ now = timezone.now().replace(hour=12, minute=0, second=0, microsecond=0)
+ anchor = now - timedelta(days=4) # past the 3-day dwell, so promotion is considered
+ # Tier 0 allows 1,000/day and the bar is half of it, so 900 qualifies. Only the anchor day
+ # and one later day clear the bar, so counting the anchor day would reach the two-day minimum.
+ daily_sends = {anchor.strftime("%Y-%m-%d"): 900, now.strftime("%Y-%m-%d"): 900}
+ decision = decide_tier(
+ history=history(sent=sum(daily_sends.values()), daily_sends=daily_sends),
+ current_tier=0,
+ tier_updated_at=anchor,
+ suspended=False,
+ now=now,
+ )
+ assert decision.new_tier == 0
+ assert decision.reason == "tier_not_used_enough"
+
+ def test_qualifying_tier_never_exceeds_the_table(self) -> None:
+ used = clean_days(5, TIER_DAILY_CAPS[-1] * 100)
+ assert highest_qualifying_tier(used) == len(TIER_DAILY_CAPS) - 1
+
+
+@override_settings(**TIER_SETTINGS)
+class TestRecomputeEmailSendingTiers(BaseTest):
+ def _config(self, **fields) -> TeamWorkflowsConfig:
+ config, _ = TeamWorkflowsConfig.objects.update_or_create(team=self.team, defaults=fields)
+ return config
+
+ def _run(
+ self,
+ histories: dict[int, TeamSendingHistory],
+ recent: dict[int, TeamSendingHistory] | None = None,
+ ) -> None:
+ with patch(
+ "products.workflows.backend.services.email_sending_tier.build_sending_history_windows",
+ return_value=SendingHistoryWindows(window=histories, recent=recent if recent is not None else histories),
+ ):
+ recompute_email_sending_tiers()
+
+ def test_returns_a_held_decision_with_its_reason(self) -> None:
+ # The admin recompute action reports why a team did not move, so the sweep must return
+ # holds with their reason rather than only the applied changes.
+ self._config(email_sending_tier=2, email_sending_tier_updated_at=timezone.now() - timedelta(days=10))
+ with patch(
+ "products.workflows.backend.services.email_sending_tier.build_sending_history_windows",
+ return_value=SendingHistoryWindows(window={}, recent={}),
+ ):
+ decisions = recompute_email_sending_tiers()
+ held = next(decision for decision in decisions if decision.team_id == self.team.id)
+ assert not held.changed
+ assert held.reason == "tier_not_used_enough"
+ assert TeamWorkflowsConfig.objects.get(team=self.team).email_sending_tier == 2
+
+ def test_promotion_is_persisted_with_a_fresh_timestamp(self) -> None:
+ self._config(email_sending_tier=0, email_sending_tier_updated_at=timezone.now() - timedelta(days=30))
+ used = clean_days(2, TIER_DAILY_CAPS[0])
+ self._run({self.team.id: history(team_id=self.team.id, sent=sum(used.values()), daily_sends=used)})
+
+ config = TeamWorkflowsConfig.objects.get(team=self.team)
+ assert config.email_sending_tier == 1
+ assert config.email_sending_tier_updated_at is not None
+ assert config.email_sending_tier_updated_at > timezone.now() - timedelta(minutes=1)
+
+ def test_suspended_team_is_demoted_even_with_no_recent_sending(self) -> None:
+ self._config(
+ email_sending_tier=3,
+ email_sending_tier_updated_at=timezone.now() - timedelta(days=30),
+ email_sending_suspended_at=timezone.now(),
+ )
+ self._run({})
+
+ assert TeamWorkflowsConfig.objects.get(team=self.team).email_sending_tier == 0
+
+ @parameterized.expand([("pinned_after_snapshot", "pin"), ("tier_set_after_snapshot", "retier")])
+ def test_stale_decision_does_not_overwrite_a_concurrent_staff_change(self, _name: str, change: str) -> None:
+ # The sweep read the row at tier 1 and decided to promote to 2. Staff then pinned or re-set
+ # the tier before the write. The stale decision must not clobber the staff change.
+ config = self._config(email_sending_tier=1, email_sending_tier_pinned=False)
+ if change == "pin":
+ TeamWorkflowsConfig.objects.filter(team=self.team).update(email_sending_tier_pinned=True)
+ expected_tier = 1
+ else:
+ TeamWorkflowsConfig.objects.filter(team=self.team).update(email_sending_tier=5)
+ expected_tier = 5
+
+ decision = TierDecision(team_id=self.team.id, previous_tier=1, new_tier=2, reason="clean_and_used")
+ assert apply_tier_decision(config, decision) is False
+ assert TeamWorkflowsConfig.objects.get(team=self.team).email_sending_tier == expected_tier
+
+ @parameterized.expand([("promotion", 0), ("demotion", 3)])
+ def test_pinned_team_never_moves(self, _name: str, tier: int) -> None:
+ self._config(
+ email_sending_tier=tier,
+ email_sending_tier_pinned=True,
+ email_sending_tier_updated_at=timezone.now() - timedelta(days=30),
+ email_sending_suspended_at=timezone.now() if tier else None,
+ )
+ used = clean_days(5, TIER_DAILY_CAPS[3])
+ self._run({self.team.id: history(team_id=self.team.id, sent=sum(used.values()), daily_sends=used)})
+
+ assert TeamWorkflowsConfig.objects.get(team=self.team).email_sending_tier == tier
+
+
+@override_settings(**TIER_SETTINGS)
+class TestBackfillEmailSendingTiers(BaseTest):
+ def test_suspended_team_is_not_promoted_despite_qualifying_history(self) -> None:
+ used = clean_days(5, TIER_DAILY_CAPS[3])
+ histories = {self.team.id: history(team_id=self.team.id, sent=sum(used.values()), daily_sends=used)}
+
+ # Control: the same history promotes when the team is not suspended.
+ TeamWorkflowsConfig.objects.update_or_create(team=self.team, defaults={"email_sending_tier": 0})
+ assert BackfillCommand()._decide(histories=histories, team_ids=[self.team.id]) != []
+
+ # A staff suspension keeps the backfill at tier 0, so reinstatement does not restore a high tier.
+ TeamWorkflowsConfig.objects.filter(team=self.team).update(email_sending_suspended_at=timezone.now())
+ assert BackfillCommand()._decide(histories=histories, team_ids=[self.team.id]) == []
+
+ def test_suspended_team_with_no_window_history_is_reset_to_tier_zero(self) -> None:
+ # A suspended team that sent nothing in the window must still be evaluated, or the backfill
+ # would leave its stored elevated tier in place for reinstatement.
+ TeamWorkflowsConfig.objects.update_or_create(
+ team=self.team,
+ defaults={"email_sending_tier": 4, "email_sending_suspended_at": timezone.now()},
+ )
+ decisions = BackfillCommand()._decide(histories={}, team_ids=[self.team.id])
+ assert [(d.new_tier, d.reason) for d in decisions] == [(0, "staff_suspension")]
+
+ def test_apply_does_not_overwrite_a_concurrent_staff_change(self) -> None:
+ # The fleet scan computes decisions before it writes. A staff pin landing in that gap must
+ # win over the stale decision, matching the daily sweep's compare-and-set.
+ TeamWorkflowsConfig.objects.update_or_create(
+ team=self.team, defaults={"email_sending_tier": 1, "email_sending_tier_pinned": True}
+ )
+ stale = TierDecision(team_id=self.team.id, previous_tier=1, new_tier=4, reason="clean_and_used")
+ assert BackfillCommand()._apply([stale]) == 0
+ assert TeamWorkflowsConfig.objects.get(team=self.team).email_sending_tier == 1
+
+ def test_history_for_a_deleted_team_is_dropped(self) -> None:
+ # app_metrics2 in ClickHouse outlives a team deleted from Postgres, so its history can name a
+ # team that no longer exists. It must not reach the distribution or the write count.
+ ghost_id = self.team.id + 10_000
+ histories = {
+ self.team.id: history(team_id=self.team.id),
+ ghost_id: history(team_id=ghost_id),
+ }
+ assert set(BackfillCommand()._without_deleted_teams(histories)) == {self.team.id}