: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): add per-workflow email pause state and honor it at send time (#89877)
Meikel Ratzbab7b9742367
diff --git a/nodejs/src/cdp/schema/hogflow.ts b/nodejs/src/cdp/schema/hogflow.tsindex 61d7ef993371..2cf3cca84975 100644--- a/nodejs/src/cdp/schema/hogflow.ts+++ b/nodejs/src/cdp/schema/hogflow.ts@@ -334,6 +334,15 @@ export const HogFlowSchema = z.object({// User-configured email pacing for deliverability. The email worker holds this flow's sends// under the limit by rescheduling over-limit sends, never dropping them.email_sending_rate_limit: HogFlowEmailSendingRateLimitSchema.optional().nullable(),+ // Set when PostHog paused this flow's email automatically because its spam complaint or hard+ // bounce rate breached a threshold. Non-null means the email service skips every send for this+ // flow, including test sends. Same value shapes as `updated_at`: pg returns a Date, fixtures+ // use epoch millis or an ISO string.+ email_sending_paused_at: z.union([z.number(), z.string(), z.date()]).optional().nullable(),+ email_sending_paused_reason: z.string().optional().nullable(),+ // "auto" (deliverability detector) or "staff". Staff pauses are not customer-resumable, so the+ // skip log tells the customer to contact support instead of pointing at the resume button.+ email_sending_paused_by: z.string().optional().nullable(),actions: z.array(HogFlowActionSchema),// Secret function inputs, split out of `actions` and stored Fernet-encrypted at rest, keyed by// action id then input key. Decrypted by the manager and merged back into `action.config.inputs`diff --git a/nodejs/src/cdp/services/hogflows/__snapshots__/hogflow-manager.service.test.ts.snap b/nodejs/src/cdp/services/hogflows/__snapshots__/hogflow-manager.service.test.ts.snapindex b16c031ac3ba..6d5de219eae3 100644--- a/nodejs/src/cdp/services/hogflows/__snapshots__/hogflow-manager.service.test.ts.snap+++ b/nodejs/src/cdp/services/hogflows/__snapshots__/hogflow-manager.service.test.ts.snap@@ -48,6 +48,9 @@ exports[`HogFlowManager returns the hog flow 1`] = `"type": "continue",},],+ "email_sending_paused_at": null,+ "email_sending_paused_by": "",+ "email_sending_paused_reason": "","email_sending_rate_limit": null,"exit_condition": "exit_on_conversion","id": "<REPLACED-UUID-0>",@@ -116,6 +119,9 @@ exports[`HogFlowManager returns the hog flow 1`] = `"type": "continue",},],+ "email_sending_paused_at": null,+ "email_sending_paused_by": "",+ "email_sending_paused_reason": "","email_sending_rate_limit": null,"exit_condition": "exit_on_conversion","id": "<REPLACED-UUID-1>",diff --git a/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-functions.service.tsindex 16157f58b4a7..ac0d60c52105 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts@@ -47,7 +47,13 @@ export class HogFlowFunctionsService {updated_at: '',// The action's config, plus flow-level send settings the email service needs at the// send choke point, where only the synthetic hog function is in scope.- metadata: { ...config, email_sending_rate_limit: hogFlow.email_sending_rate_limit ?? null },+ metadata: {+ ...config,+ email_sending_rate_limit: hogFlow.email_sending_rate_limit ?? null,+ email_sending_paused_at: hogFlow.email_sending_paused_at ?? null,+ email_sending_paused_reason: hogFlow.email_sending_paused_reason ?? null,+ email_sending_paused_by: hogFlow.email_sending_paused_by ?? null,+ },}return hogFunctiondiff --git a/nodejs/src/cdp/services/hogflows/hogflow-manager.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-manager.service.test.tsindex 88d0a22ecf22..4c0cc4e60f87 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-manager.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-manager.service.test.ts@@ -147,6 +147,33 @@ describe('HogFlowManager', () => {}, 10000)})+ describe('email sending pause', () => {+ // The pause only reaches the send choke point through the manager's column list, so a+ // column left out of HOG_FLOW_FIELDS silently lets a paused workflow keep sending.+ it('carries the pause state and reaches the worker on a reload', async () => {+ let items = await manager.getHogFlowsForTeam(teamId1)+ expect(items.find((item) => item.id === hogFlows[0].id)?.email_sending_paused_at).toBeNull()++ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `UPDATE posthog_hogflow+ SET email_sending_paused_at = NOW(),+ email_sending_paused_reason = 'Spam complaints reached 2% of the 400 emails sent.',+ updated_at = NOW()+ WHERE id = $1`,+ [hogFlows[0].id],+ 'testKey'+ )+ // Normally dispatched by the HogFlow post_save signal+ manager['onHogFlowsReloaded'](teamId1, [hogFlows[0].id])++ items = await manager.getHogFlowsForTeam(teamId1)+ const paused = items.find((item) => item.id === hogFlows[0].id)+ expect(paused?.email_sending_paused_at).toBeTruthy()+ expect(paused?.email_sending_paused_reason).toBe('Spam complaints reached 2% of the 400 emails sent.')+ })+ })+describe('getHogFlowIdsForTeam', () => {it('returns function IDs', async () => {const result = await manager.getHogFlowIdsForTeams([teamId1, teamId2])diff --git a/nodejs/src/cdp/services/hogflows/hogflow-manager.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-manager.service.tsindex fe25902786af..ef607f18481d 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-manager.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-manager.service.ts@@ -34,6 +34,9 @@ const HOG_FLOW_FIELDS = ['conversion','exit_condition','email_sending_rate_limit',+ 'email_sending_paused_at',+ 'email_sending_paused_reason',+ 'email_sending_paused_by','edges','actions','encrypted_inputs',diff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.tsindex 5aecb2cfd993..6558d844f3a1 100644--- a/nodejs/src/cdp/services/messaging/email.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts@@ -1133,6 +1133,65 @@ describe('EmailService', () => {expect(result.metrics).toEqual([])})+ // A per-workflow pause holds one workflow's email while the rest of the project keeps+ // sending. Same choke point as the team switch above, so no upstream route bypasses it.+ it('does not call SES while the workflow is paused and records email_paused', async () => {+ invocation.hogFunction.metadata = {+ email_sending_paused_at: '2026-01-01T00:00:00Z',+ email_sending_paused_reason: 'Spam complaints reached 2% of the 400 emails sent.',+ }+ sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })++ const result = await service.executeSendEmail(invocation)++ expect(sendEmailSpy).not.toHaveBeenCalled()+ expect(result.metrics.map((m) => m.metric_name)).toEqual(['email_paused'])+ expect(invocation.state.vmState?.stack).toEqual([{ success: false }])+ expect(result.logs.map((l) => l.message).join(' ')).toContain('Spam complaints reached 2%')+ // Flags the skip so the flow-level billing gate charges nothing for a send that never sent.+ expect(result.skipped).toBe(true)+ })++ it('tells a staff-paused workflow to contact support instead of the resume button', async () => {+ invocation.hogFunction.metadata = {+ email_sending_paused_at: '2026-01-01T00:00:00Z',+ email_sending_paused_reason:+ "PostHog staff paused this workflow's email to protect delivery for everyone.",+ email_sending_paused_by: 'staff',+ }+ sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })++ const result = await service.executeSendEmail(invocation)++ expect(sendEmailSpy).not.toHaveBeenCalled()+ const messages = result.logs.map((l) => l.message).join(' ')+ expect(messages).toContain('Contact support')+ expect(messages).not.toContain('Resume it from the workflow page')+ })++ it('blocks editor test sends while the workflow is paused without recording metrics', async () => {+ invocation.hogFunction.metadata = { email_sending_paused_at: '2026-01-01T00:00:00Z' }+ sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })++ const result = await service.executeSendEmail(invocation, true)++ expect(sendEmailSpy).not.toHaveBeenCalled()+ expect(result.metrics).toEqual([])+ })++ it('sends once the workflow pause is cleared', async () => {+ invocation.hogFunction.metadata = {+ email_sending_paused_at: null,+ email_sending_paused_reason: null,+ }+ sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })++ const result = await service.executeSendEmail(invocation)++ expect(sendEmailSpy).toHaveBeenCalledTimes(1)+ expect(result.metrics.map((m) => m.metric_name)).toContain('email_sent')+ })+const setProviderTenantStatus = async (status: string): Promise<void> => {await hub.postgres.query(PostgresUse.COMMON_WRITE,diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.tsindex 7a5f21baa7bc..99d9e523c53b 100644--- a/nodejs/src/cdp/services/messaging/email.service.ts+++ b/nodejs/src/cdp/services/messaging/email.service.ts@@ -100,6 +100,30 @@ function parseWorkflowEmailRateLimit(metadata: HogFunctionType['metadata']): Hogreturn parsed.success ? parsed.data : null}+const workflowEmailPausedTotal = new Counter({+ name: 'cdp_workflow_email_paused_total',+ help: 'Email sends skipped because the workflow they belong to had its email paused for complaints or hard bounces.',+})++/**+ * Whether this workflow's email is paused, and the customer-facing reason.+ *+ * Stamped into the synthetic hog function's metadata by HogFlowFunctionsService, which is the only+ * flow-level state in scope here. The `HogFlow` post_save signal publishes a worker config reload+ * when the pause is written, so an in-flight run and an already-queued batch send both stop at this+ * choke point instead of only newly started runs.+ */+function parseWorkflowEmailPause(metadata: HogFunctionType['metadata']): { reason: string; byStaff: boolean } | null {+ if (!metadata?.email_sending_paused_at) {+ return null+ }+ const reason = metadata.email_sending_paused_reason+ return {+ reason: typeof reason === 'string' ? reason : '',+ byStaff: metadata.email_sending_paused_by === 'staff',+ }+}+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.@@ -391,6 +415,41 @@ export class EmailService {return result}+ // Per-workflow pause: this workflow's complaint or hard bounce rate breached a+ // threshold, so its email is held while the rest of the project keeps sending. Placed+ // at the same choke point as the team-level switch above, for the same reason. Test+ // sends are blocked too, because they hit SES and count against the tenant all the same.+ const workflowPause = parseWorkflowEmailPause(invocation.hogFunction.metadata)+ if (workflowPause) {+ workflowEmailPausedTotal.inc()+ const pauseDetail = workflowPause.reason ? ` ${workflowPause.reason}` : ''+ // Error rather than warn: the email did not go out, and warn-level lines get skimmed+ // past in the run logs. The run itself still continues; a pause is policy, not a+ // fault, so it must not enter retry or abort handling.+ addLog(+ 'error',+ workflowPause.byStaff+ ? `Skipping send: PostHog staff paused email sending for this workflow.${pauseDetail} Contact support to get sending re-enabled.`+ : `Skipping send: email sending is paused for this workflow.${pauseDetail} Resume it from the workflow page once the audience is cleaned up.`+ )+ if (!isTest) {+ result.metrics.push({+ team_id: invocation.teamId,+ app_source_id: invocation.parentRunId ?? invocation.functionId,+ instance_id: invocation.state.actionId || invocation.id,+ metric_kind: 'email',+ metric_name: 'email_paused',+ count: 1,+ })+ }+ // Mark the skip so the flow-level billing gate does not charge for a send that+ // never reached the provider, and does not re-pin the run's attribution version to+ // one that delivered nothing. Mirrors the pre-send opt-out and bounce skip paths.+ result.skipped = true+ result.invocation.state.vmState?.stack.push({ success: false })+ return result+ }+// Wrong-team references deliberately read as not-found so an ID's existence on another team can't be probedif (!integration || integration.team_id !== invocation.teamId) {throw new Error(diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex b506b05714d8..c419830cd541 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -253,6 +253,7 @@ export type MinimalAppMetric = {| 'email_bounce_prevented'| 'email_suppressed'| 'email_suspended'+ | 'email_paused'| 'email_blocked'| 'email_unsubscribed'| 'email_untracked'