:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): give each team an email sending tier and derive its caps (#89923)
Meikel Ratz19176793afd6
diff --git a/docs/internal/workflows-email-sending-tiers.md b/docs/internal/workflows-email-sending-tiers.mdnew file mode 100644index 000000000000..9b01f068cd38--- /dev/null+++ b/docs/internal/workflows-email-sending-tiers.md@@ -0,0 +1,60 @@+# Workflow email sending tiers++Every project has a trust tier that caps how much workflow email it can send: an hourly cap, a daily cap, and a maximum batch audience.+Projects start at the lowest tier and earn higher ones by sending cleanly; dirty rates, AWS tenant reputation findings, suspensions, and long dormancy move them down.+The tiers exist because all workflow email shares one SES account whose reputation pools every project's complaints.+Only workflows that send email are subject to the tiers; SMS, push, and webhook activity is never capped by them.++## Where the pieces live++- Tier state: `email_sending_tier`, `email_sending_tier_updated_at` (dwell anchor), `email_sending_tier_demoted_at` (demotion cooldown anchor), and `email_sending_tier_pinned` on `TeamWorkflowsConfig`.+- Tier movement: a daily Celery sweep (07:15 UTC, after the SES tenant-state reconcile at 07:00) in `products/workflows/backend/services/email_sending_tier.py`.+- Batch audience cap: `get_hogflow_batch_trigger_limit` in `products/workflows/backend/utils/batch_trigger_limit.py`, applied at batch dispatch and shown in the blast radius preview.+- Send-time caps: two Valkey token buckets per team in the CDP email worker (`claimTeamSendingBudget` in `nodejs/src/cdp/services/messaging/email.service.ts`).+- Staff controls: the team's Django admin page (view state, set/pin a tier, recompute now).+- Customer surface: the Reputation tab's sending allowance card, shown only while the team is enforced.++## Configuration++Two sides read their own env vars because the worker never reads Django settings.+Set them together; drift means the UI describes limits the worker does not apply, or the reverse.++Django (`posthog/settings/web.py`):++- `WORKFLOWS_EMAIL_TIER_MODE`: `off` (default), `shadow`, or `enforce`. Unrecognized values read as `off`.+- `WORKFLOWS_EMAIL_TIER_HOURLY_CAPS`, `WORKFLOWS_EMAIL_TIER_DAILY_CAPS`, `WORKFLOWS_EMAIL_TIER_BATCH_AUDIENCE_CAPS`: comma-separated tables indexed by tier. The shortest table decides the tier count.+- `WORKFLOWS_EMAIL_TIER_MIN_DAYS_AT_TIER`: per-tier dwell before promotion, comma-separated, clamped to the last entry.+- `WORKFLOWS_EMAIL_TIER_ENFORCE_TEAMS_CREATED_AFTER`: ISO date. Empty enforces every team; a valid date enforces only teams created on or after it; an unparseable value enforces nobody, so a typo narrows instead of widening.+- Promotion and demotion knobs: `WORKFLOWS_EMAIL_TIER_RATE_WINDOW_DAYS` (promotion window), `WORKFLOWS_EMAIL_TIER_DEMOTION_WINDOW_DAYS`, `WORKFLOWS_EMAIL_TIER_DEMOTION_COOLDOWN_DAYS` (keep at least as long as the demotion window), `WORKFLOWS_EMAIL_TIER_INACTIVITY_DECAY_DAYS` (0 disables decay), `WORKFLOWS_EMAIL_TIER_MIN_ACTIVE_DAYS`, `WORKFLOWS_EMAIL_TIER_MIN_DAILY_USE_RATIO`, `WORKFLOWS_EMAIL_TIER_MAX_COMPLAINT_RATE`, `WORKFLOWS_EMAIL_TIER_MAX_BOUNCE_RATE`, `WORKFLOWS_EMAIL_TIER_COMPLAINT_RATE_MIN_SENDS`, `WORKFLOWS_EMAIL_TIER_COMPLAINT_COUNT_BACKSTOP`, `WORKFLOWS_EMAIL_TIER_BOUNCE_RATE_MIN_SENDS`.+- `HOGFLOW_BATCH_TRIGGER_ELEVATED_TEAM_IDS`: the pre-tier allowlist. It overrides the tier entirely, so a saved tier does nothing for a listed team.++Worker (`nodejs/src/cdp/config.ts`):++- `EMAIL_TEAM_SENDING_CAP_MODE`: `off` (default), `shadow`, or `enforce`.+- `EMAIL_TEAM_SENDING_CAP_HOURLY_BY_TIER`, `EMAIL_TEAM_SENDING_CAP_DAILY_BY_TIER`: must mirror the Django tables. An unusable table turns the cap off rather than applying a wrong number.+- `EMAIL_TEAM_SENDING_CAP_TEAMS_CREATED_AFTER`: same three-state semantics as the Django cutoff, except that empty caps every team and an unparseable value caps nobody.++All of these reach production as environment variables through `posthog/charts` (with any secret values via `posthog/secrets`).+None of them are wired there yet; the charts change is part of turning the rollout mode on, not part of merging the code.++## Decision rules the sweep applies++In order: staff suspension or an AWS-paused tenant drops to tier 0; a dirty 7-day window, a workflow auto-pause, or a HIGH tenant reputation impact demotes one tier (at most once per cooldown, anchored on the last rate demotion); a tier above 0 with zero sends for the decay period drops one step per period; promotion needs the dwell served, real use of the tier (at least the use ratio of the daily cap on the minimum number of separate days, counted only after the tier anchor), a clean 30-day window, and a clean tenant reputation.+Rates only count on a meaningful denominator; below the complaint floor, the absolute complaint backstop still applies, including in windows with no sends.+Pinned teams never move automatically.++## Rollout order++1. Merge and deploy with both modes `off`. The daily sweep starts computing and storing tiers immediately.+2. Run `python manage.py backfill_workflows_email_sending_tiers` per region, read the printed distribution, then re-run with `--apply`. This lands established senders on their earned tier in one step.+3. Set both modes to `shadow` via charts. Nothing is delayed; would-be delays log and count in `cdp_team_email_cap_delayed_total{mode="shadow"}`. Watch that against real traffic.+4. Set both modes to `enforce`, optionally with the created-after cutoffs so only new projects are enforced first. The Reputation tab's allowance card appears for enforced teams at this point.+ Never set the Django mode to `enforce` on a deployment whose email worker does not carry the send-time caps: the batch audience cap alone can be sidestepped by editing a workflow while a batch is queued, and the send-time buckets are what bound that.+5. To back out, set the modes back to `off`; the tiers keep computing and nothing else changes.++## Known limits++- The batch audience cap is decided when the batch is dispatched. Adding an email step to the workflow while a batch is queued does not re-cap it; the send-time buckets still cap every email at execution. This is why enforcement requires the worker caps to be deployed (see the rollout order).+- Test-panel sends bypass the team buckets on purpose, matching the per-workflow rate limit.+- The buckets are token buckets: a full idle bucket plus refill allows up to roughly twice the stated cap in the very first period. The bucket TTLs exceed the refill periods so this does not recur from idling.+- Gmail provides no per-message feedback loop, so complaint rates (ours and AWS's) cannot see Gmail complaints at all.diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex c9669fe24dec..ed2fb951dc90 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -1229,6 +1229,93 @@ HOGFLOW_BATCH_TRIGGER_ELEVATED_TEAM_IDS: set[int] = {int(team_id) for team_id in get_list(get_from_env("HOGFLOW_BATCH_TRIGGER_ELEVATED_TEAM_IDS", ""))}+# Trust-tiered per-team caps on workflow email ("team warming"). All workflow email shares one SES+# account, so the complaint rate that account is judged on pools every team's sends. A team starts+# at tier 0 and earns the next tier by sending cleanly over time, which bounds how much damage an+# unproven team can do and keeps its early volume small enough that complaint feedback (which lags+# by hours) arrives while total volume is still low.+# The three lists are indexed by tier and must all be the same length. The top tier matches+# HOGFLOW_BATCH_TRIGGER_LIMIT_ELEVATED so a fully graduated team is no more limited than it was+# before tiers existed. Adjacent tiers stay roughly 3x apart: published warmup ramps (SendGrid,+# Mailgun, Oracle) grow 25-50% per step and warn against jumps above 2x, and a promotion is an+# overnight allowance jump, so a 3x step with the utilization bar below approximates that ramp+# while keeping the tier count small enough to reason about. Two deliberate exceptions at the+# bottom: tier 0 is a 100/day probation tier for completely unproven domains (SendGrid trials+# start at 100/day, Customer.io at 200), and its hourly cap is half the daily cap rather than the+# usual fifth so a first real send does not crawl at 20 an hour. The 10x step off tier 0 is fine+# at that absolute volume.+WORKFLOWS_EMAIL_TIER_HOURLY_CAPS: list[int] = [+ int(cap)+ for cap in get_list(get_from_env("WORKFLOWS_EMAIL_TIER_HOURLY_CAPS", "50,200,600,2000,6000,20000,60000,200000"))+]+WORKFLOWS_EMAIL_TIER_DAILY_CAPS: list[int] = [+ int(cap)+ for cap in get_list(+ get_from_env("WORKFLOWS_EMAIL_TIER_DAILY_CAPS", "100,1000,3000,10000,30000,100000,300000,1000000")+ )+]+WORKFLOWS_EMAIL_TIER_BATCH_AUDIENCE_CAPS: list[int] = [+ int(cap)+ for cap in get_list(+ get_from_env("WORKFLOWS_EMAIL_TIER_BATCH_AUDIENCE_CAPS", "100,1000,3000,10000,30000,100000,300000,1000000")+ )+]++# Promotion bar. A team must sit at its tier for this long, actually use the tier, and keep its+# rates under the thresholds below before it moves up one step. Indexed by the tier the team is+# promoted from, clamped to the last entry, so the dwell grows with the volume at stake and a full+# climb takes the 4-6 weeks the industry treats as a complete warmup.+WORKFLOWS_EMAIL_TIER_MIN_DAYS_AT_TIER: list[int] = [+ int(days) for days in get_list(get_from_env("WORKFLOWS_EMAIL_TIER_MIN_DAYS_AT_TIER", "3,3,3,5,5,7,7,7"))+]+# Trailing window the complaint and bounce rates are measured over for promotion. 30 days is how+# the industry quotes these thresholds, and it matches the reputation surface in the workflows UI.+WORKFLOWS_EMAIL_TIER_RATE_WINDOW_DAYS = int(get_from_env("WORKFLOWS_EMAIL_TIER_RATE_WINDOW_DAYS", 30))+# Demotion reads a shorter window than promotion, so one incident stops demoting once it ages out+# of the short window instead of holding the team down for the full promotion window.+WORKFLOWS_EMAIL_TIER_DEMOTION_WINDOW_DAYS = int(get_from_env("WORKFLOWS_EMAIL_TIER_DEMOTION_WINDOW_DAYS", 7))+# After a rate-based demotion, further rate-based demotions wait this long. Without it the daily+# sweep re-reads the same dirty window every run and one incident cascades a team to the bottom.+# Keep this at least as long as the demotion window: at that length the incident that caused the+# last demotion has aged out of the window by the time demotions resume, so a second demotion can+# only come from new evidence.+WORKFLOWS_EMAIL_TIER_DEMOTION_COOLDOWN_DAYS = int(get_from_env("WORKFLOWS_EMAIL_TIER_DEMOTION_COOLDOWN_DAYS", 7))+# 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.+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))+# Rates are meaningless on tiny denominators: at the 0.1% complaint threshold one complaint per+# 1,000 sends IS the line, so judging a window with fewer sends turns a single complaint into a+# demotion. Below the floor a metric only counts through the absolute backstop next to it.+WORKFLOWS_EMAIL_TIER_COMPLAINT_RATE_MIN_SENDS = int(get_from_env("WORKFLOWS_EMAIL_TIER_COMPLAINT_RATE_MIN_SENDS", 1000))+WORKFLOWS_EMAIL_TIER_COMPLAINT_COUNT_BACKSTOP = int(get_from_env("WORKFLOWS_EMAIL_TIER_COMPLAINT_COUNT_BACKSTOP", 3))+WORKFLOWS_EMAIL_TIER_BOUNCE_RATE_MIN_SENDS = int(get_from_env("WORKFLOWS_EMAIL_TIER_BOUNCE_RATE_MIN_SENDS", 200))+# A team that has sent nothing has proven nothing, so promotion also needs real use of the current+# tier: this many separate days on which the team sent at least this fraction of its daily cap.+WORKFLOWS_EMAIL_TIER_MIN_ACTIVE_DAYS = int(get_from_env("WORKFLOWS_EMAIL_TIER_MIN_ACTIVE_DAYS", 2))+WORKFLOWS_EMAIL_TIER_MIN_DAILY_USE_RATIO = float(get_from_env("WORKFLOWS_EMAIL_TIER_MIN_DAILY_USE_RATIO", 0.5))+# app_metrics2 metric names that count as a per-workflow auto-pause for the tier decision. Empty+# means the signal contributes nothing, so the decision rests on rates and staff suspensions.+WORKFLOWS_EMAIL_TIER_AUTO_PAUSE_METRIC_NAMES: list[str] = get_list(+ get_from_env("WORKFLOWS_EMAIL_TIER_AUTO_PAUSE_METRIC_NAMES", "")+)++# Rollout mode, shared by the batch audience cap and the send-time cap:+# "off" - tiers are computed and stored, nothing reads them. Pre-tier behavior everywhere.+# "shadow" - tiers are computed and stored, and every send that a cap would have delayed is+# logged, but no send is delayed and no audience is rejected.+# "enforce" - caps apply.+# The email worker has its own copy of these two, EMAIL_TEAM_SENDING_CAP_MODE and+# EMAIL_TEAM_SENDING_CAP_TEAMS_CREATED_AFTER in nodejs/src/cdp/config.ts, because it never reads+# Django settings. Set both sides together: this pair drives the batch audience cap and what the+# workflows UI shows, and the worker's pair drives the send-time cap.+WORKFLOWS_EMAIL_TIER_MODE = get_from_env("WORKFLOWS_EMAIL_TIER_MODE", "off")+# Narrows enforcement to teams created on or after this date (ISO 8601, e.g. "2026-01-01"), so the+# caps can be turned on for new projects without touching established ones. Empty means all teams.+WORKFLOWS_EMAIL_TIER_ENFORCE_TEAMS_CREATED_AFTER = get_from_env("WORKFLOWS_EMAIL_TIER_ENFORCE_TEAMS_CREATED_AFTER", "")+# Comma-separated list of org ids allowed to receive the Error Tracking weekly digest# "*" for all, empty to disable featureERROR_TRACKING_WEEKLY_DIGEST_ORG_IDS = get_list(get_from_env("ERROR_TRACKING_WEEKLY_DIGEST_ORG_IDS", ""))diff --git a/products/workflows/backend/migrations/0020_teamworkflowsconfig_email_sending_tier_and_more.py b/products/workflows/backend/migrations/0020_teamworkflowsconfig_email_sending_tier_and_more.pynew file mode 100644index 000000000000..05bc177332c2--- /dev/null+++ b/products/workflows/backend/migrations/0020_teamworkflowsconfig_email_sending_tier_and_more.py@@ -0,0 +1,32 @@+# Generated by Django 5.2.17 on 2026-08-26 11:30++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("workflows", "0019_hogflow_email_sending_rate_limit"),+ ]++ operations = [+ migrations.AddField(+ model_name="teamworkflowsconfig",+ name="email_sending_tier",+ field=models.IntegerField(db_default=0, default=0),+ ),+ migrations.AddField(+ model_name="teamworkflowsconfig",+ name="email_sending_tier_pinned",+ field=models.BooleanField(db_default=False, default=False),+ ),+ migrations.AddField(+ model_name="teamworkflowsconfig",+ name="email_sending_tier_updated_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="teamworkflowsconfig",+ name="email_sending_tier_demoted_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/products/workflows/backend/migrations/max_migration.txt b/products/workflows/backend/migrations/max_migration.txtindex 4f21e3ed545c..79087aafb222 100644--- a/products/workflows/backend/migrations/max_migration.txt+++ b/products/workflows/backend/migrations/max_migration.txt@@ -1 +1 @@-0019_hogflow_email_sending_rate_limit+0020_teamworkflowsconfig_email_sending_tier_and_morediff --git a/products/workflows/backend/models/hog_flow_batch_job/hog_flow_batch_job.py b/products/workflows/backend/models/hog_flow_batch_job/hog_flow_batch_job.pyindex 0543e0edbabb..0fd3e6a9318b 100644--- a/products/workflows/backend/models/hog_flow_batch_job/hog_flow_batch_job.py+++ b/products/workflows/backend/models/hog_flow_batch_job/hog_flow_batch_job.py@@ -7,7 +7,7 @@ import structlogfrom posthog.models.utils import RootTeamMixin, UUIDTModelfrom posthog.plugins.plugin_server_api import create_batch_hog_flow_job_invocation-from products.workflows.backend.utils.batch_trigger_limit import get_hogflow_batch_trigger_limit+from products.workflows.backend.utils.batch_trigger_limit import get_hogflow_batch_trigger_limit, hog_flow_sends_emaillogger = structlog.get_logger(__name__)@@ -52,7 +52,14 @@ def handle_hog_flow_batch_job_created(sender, instance, created, **kwargs):team_id=instance.team.id,hog_flow_id=instance.hog_flow.id,batch_job_id=instance.id,- max_audience_size=get_hogflow_batch_trigger_limit(instance.team.id),+ max_audience_size=get_hogflow_batch_trigger_limit(+ instance.team.id,+ # The dispatch runs the live config, so the live actions decide the channel.+ # Adding an email step after this write does not re-cap the queued batch; that+ # gap is bounded by the send-time buckets, which cap every email at execution+ # regardless of the audience size dispatched here.+ sends_email=hog_flow_sends_email(instance.hog_flow.actions),+ ),# The audience snapshot the confirm check validated - the resolver dispatches from# this, not the live trigger, so a trigger edit racing the dispatch can't widen it.filters=instance.filters,diff --git a/products/workflows/backend/models/team_workflows_config.py b/products/workflows/backend/models/team_workflows_config.pyindex c273b3fedb99..6bea1bb29f2c 100644--- a/products/workflows/backend/models/team_workflows_config.py+++ b/products/workflows/backend/models/team_workflows_config.py@@ -46,5 +46,20 @@ class TeamWorkflowsConfig(models.Model):ses_tenant_reputation_impact = models.CharField(max_length=32, blank=True, default="", db_default="")ses_tenant_state_synced_at = models.DateTimeField(null=True, blank=True)+ # Trust tier for workflow email. The tier picks the team's hourly cap, daily cap and maximum+ # batch audience from the tables in settings, so an unproven team cannot send fast enough to+ # damage the shared SES account's reputation. Every team starts at 0 and a periodic task moves+ # it one step at a time based on how much it sent and how clean the sending was.+ # db_default so raw INSERTs from non-Django writers keep working.+ email_sending_tier = models.IntegerField(default=0, db_default=0)+ email_sending_tier_updated_at = models.DateTimeField(null=True, blank=True)+ # When the team was last demoted for dirty rates, an auto-pause, or a HIGH tenant reputation+ # impact. Separate from email_sending_tier_updated_at so promotions and staff writes do not arm+ # the demotion cooldown, and a demotion does not have to share its anchor with the dwell clock.+ email_sending_tier_demoted_at = models.DateTimeField(null=True, blank=True)+ # Staff override. While set, automatic promotion and demotion both skip this team, so a team+ # can be held at a tier that its sending history would not give it.+ email_sending_tier_pinned = models.BooleanField(default=False, db_default=False)+register_team_extension_signal(TeamWorkflowsConfig, logger=logger)diff --git a/products/workflows/backend/utils/batch_trigger_limit.py b/products/workflows/backend/utils/batch_trigger_limit.pyindex 38febf0c2442..d46b64ac2a25 100644--- a/products/workflows/backend/utils/batch_trigger_limit.py+++ b/products/workflows/backend/utils/batch_trigger_limit.py@@ -1,7 +1,53 @@from django.conf import settings+from products.workflows.backend.utils.email_sending_tiers import (+ email_sending_tier_mode,+ resolve_team_email_sending_tier,+)-def get_hogflow_batch_trigger_limit(team_id: int) -> int:+# Kept in sync with _FIXED_TEMPLATE_IDS["function_email"] in products/workflows/backend/api/hog_flow.py.+_EMAIL_TEMPLATE_ID = "template-email"+++def _action_sends_email(action: object) -> bool:+ if not isinstance(action, dict):+ return False+ if action.get("type") == "function_email":+ return True+ # The worker executes function steps by template, not by declared type, so any step carrying+ # the email template sends email regardless of what its type claims. Keying on the template id+ # closes the whole class of mislabeled-step bypasses at once.+ config = action.get("config")+ return isinstance(config, dict) and config.get("template_id") == _EMAIL_TEMPLATE_ID+++def hog_flow_sends_email(actions: object) -> bool:+ """Whether a workflow's action list contains an email step. The email sending tiers exist to+ protect the shared SES account, so only workflows that send email are subject to them. Typed+ `object` because the input is a JSONField whose shape the isinstance checks establish."""+ if not isinstance(actions, list):+ return False+ return any(_action_sends_email(action) for action in actions)+++def get_hogflow_batch_trigger_limit(team_id: int, *, sends_email: bool = True) -> int:+ """+ Maximum audience size for this team's batch triggers.++ Once the trust tiers are enforced the limit comes from the team's tier, so a team that has not+ sent cleanly yet cannot queue a blast large enough to hurt the shared SES account. The tier+ only applies when the workflow sends email; SMS, push, and webhook batches keep the flat+ ceiling because they cannot touch SES reputation. `sends_email` defaults to True so a caller+ that cannot see the workflow fails toward the capped side. Teams on the pre-tier allowlist+ keep the elevated ceiling, and while the rollout mode is not "enforce" every team keeps the+ flat ceiling it had before tiers existed.+ """if team_id in settings.HOGFLOW_BATCH_TRIGGER_ELEVATED_TEAM_IDS:return settings.HOGFLOW_BATCH_TRIGGER_LIMIT_ELEVATED- return settings.HOGFLOW_BATCH_TRIGGER_LIMIT+ if not sends_email or email_sending_tier_mode() != "enforce":+ return settings.HOGFLOW_BATCH_TRIGGER_LIMIT++ resolved = resolve_team_email_sending_tier(team_id)+ if not resolved.enforced:+ return settings.HOGFLOW_BATCH_TRIGGER_LIMIT+ return resolved.limits.max_batch_audiencediff --git a/products/workflows/backend/utils/email_sending_tiers.py b/products/workflows/backend/utils/email_sending_tiers.pynew file mode 100644index 000000000000..6e0307760af6--- /dev/null+++ b/products/workflows/backend/utils/email_sending_tiers.py@@ -0,0 +1,199 @@+from datetime import UTC, datetime+from typing import Literal, Optional++from django.conf import settings+from django.utils.dateparse import parse_datetime++import structlog++from posthog.dataclasses import frozen+from posthog.models.team import Team++from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig++logger = structlog.get_logger(__name__)++TierMode = Literal["off", "shadow", "enforce"]++MIN_EMAIL_SENDING_TIER = 0+++@frozen+class EmailSendingTierLimits:+ """What a trust tier allows: two send-rate caps and a maximum batch audience."""++ tier: int+ per_hour: int+ per_day: int+ max_batch_audience: int+++@frozen+class TeamEmailSendingTier:+ tier: int+ pinned: bool+ limits: EmailSendingTierLimits+ # False while the rollout mode is "off" or "shadow", or while enforcement is narrowed to teams+ # created after a cutoff this team predates. Callers must fall back to pre-tier behavior.+ enforced: bool+++def email_sending_tier_mode() -> TierMode:+ """Rollout mode. An unrecognized value reads as "off" so a typo cannot start throttling teams."""+ mode = str(settings.WORKFLOWS_EMAIL_TIER_MODE or "").strip().lower()+ if mode == "shadow":+ return "shadow"+ if mode == "enforce":+ return "enforce"+ return "off"+++def max_email_sending_tier() -> int:+ return _tier_count() - 1+++def min_days_at_tier(tier: int) -> int:+ """Days a team must hold `tier` before it can be promoted off it. Clamped into the configured+ list so a partial env override cannot raise on a high tier."""+ days = settings.WORKFLOWS_EMAIL_TIER_MIN_DAYS_AT_TIER+ if not days:+ return 0+ return int(days[min(max(tier, 0), len(days) - 1)])+++def _tier_count() -> int:+ # The shortest list wins so a partial env override cannot index past the end of another table.+ return min(+ len(settings.WORKFLOWS_EMAIL_TIER_HOURLY_CAPS),+ len(settings.WORKFLOWS_EMAIL_TIER_DAILY_CAPS),+ len(settings.WORKFLOWS_EMAIL_TIER_BATCH_AUDIENCE_CAPS),+ )+++def get_email_sending_tier_limits(tier: int) -> EmailSendingTierLimits:+ """+ Caps for a tier, clamped into the configured table.++ An unusable table (an env override that emptied one of the lists) falls back to the pre-tier+ ceiling rather than to a small number. Misconfiguration must never throttle a paying customer.+ """+ count = _tier_count()+ if count <= 0:+ logger.warning("workflows_email_tier_table_empty", tier=tier)+ elevated = settings.HOGFLOW_BATCH_TRIGGER_LIMIT_ELEVATED+ return EmailSendingTierLimits(+ tier=tier,+ per_hour=elevated,+ per_day=elevated,+ max_batch_audience=elevated,+ )++ clamped = min(max(tier, MIN_EMAIL_SENDING_TIER), count - 1)+ return EmailSendingTierLimits(+ tier=clamped,+ per_hour=settings.WORKFLOWS_EMAIL_TIER_HOURLY_CAPS[clamped],+ per_day=settings.WORKFLOWS_EMAIL_TIER_DAILY_CAPS[clamped],+ max_batch_audience=settings.WORKFLOWS_EMAIL_TIER_BATCH_AUDIENCE_CAPS[clamped],+ )+++def _enforcement_cutoff_raw() -> str:+ return str(settings.WORKFLOWS_EMAIL_TIER_ENFORCE_TEAMS_CREATED_AFTER or "").strip()+++def _enforcement_cutoff() -> Optional[datetime]:+ raw = _enforcement_cutoff_raw()+ if not raw:+ return None+ # Read on the send path, so a typo in the env var must not raise here.+ try:+ parsed = parse_datetime(raw)+ except ValueError:+ parsed = None+ if parsed is None:+ logger.warning("workflows_email_tier_cutoff_unparseable", value=raw)+ return None+ # A bare date ("2026-01-01") parses to a naive datetime, while the team creation dates it is+ # compared against are UTC-aware. Read a naive cutoff as UTC instead of raising on the compare.+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)+++def is_tier_enforced_for_team(team_created_at: Optional[datetime]) -> bool:+ if email_sending_tier_mode() != "enforce":+ return False+ cutoff = _enforcement_cutoff()+ if cutoff is None:+ # An empty cutoff enforces every team. A set but unparseable cutoff must not, because an+ # operator typo has to narrow enforcement rather than widen it to everyone. This matches+ # email_sending_tier_mode(), which reads an unrecognized value as "off", and the module's+ # rule that a config problem must never throttle a paying customer.+ return not _enforcement_cutoff_raw()+ # An unknown creation date reads as "not after the cutoff": the cutoff exists to spare+ # established teams, so an unresolvable team must land on the established side.+ return team_created_at is not None and team_created_at >= cutoff+++def resolve_team_email_sending_tier(team_id: int) -> TeamEmailSendingTier:+ """+ A team's stored tier plus the caps it maps to.++ Fails open: any lookup problem reads as the top tier, matching TeamWorkflowsConfigService in the+ email worker. A config blip must not throttle a legitimate customer.+ """+ top_tier = max(max_email_sending_tier(), MIN_EMAIL_SENDING_TIER)+ # The guard wraps the whole resolution, not just the first query: the allowlist and no-row+ # branches run their own creation-date lookup, and a database blip there must fail open too+ # rather than crash the send path.+ try:+ return _resolve_team_email_sending_tier(team_id, top_tier)+ except Exception:+ logger.exception("workflows_email_tier_lookup_failed", team_id=team_id)+ return TeamEmailSendingTier(+ tier=top_tier,+ pinned=False,+ limits=get_email_sending_tier_limits(top_tier),+ enforced=False,+ )+++def _resolve_team_email_sending_tier(team_id: int, top_tier: int) -> TeamEmailSendingTier:+ row = (+ TeamWorkflowsConfig.objects.filter(team_id=team_id)+ .values("email_sending_tier", "email_sending_tier_pinned", "team__created_at")+ .first()+ )++ if team_id in settings.HOGFLOW_BATCH_TRIGGER_ELEVATED_TEAM_IDS:+ # The pre-tier allowlist keeps working as a staff pin at the top tier.+ return TeamEmailSendingTier(+ tier=top_tier,+ pinned=True,+ limits=get_email_sending_tier_limits(top_tier),+ enforced=is_tier_enforced_for_team(row["team__created_at"] if row else _team_created_at(team_id)),+ )++ if row is None:+ # No row means the team never touched a workflows setting, so it starts at tier 0. Reading+ # the creation date still matters: enforcement can be narrowed to teams created after a+ # cutoff, and a team without a row can sit on either side of it.+ tier = MIN_EMAIL_SENDING_TIER+ pinned = False+ created_at = _team_created_at(team_id)+ else:+ tier = row["email_sending_tier"]+ pinned = row["email_sending_tier_pinned"]+ created_at = row["team__created_at"]++ return TeamEmailSendingTier(+ tier=tier,+ pinned=pinned,+ limits=get_email_sending_tier_limits(tier),+ enforced=is_tier_enforced_for_team(created_at),+ )+++def _team_created_at(team_id: int) -> Optional[datetime]:+ if _enforcement_cutoff() is None:+ # Without a cutoff the date changes nothing, so skip the query.+ return None+ return Team.objects.filter(id=team_id).values_list("created_at", flat=True).first()diff --git a/products/workflows/backend/utils/test_batch_trigger_limit.py b/products/workflows/backend/utils/test_batch_trigger_limit.pyindex 6d60daf7e615..5bb06288f83b 100644--- a/products/workflows/backend/utils/test_batch_trigger_limit.py+++ b/products/workflows/backend/utils/test_batch_trigger_limit.py@@ -1,6 +1,16 @@+from posthog.test.base import BaseTest+from unittest.mock import patch+from django.test import TestCase, override_settings-from products.workflows.backend.utils.batch_trigger_limit import get_hogflow_batch_trigger_limit+from parameterized import parameterized++from posthog.models.team import Team++from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig+from products.workflows.backend.utils.batch_trigger_limit import get_hogflow_batch_trigger_limit, hog_flow_sends_email++TIER_BATCH_CAPS = [100, 1000, 3000, 10000, 30000, 100000, 300000, 1000000]class TestGetHogflowBatchTriggerLimit(TestCase):@@ -40,3 +50,104 @@ class TestGetHogflowBatchTriggerLimit(TestCase):# production tweak via env var is reflected immediately.assert get_hogflow_batch_trigger_limit(42) == 456assert get_hogflow_batch_trigger_limit(1) == 123+++@override_settings(+ HOGFLOW_BATCH_TRIGGER_LIMIT=5000,+ HOGFLOW_BATCH_TRIGGER_LIMIT_ELEVATED=50000,+ HOGFLOW_BATCH_TRIGGER_ELEVATED_TEAM_IDS=set(),+ WORKFLOWS_EMAIL_TIER_BATCH_AUDIENCE_CAPS=TIER_BATCH_CAPS,+)+class TestTieredHogflowBatchTriggerLimit(BaseTest):+ @parameterized.expand([(tier, cap) for tier, cap in enumerate(TIER_BATCH_CAPS)])+ @override_settings(WORKFLOWS_EMAIL_TIER_MODE="enforce")+ def test_enforced_limit_follows_the_teams_tier(self, tier: int, expected_cap: int) -> None:+ TeamWorkflowsConfig.objects.update_or_create(team=self.team, defaults={"email_sending_tier": tier})+ assert get_hogflow_batch_trigger_limit(self.team.id) == expected_cap++ @parameterized.expand([("off",), ("shadow",)])+ def test_limit_stays_flat_until_the_mode_is_enforce(self, mode: str) -> None:+ TeamWorkflowsConfig.objects.update_or_create(team=self.team, defaults={"email_sending_tier": 0})+ with override_settings(WORKFLOWS_EMAIL_TIER_MODE=mode):+ assert get_hogflow_batch_trigger_limit(self.team.id) == 5000++ @override_settings(WORKFLOWS_EMAIL_TIER_MODE="enforce")+ def test_allowlisted_team_keeps_the_elevated_limit_regardless_of_tier(self) -> None:+ TeamWorkflowsConfig.objects.update_or_create(team=self.team, defaults={"email_sending_tier": 0})+ with override_settings(HOGFLOW_BATCH_TRIGGER_ELEVATED_TEAM_IDS={self.team.id}):+ assert get_hogflow_batch_trigger_limit(self.team.id) == 50000++ @override_settings(+ WORKFLOWS_EMAIL_TIER_MODE="enforce",+ WORKFLOWS_EMAIL_TIER_ENFORCE_TEAMS_CREATED_AFTER="2099-01-01",+ )+ def test_team_created_before_the_cutoff_keeps_the_flat_limit(self) -> None:+ TeamWorkflowsConfig.objects.update_or_create(team=self.team, defaults={"email_sending_tier": 0})+ assert get_hogflow_batch_trigger_limit(self.team.id) == 5000++ @override_settings(+ WORKFLOWS_EMAIL_TIER_MODE="enforce",+ WORKFLOWS_EMAIL_TIER_ENFORCE_TEAMS_CREATED_AFTER="not-a-date",+ )+ def test_unparseable_cutoff_does_not_enforce_globally(self) -> None:+ # A typo in the cutoff must fail open. It cannot silently widen enforcement to every team,+ # so an unparseable value leaves the team on the flat ceiling instead of the tier-0 cap.+ TeamWorkflowsConfig.objects.update_or_create(team=self.team, defaults={"email_sending_tier": 0})+ assert get_hogflow_batch_trigger_limit(self.team.id) == 5000++ @override_settings(+ WORKFLOWS_EMAIL_TIER_MODE="enforce",+ WORKFLOWS_EMAIL_TIER_ENFORCE_TEAMS_CREATED_AFTER="2020-01-01",+ )+ def test_a_database_error_during_resolution_fails_open(self) -> None:+ # The creation-date lookup runs outside the first config query, so the fail-open guard must+ # cover the whole resolution: a database blip on the send path returns the flat limit+ # instead of raising.+ TeamWorkflowsConfig.objects.filter(team=self.team).delete()+ with patch(+ "products.workflows.backend.utils.email_sending_tiers.Team.objects.filter",+ side_effect=Exception("db down"),+ ):+ assert get_hogflow_batch_trigger_limit(self.team.id) == 5000++ @override_settings(WORKFLOWS_EMAIL_TIER_MODE="enforce")+ def test_a_workflow_without_an_email_step_keeps_the_flat_limit(self) -> None:+ # The tiers protect SES reputation, so an SMS or push batch must not inherit the email cap.+ TeamWorkflowsConfig.objects.update_or_create(team=self.team, defaults={"email_sending_tier": 0})+ assert get_hogflow_batch_trigger_limit(self.team.id, sends_email=False) == 5000+ assert get_hogflow_batch_trigger_limit(self.team.id, sends_email=True) == TIER_BATCH_CAPS[0]++ @parameterized.expand(+ [+ ("an email step", [{"type": "function_email"}], True),+ (+ "the email template on a generic function step",+ [{"type": "function", "config": {"template_id": "template-email"}}],+ True,+ ),+ (+ "the email template on a mislabeled sms step",+ [{"type": "function_sms", "config": {"template_id": "template-email"}}],+ True,+ ),+ (+ "a webhook template on a generic function step",+ [{"type": "function", "config": {"template_id": "template-webhook"}}],+ False,+ ),+ ("only sms and delay steps", [{"type": "function_sms"}, {"type": "delay"}], False),+ ("a non-list actions value", None, False),+ ]+ )+ def test_email_step_detection(self, _name: str, actions: object, expected: bool) -> None:+ # The serializer accepts the email template on a generic function step and the worker+ # executes it, so the detector must not key on the declared type alone.+ assert hog_flow_sends_email(actions) is expected++ @override_settings(WORKFLOWS_EMAIL_TIER_MODE="enforce")+ def test_team_without_a_config_row_is_treated_as_tier_zero(self) -> None:+ # A brand-new project has no workflows config row yet, and it must land on the lowest tier+ # rather than on the flat ceiling.+ team = Team.objects.create(organization=self.organization, name="no config")+ TeamWorkflowsConfig.objects.filter(team=team).delete()+ assert get_hogflow_batch_trigger_limit(team.id) == TIER_BATCH_CAPS[0]