: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(messaging): suppress recipients who report email as spam (#89831)
Meikel Ratz1433111f3b7d
diff --git a/nodejs/src/cdp/services/messaging/email-suppression.service.test.ts b/nodejs/src/cdp/services/messaging/email-suppression.service.test.tsindex 7f508d67c543..6bf1d8dfb400 100644--- a/nodejs/src/cdp/services/messaging/email-suppression.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email-suppression.service.test.ts@@ -203,6 +203,102 @@ describe('EmailSuppressionService', () => {})})+ describe('recordComplaints', () => {+ it('suppresses immediately with source=COMPLAINT and the feedback type in the reason', async () => {+ const svc = new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ const email = '[email protected]'+ await svc.recordComplaints(team.id, [email], 'abuse')++ expect(await readRow(email)).toMatchObject({+ identifier: email,+ source: 'COMPLAINT',+ suppressed: true,+ transient_bounce_count: 0,+ deleted: false,+ })+ const detail = await hub.postgres.query<{ reason: string }>(+ PostgresUse.COMMON_READ,+ `SELECT reason FROM posthog_messagesuppression WHERE team_id = $1 AND identifier = $2`,+ [team.id, email],+ 'test-read-complaint-reason'+ )+ expect(detail.rows[0].reason).toBe('Auto-suppressed after a spam complaint (feedback type: abuse)')+ })++ it('re-keys an unsuppressed BOUNCE counter to COMPLAINT when a complaint lands', async () => {+ process.env.EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD = '5'+ const svc = new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ const email = '[email protected]'+ await svc.recordTransientBounces(team.id, [email], 'temp')+ expect(await readRow(email)).toMatchObject({ source: 'BOUNCE', suppressed: false })++ await svc.recordComplaints(team.id, [email])+ expect(await readRow(email)).toMatchObject({+ source: 'COMPLAINT',+ suppressed: true,+ // Counter is history; we keep it. The complaint is now the operative reason.+ transient_bounce_count: 1,+ })+ })++ it('does not override a MANUAL entry (user-managed rows are authoritative)', async () => {+ const email = '[email protected]'+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `INSERT INTO posthog_messagesuppression+ (id, team_id, identifier, source, reason, transient_bounce_count,+ suppressed, suppressed_at, deleted, created_at, updated_at)+ VALUES (gen_random_uuid(), $1, $2, 'MANUAL', 'Manually added', 0,+ true, NOW(), false, NOW(), NOW())`,+ [team.id, email],+ 'test-insert-manual'+ )++ const svc = new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ await svc.recordComplaints(team.id, [email], 'abuse')++ expect(await readRow(email)).toMatchObject({ source: 'MANUAL', suppressed: true })+ const detail = await hub.postgres.query<{ reason: string }>(+ PostgresUse.COMMON_READ,+ `SELECT reason FROM posthog_messagesuppression WHERE team_id = $1 AND identifier = $2`,+ [team.id, email],+ 'test-read-reason'+ )+ expect(detail.rows[0].reason).toBe('Manually added')+ })++ it.each(['hard', 'transient'] as const)(+ 'keeps source and reason on a complaint row when a later %s bounce lands',+ async (bounceType) => {+ // Threshold=1 so one soft bounce crosses it. Above 1 the transient path never+ // reaches the branch that rewrites the reason, and the case would prove nothing.+ process.env.EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD = '1'+ const svc = new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ const email = `complained-then-${bounceType}@example.com`+ const diagnostic = 'smtp; 550 5.1.1 user unknown'++ await svc.recordComplaints(team.id, [email], 'abuse')+ await (bounceType === 'hard'+ ? svc.recordHardBounces(team.id, [email], diagnostic)+ : svc.recordTransientBounces(team.id, [email], diagnostic))++ expect(await readRow(email)).toMatchObject({ source: 'COMPLAINT', suppressed: true })+ const detail = await hub.postgres.query<{ reason: string; last_bounce_diagnostic: string }>(+ PostgresUse.COMMON_READ,+ `SELECT reason, last_bounce_diagnostic FROM posthog_messagesuppression+ WHERE team_id = $1 AND identifier = $2`,+ [team.id, email],+ 'test-read-complaint-then-bounce'+ )+ // Without the precedence the row would read as a bounce suppression while still+ // tagged COMPLAINT.+ expect(detail.rows[0].reason).toBe('Auto-suppressed after a spam complaint (feedback type: abuse)')+ // The bounce is still recorded, just not as the row's headline reason.+ expect(detail.rows[0].last_bounce_diagnostic).toBe(diagnostic)+ }+ )+ })+describe('cache invalidation', () => {it("a write for one team does not evict another team's cached entries", async () => {// Guards against a regression from markForRefresh(touchedKeys) back to clear() — clear()diff --git a/nodejs/src/cdp/services/messaging/email-suppression.service.ts b/nodejs/src/cdp/services/messaging/email-suppression.service.tsindex f72b0bf40a2f..e8ee9bf1c879 100644--- a/nodejs/src/cdp/services/messaging/email-suppression.service.ts+++ b/nodejs/src/cdp/services/messaging/email-suppression.service.ts@@ -6,7 +6,7 @@ import { logger } from '~/common/utils/logger'const cdpEmailSuppressionTotal = new Counter({name: 'cdp_email_suppression_total',- help: 'Email suppression-list outcomes. `suppressed_hit` = a send skipped because the recipient is on the list; `transient_bounce` = a soft-bounce counter increment; `hard_bounce` = an address suppressed immediately after a permanent bounce.',+ help: 'Email suppression-list outcomes. `suppressed_hit` = a send skipped because the recipient is on the list; `transient_bounce` = a soft-bounce counter increment; `hard_bounce` = an address suppressed immediately after a permanent bounce; `complaint` = an address suppressed immediately after a spam complaint.',labelNames: ['result'],})@@ -41,7 +41,9 @@ export function emailSuppressionConfigFromEnv(): EmailSuppressionConfig {* Write path (SES webhook): `recordTransientBounces` counts consecutive soft bounces per address* and flips it to suppressed once the count crosses the threshold; `recordDeliveries` resets the* count on any successful delivery so a one-off outage never accumulates into a suppression.- * Manual entries (added via the API/UI) are never touched by the bounce/delivery bookkeeping.+ * `recordHardBounces` and `recordComplaints` suppress an address immediately — a permanent bounce+ * or a spam complaint is definitive. Manual entries (added via the API/UI) are never touched by+ * any of this bookkeeping.** Cache invalidation window (v1):* The LazyLoader cache is per-process. `clear()` only fires on the Node process that performed@@ -94,7 +96,7 @@ export class EmailSuppressionService {/*** Record one or more soft (Transient) bounces. Increments each address's consecutive-bounce* counter and auto-suppresses it in the same statement once it reaches the threshold. Manual- * entries keep their suppressed state untouched.+ * entries keep their suppressed state untouched, and complaint entries keep their reason.*/public async recordTransientBounces(teamId: number, emails: string[], diagnostic?: string): Promise<void> {const identifiers = Array.from(new Set(emails.map(normalizeIdentifier).filter(Boolean)))@@ -138,8 +140,10 @@ export class EmailSuppressionService {AND posthog_messagesuppression.suppressed = falseAND posthog_messagesuppression.transient_bounce_count + 1 >= $3 THEN NOW()ELSE posthog_messagesuppression.suppressed_at END,+ -- Same precedence as the hard-bounce path: a COMPLAINT row keeps its reason so it+ -- can't end up labelled COMPLAINT while reading as a soft-bounce suppression.reason = CASE- WHEN posthog_messagesuppression.source <> 'MANUAL'+ WHEN posthog_messagesuppression.source NOT IN ('MANUAL', 'COMPLAINT')AND posthog_messagesuppression.transient_bounce_count + 1 >= $3 THEN $2ELSE posthog_messagesuppression.reason END,-- A provably-undeliverable address coming back over threshold un-deletes itself.@@ -163,7 +167,9 @@ export class EmailSuppressionService {/*** Record one or more hard (Permanent) bounces. Suppresses each address immediately — no* threshold, no counter — because a permanent bounce is definitive. Manual entries are never- * touched. If a row already exists as an unsuppressed BOUNCE counter, this escalates it.+ * touched. If a row already exists as an unsuppressed BOUNCE counter, this escalates it. A row+ * that a complaint already claimed keeps its source and reason, so the bounce refreshes the+ * diagnostic without relabelling why the address is suppressed.*/public async recordHardBounces(teamId: number, emails: string[], diagnostic?: string): Promise<void> {const identifiers = Array.from(new Set(emails.map(normalizeIdentifier).filter(Boolean)))@@ -201,8 +207,12 @@ export class EmailSuppressionService {WHEN posthog_messagesuppression.source = 'MANUAL' THEN posthog_messagesuppression.suppressed_atWHEN posthog_messagesuppression.suppressed = false THEN NOW()ELSE posthog_messagesuppression.suppressed_at END,+ -- A complaint outranks a bounce as the reason a row exists, so it keeps its reason+ -- here the way a manual entry does. This upsert never reassigns the source, so+ -- overwriting the reason on a COMPLAINT row would leave the two contradicting each+ -- other. The bounce still refreshes the diagnostic and the suppression state above.reason = CASE- WHEN posthog_messagesuppression.source = 'MANUAL' THEN posthog_messagesuppression.reason+ WHEN posthog_messagesuppression.source IN ('MANUAL', 'COMPLAINT') THEN posthog_messagesuppression.reasonELSE EXCLUDED.reason END,-- A provably-undeliverable address coming back un-deletes itself.deleted = CASE@@ -221,6 +231,75 @@ export class EmailSuppressionService {}}+ /**+ * Record one or more spam complaints. Suppresses each address immediately — no threshold —+ * because a complaint is the recipient asking us to stop, and provider complaint-rate+ * thresholds are far tighter than bounce thresholds. Manual entries are never touched; any+ * other existing row is re-keyed to COMPLAINT so the list shows the operative reason. The+ * bounce paths then treat COMPLAINT as authoritative, so a later bounce can't relabel the row.+ */+ public async recordComplaints(teamId: number, emails: string[], feedbackType?: string): Promise<void> {+ const identifiers = Array.from(new Set(emails.map(normalizeIdentifier).filter(Boolean)))+ if (identifiers.length === 0) {+ return+ }++ // The feedback type is the provider's classification of the report (e.g. "abuse",+ // "fraud"); surface it in the reason for operator visibility.+ const reason = feedbackType+ ? `Auto-suppressed after a spam complaint (feedback type: ${feedbackType.slice(0, 100)})`+ : 'Auto-suppressed after a spam complaint'++ // Params: teamId, reason, then one identifier per row.+ const valueClauses: string[] = []+ const params: (number | string | null)[] = [teamId, reason]+ identifiers.forEach((identifier, i) => {+ const p = params.length + 1 + i+ valueClauses.push(+ `(gen_random_uuid(), $1, $${p}, 'COMPLAINT', $2, 0, NULL, NULL, true, NOW(), false, NOW(), NOW())`+ )+ })+ params.push(...identifiers)++ const query = `+ INSERT INTO posthog_messagesuppression+ (id, team_id, identifier, source, reason, transient_bounce_count, last_bounce_at,+ last_bounce_diagnostic, suppressed, suppressed_at, deleted, created_at, updated_at)+ VALUES ${valueClauses.join(', ')}+ ON CONFLICT (team_id, identifier) DO UPDATE SET+ -- Manual entries are authoritative; never override them. Any other row re-keys to+ -- COMPLAINT: the complaint is the operative reason the address is suppressed now.+ source = CASE+ WHEN posthog_messagesuppression.source = 'MANUAL' THEN posthog_messagesuppression.source+ ELSE 'COMPLAINT' END,+ suppressed = CASE+ WHEN posthog_messagesuppression.source = 'MANUAL' THEN posthog_messagesuppression.suppressed+ ELSE true END,+ suppressed_at = CASE+ WHEN posthog_messagesuppression.source = 'MANUAL' THEN posthog_messagesuppression.suppressed_at+ WHEN posthog_messagesuppression.suppressed = false THEN NOW()+ ELSE posthog_messagesuppression.suppressed_at END,+ reason = CASE+ WHEN posthog_messagesuppression.source = 'MANUAL' THEN posthog_messagesuppression.reason+ ELSE EXCLUDED.reason END,+ -- A soft-deleted row comes back: the complaint is fresh evidence the recipient+ -- must not be mailed.+ deleted = CASE+ WHEN posthog_messagesuppression.source = 'MANUAL' THEN posthog_messagesuppression.deleted+ ELSE false END,+ updated_at = NOW()+ `++ try {+ await this.postgres.query(PostgresUse.COMMON_WRITE, query, params, 'recordComplaints')+ cdpEmailSuppressionTotal.inc({ result: 'complaint' }, identifiers.length)+ // Only invalidate the keys we touched — cross-team entries stay warm.+ this.lazyLoader.markForRefresh(identifiers.map((identifier) => toKey(teamId, identifier)))+ } catch (error) {+ logger.error('[EmailSuppression] Failed to record complaints', { teamId, error })+ }+ }+/*** Record successful deliveries. Resets the consecutive-bounce counter for auto (non-manual)* entries that haven't yet been suppressed, so a transient outage never accumulates.diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.test.tsindex 9d55b56cfce0..0e8dae20bb25 100644--- a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts@@ -565,6 +565,39 @@ describe('EmailTrackingService', () => {.send(JSON.stringify(envelope))}+ const postComplaint = async (functionId: string, emailAddress: string): Promise<supertest.Response> => {+ const trackingCode = signer.generate({ functionId, id: 'invocation-id', teamId: team.id })+ const sesRecord = {+ eventType: 'Complaint',+ mail: {+ timestamp: '2024-01-01T00:00:00.000Z',+ source: '[email protected]',+ messageId: 'ses-message-id',+ destination: [emailAddress],+ headers: [{ name: TRACKING_CODE_HEADER_NAME, value: trackingCode }],+ },+ complaint: {+ complainedRecipients: [{ emailAddress }],+ complaintFeedbackType: 'abuse',+ timestamp: '2024-01-01T00:00:00.000Z',+ },+ }+ const envelope = {+ Type: 'Notification',+ MessageId: 'sns-message-id',+ TopicArn: 'arn:aws:sns:us-east-1:123456789012:ses-events',+ Message: JSON.stringify(sesRecord),+ Timestamp: '2024-01-01T00:00:00.000Z',+ SignatureVersion: '1',+ Signature: 'stubbed',+ SigningCertURL: 'https://sns.us-east-1.amazonaws.com/cert.pem',+ }+ return await supertest(app)+ .post('/public/m/ses_webhook')+ .set('Content-Type', 'text/plain')+ .send(JSON.stringify(envelope))+ }+it('inserts a suppression row and marks it suppressed after a Transient bounce webhook', async () => {const hogFlow = await insertHogFlow(hub.postgres, new FixtureHogFlowBuilder().withTeamId(team.id).build())const email = '[email protected]'@@ -632,6 +665,38 @@ describe('EmailTrackingService', () => {},])})++ it('inserts a suppressed row for a Complaint webhook', async () => {+ const hogFlow = await insertHogFlow(hub.postgres, new FixtureHogFlowBuilder().withTeamId(team.id).build())+ const email = '[email protected]'++ const res = await postComplaint(hogFlow.id, email)+ expect(res.status).toBe(200)++ const result = await hub.postgres.query<{+ identifier: string+ source: string+ suppressed: boolean+ transient_bounce_count: number+ deleted: boolean+ }>(+ PostgresUse.COMMON_READ,+ `SELECT identifier, source, suppressed, transient_bounce_count, deleted+ FROM posthog_messagesuppression+ WHERE team_id = $1 AND identifier = $2`,+ [team.id, email],+ 'test-read-complaint-suppression'+ )+ expect(result.rows).toEqual([+ {+ identifier: email,+ source: 'COMPLAINT',+ suppressed: true,+ transient_bounce_count: 0,+ deleted: false,+ },+ ])+ })})describe('resolveEmailEngagementDistinctId', () => {diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.tsindex 1e6fa13d1b54..9f80b3051ebe 100644--- a/nodejs/src/cdp/services/messaging/email-tracking.service.ts+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.ts@@ -390,6 +390,7 @@ export class EmailTrackingService {logEntries,transientBounceRecipients,hardBounceRecipients,+ complainedRecipients,deliveredRecipients,} = await this.sesWebhookHandler.handleWebhook({body: parseJSON(req.body),@@ -436,10 +437,10 @@ export class EmailTrackingService {emailTrackingErrorsCounter.inc({ error_type: 'track_logs_failed', source: 'ses' })}- // Feed bounces 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 conservatively (count resets,- // then the fresh bounce re-counts from a clean slate).+ // 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 conservatively+ // (count resets, then the fresh bounce re-counts from a clean slate).try {for (const { teamId, emailAddresses, timestamp } of deliveredRecipients || []) {const parsedTeamId = teamId ? parseInt(teamId, 10) : NaN@@ -463,6 +464,12 @@ export class EmailTrackingService {await this.emailSuppressionService.recordHardBounces(parsedTeamId, emailAddresses, diagnostic)}}+ for (const { teamId, emailAddresses, feedbackType } of complainedRecipients || []) {+ const parsedTeamId = teamId ? parseInt(teamId, 10) : NaN+ if (parsedTeamId && !isNaN(parsedTeamId)) {+ await this.emailSuppressionService.recordComplaints(parsedTeamId, emailAddresses, feedbackType)+ }+ }} catch (error) {logger.error('[EmailTrackingService] Failed to update suppression list', { error })emailTrackingErrorsCounter.inc({ error_type: 'suppression_update_failed', source: 'ses' })diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts b/nodejs/src/cdp/services/messaging/helpers/ses.test.tsindex eec71c9d6421..1fd38a293fc8 100644--- a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts+++ b/nodejs/src/cdp/services/messaging/helpers/ses.test.ts@@ -1,3 +1,5 @@+import { register } from 'prom-client'+import { defaultConfig } from '~/common/config/config'import { SesWebhookHandler, normalizeClickUrl, resolveClickDestination } from './ses'@@ -423,10 +425,22 @@ describe('SesWebhookHandler', () => {},'deliveredRecipients' as const,],+ [+ 'Complaint',+ {+ eventType: 'Complaint',+ complaint: {+ complainedRecipients: [{ emailAddress: '[email protected]' }],+ timestamp: '2025-10-03T12:05:00Z',+ },+ },+ 'complainedRecipients' as const,+ ],])('does not populate %s suppression writes for test sends', async (_label, eventFields, arrayKey) => {- // Same guarantee as the permanent-bounce test above but for the counter-driving events:- // a "Run test" from the editor must not push into the suppression counter (transient) or- // reset it (delivery), which could otherwise perturb production suppression state.+ // Same guarantee as the permanent-bounce test above but for the other state-changing+ // events: a "Run test" from the editor must not push into the suppression counter+ // (transient), reset it (delivery), or suppress outright (complaint), which could+ // otherwise perturb production suppression state.const testMail = {...baseMail,headers: [{ name: TRACKING_CODE_HEADER, value: signer.generate(baseInvocation, true) }],@@ -555,22 +569,37 @@ describe('SesWebhookHandler', () => {expect(result.hardBounceRecipients).toBeUndefined()})- it('parses a raw Complaint event', async () => {- const body = [- {- eventType: 'Complaint',- mail: baseMail,- complaint: {- complainedRecipients: [{ emailAddress: '[email protected]' }],- timestamp: '2025-10-03T12:05:00Z',+ it.each([+ // A registered spam complaint surfaces the recipient for suppression.+ {+ feedbackType: 'abuse',+ expectedRecipients: [{ teamId: '1', emailAddresses: ['[email protected]'], feedbackType: 'abuse' }],+ },+ // "not-spam" is a correction, not a complaint, so the recipient must not be suppressed. The+ // metric still counts the event.+ { feedbackType: 'not-spam', expectedRecipients: [] },+ ])(+ 'parses a raw Complaint event with feedback type "$feedbackType" and surfaces the right recipients',+ async ({ feedbackType, expectedRecipients }) => {+ const body = [+ {+ eventType: 'Complaint',+ mail: baseMail,+ complaint: {+ complainedRecipients: [{ emailAddress: '[email protected]' }],+ timestamp: '2025-10-03T12:05:00Z',+ complaintFeedbackType: feedbackType,+ },},- },- ]- const result = await handler.handleWebhook({ body, headers: {} })- expect(result.status).toBe(200)- expect(result.metrics?.[0].metricName).toBe('email_blocked')- expect(result.metrics?.[0].distinctId).toBe('user-123')- })+ ]+ const result = await handler.handleWebhook({ body, headers: {} })+ expect(result.status).toBe(200)+ expect(result.metrics?.[0].metricName).toBe('email_blocked')+ expect(result.metrics?.[0].distinctId).toBe('user-123')+ expect(result.metrics?.[0].properties).toMatchObject({ $complaint_feedback_type: feedbackType })+ expect(result.complainedRecipients).toEqual(expectedRecipients)+ }+ )it('returns 200 and no metrics if tracking code is missing from both carriers', async () => {const body = [@@ -589,6 +618,39 @@ describe('SesWebhookHandler', () => {expect(result.metrics).toEqual([])})+ it('labels a dropped record "missing" when no code is present and "invalid" when it is present but unparseable', async () => {+ // Read the specific label combination as a delta, so accumulation from other tests in the+ // process cannot make this assertion flaky.+ const droppedCount = async (reason: string): Promise<number> => {+ const metric = await register.getSingleMetric('email_tracking_unattributed_total')!.get()+ return metric.values.find((v) => v.labels.event_type === 'Open' && v.labels.reason === reason)?.value ?? 0+ }+ const missingBefore = await droppedCount('missing')+ const invalidBefore = await droppedCount('invalid')++ const open = { ipAddress: '1.2.3.4', userAgent: 'UA', timestamp: '2025-10-03T12:01:00Z' }+ const body = [+ // Neither carrier holds a value: the code is missing.+ { eventType: 'Open', mail: { ...baseMail, tags: {}, headers: [] }, open },+ // A signed header is present but its signature no longer verifies (e.g. after a signing+ // key rotated out): the code is present but invalid, and this incident must not read as a+ // carrier loss.+ {+ eventType: 'Open',+ mail: {+ ...baseMail,+ tags: {},+ headers: [{ name: TRACKING_CODE_HEADER, value: 'stale-payload.badsignature' }],+ },+ open,+ },+ ]+ const result = await handler.handleWebhook({ body, headers: {} })+ expect(result.status).toBe(200)+ expect(await droppedCount('missing')).toBe(missingBefore + 1)+ expect(await droppedCount('invalid')).toBe(invalidBefore + 1)+ })+// Real SNS SubscriptionConfirmation shape: SubscribeURL is a top-level envelope field and// Message is human-readable text, not JSON.const buildConfirmationEnvelope = (subscribeUrl: string): Record<string, any> => ({@@ -1016,11 +1078,20 @@ describe('SesWebhookHandler', () => {mail: unsignedMail,delivery: { timestamp: '2025-10-03T12:05:00Z', recipients: ['[email protected]'] },},+ {+ eventType: 'Complaint',+ mail: unsignedMail,+ complaint: {+ complainedRecipients: [{ emailAddress: '[email protected]' }],+ timestamp: '2025-10-03T12:06:00Z',+ },+ },]const result = await handler.handleWebhook({ body, headers: {} })expect(result.status).toBe(200)expect(result.transientBounceRecipients).toEqual([])expect(result.hardBounceRecipients).toEqual([])+ expect(result.complainedRecipients).toEqual([])expect(result.deliveredRecipients).toEqual([])// Metrics are unaffected — engagement signal is still emitted for the parsed events.expect(result.metrics?.length).toBeGreaterThan(0)diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.ts b/nodejs/src/cdp/services/messaging/helpers/ses.tsindex 48be2e481189..10a63c53ca2b 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 { Counter } from 'prom-client'import { z } from 'zod'import { MinimalAppMetric } from '~/cdp/types'@@ -183,6 +184,18 @@ export type SesEventLogLine = {message: string}+// Records with no usable tracking code can't be attributed to a workflow, so they're dropped. A+// silent drop hides systemic loss, so count what's dropped, by event type and reason. `reason`+// separates two different failures with different owners: `missing` (no carrier value at all, for+// example a configuration set that stops emitting the original headers or tags) from `invalid` (a+// carrier value was present but did not parse, for example a signed header left over after a+// signing key rotated out).+const sesUnattributedEventsCounter = new Counter({+ name: 'email_tracking_unattributed_total',+ help: 'SES webhook records dropped because their tracking code was missing or unparseable',+ labelNames: ['event_type', 'reason'],+})+// SES link tag naming an anchor's ordinal position in the email body. Set on each `<a>` at send// time and echoed back on the Click event, which is what lets two anchors pointing at the same URL// (a header logo and a footer link, say) be counted separately. SES restricts tag names and values@@ -559,6 +572,14 @@ export class SesWebhookHandler {emailAddresses: string[]diagnostic?: string}[]+ // Spam complaints — recorded in the suppression list so future sends to the address are+ // blocked. A complaint is the recipient asking us to stop, and provider complaint-rate+ // thresholds are far tighter than bounce thresholds.+ complainedRecipients?: {+ teamId?: string+ emailAddresses: string[]+ feedbackType?: string+ }[]// Successful deliveries — reset the suppression counter so transient outages don't accumulate.// Timestamp is threaded through so the reset ignores an out-of-order delivery from an older send// arriving after a newer bounce.@@ -655,6 +676,11 @@ export class SesWebhookHandler {emailAddresses: string[]diagnostic?: string}[] = []+ const complainedRecipients: {+ teamId?: string+ emailAddresses: string[]+ feedbackType?: string+ }[] = []const deliveredRecipients: {teamId?: stringemailAddresses: string[]@@ -670,7 +696,8 @@ export class SesWebhookHandler {(h) => h.name.toLowerCase() === TRACKING_CODE_HEADER_NAME.toLowerCase())?.valueconst tagValue = rec.mail.tags?.ph_id?.[0]- const parsedCode = this.trackingCodeSigner.parse(headerValue ?? tagValue ?? '')+ const rawCode = headerValue ?? tagValue ?? ''+ const parsedCode = this.trackingCodeSigner.parse(rawCode)if (parsedCode) {trackingCodeFormatCounter.inc({ format: parsedCode.format, source: 'ses' })}@@ -678,6 +705,10 @@ export class SesWebhookHandler {parsedCode || {}if (!functionId && !invocationId) {+ // A present but unparseable code is a different incident from a wholly absent one, so+ // record which occurred. An empty `rawCode` means neither carrier held a value.+ const reason = rawCode === '' ? 'missing' : 'invalid'+ sesUnattributedEventsCounter.inc({ event_type: rec.eventType, reason })logger.error('[SesWebhookHandler] handleWebhook: No functionId or invocationId found', { rec })continue}@@ -711,6 +742,10 @@ export class SesWebhookHandler {timestamp = rec.bounce.timestamp} else if ('complaint' in rec && rec.complaint) {timestamp = rec.complaint.timestamp+ if (rec.complaint.complaintFeedbackType) {+ // The provider's classification of the report (e.g. "abuse", "fraud").+ properties.$complaint_feedback_type = rec.complaint.complaintFeedbackType+ }}timestamp = timestamp ?? rec.mail.timestamp@@ -813,6 +848,25 @@ export class SesWebhookHandler {transientBounceRecipients.push({ teamId, emailAddresses: emails, diagnostic })}+ // Record complaints in the suppression list so future sends to the address are blocked.+ // The recipient reported the message as spam — one complaint suppresses immediately,+ // like a hard bounce. Skip a "not-spam" feedback type, because that is a correction:+ // the recipient or their provider states the message is not spam, so it must not+ // suppress (and would otherwise resurrect a manually removed row). The value comes from+ // an external provider, so compare case-insensitively.+ if (+ suppressionAllowed &&+ rec.eventType === 'Complaint' &&+ rec.complaint.complaintFeedbackType?.toLowerCase() !== 'not-spam'+ ) {+ const emails = rec.complaint.complainedRecipients.map((r) => r.emailAddress)+ complainedRecipients.push({+ teamId,+ emailAddresses: emails,+ feedbackType: rec.complaint.complaintFeedbackType,+ })+ }+// Successful delivery resets an address's soft-bounce counter — but only if newer than the// last-recorded bounce (checked at the SQL layer), so an out-of-order delivery from an// older send can't erase a fresh bounce.@@ -831,6 +885,7 @@ export class SesWebhookHandler {logEntries,transientBounceRecipients,hardBounceRecipients,+ complainedRecipients,deliveredRecipients,}}