: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): make email MX validation always-on and remove the rollout gates (#69179)
Meikel Ratz1f76b470ca62
diff --git a/nodejs/src/cdp/cdp-api.test.ts b/nodejs/src/cdp/cdp-api.test.tsindex b596b0be3c1b..7ba597f35482 100644--- a/nodejs/src/cdp/cdp-api.test.ts+++ b/nodejs/src/cdp/cdp-api.test.ts@@ -32,6 +32,19 @@ import { posthogFilterOutPlugin } from './legacy-plugins/_transformations/posthoimport { BASE_REDIS_KEY, HogWatcherState } from './services/monitoring/hog-watcher.service'import { HogFunctionInvocationGlobals, HogFunctionType } from './types'+// Email MX validation runs on every email send, so without a mock the test-panel+// email tests would do live DNS lookups for their fixture recipients (and+// example.com publishes a null MX, which validation correctly blocks). Resolve+// everything as deliverable — validation behavior is covered by+// email-validation.service.test.ts.+jest.mock('node:dns/promises', () => ({+ Resolver: jest.fn().mockImplementation(() => ({+ resolveMx: jest.fn().mockResolvedValue([{ exchange: 'mx.example.com', priority: 10 }]),+ resolve4: jest.fn().mockResolvedValue(['1.2.3.4']),+ resolve6: jest.fn().mockResolvedValue([]),+ })),+}))+describe('CDP API', () => {let hub: Hublet cdpDeps: CdpConsumerBaseDepsdiff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex de7a384d5d24..1a84f231922c 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -149,8 +149,6 @@ export type CdpCoreServicesConfig = Pick<| 'CDP_FETCH_BACKOFF_MAX_MS'| 'CDP_SELF_LOOP_GUARD_MODE'| 'CDP_EMAIL_TRACKING_URL'- | 'CDP_EMAIL_MX_VALIDATION_ENABLED'- | 'CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS'| 'HOG_FUNCTION_MONITORING_APP_METRICS_TOPIC'| 'HOG_FUNCTION_MONITORING_APP_METRICS_PRODUCER'| 'HOG_FUNCTION_MONITORING_LOG_ENTRIES_TOPIC'@@ -439,7 +437,7 @@ export function createCdpCoreServices(// limiter, separate pool). The pool is created by the server only on pods// whose capabilities execute email actions; everywhere else this is null// and EmailValidationService degrades to the local cache + DNS.- const emailValidationService = new EmailValidationService(config, deps.emailValidationValkey)+ const emailValidationService = new EmailValidationService(deps.emailValidationValkey)// Observer mirrors writes to Valkey (load-only); only the primary path drives metrics.const hogFlowDuplicateObserver = new HogFlowDuplicateObserverService(redis, valkeyShadow?.writer ?? null)const hogFlowExecutor = new HogFlowExecutorService(diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex d3b44bf4d7f9..13fd2a7b5d2e 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -52,18 +52,6 @@ export type CdpConfig = ClickhouseConfig & {CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: CyclotronJobQueueSourceCDP_CYCLOTRON_STRIP_PERSON_FROM_STATE_TEAMS: string- // Master switch for pre-send email MX validation, off by default. When true,- // every email send is validated (syntax + MX lookup, cached per domain) and- // would-skip outcomes are recorded in Prometheus — shadow mode unless the team- // is also matched by CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS, which controls- // actual skipping.- CDP_EMAIL_MX_VALIDATION_ENABLED: boolean- // Teams whose predicted hard bounces are actually skipped (same string format as- // the other team matchers: '' = none, '*' = all, '2,7' = exact set). Teams not- // matched here are observe-only: validation runs and metrics are recorded, but- // the send always proceeds.- CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS: string-CDP_LEGACY_EVENT_CONSUMER_GROUP_ID: stringCDP_LEGACY_EVENT_CONSUMER_TOPIC: stringCDP_LEGACY_EVENT_CONSUMER_INCLUDE_WEBHOOKS: boolean@@ -189,8 +177,6 @@ export function getDefaultCdpConfig(): CdpConfig {CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_KIND: 'hog',CDP_CYCLOTRON_JOB_QUEUE_CONSUMER_MODE: 'kafka',CDP_CYCLOTRON_STRIP_PERSON_FROM_STATE_TEAMS: '',- CDP_EMAIL_MX_VALIDATION_ENABLED: false,- CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS: '',CDP_LEGACY_EVENT_CONSUMER_GROUP_ID: 'clickhouse-plugin-server-async-onevent',CDP_LEGACY_EVENT_CONSUMER_TOPIC: KAFKA_EVENTS_JSON,diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.tsindex 71b00950ce95..dd0c56ffd714 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts@@ -100,11 +100,12 @@ describe('Hogflow Executor', () => {)const recipientsManager = new RecipientsManagerService(hub.postgres)const recipientPreferencesService = new RecipientPreferencesService(recipientsManager)- // Kill switch off — getSkipReason short-circuits to null, so email validation never does real DNS here.- const emailValidationService = new EmailValidationService(- { CDP_EMAIL_MX_VALIDATION_ENABLED: false, CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS: '' },- null- )+ // Stubbed to always allow: this suite covers executor routing and flow control,+ // not MX validation (email-validation.service.test.ts does), and the real+ // service would fire live DNS lookups for the fixture recipients here.+ const emailValidationService = {+ getSkipReason: () => Promise.resolve(null),+ } as unknown as EmailValidationServiceawait insertHogFunctionTemplate(hub.postgres, {id: 'template-test-hogflow-executor',diff --git a/nodejs/src/cdp/services/messaging/email-validation.service.test.ts b/nodejs/src/cdp/services/messaging/email-validation.service.test.tsindex 8b11fb629598..463d5c5070fb 100644--- a/nodejs/src/cdp/services/messaging/email-validation.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email-validation.service.test.ts@@ -38,13 +38,10 @@ describe('EmailValidationService', () => {mockResolveMx.mockResolvedValue([{ exchange: 'mx.example.com', priority: 10 }])mockResolve4.mockResolvedValue(['1.2.3.4'])mockResolve6.mockResolvedValue([])- service = new EmailValidationService(- { CDP_EMAIL_MX_VALIDATION_ENABLED: true, CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS: '2' },- null- )+ service = new EmailValidationService(null)})- describe('gating and shadow mode', () => {+ describe('gating', () => {it('does not validate (returns null, no DNS) for non-email actions', async () => {const reason = await service.getSkipReason(emailInvocation('[email protected]'), {type: 'function_sms',@@ -54,43 +51,19 @@ describe('EmailValidationService', () => {expect(mockResolveMx).not.toHaveBeenCalled()})- it('does nothing when the kill switch is off, even for a dead domain', async () => {- const disabled = new EmailValidationService(- { CDP_EMAIL_MX_VALIDATION_ENABLED: false, CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS: '*' },- null- )- expect(await disabled.getSkipReason(emailInvocation('[email protected]'), emailAction)).toBeNull()- expect(mockResolveMx).not.toHaveBeenCalled()- })-- it('shadow mode: validates and records the would-skip, but lets the send proceed', async () => {+ it('records the per-team skip metric when blocking', async () => {mockResolveMx.mockRejectedValue(dnsError('ENOTFOUND'))mockResolve4.mockRejectedValue(dnsError('ENOTFOUND'))mockResolve6.mockRejectedValue(dnsError('ENOTFOUND'))- // Team 3 is not in the enforce list ('2') — observe-only.const reason = await service.getSkipReason(emailInvocation('[email protected]', 3), emailAction)- expect(reason).toBeNull()- expect(mockResolveMx).toHaveBeenCalled()- const metric = await register.getSingleMetric('cdp_email_mx_would_skip_total')!.get()+ expect(reason).toContain('no reachable mail servers')+ const metric = await register.getSingleMetric('cdp_email_mx_skipped_total')!.get()expect(metric.values).toContainEqual(expect.objectContaining({ labels: { team_id: '3', reason: 'invalid_domain' } }))})-- it('enforces skips for all teams when configured with "*"', async () => {- const wildcard = new EmailValidationService(- { CDP_EMAIL_MX_VALIDATION_ENABLED: true, CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS: '*' },- null- )- mockResolveMx.mockRejectedValue(dnsError('ENOTFOUND'))- mockResolve4.mockRejectedValue(dnsError('ENOTFOUND'))- mockResolve6.mockRejectedValue(dnsError('ENOTFOUND'))-- const reason = await wildcard.getSkipReason(emailInvocation('[email protected]', 999), emailAction)- expect(reason).toContain('no reachable mail servers')- })})describe('syntax validation', () => {@@ -257,10 +230,7 @@ describe('EmailValidationService', () => {useClient: jest.fn().mockResolvedValue('0'), // '0' = domain previously found undeliverableusePipeline: jest.fn(),}- const withValkey = new EmailValidationService(- { CDP_EMAIL_MX_VALIDATION_ENABLED: true, CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS: '2' },- valkey- )+ const withValkey = new EmailValidationService(valkey)const reason = await withValkey.getSkipReason(emailInvocation('[email protected]'), emailAction)expect(reason).toContain('no reachable mail servers')diff --git a/nodejs/src/cdp/services/messaging/email-validation.service.ts b/nodejs/src/cdp/services/messaging/email-validation.service.tsindex 59ae6e437c0f..fd1eafde3e3c 100644--- a/nodejs/src/cdp/services/messaging/email-validation.service.ts+++ b/nodejs/src/cdp/services/messaging/email-validation.service.ts@@ -4,11 +4,8 @@ import { domainToASCII } from 'node:url'import { Counter } from 'prom-client'import { HogFlowAction } from '~/cdp/schema/hogflow'-import { buildIntegerMatcher } from '~/common/config/config'import { RedisV2 } from '~/common/redis/redis-v2'-import { ValueMatcher } from '~/types'-import { CdpConfig } from '../../config'import { CyclotronJobInvocationHogFunction } from '../../types'const cdpEmailMxValidationTotal = new Counter({@@ -17,9 +14,9 @@ const cdpEmailMxValidationTotal = new Counter({labelNames: ['result'],})-const cdpEmailMxWouldSkipTotal = new Counter({- name: 'cdp_email_mx_would_skip_total',- help: 'Sends that pre-send email validation would skip as predicted hard bounces, per team. Increments in both shadow and enforce mode so the series is continuous across the enforce rollout; whether the send was actually skipped depends on CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS.',+const cdpEmailMxSkippedTotal = new Counter({+ name: 'cdp_email_mx_skipped_total',+ help: 'Sends skipped by pre-send email validation as predicted hard bounces, per team.',labelNames: ['team_id', 'reason'],})@@ -78,39 +75,26 @@ function classifyDnsError(error: unknown): 'none' | 'transient' {** Fail-open by design: only a definitive "this domain has no mail exchange"* blocks a send. A DNS hiccup must never nuke a batch of legitimate mail.- *- * Rollout is shadow-first: when enabled, every team is validated and would-skip- * outcomes are recorded per team in Prometheus, but only teams matched by- * CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS actually get their sends skipped.*/export class EmailValidationService {- private readonly enabled: boolean- private readonly enforceMatcher: ValueMatcher<number>private readonly resolver: Resolverprivate readonly localCache = new Map<string, CacheEntry>()private readonly inFlight = new Map<string, Promise<boolean>>()- constructor(- config: Pick<CdpConfig, 'CDP_EMAIL_MX_VALIDATION_ENABLED' | 'CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS'>,- private valkey: RedisV2 | null- ) {- this.enabled = config.CDP_EMAIL_MX_VALIDATION_ENABLED- this.enforceMatcher = buildIntegerMatcher(config.CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS, true)+ constructor(private valkey: RedisV2 | null) {this.resolver = new Resolver({ timeout: DNS_TIMEOUT_MS, tries: DNS_TRIES })}/*** Returns a human-readable reason to skip the send, or null to proceed.- * Only acts on `function_email` actions; anything else (kill switch off,- * missing recipient, non-email action) returns null so the existing send- * path is untouched. Teams outside the enforce list are observe-only:- * validation runs and metrics are recorded, but null is returned.+ * Only acts on `function_email` actions; anything else (missing recipient,+ * non-email action) returns null so the existing send path is untouched.*/public async getSkipReason(invocation: CyclotronJobInvocationHogFunction,action: HogFlowAction): Promise<string | null> {- if (!this.enabled || action.type !== 'function_email') {+ if (action.type !== 'function_email') {return null}@@ -123,7 +107,7 @@ export class EmailValidationService {if (!EMAIL_SYNTAX_RE.test(email)) {cdpEmailMxValidationTotal.inc({ result: 'invalid_syntax' })- return this.skipOrObserve(+ return this.skip(invocation.teamId,'invalid_syntax',`Skipping send: "${email}" is not a valid email address, so it would hard bounce.`@@ -139,7 +123,7 @@ export class EmailValidationService {const domain = domainToASCII(rawDomain) || rawDomain.toLowerCase()const deliverable = await this.resolveDeliverability(domain)if (!deliverable) {- return this.skipOrObserve(+ return this.skip(invocation.teamId,'invalid_domain',`Skipping send: the domain "${domain}" has no reachable mail servers, so this message would hard bounce.`@@ -148,9 +132,9 @@ export class EmailValidationService {return null}- private skipOrObserve(teamId: number, reason: 'invalid_syntax' | 'invalid_domain', message: string): string | null {- cdpEmailMxWouldSkipTotal.inc({ team_id: String(teamId), reason })- return this.enforceMatcher(teamId) ? message : null+ private skip(teamId: number, reason: 'invalid_syntax' | 'invalid_domain', message: string): string {+ cdpEmailMxSkippedTotal.inc({ team_id: String(teamId), reason })+ return message}private async resolveDeliverability(domain: string): Promise<boolean> {diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.tsindex 7d0840703ed7..84a0220f9091 100644--- a/nodejs/src/cdp/workflows-e2e.test.ts+++ b/nodejs/src/cdp/workflows-e2e.test.ts@@ -1730,11 +1730,6 @@ describe('Workflows E2E (email queue)', () => {hub = await createHub()hub.CDP_CYCLOTRON_BATCH_DELAY_MS = 50- // Enforce mode for the whole block: existing tests prove deliverable recipients- // pass validation untouched; the skip test proves dead domains never reach the queue.- hub.CDP_EMAIL_MX_VALIDATION_ENABLED = true- hub.CDP_EMAIL_MX_VALIDATION_ENFORCE_TEAMS = '*'-// `.invalid` domains are NXDOMAIN, everything else resolves as deliverable.const nxdomain = () => Promise.reject(Object.assign(new Error('queryMx ENOTFOUND'), { code: 'ENOTFOUND' }))mockDnsResolveMx.mockImplementation((domain: string) =>diff --git a/nodejs/src/server.ts b/nodejs/src/server.tsindex 5d893286b1da..e616f3de56b4 100644--- a/nodejs/src/server.ts+++ b/nodejs/src/server.ts@@ -437,13 +437,10 @@ export class PluginServer implements NodeServer {* deps. Only the cyclotron workers that run the hogflow email action call this, so* the pool is never opened on other CDP consumers or cdp-api — an idle Valkey sized* for the SES rate limiter shouldn't hold connections from pods that never validate.- * Null (the shared-deps default) when the kill switch is off, in which case+ * Null when no SES Valkey host is configured (local dev), in which case* EmailValidationService degrades to its local cache + DNS.*/private withEmailValidationValkey(deps: CdpConsumerBaseDeps): CdpConsumerBaseDeps {- if (!this.config.CDP_EMAIL_MX_VALIDATION_ENABLED) {- return deps- }return { ...deps, emailValidationValkey: createSesRateLimiterValkeyPool(this.config, 'email-mx-validation') }}diff --git a/nodejs/tests/helpers/cdp.ts b/nodejs/tests/helpers/cdp.tsindex eca99e5fb86f..ec6d6da62f98 100644--- a/nodejs/tests/helpers/cdp.ts+++ b/nodejs/tests/helpers/cdp.ts@@ -64,8 +64,6 @@ export function createCdpConsumerDeps(hub: Hub, kafkaProducer?: KafkaProducerWrageoipService: hub.geoipService,groupRepository: noopGroupReadRepository,quotaLimiting: hub.quotaLimiting,- emailValidationValkey: hub.CDP_EMAIL_MX_VALIDATION_ENABLED- ? createSesRateLimiterValkeyPool(hub, 'email-mx-validation')- : null,+ emailValidationValkey: createSesRateLimiterValkeyPool(hub, 'email-mx-validation'),}}