: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(cdp): record skipped, failed and delivered transactional emails (#124751)
Harley Alexandera17f62e96b35
diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.tsindex e3bd345a759e..c08af8df2435 100644--- a/nodejs/src/cdp/cdp-api.ts+++ b/nodejs/src/cdp/cdp-api.ts@@ -252,7 +252,8 @@ export class CdpApi {services.capturedEventsService,services.teamWorkflowsConfigService,new EmailTrackingCodeSigner(config.ENCRYPTION_SALT_KEYS, config.CDP_EMAIL_TRACKING_URL),- services.emailSuppressionService+ services.emailSuppressionService,+ services.emailStatusService)this.groupsManager = new GroupsManagerService(deps.teamManager, deps.groupRepository)this.batchExportHogFunctionService = new BatchExportHogFunctionService(diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex a61771e3e788..72664c6604a1 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -565,6 +565,7 @@ export function createCdpCoreServices(emailValidationService,cohortMembershipRepository,deps.integrationManager,+ emailStatusService,hogFlowDuplicateObserver,cdpUsageReporter,{ awaitedStepsEnabled: config.CDP_HOGFLOW_AWAITED_STEPS_ENABLED }diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.tsindex 211b4b90f0b3..6e6718bbf887 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts@@ -110,6 +110,7 @@ export class CdpCyclotronWorkerHogFlow extends CdpCyclotronWorker {})failedInvocations.push(item)+ this.invocationResultsService.emailStatusService.queueUnavailableRun(item)return}diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.tsindex a268665367ac..67e4c7aec197 100644--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts@@ -6,13 +6,16 @@ import { register } from 'prom-client'import { FixtureHogFlowBuilder } from '~/cdp/_tests/builders/hogflow.builder'import { insertHogFunctionTemplate, insertIntegration } from '~/cdp/_tests/fixtures'import { createExampleHogFlowInvocation } from '~/cdp/_tests/fixtures-hogflows'+import { EmailStatusOutput } from '~/cdp/outputs/outputs'import { HogFlowAction } from '~/cdp/schema/hogflow'import { createInvocationResult } from '~/cdp/utils/invocation-utils'import { PosthogJwtAudience } from '~/cdp/utils/jwt-utils'import { ScopedServiceJwt } from '~/cdp/utils/scoped-service-jwt'import { workflowStepDispatchKeyFromInvocation } from '~/cdp/utils/workflow-step-dispatch-key'+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { closeHub, createHub } from '~/common/utils/db/hub'import { parseJSON } from '~/common/utils/json-parse'+import { UUIDT } from '~/common/utils/utils'import { createTestTeamFixture } from '~/tests/helpers/sql'import { Hub, Team } from '~/types'@@ -23,6 +26,7 @@ import { HogInputsService } from '../../hog-inputs.service'import { HogFunctionTemplateManagerService } from '../../managers/hog-function-template-manager.service'import { RecipientsManagerService } from '../../managers/recipients-manager.service'import { TeamWorkflowsConfigService } from '../../managers/team-workflows-config.service'+import { EmailStatusService } from '../../messaging/email-status.service'import { EmailSuppressionService, emailSuppressionConfigFromEnv } from '../../messaging/email-suppression.service'import { EmailValidationService } from '../../messaging/email-validation.service'import { EmailService } from '../../messaging/email.service'@@ -31,6 +35,7 @@ import { RecipientPreferencesService } from '../../messaging/recipient-preferencimport { RecipientTokensService } from '../../messaging/recipient-tokens.service'import { CdpUsageReporterService } from '../../usage/cdp-usage-reporter.service'import { HogFlowFunctionsService } from '../hogflow-functions.service'+import { TRANSACTIONAL_EMAIL_EVENT } from '../hogflow-sensitivity'import { findActionByType } from '../hogflow-utils'import { HogFunctionHandler, messageOptOutsAfterStep } from './hog_function'@@ -133,7 +138,8 @@ describe('HogFunctionHandler', () => {mockHogFlowFunctionsService,mockRecipientPreferencesService,mockEmailValidationService,- 'fetch'+ 'fetch',+ null)// Simple hog function that prints the inputs@@ -557,6 +563,99 @@ describe('HogFunctionHandler', () => {})+ describe('transactional email status', () => {+ const skipOptedOut = (): void => {+ ;(mockRecipientPreferencesService.shouldSkipAction as jest.Mock).mockResolvedValueOnce('opted_out')+ }+ const skipSuppressed = (): void => {+ ;(mockRecipientPreferencesService.shouldSkipAction as jest.Mock).mockResolvedValueOnce('suppressed')+ }+ const skipUnreachable = (): void => {+ ;(mockEmailValidationService.getSkipReason as jest.Mock).mockResolvedValueOnce(+ 'Skipping send: the domain has no reachable mail servers.'+ )+ }+ const skipFrequencyCapped = (): void => {+ ;(mockRecipientPreferencesService.isFrequencyCapped as jest.Mock).mockResolvedValueOnce(true)+ }++ it.each([+ ['an opt-out', skipOptedOut, TRANSACTIONAL_EMAIL_EVENT, 'function_email', false, 'recipient_opted_out'],+ [+ 'a suppression',+ skipSuppressed,+ TRANSACTIONAL_EMAIL_EVENT,+ 'function_email',+ false,+ 'recipient_suppressed',+ ],+ [+ 'a predicted bounce',+ skipUnreachable,+ TRANSACTIONAL_EMAIL_EVENT,+ 'function_email',+ false,+ 'recipient_unreachable',+ ],+ [+ 'the frequency cap',+ skipFrequencyCapped,+ TRANSACTIONAL_EMAIL_EVENT,+ 'function_email',+ false,+ 'frequency_capped',+ ],+ ['a suppression of a test send', skipSuppressed, TRANSACTIONAL_EMAIL_EVENT, 'function_email', true, null],+ ['a suppression of a workflow email', skipSuppressed, '$pageview', 'function_email', false, null],+ ['a suppression of an SMS step', skipSuppressed, TRANSACTIONAL_EMAIL_EVENT, 'function_sms', false, null],+ ] as const)(+ 'records the email status of a send skipped by %s',+ async (_desc, skip, triggerEvent, actionType, isTest, reason) => {+ const produce = jest.fn().mockResolvedValue(undefined)+ const emailStatusService = new EmailStatusService(+ { produce } as unknown as IngestionOutputs<EmailStatusOutput>,+ { EMAIL_STATUS_ENABLED: true }+ )+ const handler = new HogFunctionHandler(+ mockHogFlowFunctionsService,+ mockRecipientPreferencesService,+ mockEmailValidationService,+ 'email',+ emailStatusService+ )+ invocation.id = new UUIDT().toString()+ invocation.state.event.event = triggerEvent+ skip()+ const invocationResult = createInvocationResult<CyclotronJobInvocationHogFlow>(invocation, {+ queue: 'hog',+ queuePriority: 0,+ })++ await handler.execute({+ invocation,+ action: { ...action, type: actionType } as Extract<HogFlowAction, { type: typeof actionType }>,+ result: invocationResult,+ hogExecutorOptions: { isTest },+ })+ await emailStatusService.flush()++ const rows = produce.mock.calls.map(([, message]) => parseJSON(message.value.toString()))+ expect(rows).toEqual(+ reason+ ? [+ expect.objectContaining({+ team_id: team.id,+ message_id: invocation.id,+ status: 'failed',+ reason,+ }),+ ]+ : []+ )+ }+ )+ })+// The billing kind is the whole point of the per-channel handlers: push bills at its own rate// (roughly half of email), so a completed invocation must emit exactly one billable_invocation// carrying the handler's billing type — never fall back to another channel's kind.@@ -575,6 +674,7 @@ describe('HogFunctionHandler', () => {mockRecipientPreferencesService,mockEmailValidationService,billingType,+ null,usageReporter)@@ -618,6 +718,7 @@ describe('HogFunctionHandler', () => {mockRecipientPreferencesService,mockEmailValidationService,'push',+ null,usageReporter)@@ -663,7 +764,8 @@ describe('HogFunctionHandler', () => {mockHogFlowFunctionsService,mockRecipientPreferencesService,mockEmailValidationService,- billingType+ billingType,+ null)// The run entered on v1; v3 is what is live now and what this step executes under.const republished = {@@ -859,6 +961,7 @@ describe('HogFunctionHandler', () => {mockRecipientPreferencesService,mockEmailValidationService,'fetch',+ null,undefined,{ awaitedStepsEnabled: true })@@ -925,6 +1028,7 @@ describe('HogFunctionHandler', () => {mockRecipientPreferencesService,mockEmailValidationService,'fetch',+ null,undefined,{ awaitedStepsEnabled })@@ -1042,6 +1146,7 @@ describe('HogFunctionHandler', () => {mockRecipientPreferencesService,mockEmailValidationService,'fetch',+ null,undefined,{ awaitedStepsEnabled })diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.tsindex 35f1b3d1fffa..991ffc996203 100644--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts@@ -18,6 +18,7 @@ import {MinimalLogEntry,} from '../../../types'import { HogExecutorExecuteAsyncOptions } from '../../hog-executor-async.service'+import { EmailSkipReason, EmailStatusService } from '../../messaging/email-status.service'import { EmailValidationService } from '../../messaging/email-validation.service'import { RecipientPreferencesService } from '../../messaging/recipient-preferences.service'import { CdpUsageReporterService } from '../../usage/cdp-usage-reporter.service'@@ -162,6 +163,9 @@ export class HogFunctionHandler implements ActionHandler {private recipientPreferencesService: RecipientPreferencesService,private emailValidationService: EmailValidationService,private hogFlowActionBillingType: HogFlowActionBillingType,+ // Required, so that a caller which builds an email handler without it fails to compile. The+ // handlers for other channels pass null.+ private emailStatusService: EmailStatusService | null,private usageReporter?: Pick<CdpUsageReporterService, 'reportBillableInvocation'>,private options: { awaitedStepsEnabled?: boolean } = {}) {}@@ -402,6 +406,18 @@ export class HogFunctionHandler implements ActionHandler {return { scheduledAt: deadline }}+ // These checks skip the send before the email service runs, so the email's status is recorded here.+ private recordSkippedEmail(+ invocation: CyclotronJobInvocationHogFunction,+ action: Action,+ reason: EmailSkipReason,+ hogExecutorOptions?: HogExecutorExecuteAsyncOptions+ ): void {+ if (action.type === 'function_email') {+ this.emailStatusService?.queueSkippedSend(invocation, reason, hogExecutorOptions?.isTest ?? false)+ }+ }+private async executeHogFunction(invocation: CyclotronJobInvocationHogFlow,action: Action,@@ -453,6 +469,12 @@ export class HogFunctionHandler implements ActionHandler {},]: []+ this.recordSkippedEmail(+ hogFunctionInvocation,+ action,+ skipReason === 'suppressed' ? 'recipient_suppressed' : 'recipient_opted_out',+ hogExecutorOptions+ )return {finished: true,skipped: true,@@ -475,6 +497,7 @@ export class HogFunctionHandler implements ActionHandler {() => this.emailValidationService.getSkipReason(hogFunctionInvocation, action))if (emailSkipReason) {+ this.recordSkippedEmail(hogFunctionInvocation, action, 'recipient_unreachable', hogExecutorOptions)return {finished: true,skipped: true,@@ -504,6 +527,7 @@ export class HogFunctionHandler implements ActionHandler {!hogExecutorOptions?.isTest &&(await this.recipientPreferencesService.isFrequencyCapped(hogFunctionInvocation, action))) {+ this.recordSkippedEmail(hogFunctionInvocation, action, 'frequency_capped', hogExecutorOptions)return {finished: true,skipped: true,diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.tsindex 6b467b61d305..a9dab8dcd977 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts@@ -184,7 +184,8 @@ describe('Hogflow Executor', () => {recipientPreferencesService,emailValidationService,cohortMembershipRepository,- hub.integrationManager+ hub.integrationManager,+ null)})diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.tsindex a4df50f07fc4..18f3b105e09d 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts@@ -30,6 +30,7 @@ import {StoredCohortMembership,} from '../cohorts/cohort-membership-repository'import { HogExecutorExecuteAsyncOptions } from '../hog-executor-async.service'+import { EmailStatusService } from '../messaging/email-status.service'import { EmailValidationService } from '../messaging/email-validation.service'import { RecipientPreferencesService } from '../messaging/recipient-preferences.service'import { CdpUsageReporterService } from '../usage/cdp-usage-reporter.service'@@ -133,6 +134,9 @@ export class HogFlowExecutorService {emailValidationService: EmailValidationService,cohortMembershipRepository: CohortMembershipRepository,integrationManager: SlackAppLookup,+ // Required, so that a caller which builds the executor without it fails to compile. Pass null+ // only where no email status is recorded.+ emailStatusService: EmailStatusService | null,duplicateObserver?: HogFlowDuplicateObserverService,usageReporter?: CdpUsageReporterService,options: { awaitedStepsEnabled?: boolean } = {}@@ -145,6 +149,7 @@ export class HogFlowExecutorService {recipientPreferencesService,emailValidationService,'fetch',+ null,usageReporter,options)@@ -153,6 +158,7 @@ export class HogFlowExecutorService {recipientPreferencesService,emailValidationService,'email',+ emailStatusService,usageReporter)const hogFunctionSmsHandler = new HogFunctionHandler(@@ -160,6 +166,7 @@ export class HogFlowExecutorService {recipientPreferencesService,emailValidationService,'sms',+ null,usageReporter,options)@@ -168,6 +175,7 @@ export class HogFlowExecutorService {recipientPreferencesService,emailValidationService,'push',+ null,usageReporter)diff --git a/nodejs/src/cdp/services/invocation-results.service.test.ts b/nodejs/src/cdp/services/invocation-results.service.test.tsindex c6bc739339b1..ebafbce62341 100644--- a/nodejs/src/cdp/services/invocation-results.service.test.ts+++ b/nodejs/src/cdp/services/invocation-results.service.test.ts@@ -55,6 +55,7 @@ describe('InvocationResultsService', () => {} as unknown as jest.Mocked<ConversionWatchersService>emailStatusService = {+ queueInvocationResults: jest.fn(),flush: jest.fn().mockResolvedValue(undefined),} as unknown as jest.Mocked<EmailStatusService>@@ -83,6 +84,8 @@ describe('InvocationResultsService', () => {expect(capturedEventsService.queueInvocationResults).toHaveBeenCalledWith(results)expect(messageAssetsService.queueInvocationResults).toHaveBeenCalledTimes(1)expect(messageAssetsService.queueInvocationResults).toHaveBeenCalledWith(results)+ expect(emailStatusService.queueInvocationResults).toHaveBeenCalledTimes(1)+ expect(emailStatusService.queueInvocationResults).toHaveBeenCalledWith(results)})it('awaits the captured-events service (which is async)', async () => {diff --git a/nodejs/src/cdp/services/invocation-results.service.ts b/nodejs/src/cdp/services/invocation-results.service.tsindex b11ae9cc3a24..77853e190926 100644--- a/nodejs/src/cdp/services/invocation-results.service.ts+++ b/nodejs/src/cdp/services/invocation-results.service.ts@@ -33,8 +33,9 @@ export interface ResultSink {* Assets tab* - `ConversionWatchersService` — per-run conversion watchers, which outlive the* run so a late conversion stays observable- * - `EmailStatusService` — status rows of transactional emails that the- * email service queues at send time+ * - `EmailStatusService` — status rows of transactional emails: the run+ * outcome when a run fails or is canceled, and+ * the rows the email service queues at send time** Callers interact with this one service instead of coordinating queue/flush* calls across the five individually. `queueInvocationResultsAndFlush` is the@@ -72,6 +73,7 @@ export class InvocationResultsService {this.warehouseWebhooksService.queueInvocationResults(results)this.messageAssetsService.queueInvocationResults(results)this.conversionWatchersService.queueInvocationResults(results)+ this.emailStatusService.queueInvocationResults(results)await this.capturedEventsService.queueInvocationResults(results)})}diff --git a/nodejs/src/cdp/services/messaging/email-status.service.test.ts b/nodejs/src/cdp/services/messaging/email-status.service.test.tsindex 97e6f4017823..bbf9ee57d9f3 100644--- a/nodejs/src/cdp/services/messaging/email-status.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email-status.service.test.ts@@ -1,10 +1,13 @@import { register } from 'prom-client'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'+import { parseJSON } from '~/common/utils/json-parse'import { UUIDT } from '~/common/utils/utils'import { EmailStatusOutput } from '../../outputs/outputs'-import { EmailStatus, EmailStatusService, buildEmailStatusRow } from './email-status.service'+import { CyclotronJobInvocation, CyclotronJobInvocationResult } from '../../types'+import { TRANSACTIONAL_EMAIL_EVENT } from '../hogflows/hogflow-sensitivity'+import { EmailStatus, EmailStatusService, EmailStatusUpdate, buildEmailStatusRow } from './email-status.service'const failedWrites = async (status: EmailStatus): Promise<number> =>(await register.getSingleMetric('cdp_email_status_write_failed')!.get()).values.find(@@ -18,36 +21,148 @@ describe('EmailStatusService', () => {it('builds a row whose created_at comes from the message id and whose version leads with the status rank', () => {const statusAt = new Date(Date.UTC(2026, 0, 3, 10, 0, 0, 123))- expect(- buildEmailStatusRow({ teamId: 2, messageId, status: 'failed', reason: 'provider_error', statusAt })- ).toEqual({+ expect(buildEmailStatusRow({ teamId: 2, messageId, status: 'bounced', reason: 'hard', statusAt })).toEqual({team_id: 2,message_id: messageId,- status: 'failed',- // 2 * 2^48 + status_at in ms, as a decimal string for ClickHouse's UInt64.- version: (2n * 2n ** 48n + BigInt(statusAt.getTime())).toString(),+ status: 'bounced',+ // 6 * 2^48 + status_at in ms, as a decimal string for ClickHouse's UInt64.+ version: (6n * 2n ** 48n + BigInt(statusAt.getTime())).toString(),created_at: '2026-01-02 03:04:05.678000',status_at: '2026-01-03 10:00:00.123000',- reason: 'provider_error',+ reason: 'hard',})})it('ranks every status above the previous one even when it is timestamped earlier', () => {- const statuses: EmailStatus[] = ['queued', 'failed', 'sent', 'delivered', 'bounced', 'complained']- const versions = statuses.map((status, index) =>+ const updates: Pick<EmailStatusUpdate, 'status' | 'reason' | 'runOutcome'>[] = [+ { status: 'queued' },+ { status: 'failed', reason: 'hog_error', runOutcome: true },+ { status: 'failed', reason: 'provider_error' },+ { status: 'sent' },+ { status: 'failed', reason: 'provider_rejected' },+ { status: 'delivered' },+ { status: 'bounced', reason: 'hard' },+ { status: 'complained' },+ ]+ const versions = updates.map((update, index) =>BigInt(buildEmailStatusRow({teamId: 2,messageId,- status,+ ...update,// Each later status carries an earlier time, as a late webhook or a clock skew would.- statusAt: new Date(createdAt + (statuses.length - index) * 60_000),+ statusAt: new Date(createdAt + (updates.length - index) * 60_000),}).version))expect(versions).toEqual([...versions].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)))- expect(new Set(versions).size).toEqual(statuses.length)+ expect(new Set(versions).size).toEqual(updates.length)+ })++ describe('run outcomes', () => {+ const runResult = (+ triggerEvent: string,+ outcome: Partial<Pick<CyclotronJobInvocationResult, 'error' | 'canceled' | 'finished'>>+ ): CyclotronJobInvocationResult =>+ ({+ invocation: {+ id: messageId,+ teamId: 2,+ functionId: 'flow-id',+ hogFlow: { id: 'flow-id' },+ state: { event: { event: triggerEvent } },+ },+ finished: true,+ ...outcome,+ }) as unknown as CyclotronJobInvocationResult++ const producedRows = async (results: CyclotronJobInvocationResult[]): Promise<Record<string, any>[]> => {+ const produce = jest.fn().mockResolvedValue(undefined)+ const service = new EmailStatusService({ produce } as unknown as IngestionOutputs<EmailStatusOutput>, {+ EMAIL_STATUS_ENABLED: true,+ })+ service.queueInvocationResults(results)+ await service.flush()+ return produce.mock.calls.map(([, message]) => parseJSON(message.value.toString()))+ }++ it.each([+ [+ 'records an errored transactional run as failed',+ TRANSACTIONAL_EMAIL_EVENT,+ { error: 'Template not found' },+ 'hog_error',+ ],+ [+ 'records a transactional run that timed out as failed',+ TRANSACTIONAL_EMAIL_EVENT,+ { error: new Error('Execution timed out') },+ 'timeout',+ ],+ [+ 'records a canceled transactional run as failed',+ TRANSACTIONAL_EMAIL_EVENT,+ { canceled: true },+ 'canceled',+ ],+ ['records nothing for a transactional run that finished', TRANSACTIONAL_EMAIL_EVENT, {}, null],+ [+ 'records nothing for a transactional run that is still in flight',+ TRANSACTIONAL_EMAIL_EVENT,+ { finished: false },+ null,+ ],+ ['records nothing for an errored workflow run', '$pageview', { error: 'Template not found' }, null],+ ['records nothing for a canceled workflow run', '$pageview', { canceled: true }, null],+ ])('%s', async (_desc, triggerEvent, outcome, reason) => {+ const rows = await producedRows([runResult(triggerEvent, outcome)])++ expect(rows).toEqual(+ reason ? [expect.objectContaining({ team_id: 2, message_id: messageId, status: 'failed', reason })] : []+ )+ })++ it.each([+ ['a sent email as sent', 'sent', undefined],+ // The transactional workflow aborts on a failed step, so a rejected send also fails its run.+ ['the reason of a send the provider rejected', 'failed', 'provider_error'],+ ] as const)('keeps %s when its run fails afterwards', async (_desc, status, reason) => {+ const step = buildEmailStatusRow({+ teamId: 2,+ messageId,+ status,+ reason,+ statusAt: new Date(createdAt + 1_000),+ })+ // The run fails after the step, so its row carries a later time.+ const [failed] = await producedRows([runResult(TRANSACTIONAL_EMAIL_EVENT, { error: 'Template not found' })])++ const latest = [step, failed].reduce((a, b) => (BigInt(b.version) > BigInt(a.version) ? b : a))+ expect(failed.status_at > step.status_at).toBe(true)+ expect(latest).toEqual(step)+ })+ })++ it.each([+ ['a transactional email', TRANSACTIONAL_EMAIL_EVENT, 1],+ ['a workflow run', '$pageview', 0],+ ])('records %s whose workflow is gone at dequeue as failed', async (_desc, triggerEvent, rows) => {+ const produce = jest.fn().mockResolvedValue(undefined)+ const service = new EmailStatusService({ produce } as unknown as IngestionOutputs<EmailStatusOutput>, {+ EMAIL_STATUS_ENABLED: true,+ })++ service.queueUnavailableRun({+ id: messageId,+ teamId: 2,+ state: { event: { event: triggerEvent } },+ } as unknown as CyclotronJobInvocation)+ await service.flush()++ expect(produce.mock.calls.map(([, message]) => parseJSON(message.value.toString()))).toEqual(+ rows ? [expect.objectContaining({ status: 'failed', reason: 'workflow_unavailable' })] : []+ )})it('returns from a flush whose produce stalls once the wait runs out', async () => {diff --git a/nodejs/src/cdp/services/messaging/email-status.service.ts b/nodejs/src/cdp/services/messaging/email-status.service.tsindex ce4f19d13c55..8a36cc9e7cd7 100644--- a/nodejs/src/cdp/services/messaging/email-status.service.ts+++ b/nodejs/src/cdp/services/messaging/email-status.service.ts@@ -5,8 +5,9 @@ import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { logger } from '~/common/utils/logger'import { EMAIL_STATUS_OUTPUT, EmailStatusOutput } from '../../outputs/outputs'-import { CyclotronJobInvocationHogFunction } from '../../types'+import { CyclotronJobInvocation, CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult } from '../../types'import { TRANSACTIONAL_EMAIL_EVENT } from '../hogflows/hogflow-sensitivity'+import { classifyError } from '../monitoring/hog-invocation-results.service'const counterEmailStatusRowsProduced = new Counter({name: 'cdp_email_status_rows_produced',@@ -23,8 +24,33 @@ const counterEmailStatusWriteFailed = new Counter({export type EmailStatus = 'queued' | 'failed' | 'sent' | 'delivered' | 'bounced' | 'complained'export type EmailStatusReason =+ // A bounce type, in the words the `$bounce_type` event property uses.+ | 'hard'+ | 'soft'+ | 'unknown'// A failed send. The provider rejected the email, or the send could not be made.- 'provider_error'+ | 'provider_error'+ // The provider refused the email after it accepted the send, for example because it found a virus.+ | 'provider_rejected'+ // A send that was skipped. The first four are also the codes the transactional email API+ // returns when it refuses a send before it queues the run.+ | EmailSkipReason+ // A run that was canceled before it finished.+ | 'canceled'+ // A run whose workflow or team no longer exists when it is dequeued.+ | 'workflow_unavailable'+ // A run that failed. The reason is the `error_kind` that hog_invocation_results stores for the+ // run, for example `hog_error` or `timeout`.+ | (string & {})++export type EmailSkipReason =+ | 'recipient_suppressed'+ | 'sending_paused'+ | 'sending_suspended'+ | 'recipient_unreachable'+ | 'missing_recipient'+ | 'recipient_opted_out'+ | 'frequency_capped'// The rank is the high part of `version`, so a message's status only moves forward in the// ReplacingMergeTree, whatever order the rows arrive in. `failed` ranks below `sent` so that a@@ -39,6 +65,14 @@ const STATUS_RANK: Record<EmailStatus, bigint> = {complained: 7n,}+// A run that fails on its email step fails after the step recorded why, for example+// `provider_error`. The run's own failure ranks lower, so it never replaces that reason.+const RUN_FAILED_RANK = 1n++// A provider rejection comes after the provider accepted the send, so it must replace `sent`. The+// provider never delivers a rejected email, so `delivered` and later statuses still rank above it.+const PROVIDER_REJECTED_RANK = 4n+// 2^48 ms is past the year 10000, so the status time never reaches into the rank bits.const STATUS_AT_BITS = 48n@@ -66,6 +100,8 @@ export interface EmailStatusUpdate {reason?: EmailStatusReason// When the status changed. Defaults to now.statusAt?: Date+ // A failure of the whole run rather than of the email step.+ runOutcome?: boolean}const isoMicroseconds = (date: Date): string => {@@ -83,7 +119,15 @@ const uuidtCreatedAt = (messageId: string): Date => {export const buildEmailStatusRow = (update: EmailStatusUpdate): EmailStatusRow => {const statusAt = update.statusAt && !Number.isNaN(update.statusAt.getTime()) ? update.statusAt : new Date()- const version = (STATUS_RANK[update.status] << STATUS_AT_BITS) + BigInt(statusAt.getTime())+ const rank =+ update.status !== 'failed'+ ? STATUS_RANK[update.status]+ : update.runOutcome+ ? RUN_FAILED_RANK+ : update.reason === 'provider_rejected'+ ? PROVIDER_REJECTED_RANK+ : STATUS_RANK.failed+ const version = (rank << STATUS_AT_BITS) + BigInt(statusAt.getTime())return {team_id: update.teamId,message_id: update.messageId,@@ -101,6 +145,13 @@ export const buildEmailStatusRow = (update: EmailStatusUpdate): EmailStatusRow =export const isTransactionalEmailSend = (invocation: CyclotronJobInvocationHogFunction): boolean =>invocation.state?.globals?.event?.event === TRANSACTIONAL_EMAIL_EVENT+const isTransactionalEmailRun = (invocation: CyclotronJobInvocation): boolean =>+ 'hogFlow' in invocation && invocation.state?.event?.event === TRANSACTIONAL_EMAIL_EVENT++// A dequeued job has no `hogFlow` yet, so only its state says which event triggered it.+const isTransactionalEmailJob = (job: CyclotronJobInvocation): boolean =>+ (job.state as { event?: { event?: string } } | null)?.event?.event === TRANSACTIONAL_EMAIL_EVENT+/*** Records each status change of a transactional email for the email_status ClickHouse table.*@@ -133,6 +184,48 @@ export class EmailStatusService {}}+ // A skipped send has no later status, so it is recorded as failed. Otherwise the message stays+ // queued, and the caller never learns that the email did not go out.+ queueSkippedSend(invocation: CyclotronJobInvocationHogFunction, reason: EmailSkipReason, isTest: boolean): void {+ if (isTest || !isTransactionalEmailSend(invocation)) {+ return+ }+ this.queue({ teamId: invocation.teamId, messageId: invocation.id, status: 'failed', reason })+ }++ // A run that fails or is canceled before its email step never reaches the email service, so the+ // run's outcome is the email's. A failed row is written even when the email went out or failed+ // earlier in the run, because a run failure ranks below both and so never replaces them.+ queueInvocationResults(results: CyclotronJobInvocationResult[]): void {+ for (const result of results) {+ if (!(result.error || result.canceled) || !isTransactionalEmailRun(result.invocation)) {+ continue+ }+ this.queue({+ teamId: result.invocation.teamId,+ messageId: result.invocation.id,+ status: 'failed',+ // Same precedence as the lifecycle row in hog_invocation_results: an error wins over a cancel.+ reason: result.error ? classifyError(result.error).kind : 'canceled',+ runOutcome: true,+ })+ }+ }++ // A job whose workflow or team is gone is dropped without a result, so nothing else records it.+ queueUnavailableRun(job: CyclotronJobInvocation): void {+ if (!isTransactionalEmailJob(job)) {+ return+ }+ this.queue({+ teamId: job.teamId,+ messageId: job.id,+ status: 'failed',+ reason: 'workflow_unavailable',+ runOutcome: true,+ })+ }+// Required by ResultSink. The rows go through the shared Kafka outputs, which the server// disconnects separately on shutdown.async stop(): Promise<void> {diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.test.tsindex c76983c6f596..1d5a227a7b25 100644--- a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts@@ -13,10 +13,11 @@ import { CdpApi } from '~/cdp/cdp-api'import { CyclotronJobInvocationHogFunction, HogFunctionType } from '~/cdp/types'import { setupExpressApp } from '~/common/api/router'import { defaultConfig } from '~/common/config/config'-import { KAFKA_APP_METRICS_2, KAFKA_LOG_ENTRIES } from '~/common/config/kafka-topics'+import { KAFKA_APP_METRICS_2, KAFKA_EMAIL_STATUS, KAFKA_LOG_ENTRIES } from '~/common/config/kafka-topics'import { closeHub, createHub } from '~/common/utils/db/hub'import { PostgresUse } from '~/common/utils/db/postgres'import * as envUtils from '~/common/utils/env-utils'+import { UUIDT } from '~/common/utils/utils'import { createCdpConsumerDeps } from '~/tests/helpers/cdp'import { waitForExpect } from '~/tests/helpers/expectations'import { createTestTeamFixture } from '~/tests/helpers/sql'@@ -444,15 +445,24 @@ describe('EmailTrackingService', () => {functionId,parentRunId,workflowVersion,+ transactionalMessageId,}: {functionId: stringparentRunId?: stringworkflowVersion?: number+ // Sends the bounce as SES reports it for a transactional email with this message id.+ transactionalMessageId?: string}): Promise<supertest.Response> => {// Third arg opts into the versioned payload, which `generate` won't emit by default// until phase two of the rollout — see EMIT_VERSIONED_PAYLOAD in tracking-code.ts.const trackingCode = signer.generate(- { functionId, id: invocationId, teamId: team.id, parentRunId, workflowVersion },+ {+ functionId,+ id: transactionalMessageId ?? invocationId,+ teamId: team.id,+ parentRunId,+ workflowVersion,+ },false,workflowVersion !== undefined)@@ -464,6 +474,12 @@ describe('EmailTrackingService', () => {messageId: 'ses-message-id',destination: ['[email protected]'],headers: [{ name: TRACKING_CODE_HEADER_NAME, value: trackingCode }],+ ...(transactionalMessageId+ ? {+ commonHeaders: { to: ['[email protected]'] },+ tags: { ph_email_status: ['true'] },+ }+ : {}),},bounce: {bounceType: 'Permanent',@@ -519,6 +535,30 @@ describe('EmailTrackingService', () => {})})+ it('records the bounced status of a transactional email', async () => {+ const hogFlow = await insertHogFlow(+ hub.postgres,+ new FixtureHogFlowBuilder().withTeamId(team.id).build()+ )+ const messageId = new UUIDT().toString()++ const res = await postBounce({ functionId: hogFlow.id, transactionalMessageId: messageId })+ expect(res.status).toBe(200)++ // The webhook flushes the status row before it answers.+ expect(mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_EMAIL_STATUS)).toEqual([+ expect.objectContaining({+ key: messageId,+ value: expect.objectContaining({+ team_id: team.id,+ message_id: messageId,+ status: 'bounced',+ reason: 'hard',+ }),+ }),+ ])+ })+it('records the metric but writes no log entry when the bounce resolves to a hog_function', async () => {const res = await postBounce({ functionId: hogFunction.id })expect(res.status).toBe(200)diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.tsindex 645866c70885..5b806ab400ab 100644--- a/nodejs/src/cdp/services/messaging/email-tracking.service.ts+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.ts@@ -20,6 +20,7 @@ import { HogFlowManagerService } from '../hogflows/hogflow-manager.service'import { HogFunctionManagerService } from '../managers/hog-function-manager.service'import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.service'import { HogFunctionMonitoringService } from '../monitoring/hog-function-monitoring.service'+import { EmailStatusService } from './email-status.service'import { EmailSuppressionService } from './email-suppression.service'import { escapeHtml } from './helpers/escape-html'import { SES_LINK_INDEX_TAG, SesWebhookHandler } from './helpers/ses'@@ -280,7 +281,8 @@ export class EmailTrackingService {private capturedEventsService: CapturedEventsService,private teamWorkflowsConfigService: TeamWorkflowsConfigService,private trackingCodeSigner: EmailTrackingCodeSigner,- private emailSuppressionService: EmailSuppressionService+ private emailSuppressionService: EmailSuppressionService,+ private emailStatusService: EmailStatusService | null = null) {const allowedTopicArns = (process.env.SES_ALLOWED_SNS_TOPIC_ARNS ?? '').split(',')this.sesWebhookHandler = new SesWebhookHandler(this.trackingCodeSigner, allowedTopicArns)@@ -493,6 +495,7 @@ export class EmailTrackingService {hardBounceRecipients,complainedRecipients,deliveredRecipients,+ emailStatusUpdates,} = await this.sesWebhookHandler.handleWebhook({body: parseJSON(req.body),headers: req.headers,@@ -539,6 +542,24 @@ export class EmailTrackingService {emailTrackingErrorsCounter.inc({ error_type: 'track_logs_failed', source: 'ses' })}+ // Best-effort like the writes around it: queue and flush never throw.+ if (this.emailStatusService && emailStatusUpdates?.length) {+ for (const update of emailStatusUpdates) {+ const teamId = parseInt(update.teamId, 10)+ if (Number.isNaN(teamId)) {+ continue+ }+ this.emailStatusService.queue({+ teamId,+ messageId: update.invocationId,+ status: update.status,+ reason: update.reason,+ statusAt: new Date(update.timestamp),+ })+ }+ await this.emailStatusService.flush()+ }+// Feed bounces, complaints and successful deliveries into the suppression list. Wrapped// so a failure here never affects the webhook's 200 response to SNS. Deliveries are// processed first so a delivery + bounce in the same batch nets out conservativelydiff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.tsindex d3655ef28311..fcfade0db311 100644--- a/nodejs/src/cdp/services/messaging/email.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts@@ -1056,17 +1056,33 @@ describe('EmailService', () => {})it.each([- ['an ordinary template', {}, [{ Name: 'ph_id', Value: expect.stringMatching(/^[A-Za-z0-9_-]+$/) }]],+ [+ 'an ordinary template',+ {},+ '$pageview',+ [{ Name: 'ph_id', Value: expect.stringMatching(/^[A-Za-z0-9_-]+$/) }],+ ],['a sensitive template',{ sensitive: true },+ '$pageview',[{ Name: 'ph_id', Value: expect.stringMatching(/^[A-Za-z0-9_-]+$/) },{ Name: 'ph_sensitive', Value: 'true' },],],- ])('should send an email if verified, for %s', async (_name, extraMetadata, expectedTags) => {+ [+ 'a transactional email run',+ {},+ TRANSACTIONAL_EMAIL_EVENT,+ [+ { Name: 'ph_id', Value: expect.stringMatching(/^[A-Za-z0-9_-]+$/) },+ { Name: 'ph_email_status', Value: 'true' },+ ],+ ],+ ])('should send an email if verified, for %s', async (_name, extraMetadata, triggerEvent, expectedTags) => {invocation.hogFunction.metadata = { message_category_type: 'transactional', ...extraMetadata }+ invocation.state.globals.event.event = triggerEventsendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })const result = await service.executeSendEmail(invocation)expect(result.error).toBeUndefined()@@ -1099,6 +1115,26 @@ describe('EmailService', () => {const sesRejects = (): void => {sendEmailSpy.mockRejectedValue(new Error('SES error'))}+ const teamSuspended = (): void => {+ sesAccepts()+ jest.spyOn(service['teamWorkflowsConfigService'], 'getEmailSendingSuspension').mockResolvedValue('staff')+ }+ const workflowPaused = (): void => {+ sesAccepts()+ invocation.hogFunction.metadata = { email_sending_paused_at: '2026-01-01T00:00:00Z' }+ }+ const recipientMissing = (): void => {+ sesAccepts()+ invocation.queueParameters = createEmailParams({+ from: { integrationId: 1 },+ to: { email: '', name: 'Test User' },+ })+ }+ const recipientSuppressed = (): void => {+ sesAccepts()+ jest.spyOn(service['emailSuppressionService'], 'isSuppressed').mockResolvedValue(true)+ }+it.each([['a transactional email that SES accepts', TRANSACTIONAL_EMAIL_EVENT, false, sesAccepts, 'sent', ''],[@@ -1109,9 +1145,50 @@ describe('EmailService', () => {'failed','provider_error',],+ [+ 'a transactional email skipped for a suspended team',+ TRANSACTIONAL_EMAIL_EVENT,+ false,+ teamSuspended,+ 'failed',+ 'sending_suspended',+ ],+ [+ 'a transactional email skipped for a paused workflow',+ TRANSACTIONAL_EMAIL_EVENT,+ false,+ workflowPaused,+ 'failed',+ 'sending_paused',+ ],+ [+ 'a transactional email skipped for a missing recipient',+ TRANSACTIONAL_EMAIL_EVENT,+ false,+ recipientMissing,+ 'failed',+ 'missing_recipient',+ ],+ [+ 'a transactional email skipped for a suppressed recipient',+ TRANSACTIONAL_EMAIL_EVENT,+ false,+ recipientSuppressed,+ 'failed',+ 'recipient_suppressed',+ ],['a test send of a transactional email', TRANSACTIONAL_EMAIL_EVENT, true, sesAccepts, null, null],+ [+ 'a skipped test send of a transactional email',+ TRANSACTIONAL_EMAIL_EVENT,+ true,+ teamSuspended,+ null,+ null,+ ],['a workflow email that SES accepts', '$pageview', false, sesAccepts, null, null],['a workflow email that SES rejects', '$pageview', false, sesRejects, null, null],+ ['a skipped workflow email', '$pageview', false, recipientSuppressed, null, null],])('records the status of %s', async (_name, triggerEvent, isTest, setup, status, reason) => {const produce = jest.fn().mockResolvedValue(undefined)const emailStatusService = new EmailStatusService(diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.tsindex 2bfa8417d268..cb74135e7723 100644--- a/nodejs/src/cdp/services/messaging/email.service.ts+++ b/nodejs/src/cdp/services/messaging/email.service.ts@@ -30,7 +30,7 @@ import {} from './email-tracking.service'import { mailDevTransport, mailDevWebUrl } from './helpers/maildev'import { maybeAddPreheaderToEmail } from './helpers/preheader'-import { SES_SENSITIVE_TAG } from './helpers/ses'+import { SES_EMAIL_STATUS_TAG, SES_SENSITIVE_TAG } from './helpers/ses'import { quoteMailbox, removeSuppressedRecipients, unquoteMailbox } from './helpers/suppressed-recipients'import { EmailTrackingCodeSigner, TRACKING_CODE_HEADER_NAME } from './helpers/tracking-code'import { addUtmTagsToEmail, renderUtmOverrides, resolveUtmTags } from './helpers/utm'@@ -428,6 +428,7 @@ export class EmailService {: 'Skipping send: our email provider paused sending for this project. Check the Reputation tab to see what to fix.'addLog('warn', skipReason)result.emailSendResult = { status: 'skipped', reason: skipReason }+ this.emailStatusService?.queueSkippedSend(invocation, 'sending_suspended', isTest)logger.warn('Skipping email send for a suspended team', {teamId: invocation.teamId,cause: suspensionCause,@@ -464,6 +465,7 @@ export class EmailService {: `Skipping send: email sending is paused for this workflow.${pauseDetail} Resume it from the workflow page once the audience is cleaned up.`addLog('error', skipReason)result.emailSendResult = { status: 'skipped', reason: skipReason }+ this.emailStatusService?.queueSkippedSend(invocation, 'sending_paused', isTest)if (!isTest) {result.metrics.push({team_id: invocation.teamId,@@ -515,6 +517,7 @@ export class EmailService {count: 1,})}+ this.emailStatusService?.queueSkippedSend(invocation, 'missing_recipient', isTest)result.skipped = trueresult.invocation.state.vmState?.stack.push({ success: false })return result@@ -535,6 +538,7 @@ export class EmailService {const skipReason = `Skipping send: ${suppression.removed.join(', ')} ${suppression.removed.length === 1 ? 'is' : 'are'} on the suppression list and no cc address can receive the email instead`addLog('info', skipReason)result.emailSendResult = { status: 'skipped', reason: skipReason }+ this.emailStatusService?.queueSkippedSend(invocation, 'recipient_suppressed', isTest)if (!isTest) {result.metrics.push({team_id: invocation.teamId,@@ -1166,6 +1170,9 @@ export class EmailService {...(result.invocation.hogFunction?.metadata?.sensitive === true? [{ Name: SES_SENSITIVE_TAG, Value: 'true' }]: []),+ ...(!isTest && isTransactionalEmailSend(result.invocation)+ ? [{ Name: SES_EMAIL_STATUS_TAG, Value: 'true' }]+ : []),],FeedbackForwardingEmailAddress: from.email,}diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts b/nodejs/src/cdp/services/messaging/helpers/ses.test.tsindex ace2fd9dcbb6..04063ec6d980 100644--- a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts+++ b/nodejs/src/cdp/services/messaging/helpers/ses.test.ts@@ -1001,6 +1001,78 @@ describe('SesWebhookHandler', () => {})})+ describe('email status updates', () => {+ // A transactional send carries the status tag and is addressed To one recipient; the cc copy+ // shares the message, so its feedback must not move the email's status.+ const transactionalMail = {+ ...baseMail,+ destination: ['[email protected]', '[email protected]'],+ commonHeaders: { subject: 'Reset your password', to: ['"Jane Doe" <[email protected]>'] },+ tags: { ...baseMail.tags, ph_email_status: ['true'] },+ }+ const delivery = (recipients: string[]) => ({+ eventType: 'Delivery',+ delivery: { timestamp: '2025-10-03T12:01:00Z', recipients },+ })+ const bounce = (bounceType: string, emailAddress = '[email protected]') => ({+ eventType: 'Bounce',+ bounce: { bounceType, bouncedRecipients: [{ emailAddress }], timestamp: '2025-10-03T12:02:00Z' },+ })+ const complaint = (emailAddress = '[email protected]', complaintFeedbackType?: string) => ({+ eventType: 'Complaint',+ complaint: {+ complainedRecipients: [{ emailAddress }],+ timestamp: '2025-10-03T12:03:00Z',+ ...(complaintFeedbackType ? { complaintFeedbackType } : {}),+ },+ })+ const update = (status: string, timestamp: string, reason?: string) => [+ { teamId: '1', invocationId: 'inv456', status, timestamp, ...(reason ? { reason } : {}) },+ ]++ it.each([+ [+ 'a delivery to the To recipient',+ {},+ delivery(['[email protected]']),+ update('delivered', '2025-10-03T12:01:00Z'),+ ],+ ['a hard bounce', {}, bounce('Permanent'), update('bounced', '2025-10-03T12:02:00Z', 'hard')],+ ['a soft bounce', {}, bounce('Transient'), update('bounced', '2025-10-03T12:02:00Z', 'soft')],+ [+ 'an undetermined bounce',+ {},+ bounce('Undetermined'),+ update('bounced', '2025-10-03T12:02:00Z', 'unknown'),+ ],+ ['a complaint', {}, complaint(), update('complained', '2025-10-03T12:03:00Z')],+ ['a not-spam correction', {}, complaint('[email protected]', 'Not-Spam'), []],+ [+ 'a rejection after SES accepted the send',+ {},+ { eventType: 'Reject', reject: { reason: 'Bad content' } },+ update('failed', transactionalMail.timestamp, 'provider_rejected'),+ ],+ ['a delivery of an untagged email', { tags: baseMail.tags }, delivery(['[email protected]']), []],+ ['a delivery to the cc recipient only', {}, delivery(['[email protected]']), []],+ ['a bounce of the cc recipient', {}, bounce('Permanent', '[email protected]'), []],+ ['a complaint from a bcc recipient', {}, complaint('[email protected]'), []],+ [+ 'a bounce of a test send',+ { headers: [{ name: TRACKING_CODE_HEADER, value: signer.generate(baseInvocation, true) }] },+ bounce('Permanent'),+ [],+ ],+ ['a bounce with only the unsigned tag code', { headers: undefined }, bounce('Permanent'), []],+ ])('gives the status update for %s', async (_desc, mailOverrides, eventFields, expected) => {+ const body = [{ mail: { ...transactionalMail, ...mailOverrides }, ...eventFields }]++ const result = await handler.handleWebhook({ body, headers: {} })++ expect(result.emailStatusUpdates).toEqual(expected)+ })+ })+describe('security: TopicArn allowlist + signed-code gate', () => {// Two-layer hardening: the TopicArn allowlist restricts which SNS topics we accept events from,// and state-changing writes require a signed tracking code (unsigned carriers only contributediff --git a/nodejs/src/cdp/services/messaging/helpers/ses.ts b/nodejs/src/cdp/services/messaging/helpers/ses.tsindex 04a6ced57eac..2d1b17f76880 100644--- a/nodejs/src/cdp/services/messaging/helpers/ses.ts+++ b/nodejs/src/cdp/services/messaging/helpers/ses.ts@@ -1,4 +1,5 @@import crypto from 'node:crypto'+import addressparser from 'nodemailer/lib/addressparser'import { Counter } from 'prom-client'import { z } from 'zod'@@ -7,6 +8,8 @@ import { parseJSON } from '~/common/utils/json-parse'import { logger } from '~/common/utils/logger'import { fetch } from '~/common/utils/request'+import type { EmailStatus, EmailStatusReason } from '../email-status.service'+import { unquoteMailbox } from './suppressed-recipients'import { EmailTrackingCodeSigner, TRACKING_CODE_HEADER_NAME, trackingCodeFormatCounter } from './tracking-code'/**@@ -44,7 +47,11 @@ const SesMailSchema = z.object({destination: z.array(z.string()),headersTruncated: z.boolean().optional(),headers: z.array(z.object({ name: z.string(), value: z.string() })).optional(),- commonHeaders: z.object({ subject: z.string().optional() }).passthrough().optional(),+ commonHeaders: z+ // A `to` of another shape only turns off the status update, never the whole record.+ .object({ subject: z.string().optional(), to: z.array(z.string()).nullish().catch(undefined) })+ .passthrough()+ .optional(),tags: z.record(z.string(), z.array(z.string())).optional(), // your message tags: { user_id: ["u_123"] }})@@ -168,7 +175,7 @@ const BOUNCE_TYPE_TO_METRIC_NAME: Record<'Permanent' | 'Transient' | 'Undetermin// The words senders use, rather than the provider's. This lands on a customer-facing event, where// "Permanent" reads as a severity rather than as the reason the address will never accept mail.-const BOUNCE_TYPE_TO_EVENT_PROPERTY: Record<'Permanent' | 'Transient' | 'Undetermined', string> = {+const BOUNCE_TYPE_TO_EVENT_PROPERTY: Record<'Permanent' | 'Transient' | 'Undetermined', 'hard' | 'soft' | 'unknown'> = {Permanent: 'hard',Transient: 'soft',Undetermined: 'unknown',@@ -217,6 +224,67 @@ export const SES_LINK_INDEX_TAG = 'phl'// tells the links apart.export const SES_SENSITIVE_TAG = 'ph_sensitive'+// SES message tag set at send time on transactional emails, the only emails whose status is recorded,+// and echoed back on every event for that message. SES allows only ASCII letters, digits, underscores+// and dashes in a tag, so the value is 'true' as for SES_SENSITIVE_TAG.+export const SES_EMAIL_STATUS_TAG = 'ph_email_status'++export type SesEmailStatusUpdate = {+ teamId: string+ invocationId: string+ status: EmailStatus+ reason?: EmailStatusReason+ timestamp: string+}++const normalizeAddress = (address: string): string => unquoteMailbox(address).trim().toLowerCase()++// The addresses in the To header. SES reports each entry as written, so a display name can wrap the address.+const toHeaderAddresses = (rec: SesEventRecord): Set<string> =>+ new Set(+ (rec.mail.commonHeaders?.to ?? []).flatMap((entry) =>+ addressparser(entry, { flatten: true }).map((parsed) => normalizeAddress(parsed.address))+ )+ )++/**+ * The status change a Delivery, Bounce, Complaint or Reject record makes to the email it reports on, or null.+ *+ * The status describes the email to its To recipient. SES reports cc and bcc copies under the same+ * message, so a record counts only when one of its recipients is in the To header.+ */+const resolveEmailStatusUpdate = (+ rec: SesEventRecord+): Pick<SesEmailStatusUpdate, 'status' | 'reason' | 'timestamp'> | null => {+ const to = toHeaderAddresses(rec)+ const reachesTo = (addresses: string[]): boolean => addresses.some((address) => to.has(normalizeAddress(address)))+ switch (rec.eventType) {+ case 'Delivery':+ return reachesTo(rec.delivery.recipients ?? [])+ ? { status: 'delivered', timestamp: rec.delivery.timestamp }+ : null+ case 'Bounce':+ return reachesTo(rec.bounce.bouncedRecipients.map((r) => r.emailAddress))+ ? {+ status: 'bounced',+ reason: BOUNCE_TYPE_TO_EVENT_PROPERTY[rec.bounce.bounceType],+ timestamp: rec.bounce.timestamp,+ }+ : null+ case 'Complaint':+ // A "not-spam" feedback type corrects an earlier spam report, so it is not a complaint.+ return rec.complaint.complaintFeedbackType?.toLowerCase() !== 'not-spam' &&+ reachesTo(rec.complaint.complainedRecipients.map((r) => r.emailAddress))+ ? { status: 'complained', timestamp: rec.complaint.timestamp }+ : null+ case 'Reject':+ // SES refuses the whole message, so the email fails for its To recipient too.+ return { status: 'failed', reason: 'provider_rejected', timestamp: rec.mail.timestamp }+ default:+ return null+ }+}+const sensitiveLinkOrigin = (link: string): string => {try {const url = new URL(link)@@ -612,6 +680,8 @@ export class SesWebhookHandler {emailAddresses: string[]timestamp?: string}[]+ // Status changes of transactional emails, for the email_status table.+ emailStatusUpdates?: SesEmailStatusUpdate[]}> {// Payloads carry recipients and clicked links, including reset links from sensitive emails,// so the logs keep identifiers only.@@ -714,6 +784,7 @@ export class SesWebhookHandler {emailAddresses: string[]timestamp?: string}[] = []+ const emailStatusUpdates: SesEmailStatusUpdate[] = []for (const rec of records) {logger.info('[SesWebhookHandler] processing record', {@@ -926,6 +997,14 @@ export class SesWebhookHandler {deliveredRecipients.push({ teamId, emailAddresses: emails, timestamp: rec.delivery.timestamp })}}++ // A status write is state-changing too, so it needs the signed code like the writes above.+ if (suppressionAllowed && invocationId && rec.mail.tags?.[SES_EMAIL_STATUS_TAG]?.[0] === 'true') {+ const update = resolveEmailStatusUpdate(rec)+ if (update) {+ emailStatusUpdates.push({ teamId, invocationId, ...update })+ }+ }}return {@@ -937,6 +1016,7 @@ export class SesWebhookHandler {hardBounceRecipients,complainedRecipients,deliveredRecipients,+ emailStatusUpdates,}}}diff --git a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.tsindex 379df2ee06ee..3fd19719bca8 100644--- a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts+++ b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.ts@@ -133,7 +133,7 @@ const truncate = (value: string, max: number): string => {// status_idx skipping index stays small. Only the message lands in// `error_message`, never the stack trace — app-level executors pass the whole// `Error` here, and its stack would otherwise leak into the Invocations tab.-const classifyError = (error: unknown): { kind: string; message: string } => {+export const classifyError = (error: unknown): { kind: string; message: string } => {if (!error) {return { kind: '', message: '' }}