: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): cap workflow email per team by earned sending tier (#89856)
Meikel Ratzc9a591638d4d
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 7c02d81822f7..c34002267316 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -6733,12 +6733,13 @@ const api = {},async getBatchTriggerBlastRadius(filters: Extract<HogFlowAction['config'], { type: 'batch' }>['filters'],- dedupeKey?: 'email'+ dedupeKey?: 'email',+ sendsEmail?: boolean): Promise<BlastRadiusApi> {return await new ApiRequest().hogFlows().withAction('user_blast_radius')- .create({ data: { filters, dedupe_key: dedupeKey ?? null } })+ .create({ data: { filters, dedupe_key: dedupeKey ?? null, sends_email: sendsEmail ?? true } })},async createHogFlowBatchJob(hogFlowId: HogFlow['id'],diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex cf5c32387573..720733bddb44 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -33,7 +33,7 @@ import { RecipientsManagerService } from './services/managers/recipients-managerimport { TeamWorkflowsConfigService } from './services/managers/team-workflows-config.service'import { EmailSuppressionService } from './services/messaging/email-suppression.service'import { EmailValidationService } from './services/messaging/email-validation.service'-import { EmailService } from './services/messaging/email.service'+import { EmailService, parseTeamEmailCapMode, parseTierCaps } from './services/messaging/email.service'import { EmailTrackingCodeSigner } from './services/messaging/helpers/tracking-code'import { MessageAssetsService } from './services/messaging/message-assets.service'import { PushNotificationService } from './services/messaging/push-notification.service'@@ -156,6 +156,10 @@ export type CdpCoreServicesConfig = Pick<| 'SES_TRACKED_CONFIGURATION_SET'| 'SES_UNTRACKED_CONFIGURATION_SET'| 'EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD'+ | 'EMAIL_TEAM_SENDING_CAP_MODE'+ | 'EMAIL_TEAM_SENDING_CAP_HOURLY_BY_TIER'+ | 'EMAIL_TEAM_SENDING_CAP_DAILY_BY_TIER'+ | 'EMAIL_TEAM_SENDING_CAP_TEAMS_CREATED_AFTER'| 'CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN'| 'CONVERSATIONS_TICKETS_JWT_SECRET'| 'CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET'@@ -421,6 +425,11 @@ export function createCdpCoreServices(const workflowEmailRateLimiter = deps.emailValidationValkey? new RateLimiterService(deps.emailValidationValkey, { name: 'workflow-email' }): null+ // Separate limiter instance from the per-workflow one so the two show up under different+ // `limiter` labels on the shared claim metrics. Same Valkey pool, different bucket keys.+ const teamEmailRateLimiter = deps.emailValidationValkey+ ? new RateLimiterService(deps.emailValidationValkey, { name: 'team-email' })+ : nullconst emailService = new EmailService({sesAccessKeyId: config.SES_ACCESS_KEY_ID,@@ -429,6 +438,10 @@ export function createCdpCoreServices(sesEndpoint: config.SES_ENDPOINT,sesTrackedConfigurationSet: config.SES_TRACKED_CONFIGURATION_SET,sesUntrackedConfigurationSet: config.SES_UNTRACKED_CONFIGURATION_SET,+ teamEmailCapMode: parseTeamEmailCapMode(config.EMAIL_TEAM_SENDING_CAP_MODE),+ teamEmailTierHourlyCaps: parseTierCaps(config.EMAIL_TEAM_SENDING_CAP_HOURLY_BY_TIER),+ teamEmailTierDailyCaps: parseTierCaps(config.EMAIL_TEAM_SENDING_CAP_DAILY_BY_TIER),+ teamEmailCapTeamsCreatedAfter: config.EMAIL_TEAM_SENDING_CAP_TEAMS_CREATED_AFTER,},deps.integrationManager,teamWorkflowsConfigService,@@ -438,7 +451,8 @@ export function createCdpCoreServices(emailSuppressionService,recipientsManager,messageAssetsService,- workflowEmailRateLimiter+ workflowEmailRateLimiter,+ teamEmailRateLimiter)const recipientTokensService = new RecipientTokensService(config.ENCRYPTION_SALT_KEYS, config.SITE_URL)const hogInputsService = new HogInputsService(deps.integrationManager, recipientTokensService, deps.encryptedFields)diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex a46f29a50fae..80c56981dfea 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -139,6 +139,21 @@ export type CdpConfig = ClickhouseConfig & {// Consecutive soft bounces before an address is auto-suppressed. Tunable without a deploy.EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD: number+ // Trust-tiered per-team workflow email caps ("team warming"). A team's tier, stored by the+ // Django side, picks an hourly and a daily cap from these tables. See+ // WORKFLOWS_EMAIL_TIER_* in posthog/settings/web.py, which must stay in step with them.+ // "off" - the caps are not consulted.+ // "shadow" - the caps are evaluated and every send they would delay is logged and counted,+ // but nothing is delayed.+ // "enforce" - a reached cap reschedules the send.+ EMAIL_TEAM_SENDING_CAP_MODE: string+ // Comma-separated caps indexed by tier. Both lists must be the same length.+ EMAIL_TEAM_SENDING_CAP_HOURLY_BY_TIER: string+ EMAIL_TEAM_SENDING_CAP_DAILY_BY_TIER: string+ // ISO date. When set, only teams created on or after it are capped, so enforcement can start+ // with new projects and leave established ones alone. Empty means every team.+ EMAIL_TEAM_SENDING_CAP_TEAMS_CREATED_AFTER: string+// Destination migration diffingDESTINATION_MIGRATION_DIFFING_ENABLED: boolean@@ -321,6 +336,13 @@ export function getDefaultCdpConfig(): CdpConfig {SES_ALLOWED_SNS_TOPIC_ARNS: '',EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD: 5,+ // Ships dark: tiers are computed and stored first, then observed in shadow mode, and only+ // then enforced. Match the defaults in posthog/settings/web.py.+ EMAIL_TEAM_SENDING_CAP_MODE: 'off',+ EMAIL_TEAM_SENDING_CAP_HOURLY_BY_TIER: '50,200,600,2000,6000,20000,60000,200000',+ EMAIL_TEAM_SENDING_CAP_DAILY_BY_TIER: '100,1000,3000,10000,30000,100000,300000,1000000',+ EMAIL_TEAM_SENDING_CAP_TEAMS_CREATED_AFTER: '',+// Destination migration diffingDESTINATION_MIGRATION_DIFFING_ENABLED: false,diff --git a/nodejs/src/cdp/services/managers/team-workflows-config.service.ts b/nodejs/src/cdp/services/managers/team-workflows-config.service.tsindex e7c93cb12131..3622974e2c98 100644--- a/nodejs/src/cdp/services/managers/team-workflows-config.service.ts+++ b/nodejs/src/cdp/services/managers/team-workflows-config.service.ts@@ -17,6 +17,10 @@ export type TeamWorkflowsConfig = {email_tracking_consent_mode: EmailTrackingConsentModeemail_sending_suspended: booleanses_tenant_provider_suspended: boolean+ /** Trust tier that picks the team's hourly and daily workflow email caps. */+ email_sending_tier: number+ /** Creation date of the team, so enforcement can be narrowed to teams created after a cutoff. */+ team_created_at: string | null}const DEFAULT_CONFIG: TeamWorkflowsConfig = {@@ -24,6 +28,13 @@ const DEFAULT_CONFIG: TeamWorkflowsConfig = {email_tracking_consent_mode: 'off',email_sending_suspended: false,ses_tenant_provider_suspended: false,+ email_sending_tier: 0,+ team_created_at: null,+}++export type TeamEmailSendingTier = {+ tier: number+ teamCreatedAt: string | null}/**@@ -88,22 +99,44 @@ export class TeamWorkflowsConfigService {}}+ /**+ * Trust tier for the team's workflow email, which the send path turns into an hourly and a+ * daily cap. Fails open with `null`: a lookup error must let the send through rather than+ * throttle a legitimate customer, same stance as `isEmailSendingSuspended`.+ */+ public async getEmailSendingTier(teamId: number): Promise<TeamEmailSendingTier | null> {+ try {+ const config = await this.get(teamId)+ return { tier: config.email_sending_tier, teamCreatedAt: config.team_created_at }+ } catch (error) {+ logger.error('[TeamWorkflowsConfig] Failed to read email sending tier', { teamId, error })+ return null+ }+ }+private async fetchConfigs(teamIds: string[]): Promise<Record<string, TeamWorkflowsConfig>> {+ // Joined to posthog_team rather than read separately: the tier cap can be scoped to teams+ // created after a cutoff, and the send path needs both values in the same cached entry.const result = await this.postgres.query<{team_id: numbercapture_workflows_engagement_events: booleanemail_tracking_consent_mode: EmailTrackingConsentModeemail_sending_suspended: booleanses_tenant_provider_suspended: boolean+ email_sending_tier: number+ team_created_at: string | null}>(PostgresUse.COMMON_READ,// Only DISABLED blocks: ENABLED and REINSTATED both permit sending, and '' means the// tenant state has never been synced for this team.- `SELECT team_id, capture_workflows_engagement_events, email_tracking_consent_mode,- email_sending_suspended_at IS NOT NULL AS email_sending_suspended,- ses_tenant_sending_status = 'DISABLED' AS ses_tenant_provider_suspended- FROM workflows_teamworkflowsconfig- WHERE team_id = ANY($1)`,+ `SELECT c.team_id, c.capture_workflows_engagement_events, c.email_tracking_consent_mode,+ c.email_sending_suspended_at IS NOT NULL AS email_sending_suspended,+ c.ses_tenant_sending_status = 'DISABLED' AS ses_tenant_provider_suspended,+ c.email_sending_tier,+ t.created_at AS team_created_at+ FROM workflows_teamworkflowsconfig c+ LEFT JOIN posthog_team t ON t.id = c.team_id+ WHERE c.team_id = ANY($1)`,[teamIds.map(Number)],'fetch-team-workflows-configs')@@ -118,6 +151,8 @@ export class TeamWorkflowsConfigService {email_tracking_consent_mode: row.email_tracking_consent_mode ?? 'off',email_sending_suspended: row.email_sending_suspended,ses_tenant_provider_suspended: row.ses_tenant_provider_suspended,+ email_sending_tier: row.email_sending_tier ?? 0,+ team_created_at: row.team_created_at ?? null,}}return configsdiff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.tsindex c26d4b4b197f..edad30cc77a5 100644--- a/nodejs/src/cdp/services/messaging/email-tracking.service.ts+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.ts@@ -239,6 +239,7 @@ export class EmailTrackingService {instanceIdOverride,deferFlush = false,workflowVersion,+ verifiedTeamId,}: {functionId?: stringinvocationId?: string@@ -254,6 +255,10 @@ export class EmailTrackingService {// and pay a single broker round-trip. The caller owns flushing when it sets this.deferFlush?: booleanworkflowVersion?: number+ // Team id from a signature-verified tracking code. Lets the metric survive the deletion+ // of its workflow: sends are recorded at send time, so dropping the delayed complaint and+ // bounce feedback here would make the team's rates read cleaner than they are.+ verifiedTeamId?: string}): Promise<void> {if (!functionId || !invocationId) {logger.error('[EmailTrackingService] trackMetric: Invalid custom ID', {@@ -271,17 +276,34 @@ export class EmailTrackingService {this.hogFlowManager.getHogFlow(functionId).catch(() => null),])- const teamId = hogFunction?.team_id ?? hogFlow?.team_id- const appSourceId = hogFunction?.id ?? hogFlow?.id+ let teamId = hogFunction?.team_id ?? hogFlow?.team_id+ let appSourceId = hogFunction?.id ?? hogFlow?.idif (!teamId || !appSourceId) {- logger.error('[EmailTrackingService] trackMetric: Hog function or flow not found', {- functionId,- invocationId,- source,- })- emailTrackingErrorsCounter.inc({ error_type: 'hog_function_or_flow_not_found', source })- return+ const fallbackTeamId = Number(verifiedTeamId)+ if (Number.isInteger(fallbackTeamId) && fallbackTeamId > 0) {+ // The workflow row is gone (deleting a finished campaign is routine housekeeping),+ // but its sends were recorded at send time, so dropping the delayed complaint and+ // bounce feedback would make the team read cleaner than it is to everything that+ // sums team totals, including the sending tiers. The tracking code is signed, so+ // its team and function ids are trustworthy without the row.+ logger.warn('[EmailTrackingService] trackMetric: recording for a deleted function or flow', {+ functionId,+ invocationId,+ source,+ })+ emailTrackingErrorsCounter.inc({ error_type: 'hog_function_or_flow_deleted', source })+ teamId = fallbackTeamId+ appSourceId = functionId+ } else {+ logger.error('[EmailTrackingService] trackMetric: Hog function or flow not found', {+ functionId,+ invocationId,+ source,+ })+ emailTrackingErrorsCounter.inc({ error_type: 'hog_function_or_flow_not_found', source })+ return+ }}this.hogFunctionMonitoringService.queueAppMetric(@@ -434,6 +456,7 @@ export class EmailTrackingService {instanceIdOverride: metric.instanceIdOverride,deferFlush: true,workflowVersion: metric.workflowVersion,+ verifiedTeamId: metric.teamId,})}if (metrics?.length) {diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.tsindex 4361e19081b3..ad73d0f11f16 100644--- a/nodejs/src/cdp/services/messaging/email.service.ts+++ b/nodejs/src/cdp/services/messaging/email.service.ts@@ -100,7 +100,7 @@ function parseWorkflowEmailRateLimit(metadata: HogFunctionType['metadata']): Hogreturn parsed.success ? parsed.data : null}-function pickWorkflowRateLimitRetryDelayMs(refillPerSecond: number): number {+function pickTokenBucketRetryDelayMs(refillPerSecond: number): number {// Wake around when the next token accrues. The 1x-2x jitter spreads a queued backlog's// retries so they don't all re-dequeue (and re-claim against one token) at the same instant.// Clamped so second-scale limits don't churn the queue and hour-scale limits still wake@@ -110,6 +110,84 @@ function pickWorkflowRateLimitRetryDelayMs(refillPerSecond: number): number {return Math.floor(baseMs * (1 + Math.random()))}+const teamEmailCapDelayedTotal = new Counter({+ name: 'cdp_team_email_cap_delayed_total',+ help: 'Workflow email sends delayed by the team trust-tier sending cap (or that would have been, in shadow mode).',+ labelNames: ['tier', 'bucket', 'mode'],+})++/**+ * Rollout mode for the per-team sending cap.+ * - `off`: the cap is not consulted at all.+ * - `shadow`: the cap is evaluated and every send it would delay is counted and logged, but no+ * send is delayed. This is how the tier distribution is checked against real traffic before+ * anything is enforced.+ * - `enforce`: a denied claim reschedules the send.+ */+export type TeamEmailCapMode = 'off' | 'shadow' | 'enforce'++/** An unrecognized mode reads as `off`, so a typo in the env cannot start throttling teams. */+export function parseTeamEmailCapMode(value: string | undefined): TeamEmailCapMode {+ const mode = (value ?? '').trim().toLowerCase()+ return mode === 'shadow' || mode === 'enforce' ? mode : 'off'+}++/** Parses a comma-separated cap table. Any unusable entry drops the whole table, which turns the+ * cap off rather than applying a wrong number to a paying customer. */+export function parseTierCaps(value: string | undefined): number[] {+ const parts = (value ?? '')+ .split(',')+ .map((part) => part.trim())+ .filter((part) => part.length > 0)+ const caps = parts.map((part) => Number(part))+ if (caps.length === 0 || caps.some((cap) => !Number.isFinite(cap) || cap <= 0)) {+ return []+ }+ return caps+}++// Mirrors WORKFLOWS_EMAIL_TIER_HOURLY_CAPS / _DAILY_CAPS in posthog/settings/web.py. Both sides+// read the same tier index, so the two tables must stay in step.+const DEFAULT_TEAM_EMAIL_TIER_HOURLY_CAPS = [50, 200, 600, 2000, 6000, 20000, 60000, 200000]+const DEFAULT_TEAM_EMAIL_TIER_DAILY_CAPS = [100, 1000, 3000, 10000, 30000, 100000, 300000, 1000000]++// Comfortably longer than the window each bucket paces, so an idle bucket is never reset to full+// by expiry before it would have refilled on its own. Without that, a team that pauses for a day+// would get a fresh daily allowance instead of waiting for the refill.+const TEAM_EMAIL_HOUR_BUCKET_TTL_SECONDS = 6 * 60 * 60+const TEAM_EMAIL_DAY_BUCKET_TTL_SECONDS = 3 * 24 * 60 * 60++type TeamEmailCapBucket = {+ name: 'hour' | 'day'+ key: string+ capacity: number+ refillPerSecond: number+ ttlSeconds: number+ /** Cap and period as the customer sees them in the log line. */+ label: string+}++function teamEmailCapBuckets(teamId: number, hourlyCap: number, dailyCap: number): TeamEmailCapBucket[] {+ return [+ {+ name: 'hour',+ key: `@posthog/team-email-rate-hour/${teamId}`,+ capacity: hourlyCap,+ refillPerSecond: hourlyCap / 3600,+ ttlSeconds: TEAM_EMAIL_HOUR_BUCKET_TTL_SECONDS,+ label: `${hourlyCap.toLocaleString('en-US')} emails per hour`,+ },+ {+ name: 'day',+ key: `@posthog/team-email-rate-day/${teamId}`,+ capacity: dailyCap,+ refillPerSecond: dailyCap / 86400,+ ttlSeconds: TEAM_EMAIL_DAY_BUCKET_TTL_SECONDS,+ label: `${dailyCap.toLocaleString('en-US')} emails per day`,+ },+ ]+}+export interface EmailServiceConfig {sesAccessKeyId: stringsesSecretAccessKey: string@@ -120,6 +198,14 @@ export interface EmailServiceConfig {// Configuration set without open/click tracking. Empty means not provisioned: tracking-off// sends fall back to the tracked set (with a warning) rather than failing.sesUntrackedConfigurationSet: string+ // Trust-tiered per-team sending caps. Optional and defaulting to off, so every send path that+ // builds an EmailService without them keeps its pre-cap behavior.+ teamEmailCapMode?: TeamEmailCapMode+ teamEmailTierHourlyCaps?: number[]+ teamEmailTierDailyCaps?: number[]+ // ISO date. When set, only teams created on or after it are capped, so the caps can be turned+ // on for new projects without touching established ones. Empty means every team.+ teamEmailCapTeamsCreatedAfter?: string}/**@@ -188,7 +274,8 @@ export class EmailService {private emailSuppressionService: EmailSuppressionService,private recipientsManager: RecipientsManagerService,private messageAssetsService?: MessageAssetsService,- private workflowEmailRateLimiter: RateLimiterService | null = null+ private workflowEmailRateLimiter: RateLimiterService | null = null,+ private teamEmailRateLimiter: RateLimiterService | null = null) {this.sesV2Client = this.sesConfig.sesRegion? new SESv2Client({@@ -334,7 +421,7 @@ export class EmailService {// send. Mirrors the fetch-retry (`result.invocation.queueParameters = params`) and// queue-routing paths, which re-attach the same way.result.invocation.queueParameters = params- const retryDelayMs = pickWorkflowRateLimitRetryDelayMs(refillPerSecond)+ const retryDelayMs = pickTokenBucketRetryDelayMs(refillPerSecond)result.invocation.queueScheduledAt = DateTime.utc().plus({ milliseconds: retryDelayMs })addLog('info',@@ -344,6 +431,27 @@ export class EmailService {}}+ // Project-wide pacing from the team's trust tier. Sits next to the per-workflow limit+ // above and behaves the same way: it delays, never drops, and test sends bypass it.+ // Charged per recipient, not per send: SES counts every to/cc/bcc address against its+ // own quota, so a send with many copies must spend that many tokens.+ const capRecipients =+ 1 + extractEmailsFromAddressList(params.cc).length + extractEmailsFromAddressList(params.bcc).length+ const capDelay = await this.claimTeamSendingBudget(invocation, isTest, capRecipients)+ if (capDelay) {+ result.finished = false+ // Re-attach the email payload before rescheduling, for the same reason as the+ // per-workflow limit above: createInvocationResult cleared queueParameters, and+ // without them the rescheduled dequeue resumes the Hog VM and drops the send.+ result.invocation.queueParameters = params+ result.invocation.queueScheduledAt = DateTime.utc().plus({ milliseconds: capDelay.retryDelayMs })+ addLog(+ 'info',+ `This project reached its email sending limit of ${capDelay.label}. Retrying this email in ${Math.round(capDelay.retryDelayMs / 1000)}s. The limit rises as the project builds a clean sending history.`+ )+ return result+ }+switch (integration.config.provider ?? 'ses') {case 'maildev':await this.sendEmailWithMaildev(result, params, from, trackingEnabled, isTest)@@ -453,6 +561,116 @@ export class EmailService {return result}+ /**+ * Claims one send (as `recipients` tokens, one per delivered copy) against the team's+ * trust-tier buckets.+ *+ * Returns the delay to reschedule with when a cap is reached, or null when the send may go out.+ * Two buckets, not one: the daily cap bounds how much damage a team can do to the shared SES+ * account's reputation, and the hourly cap forces that volume to spread out so complaint+ * feedback (which lags by hours) arrives while the team's total volume is still small.+ *+ * Failure stances differ on purpose. A failed tier lookup lets the send through, because a+ * config blip must never throttle a legitimate customer. A failed bucket claim returns 0 from+ * the limiter, which delays the send, because we must not send when we cannot account for it.+ */+ private async claimTeamSendingBudget(+ invocation: CyclotronJobInvocationHogFunction,+ isTest: boolean,+ recipients: number = 1+ ): Promise<{ retryDelayMs: number; label: string } | null> {+ const mode: TeamEmailCapMode = this.sesConfig.teamEmailCapMode ?? 'off'+ if (mode === 'off' || isTest || !this.teamEmailRateLimiter) {+ return null+ }++ const teamTier = await this.teamWorkflowsConfigService.getEmailSendingTier(invocation.teamId)+ if (!teamTier || !this.teamEmailCapApplies(teamTier.teamCreatedAt)) {+ return null+ }++ const hourlyCaps = this.sesConfig.teamEmailTierHourlyCaps?.length+ ? this.sesConfig.teamEmailTierHourlyCaps+ : DEFAULT_TEAM_EMAIL_TIER_HOURLY_CAPS+ const dailyCaps = this.sesConfig.teamEmailTierDailyCaps?.length+ ? this.sesConfig.teamEmailTierDailyCaps+ : DEFAULT_TEAM_EMAIL_TIER_DAILY_CAPS+ const topTier = Math.min(hourlyCaps.length, dailyCaps.length) - 1+ if (topTier < 0) {+ return null+ }+ const tier = Math.min(Math.max(teamTier.tier, 0), topTier)++ const buckets = teamEmailCapBuckets(invocation.teamId, hourlyCaps[tier], dailyCaps[tier])+ // Clamped to the smaller capacity: a send with more copies than a whole allowance could+ // never be granted and would reschedule forever. It charges the entire bucket instead, so+ // it still waits for full capacity and pays everything there is.+ const requested = Math.min(Math.max(1, recipients), buckets[0].capacity, buckets[1].capacity)++ if (mode === 'enforce') {+ // Both buckets in one atomic claim, granted whole or not at all. A denial consumes+ // nothing, so a rescheduled multi-recipient send cannot burn the partial refill on+ // every retry and starve the team's other emails while never sending itself.+ const claim = await this.teamEmailRateLimiter.claimAllOrNothingPair([buckets[0], buckets[1]], requested)+ if (claim.granted) {+ return null+ }+ const denied = buckets[claim.deniedIndex ?? 1]+ teamEmailCapDelayedTotal.inc({ tier: String(tier), bucket: denied.name, mode })+ return {+ retryDelayMs: pickTokenBucketRetryDelayMs(denied.refillPerSecond),+ label: denied.label,+ }+ }++ // Shadow mode: the send goes out regardless, so drain each bucket by what the send costs+ // and log the first cap that would have delayed it, measuring both against real traffic.+ let firstDenial: TeamEmailCapBucket | null = null+ for (const bucket of buckets) {+ const granted = await this.teamEmailRateLimiter.claimUpTo({+ key: bucket.key,+ requested,+ capacity: bucket.capacity,+ refillPerSecond: bucket.refillPerSecond,+ ttlSeconds: bucket.ttlSeconds,+ })+ if (granted >= requested) {+ continue+ }+ teamEmailCapDelayedTotal.inc({ tier: String(tier), bucket: bucket.name, mode })+ firstDenial = firstDenial ?? bucket+ }++ if (firstDenial) {+ logger.info('📧', 'Team email sending cap would have delayed this send', {+ teamId: invocation.teamId,+ tier,+ bucket: firstDenial.name,+ cap: firstDenial.label,+ })+ }+ return null+ }++ /** Whether the cap applies to a team, given the optional created-after cutoff. */+ private teamEmailCapApplies(teamCreatedAt: string | null): boolean {+ const cutoff = this.sesConfig.teamEmailCapTeamsCreatedAfter?.trim()+ if (!cutoff) {+ return true+ }+ const cutoffMs = Date.parse(cutoff)+ if (Number.isNaN(cutoffMs)) {+ // An unparseable cutoff caps nobody. The cutoff exists to spare established teams, so+ // a bad value must fail towards leaving every team alone.+ return false+ }+ if (!teamCreatedAt) {+ return false+ }+ const createdMs = Date.parse(teamCreatedAt)+ return !Number.isNaN(createdMs) && createdMs >= cutoffMs+ }+// Returns a human-readable log string when any destination address is suppressed for the team,// or null when the send should proceed. Scans to + cc + bcc — SES delivers to every list, so a// suppressed address anywhere blocks the whole send. `cc` and `bcc` can be comma-separateddiff --git a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts b/nodejs/src/cdp/services/messaging/helpers/ses.test.tsindex 1fd38a293fc8..ef55ca12829f 100644--- a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts+++ b/nodejs/src/cdp/services/messaging/helpers/ses.test.ts@@ -59,6 +59,7 @@ describe('SesWebhookHandler', () => {invocationId: 'inv456',actionId: 'act789',distinctId: 'user-123',+ teamId: '1',metricName: 'email_opened',properties: { $email_to: '[email protected]' },timestamp: '2025-10-03T12:01:00Z',@@ -466,6 +467,7 @@ describe('SesWebhookHandler', () => {invocationId: 'inv456',actionId: 'act789',distinctId: 'user-123',+ teamId: '1',metricName: 'email_delivered',properties: { $email_to: '[email protected]' },timestamp: '2025-10-03T12:03:00Z',@@ -746,6 +748,7 @@ describe('SesWebhookHandler', () => {invocationId: 'child-invocation-id',actionId: 'email-action',parentRunId: 'batch-run-id',+ teamId: '1',metricName: 'email_opened',properties: { $email_to: '[email protected]' },timestamp: '2025-10-03T12:01:00Z',diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.ts b/nodejs/src/cdp/services/messaging/helpers/ses.tsindex 10a63c53ca2b..5a02a95227b3 100644--- a/nodejs/src/cdp/services/messaging/helpers/ses.ts+++ b/nodejs/src/cdp/services/messaging/helpers/ses.ts@@ -542,6 +542,7 @@ export class SesWebhookHandler {actionId?: stringparentRunId?: stringdistinctId?: string+ teamId?: stringmetricName: MinimalAppMetric['metric_name']// Replaces the instance_id trackMetric would derive, for metrics keyed by something// other than the action or invocation (see buildLinkInstanceId).@@ -651,6 +652,7 @@ export class SesWebhookHandler {actionId?: stringparentRunId?: stringdistinctId?: string+ teamId?: stringmetricName: MinimalAppMetric['metric_name']instanceIdOverride?: stringproperties?: Record<string, any>@@ -755,6 +757,7 @@ export class SesWebhookHandler {actionId,parentRunId,distinctId,+ teamId,metricName,properties,timestamp,@@ -773,6 +776,7 @@ export class SesWebhookHandler {actionId,parentRunId,distinctId,+ teamId,metricName: 'email_link_clicked_by_link',instanceIdOverride: buildLinkInstanceId(actionId,@@ -796,6 +800,7 @@ export class SesWebhookHandler {actionId,parentRunId,distinctId,+ teamId,metricName: BOUNCE_TYPE_TO_METRIC_NAME[rec.bounce.bounceType],properties,timestamp,diff --git a/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.test.ts b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.test.tsindex 66f35bea3580..106939752259 100644--- a/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.test.ts+++ b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.test.ts@@ -196,4 +196,55 @@ describe('RateLimiterService', () => {expect(after - before).toBe(1)})})++ describe('claimAllOrNothingPair', () => {+ const KEY_A = `${KEY}/pair-a`+ const KEY_B = `${KEY}/pair-b`++ it('grants from both buckets when both can cover the request', async () => {+ const claim = await limiter.claimAllOrNothingPair(+ [+ { key: KEY_A, capacity: 50, refillPerSecond: 0 },+ { key: KEY_B, capacity: 100, refillPerSecond: 0 },+ ],+ 30+ )+ expect(claim).toEqual({ granted: true, deniedIndex: null })+ // Both pools were charged: the remainder is all that is left to claim.+ expect(await limiter.claimUpTo({ key: KEY_A, requested: 50, capacity: 50, refillPerSecond: 0 })).toBe(20)+ expect(await limiter.claimUpTo({ key: KEY_B, requested: 100, capacity: 100, refillPerSecond: 0 })).toBe(70)+ })++ it('consumes nothing on denial, so retries cannot starve the buckets', async () => {+ // The second bucket cannot cover the request, so the claim must leave BOTH pools+ // untouched. Without that, a rescheduled multi-recipient send would burn the first+ // bucket's refill on every retry while never sending.+ const claim = await limiter.claimAllOrNothingPair(+ [+ { key: KEY_A, capacity: 50, refillPerSecond: 0 },+ { key: KEY_B, capacity: 10, refillPerSecond: 0 },+ ],+ 30+ )+ expect(claim).toEqual({ granted: false, deniedIndex: 1 })+ expect(await limiter.claimUpTo({ key: KEY_A, requested: 50, capacity: 50, refillPerSecond: 0 })).toBe(50)+ expect(await limiter.claimUpTo({ key: KEY_B, requested: 10, capacity: 10, refillPerSecond: 0 })).toBe(10)+ })++ it('fails closed when the Lua call throws', async () => {+ const brokenValkey = {+ useClient: jest.fn().mockRejectedValue(new Error('connection lost')),+ usePipeline: jest.fn(),+ } as unknown as RedisV2+ const brokenLimiter = new RateLimiterService(brokenValkey, { name: 'broken-limiter' })+ const claim = await brokenLimiter.claimAllOrNothingPair(+ [+ { key: KEY_A, capacity: 50, refillPerSecond: 0 },+ { key: KEY_B, capacity: 10, refillPerSecond: 0 },+ ],+ 5+ )+ expect(claim).toEqual({ granted: false, deniedIndex: null })+ })+ })})diff --git a/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.ts b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.tsindex f1566e993c46..74f5990577cc 100644--- a/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.ts+++ b/nodejs/src/cdp/services/rate-limiter/rate-limiter.service.ts@@ -95,6 +95,55 @@ redis.call('expire', key, ttlSeconds)return granted`+// Atomic all-or-nothing claim across two buckets. Same refill math as CLAIM_UP_TO_LUA per bucket,+// but the claim succeeds only when BOTH buckets can cover the full request, and a denial writes+// nothing at all — no partial consumption, no timestamp refresh. Without that, a caller retrying a+// multi-token claim would burn each bucket's partial refill on every attempt and could keep a+// shared bucket empty without ever succeeding.+// KEYS[1..2] = the two bucket hash keys+// ARGV[1] = requested tokens (integer)+// ARGV[2..4] = capacity, refill/sec, TTL seconds for KEYS[1]+// ARGV[5..7] = capacity, refill/sec, TTL seconds for KEYS[2]+// Returns {1, 0} on success, {0, i} when bucket i (1-based) is the first that cannot cover it.+const CLAIM_ALL_OR_NOTHING_PAIR_LUA = `+local time = redis.call('TIME')+local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)+local requested = tonumber(ARGV[1])++local available = {}+for i = 1, 2 do+ local capacity = tonumber(ARGV[(i - 1) * 3 + 2])+ local refillPerSecond = tonumber(ARGV[(i - 1) * 3 + 3])+ local existing = redis.call('hmget', KEYS[i], 'ts', 'pool')+ local avail+ if existing[1] == false then+ avail = capacity+ else+ local elapsedMs = now - tonumber(existing[1])+ if elapsedMs < 0 then+ elapsedMs = 0+ end+ local currentTokens = capacity+ if existing[2] ~= false then+ currentTokens = tonumber(existing[2])+ end+ avail = math.min(capacity, currentTokens + (elapsedMs / 1000.0) * refillPerSecond)+ end+ if avail < requested then+ return {0, i}+ end+ available[i] = avail+end++for i = 1, 2 do+ local ttlSeconds = tonumber(ARGV[(i - 1) * 3 + 4])+ redis.call('hset', KEYS[i], 'ts', now, 'pool', available[i] - requested)+ redis.call('expire', KEYS[i], ttlSeconds)+end++return {1, 0}+`+export interface RateLimiterConfig {/** Logical name for metrics/logging only (e.g. 'ses'). */name: string@@ -185,4 +234,60 @@ export class RateLimiterService {endTimer()}}++ /**+ * Atomically claim `requested` tokens from BOTH buckets, or neither. A denial consumes+ * nothing, so a caller that retries a multi-token claim cannot drain the buckets while never+ * succeeding. Returns which bucket denied (index into `buckets`), or null when granted.+ * Runtime errors deny with `deniedIndex: null` — fail-closed, like claimUpTo.+ */+ public async claimAllOrNothingPair(+ buckets: [Omit<ClaimRequest, 'requested'>, Omit<ClaimRequest, 'requested'>],+ requested: number+ ): Promise<{ granted: boolean; deniedIndex: 0 | 1 | null }> {+ const endTimer = claimLatency.startTimer({ limiter: this.config.name })+ try {+ const result = await this.valkey.useClient(+ { name: `rate-limiter:${this.config.name}:claimPair`, timeout: 1000 },+ (client) =>+ client.eval(+ CLAIM_ALL_OR_NOTHING_PAIR_LUA,+ 2,+ buckets[0].key,+ buckets[1].key,+ String(requested),+ String(buckets[0].capacity),+ String(buckets[0].refillPerSecond),+ String(buckets[0].ttlSeconds ?? 3600),+ String(buckets[1].capacity),+ String(buckets[1].refillPerSecond),+ String(buckets[1].ttlSeconds ?? 3600)+ )+ )++ const [granted, deniedBucket] = Array.isArray(result) ? result.map(Number) : [NaN, NaN]+ if (granted !== 0 && granted !== 1) {+ logger.warn('🪙', `RateLimiterService(${this.config.name}) pair claim returned invalid result`, {+ keys: [buckets[0].key, buckets[1].key],+ raw: result,+ })+ claimCounter.inc({ limiter: this.config.name, result: 'valkey_error' })+ return { granted: false, deniedIndex: null }+ }++ claimCounter.inc({ limiter: this.config.name, result: granted === 1 ? 'granted_full' : 'denied' })+ return granted === 1+ ? { granted: true, deniedIndex: null }+ : { granted: false, deniedIndex: deniedBucket === 2 ? 1 : 0 }+ } catch (err) {+ logger.warn('🪙', `RateLimiterService(${this.config.name}) pair claim threw`, {+ keys: [buckets[0].key, buckets[1].key],+ error: String(err),+ })+ claimCounter.inc({ limiter: this.config.name, result: 'valkey_error' })+ return { granted: false, deniedIndex: null }+ } finally {+ endTimer()+ }+ }}diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 381600d5be50..47204427c4d7 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -4,7 +4,7 @@ import uuid as uuid_modimport hashlibimport dataclassesfrom copy import deepcopy-from datetime import timedelta+from datetime import datetime, timedeltafrom time import monotonicfrom typing import Any, NamedTuple, Optional, castfrom zoneinfo import ZoneInfo, ZoneInfoNotFoundError@@ -44,7 +44,11 @@ from posthog.hogql.compiler.bytecode import create_bytecodefrom posthog.hogql.context import HogQLContextfrom posthog.hogql.parser import parse_expr-from posthog.api.app_metrics2 import AppMetricsMixin, fetch_app_metric_totals_by_source+from posthog.api.app_metrics2 import (+ AppMetricsMixin,+ fetch_app_metric_totals_by_source,+ fetch_app_metric_totals_by_team_and_source,+)from posthog.api.documentation import _FallbackSerializerfrom posthog.api.hog_invocation_cancel import (HogInvocationCancelRequestSerializer,@@ -77,6 +81,7 @@ from posthog.cdp.validation import (generate_template_bytecode,)from posthog.clickhouse.query_tagging import Feature, tag_queries+from posthog.dataclasses import frozenfrom posthog.event_usage import AGENT_EVENT_SOURCES, EventSource, get_event_source, report_user_actionfrom posthog.models import Teamfrom posthog.models.filters import Filter@@ -158,6 +163,7 @@ from products.workflows.backend.services.timing_reschedule import (from products.workflows.backend.services.wait_clock_conditions import find_clock_functionfrom products.workflows.backend.tasks.hog_flows import reschedule_hog_flow_timingfrom products.workflows.backend.utils.batch_trigger_limit import get_hogflow_batch_trigger_limit+from products.workflows.backend.utils.email_sending_tiers import max_email_sending_tier, resolve_team_email_sending_tierfrom products.workflows.backend.utils.rrule_utils import compute_next_occurrences, validate_rrulelogger = structlog.get_logger(__name__)@@ -593,7 +599,7 @@ def _parse_uuid_or_none(value: Any) -> Optional[uuid_mod.UUID]:return None-def _apply_fixed_template_id(config: dict, template_id: str, fixed_template_id: str) -> str:+def _apply_fixed_template_id(config: dict, template_id: str, fixed_template_id: str, *, strict: bool) -> str:"""template_id on fixed-template steps is fully determined by the step type, so infer it whenomitted instead of rejecting for leaving out a constant, and move a UUID-shaped value (a savedlibrary template reference, the dominant authoring mistake) into config.template_uuid where it@@ -605,6 +611,20 @@ def _apply_fixed_template_id(config: dict, template_id: str, fixed_template_id:return template_idlibrary_uuid = _parse_uuid_or_none(template_id)if library_uuid is None:+ if strict:+ # A different literal template on a fixed-template step is never legitimate: the worker+ # executes by template, so a mislabeled step (an sms step carrying template-email) would+ # run the other channel's send and dodge that channel's checks, like the email tier cap.+ # Non-strict (internal re-save) passes through so a legacy stored mismatch cannot brick+ # unrelated edits; it is rejected the next time a person saves the step.+ raise serializers.ValidationError(+ {+ "template_id": (+ f"template_id must be the literal '{fixed_template_id}' for this step type, "+ f"not '{template_id}'."+ )+ }+ )return template_idif config.get("template_uuid") and _parse_uuid_or_none(config["template_uuid"]) != library_uuid:raise serializers.ValidationError(@@ -888,6 +908,11 @@ class BlastRadiusRequestSerializer(serializers.Serializer):allow_null=True,help_text="When 'email', count unique email addresses instead of persons, matching how batch email sends deduplicate recipients.",)+ sends_email = serializers.BooleanField(+ default=True,+ help_text="Whether the workflow contains an email step. The tiered audience limit only applies to "+ "email sends; SMS, push, and webhook batches keep the flat limit. Defaults to true.",+ )class BlastRadiusSerializer(serializers.Serializer):@@ -1512,7 +1537,7 @@ class HogFlowActionSerializer(serializers.Serializer):template_id = config.get("template_id", "")fixed_template_id = _FIXED_TEMPLATE_IDS.get(data.get("type", ""))if fixed_template_id:- template_id = _apply_fixed_template_id(config, template_id, fixed_template_id)+ template_id = _apply_fixed_template_id(config, template_id, fixed_template_id, strict=strict)# After the fixed-id coercion, so a library UUID sent as template_id (the dominant# authoring mistake) lands in template_uuid first and still gets materialized.if data.get("type") == "function_email" and config.get("template_uuid"):@@ -2019,6 +2044,57 @@ def _email_sending_rates(sent: int, bounced: int, complained: int) -> dict[str,}+SENDING_ALLOWANCE_CACHE_SECONDS = 60+++@frozen+class EmailSendingAllowance:+ """A project's sending tier, what it allows, and how much of that it has used."""++ tier: int+ max_tier: int+ emails_per_hour: int+ emails_per_day: int+ max_batch_audience: int+ emails_sent_last_hour: int+ emails_sent_last_day: int+ enforced: bool+++def _team_email_sending_allowance(team_id: int) -> EmailSendingAllowance:+ """+ Usage comes from the send metrics rather than the worker's token buckets, so the numbers match+ what the rest of this page reports. Cached briefly because the endpoint reloads on every search+ keystroke while these two aggregations do not depend on the search.+ """+ cache_key = f"workflows_email_sending_allowance_{team_id}"+ cached = cache.get(cache_key)+ if cached is not None:+ return cached++ resolved = resolve_team_email_sending_tier(team_id)+ now = timezone.now()+ allowance = EmailSendingAllowance(+ tier=resolved.tier,+ max_tier=max_email_sending_tier(),+ emails_per_hour=resolved.limits.per_hour,+ emails_per_day=resolved.limits.per_day,+ max_batch_audience=resolved.limits.max_batch_audience,+ emails_sent_last_hour=_team_email_sends_since(team_id, now - timedelta(hours=1)),+ emails_sent_last_day=_team_email_sends_since(team_id, now - timedelta(days=1)),+ enforced=resolved.enforced,+ )+ cache.set(cache_key, allowance, SENDING_ALLOWANCE_CACHE_SECONDS)+ return allowance+++def _team_email_sends_since(team_id: int, after: datetime) -> int:+ totals = fetch_app_metric_totals_by_team_and_source(+ app_source="hog_flow", name=["email_sent"], after=after, team_ids=[team_id]+ )+ return sum(counts.get("email_sent", 0) for counts in totals.get(team_id, {}).values())++AWS_TENANT_REPUTATION_CACHE_SECONDS = 5 * 60# Failures cache too, but far shorter than successes: long enough that an unreachable SES isn't# re-dialled on every request, short enough that a just-fixed config recovers within a minute.@@ -2154,6 +2230,33 @@ class AwsTenantReputationSerializer(serializers.Serializer):)+class EmailSendingAllowanceSerializer(serializers.Serializer):+ """How much workflow email this project may send, and how much of that it has used."""++ tier = serializers.IntegerField(+ read_only=True,+ help_text="The project's current sending tier. Projects start at 0 and move up as they build a clean sending history.",+ )+ max_tier = serializers.IntegerField(+ read_only=True, help_text="The highest tier there is, so the current tier can be shown as progress."+ )+ emails_per_hour = serializers.IntegerField(read_only=True, help_text="How many emails this tier allows per hour.")+ emails_per_day = serializers.IntegerField(read_only=True, help_text="How many emails this tier allows per day.")+ max_batch_audience = serializers.IntegerField(+ read_only=True, help_text="The largest audience this tier allows for a single batch send."+ )+ emails_sent_last_hour = serializers.IntegerField(+ read_only=True, help_text="Emails sent by this project's workflows in the last hour."+ )+ emails_sent_last_day = serializers.IntegerField(+ read_only=True, help_text="Emails sent by this project's workflows in the last 24 hours."+ )+ enforced = serializers.BooleanField(+ read_only=True,+ help_text="True when these allowances are applied to sends. False while they are only being measured.",+ )++class TeamEmailReputationResponseSerializer(serializers.Serializer):aws = AwsTenantReputationSerializer(allow_null=True,@@ -2191,6 +2294,14 @@ class TeamEmailReputationResponseSerializer(serializers.Serializer):allow_blank=True,help_text="Staff-authored reason shown to customers alongside the suspension notice; empty when not suspended.",)+ sending_allowance = EmailSendingAllowanceSerializer(+ allow_null=True,+ read_only=True,+ help_text=(+ "The project's sending tier, what it allows, and how much of it has been used; null when the "+ "caller lacks project-wide workflow access."+ ),+ )class EmailSendingSuspensionStatusSerializer(serializers.Serializer):@@ -4309,7 +4420,7 @@ class HogFlowViewSet({"affected": get_account_audience_count(self.team, filters),"total": get_account_audience_count(self.team, {"audience_type": "accounts"}),- "limit": get_hogflow_batch_trigger_limit(self.team_id),+ "limit": get_hogflow_batch_trigger_limit(self.team_id, sends_email=params["sends_email"]),"dedupe_key": None,"confirm_token": mint_audience_confirm_token(self.team_id, filters, None, None),}@@ -4338,7 +4449,7 @@ class HogFlowViewSet({"affected": blast_radius.affected,"total": blast_radius.total,- "limit": get_hogflow_batch_trigger_limit(self.team_id),+ "limit": get_hogflow_batch_trigger_limit(self.team_id, sends_email=params["sends_email"]),"dedupe_key": applied_dedupe_key,"confirm_token": mint_audience_confirm_token(self.team_id, filters, group_type_index, applied_dedupe_key@@ -4755,6 +4866,11 @@ class HogFlowViewSet("email_sending_suspended": suspended_at is not None,"email_sending_suspended_at": suspended_at,"email_sending_suspension_reason": suspension_reason if suspended_at is not None else "",+ # Same gate again: the allowance is project-wide, so an object-level grant is+ # not enough to read it.+ "sending_allowance": _team_email_sending_allowance(self.team_id)+ if can_read_all_workflows+ else None,}).data)@@ -5110,7 +5226,9 @@ class InternalHogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMi{"affected": result.affected,"total": result.total,- "limit": get_hogflow_batch_trigger_limit(team.id),+ "limit": get_hogflow_batch_trigger_limit(+ team.id, sends_email=bool(request.data.get("sends_email", True))+ ),"dedupe_key": None,}).datadiff --git a/products/workflows/backend/api/test/test_email_reputation.py b/products/workflows/backend/api/test/test_email_reputation.pyindex 1be9f69c5b51..956f2fa5914e 100644--- a/products/workflows/backend/api/test/test_email_reputation.py+++ b/products/workflows/backend/api/test/test_email_reputation.py@@ -56,7 +56,15 @@ class TestEmailReputationAPI(APIBaseTest):return response.json()def test_reputation_endpoint_returns_empty_shape_when_nothing_was_sent(self):- assert self._get_reputation({}) == {+ data = self._get_reputation({})+ # The allowance values come from the tier tables, which are deployment configuration, so+ # assert the fresh-team invariants rather than the numbers.+ allowance = data.pop("sending_allowance")+ assert allowance["tier"] == 0+ assert allowance["enforced"] is False+ assert allowance["emails_sent_last_hour"] == 0+ assert allowance["emails_sent_last_day"] == 0+ assert data == {"aws": None,"reputation": None,"workflows": [],diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex d7d58fad398a..967e7eb50108 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -368,6 +368,12 @@ class TestHogFlowAPI(APIBaseTest):"template-does-not-exist",["must be the literal 'template-email'"],),+ (+ "another_channels_template_on_fixed_step",+ "function_sms",+ "template-email",+ ["must be the literal 'template-twilio'"],+ ),])def test_unknown_template_id_error_names_the_expected_form(self, _name, action_type, template_id, fragments):diff --git a/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx b/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsxindex f7be4ab7c40f..2f84ccf336d8 100644--- a/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx+++ b/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx@@ -2,12 +2,14 @@ import { useActions, useValues } from 'kea'import { LemonBanner, LemonInput, LemonTable, LemonTag, LemonTagType, Link, Tooltip } from '@posthog/lemon-ui'+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'import { urls } from 'scenes/urls'import type {AwsTenantReputationApi,AwsTenantReputationHealthEnumApi,+ EmailSendingAllowanceApi,EmailSendingRatesApi,WorkflowEmailSendingRatesApi,} from 'products/workflows/frontend/generated/api.schemas'@@ -184,8 +186,60 @@ function TeamRatesCard({)}+function SendingAllowanceCard({ allowance }: { allowance: EmailSendingAllowanceApi }): JSX.Element {+ const hourlyPercent = Math.min(100, (allowance.emails_sent_last_hour / allowance.emails_per_hour) * 100)+ const dailyPercent = Math.min(100, (allowance.emails_sent_last_day / allowance.emails_per_day) * 100)+ return (+ <div className="border rounded p-4 bg-surface-primary" data-attr="workflows-sending-allowance">+ <div className="flex items-center gap-2">+ <h3 className="mb-0">Sending allowance</h3>+ <Tooltip title="Every project shares PostHog's sending infrastructure, so allowances start small and grow with a clean sending record.">+ <LemonTag type="muted">+ Tier {allowance.tier} of {allowance.max_tier}+ </LemonTag>+ </Tooltip>+ </div>+ <p className="text-secondary mt-2 mb-0">+ Your allowance grows as your workflows keep sending with low bounce and spam complaint rates. Emails+ above the allowance are not dropped, they are sent later.+ </p>+ <div className="flex flex-wrap gap-8 mt-3">+ <div className="min-w-48">+ <MetricLabel+ label="Emails this hour"+ tooltip="Emails your workflows sent in the last hour, against what this tier allows per hour."+ />+ <div className="text-lg font-semibold">+ {humanFriendlyNumber(allowance.emails_sent_last_hour)} of{' '}+ {humanFriendlyNumber(allowance.emails_per_hour)}+ </div>+ <LemonProgress percent={hourlyPercent} className="mt-1" />+ </div>+ <div className="min-w-48">+ <MetricLabel+ label="Emails today"+ tooltip="Emails your workflows sent in the last 24 hours, against what this tier allows per day."+ />+ <div className="text-lg font-semibold">+ {humanFriendlyNumber(allowance.emails_sent_last_day)} of{' '}+ {humanFriendlyNumber(allowance.emails_per_day)}+ </div>+ <LemonProgress percent={dailyPercent} className="mt-1" />+ </div>+ <div>+ <MetricLabel+ label="Largest batch audience"+ tooltip="The biggest audience this tier allows for a single batch send."+ />+ <div className="text-lg font-semibold">{humanFriendlyNumber(allowance.max_batch_audience)}</div>+ </div>+ </div>+ </div>+ )+}+export function WorkflowsReputation(): JSX.Element {- const { awsReputation, teamReputation, workflowSnapshots, reputationResponseLoading, search } =+ const { awsReputation, sendingAllowance, teamReputation, workflowSnapshots, reputationResponseLoading, search } =useValues(workflowsReputationLogic)const { setSearch } = useActions(workflowsReputationLogic)@@ -202,6 +256,7 @@ export function WorkflowsReputation(): JSX.Element {Sending health is shown for transparency: high bounce or spam complaint rates hurt email deliverability.We judge and enforce reputation per project.</LemonBanner>+ {sendingAllowance?.enforced && <SendingAllowanceCard allowance={sendingAllowance} />}{teamReputation || awsReputation ? (<TeamRatesCard reputation={teamReputation} aws={awsReputation} />) : (diff --git a/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.ts b/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.tsindex cb53b6b9edfa..c0a92687bedf 100644--- a/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.ts+++ b/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.ts@@ -6,6 +6,7 @@ import { projectLogic } from 'scenes/projectLogic'import { hogFlowsReputationRetrieve } from 'products/workflows/frontend/generated/api'import type {AwsTenantReputationApi,+ EmailSendingAllowanceApi,EmailSendingRatesApi,TeamEmailReputationResponseApi,WorkflowEmailSendingRatesApi,@@ -18,6 +19,7 @@ export interface workflowsReputationLogicValues {reputationResponse: TeamEmailReputationResponseApi | nullreputationResponseLoading: booleansearch: string+ sendingAllowance: EmailSendingAllowanceApi | nullteamReputation: EmailSendingRatesApi | nullworkflowSnapshots: readonly WorkflowEmailSendingRatesApi[]}@@ -54,6 +56,7 @@ export interface workflowsReputationLogicActions {export interface workflowsReputationLogicMeta {__keaTypeGenInternalSelectorTypes: {awsReputation: (reputationResponse: TeamEmailReputationResponseApi | null) => AwsTenantReputationApi | null+ sendingAllowance: (reputationResponse: TeamEmailReputationResponseApi | null) => EmailSendingAllowanceApi | nullteamReputation: (reputationResponse: TeamEmailReputationResponseApi | null) => EmailSendingRatesApi | nullworkflowSnapshots: (reputationResponse: TeamEmailReputationResponseApi | null@@ -119,6 +122,11 @@ export const workflowsReputationLogic = kea<workflowsReputationLogicType>([(s) => [s.reputationResponse],(response: TeamEmailReputationResponseApi | null): AwsTenantReputationApi | null => response?.aws ?? null,],+ sendingAllowance: [+ (s) => [s.reputationResponse],+ (response: TeamEmailReputationResponseApi | null): EmailSendingAllowanceApi | null =>+ response?.sending_allowance ?? null,+ ],teamReputation: [(s) => [s.reputationResponse],(response: TeamEmailReputationResponseApi | null): EmailSendingRatesApi | null =>diff --git a/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButton.tsx b/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButton.tsxindex 9f535375f078..692993260732 100644--- a/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButton.tsx+++ b/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButton.tsx@@ -11,7 +11,7 @@ import { CyclotronJobInputSchemaType } from '~/types'import { WorkflowLogicProps, workflowLogic } from '../workflowLogic'import { hogFlowManualTriggerButtonLogic } from './HogFlowManualTriggerButtonLogic'-import { batchTriggerLogic, getAudienceDedupeKey } from './steps/batchTriggerLogic'+import { batchTriggerLogic, getAudienceDedupeKey, hogFlowSendsEmail } from './steps/batchTriggerLogic'const TriggerPopover = ({setPopoverVisible,@@ -33,6 +33,7 @@ const TriggerPopover = ({filters: workflow?.trigger?.type === 'batch' ? workflow?.trigger?.filters : undefined,// Account audiences carry no person, so email dedup never applies to them.dedupeKey: isAccountAudience ? undefined : getAudienceDedupeKey(workflow),+ sendsEmail: hogFlowSendsEmail(workflow),}))@@ -114,7 +115,7 @@ const TriggerPopover = ({loading={blastRadiusLoading}disabledReason={blastRadiusExceeded && blastRadius?.limit != null- ? `Batch size exceeds the limit of ${humanFriendlyNumber(blastRadius.limit)} ${isAccountAudience ? 'accounts' : 'users'}. Add filters to narrow your audience. This limit will be loosened in the future.`+ ? `Your audience is above this project's batch limit of ${humanFriendlyNumber(blastRadius.limit)} ${isAccountAudience ? 'accounts' : 'users'}. Add filters to narrow it.${hogFlowSendsEmail(workflow) ? ' The limit rises as the project builds a clean sending history.' : ''}`: undefined}onClick={() => {diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsxindex 41289da8d1ff..2e67c4e2b896 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx@@ -57,7 +57,7 @@ import { workflowLogic } from '../../workflowLogic'import { HogFlowEventFilters, WORKFLOW_OPERATOR_ALLOWLIST } from '../filters/HogFlowFilters'import { TriggerFrequencyOption, getRegisteredTriggerTypes } from '../registry/triggers/triggerTypeRegistry'import { HogFlowAction } from '../types'-import { batchTriggerLogic, getAudienceDedupeKey } from './batchTriggerLogic'+import { batchTriggerLogic, getAudienceDedupeKey, hogFlowSendsEmail } from './batchTriggerLogic'import { HogFlowFunctionConfiguration } from './components/HogFlowFunctionConfiguration'import { RecurringSchedulePicker } from './components/RecurringSchedulePicker'import { ScheduleStatusBadge } from './components/ScheduleStatusBadge'@@ -520,7 +520,7 @@ function StepTriggerAffectedUsers({ actionId, filters }: { actionId: string; filconst isAccountAudience = filters?.audience_type === 'accounts'// Account audiences carry no person, so email dedup never applies to them.const dedupeKey = isAccountAudience ? undefined : getAudienceDedupeKey(workflow)- const logic = batchTriggerLogic({ id: actionId, filters, dedupeKey })+ const logic = batchTriggerLogic({ id: actionId, filters, dedupeKey, sendsEmail: hogFlowSendsEmail(workflow) })const { blastRadiusLoading, blastRadius, blastRadiusError } = useValues(logic)if (blastRadiusLoading) {@@ -561,9 +561,11 @@ function StepTriggerAffectedUsers({ actionId, filters }: { actionId: string; fil</div>{exceeded && limit != null && (<div className="text-danger text-xs">- Batch size exceeds the limit of {humanFriendlyNumber(limit)}{' '}- {isAccountAudience ? 'accounts' : 'users'}. Add filters to narrow your audience. This limit will- be loosened in the future.+ Your audience is above this project's batch limit of {humanFriendlyNumber(limit)}{' '}+ {isAccountAudience ? 'accounts' : 'users'}. Add filters to narrow it.+ {hogFlowSendsEmail(workflow)+ ? ' The limit rises as the project builds a clean sending history.'+ : ''}</div>)}</div>diff --git a/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.tsindex ceebc1a6b7ae..10a32d77d37a 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.ts@@ -27,11 +27,23 @@ export function getAudienceDedupeKey(workflow?: { actions?: HogFlowAction[] } |return allDefault ? 'email' : undefined}+export function hogFlowSendsEmail(workflow?: { actions?: HogFlowAction[] } | null): boolean {+ // The tiered batch audience limit only applies to workflows with an email step; SMS, push,+ // and webhook batches keep the flat limit. Mirrors hog_flow_sends_email on the backend:+ // the worker executes function steps by template, so the email template counts as an email+ // step regardless of the declared action type.+ return (workflow?.actions ?? []).some(+ (action) => action.type === 'function_email' || (action as any)?.config?.template_id === 'template-email'+ )+}+export interface BatchTriggerLogicProps {id?: string | 'new'filters?: Extract<HogFlowAction['config'], { type: 'batch' }>['filters']/** When 'email', the count reflects unique email addresses, matching batch send dedup. */dedupeKey?: 'email'+ /** Whether the workflow contains an email step, which decides if the tiered audience limit applies. */+ sendsEmail?: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -110,7 +122,11 @@ export const batchTriggerLogic = kea<batchTriggerLogicType>([if (!props.filters) {return null}- return await api.hogFlows.getBatchTriggerBlastRadius(props.filters, props.dedupeKey)+ return await api.hogFlows.getBatchTriggerBlastRadius(+ props.filters,+ props.dedupeKey,+ props.sendsEmail+ )},},],@@ -126,7 +142,12 @@ export const batchTriggerLogic = kea<batchTriggerLogicType>([},})),propsChanged(({ actions, props }, oldProps) => {- if (!oldProps || !objectsEqual(props.filters, oldProps.filters) || props.dedupeKey !== oldProps.dedupeKey) {+ if (+ !oldProps ||+ !objectsEqual(props.filters, oldProps.filters) ||+ props.dedupeKey !== oldProps.dedupeKey ||+ props.sendsEmail !== oldProps.sendsEmail+ ) {actions.loadBlastRadius()}}),diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex 7d5d1a4771ee..ded130887cfd 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -1417,6 +1417,28 @@ export interface WorkflowEmailSendingRatesApi {readonly hog_flow_name: string}+/**+ * How much workflow email this project may send, and how much of that it has used.+ */+export interface EmailSendingAllowanceApi {+ /** The project's current sending tier. Projects start at 0 and move up as they build a clean sending history. */+ readonly tier: number+ /** The highest tier there is, so the current tier can be shown as progress. */+ readonly max_tier: number+ /** How many emails this tier allows per hour. */+ readonly emails_per_hour: number+ /** How many emails this tier allows per day. */+ readonly emails_per_day: number+ /** The largest audience this tier allows for a single batch send. */+ readonly max_batch_audience: number+ /** Emails sent by this project's workflows in the last hour. */+ readonly emails_sent_last_hour: number+ /** Emails sent by this project's workflows in the last 24 hours. */+ readonly emails_sent_last_day: number+ /** True when these allowances are applied to sends. False while they are only being measured. */+ readonly enforced: boolean+}+export interface TeamEmailReputationResponseApi {/** Sending health as judged and enforced by AWS SES for this project's tenant; null when the caller lacks project-wide workflow access, no tenant is provisioned, or AWS is unreachable. */readonly aws: AwsTenantReputationApi | null@@ -1433,6 +1455,8 @@ export interface TeamEmailReputationResponseApi {readonly email_sending_suspended_at: string | null/** Staff-authored reason shown to customers alongside the suspension notice; empty when not suspended. */readonly email_sending_suspension_reason: string+ /** The project's sending tier, what it allows, and how much of it has been used; null when the caller lacks project-wide workflow access. */+ readonly sending_allowance: EmailSendingAllowanceApi | null}/**@@ -1461,6 +1485,8 @@ export interface BlastRadiusRequestApi {** * `email` - email */dedupe_key?: DedupeKeyEnumApi | null+ /** Whether the workflow contains an email step. The tiered audience limit only applies to email sends; SMS, push, and webhook batches keep the flat limit. Defaults to true. */+ sends_email?: boolean}export interface BlastRadiusApi {diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.tsindex 15acc6836b25..42bb0a60de9f 100644--- a/products/workflows/frontend/generated/api.zod.ts+++ b/products/workflows/frontend/generated/api.zod.ts@@ -2834,6 +2834,8 @@ export const HogFlowsBulkDeleteCreateBody = /* @__PURE__ */ zod}).describe('Mixin for serializers to add user access control fields')+export const hogFlowsUserBlastRadiusCreateBodySendsEmailDefault = true+export const HogFlowsUserBlastRadiusCreateBody = /* @__PURE__ */ zod.object({filters: zod.record(zod.string(), zod.unknown()).describe('Property filters to apply'),group_type_index: zod.number().nullish().describe('Group type index for group-based targeting'),@@ -2843,4 +2845,10 @@ export const HogFlowsUserBlastRadiusCreateBody = /* @__PURE__ */ zod.object({.describe("When 'email', count unique email addresses instead of persons, matching how batch email sends deduplicate recipients.\n\n\* `email` - email"),+ sends_email: zod+ .boolean()+ .default(hogFlowsUserBlastRadiusCreateBodySendsEmailDefault)+ .describe(+ 'Whether the workflow contains an email step. The tiered audience limit only applies to email sends; SMS, push, and webhook batches keep the flat limit. Defaults to true.'+ ),})diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3f1e6ea09b48..6aebdbef37ca 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -14195,6 +14195,8 @@ export namespace Schemas {** * `email` - email */dedupe_key?: DedupeKeyEnum | null;+ /** Whether the workflow contains an email step. The tiered audience limit only applies to email sends; SMS, push, and webhook batches keep the flat limit. Defaults to true. */+ sends_email?: boolean;}/**@@ -29791,6 +29793,28 @@ export namespace Schemas {name: string;}+ /**+ * How much workflow email this project may send, and how much of that it has used.+ */+ export interface EmailSendingAllowance {+ /** The project's current sending tier. Projects start at 0 and move up as they build a clean sending history. */+ readonly tier: number;+ /** The highest tier there is, so the current tier can be shown as progress. */+ readonly max_tier: number;+ /** How many emails this tier allows per hour. */+ readonly emails_per_hour: number;+ /** How many emails this tier allows per day. */+ readonly emails_per_day: number;+ /** The largest audience this tier allows for a single batch send. */+ readonly max_batch_audience: number;+ /** Emails sent by this project's workflows in the last hour. */+ readonly emails_sent_last_hour: number;+ /** Emails sent by this project's workflows in the last 24 hours. */+ readonly emails_sent_last_day: number;+ /** True when these allowances are applied to sends. False while they are only being measured. */+ readonly enforced: boolean;+ }+/*** Bounce/complaint rates over the last 30 days of workflow email, computed on the fly from app metrics.*/@@ -85057,6 +85081,8 @@ export namespace Schemas {readonly email_sending_suspended_at: string | null;/** Staff-authored reason shown to customers alongside the suspension notice; empty when not suspended. */readonly email_sending_suspension_reason: string;+ /** The project's sending tier, what it allows, and how much of it has been used; null when the caller lacks project-wide workflow access. */+ readonly sending_allowance: EmailSendingAllowance | null;}export const TeamMCPGatewayConfigMemberDefaultPreset = {...MCPPolicyPresetEnum,...BlankEnum,} as const