Skip to content

: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.

feat(messaging): skip metrics for test email sends (#63550)

Daniel Marchuk9d39a6a050a5
diff --git a/nodejs/src/cdp/services/hog-executor.service.ts b/nodejs/src/cdp/services/hog-executor.service.ts
index 08b6a7d3ee8a..7e816d971bfe 100644
--- a/nodejs/src/cdp/services/hog-executor.service.ts
+++ b/nodejs/src/cdp/services/hog-executor.service.ts
@@ -392,7 +392,12 @@ export class HogExecutorService {
if (routeToEmailQueue) {
result = this.routeEmailToQueue(nextInvocation)
} else {
- result = await this.emailService.executeSendEmail(nextInvocation)
+ // `sendEmailsInline` is only set by the test panel, so it doubles as the
+ // "this is a test send" signal — propagated into the email's tracking code.
+ result = await this.emailService.executeSendEmail(
+ nextInvocation,
+ options?.sendEmailsInline ?? false
+ )
}
} else {
throw new Error(`Unknown queue type: ${queueParamsType}`)
diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.ts
index 922e0f09690a..b8b5b51ec651 100644
--- a/nodejs/src/cdp/services/messaging/email-tracking.service.ts
+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.ts
@@ -40,9 +40,10 @@ export const generateTrackingRedirectUrl = (
parentRunId?: string | null
state?: { actionId?: string }
},
- targetUrl: string
+ targetUrl: string,
+ isTest = false
): string => {
- return `${defaultConfig.CDP_EMAIL_TRACKING_URL}/public/m/redirect?ph_id=${generateEmailTrackingCode(invocation)}&target=${encodeURIComponent(targetUrl)}`
+ return `${defaultConfig.CDP_EMAIL_TRACKING_URL}/public/m/redirect?ph_id=${generateEmailTrackingCode(invocation, isTest)}&target=${encodeURIComponent(targetUrl)}`
}
// HTML attribute values arrive entity-encoded (e.g. `&`, `&`). Decode before
@@ -63,8 +64,12 @@ export const decodeHtmlEntitiesInHref = (value: string): string => {
})
}
-export const addTrackingToEmail = (html: string, invocation: CyclotronJobInvocationHogFunction): string => {
- const trackingUrl = generateEmailTrackingPixelUrl(invocation)
+export const addTrackingToEmail = (
+ html: string,
+ invocation: CyclotronJobInvocationHogFunction,
+ isTest = false
+): string => {
+ const trackingUrl = generateEmailTrackingPixelUrl(invocation, isTest)
html = html.replace(LINK_REGEX, (m, d, s, u) => {
const href = decodeHtmlEntitiesInHref(d || s || u || '')
@@ -73,7 +78,7 @@ export const addTrackingToEmail = (html: string, invocation: CyclotronJobInvocat
if (/^\s*javascript:/i.test(href)) {
return m
}
- const tracked = generateTrackingRedirectUrl(invocation, href)
+ const tracked = generateTrackingRedirectUrl(invocation, href, isTest)
// replace just the href in the original tag to preserve other attributes
return m.replace(/\bhref\s*=\s*(?:"[^"]*"|'[^']*'|[^'">\s]+)/i, `href="${tracked}"`)
diff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.ts
index 4fe41b65e8a1..d04b6f3de22c 100644
--- a/nodejs/src/cdp/services/messaging/email.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts
@@ -366,6 +366,16 @@ describe('EmailService', () => {
})
})
+ it('records a send-time metric for normal sends but not for test sends', async () => {
+ sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })
+
+ const normal = await service.executeSendEmail(invocation)
+ expect(normal.metrics.map((m) => m.metric_name)).toContain('email_sent')
+
+ const testSend = await service.executeSendEmail(invocation, true)
+ expect(testSend.metrics).toEqual([])
+ })
+
it('should include cc addresses in SES destination', async () => {
sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })
invocation.queueParameters = createEmailParams({
diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.ts
index 27133fdc8fec..ca81fdc149eb 100644
--- a/nodejs/src/cdp/services/messaging/email.service.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.ts
@@ -67,9 +67,11 @@ export class EmailService {
this.recipientTokensService = new RecipientTokensService(encryptionSaltKeys, siteUrl)
}
- // Send email
+ // Send email. `isTest` flags sends from the editor's "Run test" path so the tracking code
+ // embedded in the email tells the SES webhook to skip recording metrics for test traffic.
public async executeSendEmail(
- invocation: CyclotronJobInvocationHogFunction
+ invocation: CyclotronJobInvocationHogFunction,
+ isTest = false
): Promise<CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>> {
if (invocation.queueParameters?.type !== 'email') {
throw new Error('Invocation passed to sendEmail is not an email function')
@@ -106,10 +108,10 @@ export class EmailService {
switch (integration.config.provider ?? 'ses') {
case 'maildev':
- await this.sendEmailWithMaildev(result, params, from)
+ await this.sendEmailWithMaildev(result, params, from, isTest)
break
case 'ses':
- await this.sendEmailWithSES(result, params, from)
+ await this.sendEmailWithSES(result, params, from, isTest)
break
case 'unsupported':
@@ -129,14 +131,18 @@ export class EmailService {
success,
})
- result.metrics.push({
- team_id: invocation.teamId,
- app_source_id: invocation.parentRunId ?? invocation.functionId,
- instance_id: invocation.state.actionId || invocation.id,
- metric_kind: 'email',
- metric_name: success ? 'email_sent' : 'email_failed',
- count: 1,
- })
+ // Test sends (from the editor's "Run test") must not record metrics — keep them out of the
+ // workflow's Metrics tab, mirroring the isTest skip the SES webhook applies to delivery/open/click.
+ if (!isTest) {
+ result.metrics.push({
+ team_id: invocation.teamId,
+ app_source_id: invocation.parentRunId ?? invocation.functionId,
+ instance_id: invocation.state.actionId || invocation.id,
+ metric_kind: 'email',
+ metric_name: success ? 'email_sent' : 'email_failed',
+ count: 1,
+ })
+ }
return result
}
@@ -157,7 +163,8 @@ export class EmailService {
private async sendEmailWithMaildev(
result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>,
params: CyclotronInvocationQueueParametersEmailType,
- from: { email: string; name: string }
+ from: { email: string; name: string },
+ isTest = false
): Promise<void> {
// This can timeout but there is no native timeout so we do our own one
const mailOptions: SendMailOptions = {
@@ -165,7 +172,7 @@ export class EmailService {
to: params.to.name ? `"${params.to.name}" <${params.to.email}>` : params.to.email,
subject: sanitizeEmailSubject(params.subject),
text: params.text,
- ...(params.html ? { html: addTrackingToEmail(params.html, result.invocation) } : {}),
+ ...(params.html ? { html: addTrackingToEmail(params.html, result.invocation, isTest) } : {}),
}
const ccAddresses = parseAddressList(params.cc)
@@ -190,21 +197,23 @@ export class EmailService {
private async sendEmailWithSES(
result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>,
params: CyclotronInvocationQueueParametersEmailType,
- from: { email: string; name: string }
+ from: { email: string; name: string },
+ isTest = false
): Promise<void> {
if (!this.sesV2Client) {
throw new Error('SES is not configured - set SES_REGION and AWS credentials')
}
- const trackingCode = generateEmailTrackingCode(result.invocation)
+ const trackingCode = generateEmailTrackingCode(result.invocation, isTest)
// Short carrier (unsigned) for the SES EmailTag — guaranteed under the 256-char tag-value
- // limit. The full signed code rides in the header below.
+ // limit. Legacy backwards-compat carrier only; the full signed code (with isTest) rides in
+ // the header below, which the webhook reads first.
const shortTrackingCode = generateShortEmailTrackingCode(result.invocation)
const htmlBody = params.html
? {
Html: {
Data: maybeAddPreheaderToEmail(
- addTrackingToEmail(params.html, result.invocation),
+ addTrackingToEmail(params.html, result.invocation, isTest),
params.preheader
),
Charset: 'UTF-8',
diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts b/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
index 959e7ba33f03..910293171f58 100644
--- a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
@@ -108,6 +108,54 @@ describe('SesWebhookHandler', () => {
expect(result.metrics?.[0]).toMatchObject({ functionId: 'abc123', invocationId: 'inv456' })
})
+ // The `if (metricName && !isTest)` guard applies to every metric-emitting event type, so
+ // suppression must hold for all of them — not just Delivery.
+ it.each([
+ ['Open', { open: { timestamp: 't' } }],
+ ['Click', { click: { link: 'l', timestamp: 't' } }],
+ ['Delivery', { delivery: { timestamp: 't' } }],
+ ])('skips metrics for test sends on a %s event (isTest tracking code)', async (eventType, eventFields) => {
+ const testMail = {
+ ...baseMail,
+ // isTest rides on the signed header code (preferred by the webhook); the short tag
+ // code stays legacy-shaped without it.
+ headers: [{ name: TRACKING_CODE_HEADER, value: generateEmailTrackingCode(baseInvocation, true) }],
+ tags: { ph_id: [generateShortEmailTrackingCode(baseInvocation)] },
+ }
+ const body = [{ eventType, mail: testMail, ...eventFields }]
+ const result = await handler.handleWebhook({ body, headers: {} })
+ expect(result.status).toBe(200)
+ expect(result.metrics).toEqual([])
+ })
+
+ it('still opts out recipients on a permanent bounce even for test sends', async () => {
+ const testMail = {
+ ...baseMail,
+ // isTest rides on the signed header code (preferred by the webhook); the short tag
+ // code stays legacy-shaped without it.
+ headers: [{ name: TRACKING_CODE_HEADER, value: generateEmailTrackingCode(baseInvocation, true) }],
+ tags: { ph_id: [generateShortEmailTrackingCode(baseInvocation)] },
+ }
+ const body = [
+ {
+ eventType: 'Bounce',
+ mail: testMail,
+ bounce: {
+ bounceType: 'Permanent',
+ bouncedRecipients: [
+ { emailAddress: '[email protected]', action: 'failed', status: '5.1.1', diagnosticCode: 'bad' },
+ ],
+ timestamp: '2025-10-03T12:04:00Z',
+ reportingMTA: 'mta',
+ },
+ },
+ ]
+ const result = await handler.handleWebhook({ body, headers: {} })
+ // No metric recorded for the test send, but the hard bounce still triggers an opt-out.
+ expect(result.metrics).toEqual([])
+ expect(result.optOutRecipients).toEqual([{ teamId: '1', emailAddresses: ['[email protected]'] }])
+ })
+
it('parses a raw Delivery event', async () => {
const body = [
{
diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.ts b/nodejs/src/cdp/services/messaging/helpers/ses.ts
index 008cecba40ae..1d8ae6d8b652 100644
--- a/nodejs/src/cdp/services/messaging/helpers/ses.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/ses.ts
@@ -392,7 +392,7 @@ export class SesWebhookHandler {
if (parsedCode) {
trackingCodeFormatCounter.inc({ format: parsedCode.format, source: 'ses' })
}
- const { functionId, invocationId, teamId, actionId, parentRunId } = parsedCode || {}
+ const { functionId, invocationId, teamId, actionId, parentRunId, isTest } = parsedCode || {}
if (!functionId && !invocationId) {
logger.error('[SesWebhookHandler] handleWebhook: No functionId or invocationId found', { rec })
@@ -400,7 +400,10 @@ export class SesWebhookHandler {
}
const metricName = EVENT_TYPE_TO_METRIC_NAME[rec.eventType]
- if (metricName) {
+ // Test sends (from the editor's "Run test") are not production activity, so we skip
+ // their delivery/open/click metrics — otherwise a draft/never-enabled workflow shows
+ // email activity in its Metrics tab. Bounce-driven opt-outs below still apply.
+ if (metricName && !isTest) {
metrics.push({ functionId, invocationId, actionId, parentRunId, metricName })
}
diff --git a/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts b/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts
index 827fad12b4c7..c6dd97eb8c1d 100644
--- a/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts
@@ -25,6 +25,43 @@ describe('email tracking code', () => {
teamId: '3',
actionId: 'act-5',
parentRunId: 'batch-4',
+ isTest: false,
+ format: 'signed',
+ },
+ },
+ {
+ name: 'roundtrips the isTest flag for test sends',
+ encoded: generateEmailTrackingCode(
+ {
+ functionId: 'fn-1',
+ id: 'inv-2',
+ teamId: 3,
+ parentRunId: 'batch-4',
+ state: { actionId: 'act-5' },
+ },
+ true
+ ),
+ expected: {
+ functionId: 'fn-1',
+ invocationId: 'inv-2',
+ teamId: '3',
+ actionId: 'act-5',
+ parentRunId: 'batch-4',
+ isTest: true,
+ format: 'signed',
+ },
+ },
+ {
+ // isTest sits after actionId/parentRunId, so it must survive both being empty.
+ name: 'roundtrips isTest when neither actionId nor parentRunId is supplied',
+ encoded: generateEmailTrackingCode({ functionId: 'fn-1', id: 'inv-2', teamId: 3 }, true),
+ expected: {
+ functionId: 'fn-1',
+ invocationId: 'inv-2',
+ teamId: '3',
+ actionId: undefined,
+ parentRunId: undefined,
+ isTest: true,
format: 'signed',
},
},
@@ -42,6 +79,7 @@ describe('email tracking code', () => {
teamId: '3',
actionId: 'act-5',
parentRunId: undefined,
+ isTest: false,
format: 'signed',
},
},
@@ -55,6 +93,7 @@ describe('email tracking code', () => {
teamId: '3',
actionId: 'act-5',
parentRunId: undefined,
+ isTest: false,
format: 'unsigned',
},
},
@@ -67,6 +106,7 @@ describe('email tracking code', () => {
teamId: '3',
actionId: 'act-5',
parentRunId: 'batch-4',
+ isTest: false,
format: 'unsigned',
},
},
diff --git a/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts b/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts
index cff6b09feb08..4d9a9be653c9 100644
--- a/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts
@@ -77,6 +77,7 @@ export const parseEmailTrackingCode = (
teamId: string
actionId?: string
parentRunId?: string
+ isTest: boolean
format: TrackingCodeFormat
} | null => {
if (!encodedTrackingCode) {
@@ -99,7 +100,7 @@ export const parseEmailTrackingCode = (
try {
const decoded = fromBase64UrlSafe(payloadB64)
- const [functionId, invocationId, teamId, actionId, parentRunId] = decoded.split(':')
+ const [functionId, invocationId, teamId, actionId, parentRunId, isTest] = decoded.split(':')
if (!functionId || !invocationId) {
return null
}
@@ -109,6 +110,7 @@ export const parseEmailTrackingCode = (
teamId,
actionId: actionId || undefined,
parentRunId: parentRunId || undefined,
+ isTest: isTest === '1',
format,
}
} catch {
@@ -119,11 +121,13 @@ export const parseEmailTrackingCode = (
// Full tracking code, HMAC-signed when a signing key is configured. Rides in the custom MIME
// header and the pixel/link URLs — carriers with no length cap — and the signature lets the
// public tracking endpoint reject forged `ph_id` values.
-export const generateEmailTrackingCode = (invocation: TrackingInvocation): string => {
+export const generateEmailTrackingCode = (invocation: TrackingInvocation, isTest = false): string => {
const actionId = invocation.state?.actionId ?? ''
const parentRunId = invocation.parentRunId ?? ''
+ // isTest marks sends from the editor's "Run test" so the SES webhook can skip recording
+ // their metrics — keeping test traffic out of the production Metrics tab.
const payload = toBase64UrlSafe(
- `${invocation.functionId}:${invocation.id}:${invocation.teamId}:${actionId}:${parentRunId}`
+ `${invocation.functionId}:${invocation.id}:${invocation.teamId}:${actionId}:${parentRunId}:${isTest ? '1' : ''}`
)
const keys = getSigningKeys()
if (keys.length === 0) {
@@ -136,12 +140,14 @@ export const generateEmailTrackingCode = (invocation: TrackingInvocation): strin
// Unsigned tracking code for the SES `EmailTags` carrier. Omitting the signature keeps the
// value short enough to stay within the 256-char tag cap; the tag arrives via the SNS webhook,
// which is already integrity-protected by SNS signing, so it does not need its own signature.
+// This is a legacy backwards-compat carrier only — new fields (e.g. isTest) live on the signed
+// code in generateEmailTrackingCode, which the webhook reads first.
export const generateShortEmailTrackingCode = (invocation: TrackingInvocation): string => {
const actionId = invocation.state?.actionId ?? ''
const parentRunId = invocation.parentRunId ?? ''
return toBase64UrlSafe(`${invocation.functionId}:${invocation.id}:${invocation.teamId}:${actionId}:${parentRunId}`)
}
-export const generateEmailTrackingPixelUrl = (invocation: TrackingInvocation): string => {
- return `${defaultConfig.CDP_EMAIL_TRACKING_URL}/public/m/pixel?ph_id=${generateEmailTrackingCode(invocation)}`
+export const generateEmailTrackingPixelUrl = (invocation: TrackingInvocation, isTest = false): string => {
+ return `${defaultConfig.CDP_EMAIL_TRACKING_URL}/public/m/pixel?ph_id=${generateEmailTrackingCode(invocation, isTest)}`
}