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): add per-invocation log entries for SES email events (#65911)

Daniel Marchukb90c08f684b0
diff --git a/frontend/src/lib/components/AppMetrics/AppMetricSummary.tsx b/frontend/src/lib/components/AppMetrics/AppMetricSummary.tsx
index 387910fc3c5c..e528c05a56da 100644
--- a/frontend/src/lib/components/AppMetrics/AppMetricSummary.tsx
+++ b/frontend/src/lib/components/AppMetrics/AppMetricSummary.tsx
@@ -1,6 +1,7 @@
import { useMemo } from 'react'
-import { LemonLabel, LemonSkeleton, SpinnerOverlay } from '@posthog/lemon-ui'
+import { IconArrowRight } from '@posthog/icons'
+import { LemonLabel, LemonSkeleton, SpinnerOverlay, Tooltip } from '@posthog/lemon-ui'
import { formatPercentageDiff, humanFriendlyNumber } from 'lib/utils/numbers'
@@ -19,6 +20,10 @@ export type AppMetricSummaryProps = {
previousPeriodTimeSeries?: AppMetricsTimeSeriesResponse | null
loading?: boolean
hideIfZero?: boolean
+ /** When set, the tile becomes clickable (e.g. to drill into matching invocations). */
+ onClick?: () => void
+ /** Tooltip shown on the drill-down affordance when `onClick` is set. */
+ onClickTooltip?: string
/** Optional content rendered at the bottom of the card, e.g. a deep-link to the underlying data. */
footer?: JSX.Element | null
}
@@ -32,6 +37,8 @@ export function AppMetricSummary({
colorIfZero,
loading,
hideIfZero = false,
+ onClick,
+ onClickTooltip,
footer,
}: AppMetricSummaryProps): JSX.Element | null {
const total = useMemo(() => {
@@ -59,13 +66,39 @@ export function AppMetricSummary({
}
return (
- <div className="flex flex-1 flex-col relative border rounded p-3 bg-surface-primary min-w-[16rem]">
+ <div
+ className={
+ onClick
+ ? 'flex flex-1 flex-col relative border rounded p-3 bg-surface-primary min-w-[16rem] cursor-pointer transition-colors hover:border-primary'
+ : 'flex flex-1 flex-col relative border rounded p-3 bg-surface-primary min-w-[16rem]'
+ }
+ role={onClick ? 'button' : undefined}
+ tabIndex={onClick ? 0 : undefined}
+ onClick={onClick}
+ onKeyDown={
+ onClick
+ ? (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault()
+ onClick()
+ }
+ }
+ : undefined
+ }
+ >
<div className="flex flex-row justify-between items-start">
<LemonLabel info={description}>{name}</LemonLabel>
{loading ? (
<LemonSkeleton className="w-20 h-6 mb-2" />
) : (
- <div className="text-right text-2xl text-muted-foreground">{humanFriendlyNumber(total)}</div>
+ <div className="flex items-center gap-1 text-right text-2xl text-muted-foreground">
+ {onClick ? (
+ <Tooltip title={onClickTooltip ?? 'View matching invocations'}>
+ <IconArrowRight className="text-base text-muted" />
+ </Tooltip>
+ ) : null}
+ {humanFriendlyNumber(total)}
+ </div>
)}
</div>
<div className="flex flex-row justify-end items-center gap-2 text-xs text-muted">
diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts
index 7cbe11d7d732..c5d580df0a89 100644
--- a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts
@@ -6,12 +6,14 @@ import { Server } from 'http'
import supertest from 'supertest'
import express from 'ultimate-express'
+import { FixtureHogFlowBuilder } from '~/cdp/_tests/builders/hogflow.builder'
import { insertHogFunction } from '~/cdp/_tests/fixtures'
+import { insertHogFlow } from '~/cdp/_tests/fixtures-hogflows'
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 } from '~/common/config/kafka-topics'
+import { KAFKA_APP_METRICS_2, KAFKA_LOG_ENTRIES } from '~/common/config/kafka-topics'
import { closeHub, createHub } from '~/common/utils/db/hub'
import * as envUtils from '~/common/utils/env-utils'
import { createCdpConsumerDeps } from '~/tests/helpers/cdp'
@@ -26,7 +28,8 @@ import {
decodeHtmlEntitiesInHref,
resolveEmailEngagementDistinctId,
} from './email-tracking.service'
-import { EmailTrackingCodeSigner } from './helpers/tracking-code'
+import { SesWebhookHandler } from './helpers/ses'
+import { EmailTrackingCodeSigner, TRACKING_CODE_HEADER_NAME } from './helpers/tracking-code'
describe('EmailTrackingService', () => {
let hub: Hub
@@ -248,6 +251,135 @@ describe('EmailTrackingService', () => {
expect(messages).toHaveLength(0)
})
})
+
+ describe('SES webhook log entries', () => {
+ // The route enforces a real SNS signature; verifying it needs AWS's private key, so we
+ // stub the check and let a posted SNS envelope flow through the real handler + service.
+ let verifySignatureSpy: jest.SpyInstance
+
+ beforeEach(() => {
+ verifySignatureSpy = jest
+ .spyOn(SesWebhookHandler.prototype as any, 'verifySnsSignature')
+ .mockResolvedValue(true)
+ })
+
+ afterEach(() => {
+ verifySignatureSpy.mockRestore()
+ })
+
+ const postBounce = async ({
+ functionId,
+ parentRunId,
+ }: {
+ functionId: string
+ parentRunId?: string
+ }): Promise<supertest.Response> => {
+ const trackingCode = signer.generate({
+ functionId,
+ id: invocationId,
+ teamId: team.id,
+ parentRunId,
+ })
+ const sesRecord = {
+ eventType: 'Bounce',
+ mail: {
+ timestamp: '2024-01-01T00:00:00.000Z',
+ source: '[email protected]',
+ messageId: 'ses-message-id',
+ destination: ['[email protected]'],
+ headers: [{ name: TRACKING_CODE_HEADER_NAME, value: trackingCode }],
+ },
+ bounce: {
+ bounceType: 'Permanent',
+ bouncedRecipients: [{ emailAddress: '[email protected]' }],
+ 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('writes a hog_flow log entry for a bounce that resolves to a flow', async () => {
+ const hogFlow = await insertHogFlow(
+ hub.postgres,
+ new FixtureHogFlowBuilder().withTeamId(team.id).build()
+ )
+
+ const res = await postBounce({ functionId: hogFlow.id })
+ expect(res.status).toBe(200)
+
+ await waitForExpect(() => {
+ const logs = mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_LOG_ENTRIES)
+ expect(logs).toHaveLength(1)
+ expect(logs[0].value).toMatchObject({
+ team_id: team.id,
+ log_source: 'hog_flow',
+ log_source_id: hogFlow.id,
+ instance_id: invocationId,
+ level: 'error',
+ })
+ expect(logs[0].value.message).toContain('Permanent bounce to [email protected]')
+ })
+
+ const metrics = mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ expect(metrics).toHaveLength(1)
+ expect(metrics[0].value).toMatchObject({
+ team_id: team.id,
+ metric_name: 'email_bounced',
+ metric_kind: 'email',
+ })
+ })
+
+ 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)
+
+ await waitForExpect(() => {
+ const metrics = mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ expect(metrics).toHaveLength(1)
+ expect(metrics[0].value).toMatchObject({
+ team_id: team.id,
+ metric_name: 'email_bounced',
+ })
+ })
+
+ const logs = mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_LOG_ENTRIES)
+ expect(logs).toHaveLength(0)
+ })
+
+ it('keys the log entry under parentRunId for batch-triggered runs', async () => {
+ const hogFlow = await insertHogFlow(
+ hub.postgres,
+ new FixtureHogFlowBuilder().withTeamId(team.id).build()
+ )
+ const parentRunId = 'batch-run-id'
+
+ const res = await postBounce({ functionId: hogFlow.id, parentRunId })
+ expect(res.status).toBe(200)
+
+ await waitForExpect(() => {
+ const logs = mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_LOG_ENTRIES)
+ expect(logs).toHaveLength(1)
+ expect(logs[0].value).toMatchObject({
+ log_source: 'hog_flow',
+ log_source_id: parentRunId,
+ instance_id: invocationId,
+ })
+ })
+ })
+ })
})
describe('resolveEmailEngagementDistinctId', () => {
diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.ts
index 59e80a012f5b..2c50f1494bfa 100644
--- a/nodejs/src/cdp/services/messaging/email-tracking.service.ts
+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.ts
@@ -1,7 +1,9 @@
+import { DateTime } from 'luxon'
import { Counter } from 'prom-client'
import express from 'ultimate-express'
-import { CyclotronJobInvocationHogFunction, MinimalAppMetric } from '~/cdp/types'
+import { HogFlow } from '~/cdp/schema/hogflow'
+import { CyclotronJobInvocationHogFunction, LogEntry, LogEntryLevel, MinimalAppMetric } from '~/cdp/types'
import { ModifiedRequest } from '~/common/api/router'
import { isDevEnv, isTestEnv } from '~/common/utils/env-utils'
import { parseJSON } from '~/common/utils/json-parse'
@@ -32,6 +34,14 @@ const emailTrackingErrorsCounter = new Counter({
labelNames: ['error_type', 'source'],
})
+// Skips here are expected (e.g. SES webhook for a hog_function rather than a hog_flow),
+// kept separate so alerts on `email_tracking_errors_total` don't fire on normal traffic.
+const emailTrackingLogSkipsCounter = new Counter({
+ name: 'email_tracking_log_skips_total',
+ help: 'Total number of email tracking log entries skipped (expected, non-error)',
+ labelNames: ['reason', 'source'],
+})
+
// Allowlist of metrics that surface as PostHog events when engagement-event capture is enabled.
// Metrics not in this map are deliberately ignored (no `$messaging_${metricName}` fallback) so a new
// internal metric can't silently leak into customers' event streams.
@@ -216,13 +226,77 @@ export class EmailTrackingService {
})
}
+ public async trackLogs(
+ entries: {
+ functionId?: string
+ invocationId?: string
+ parentRunId?: string
+ level: LogEntryLevel
+ message: string
+ }[]
+ ): Promise<void> {
+ if (entries.length === 0) {
+ return
+ }
+
+ const uniqueFunctionIds = Array.from(
+ new Set(entries.map((e) => e.functionId).filter((id): id is string => Boolean(id)))
+ )
+
+ let hogFlows: Record<string, HogFlow | null> = {}
+ try {
+ hogFlows = await this.hogFlowManager.getHogFlows(uniqueFunctionIds)
+ } catch (error) {
+ logger.error('[EmailTrackingService] trackLogs: Failed to load hog flows', { error })
+ emailTrackingErrorsCounter.inc({ error_type: 'hog_flow_lookup_failed', source: 'ses' })
+ return
+ }
+
+ const now = DateTime.utc()
+ const logEntries: LogEntry[] = []
+ for (const entry of entries) {
+ if (!entry.functionId || !entry.invocationId) {
+ logger.error('[EmailTrackingService] trackLogs: Invalid custom ID', {
+ functionId: entry.functionId,
+ invocationId: entry.invocationId,
+ })
+ emailTrackingErrorsCounter.inc({ error_type: 'invalid_custom_id', source: 'ses' })
+ continue
+ }
+
+ const hogFlow = hogFlows[entry.functionId]
+ if (!hogFlow) {
+ emailTrackingLogSkipsCounter.inc({ reason: 'non_flow', source: 'ses' })
+ continue
+ }
+
+ logEntries.push({
+ team_id: hogFlow.team_id,
+ log_source: 'hog_flow',
+ // Batch-triggered runs log under the batch run id (parentRunId); mirror the metrics path.
+ log_source_id: entry.parentRunId ?? hogFlow.id,
+ instance_id: entry.invocationId,
+ timestamp: now,
+ level: entry.level,
+ message: entry.message,
+ })
+ }
+
+ if (logEntries.length === 0) {
+ return
+ }
+
+ this.hogFunctionMonitoringService.queueLogs(logEntries, 'hog_flow')
+ await this.hogFunctionMonitoringService.flush()
+ }
+
public async handleSesWebhook(req: ModifiedRequest): Promise<{ status: number; message?: string }> {
if (!req.body) {
return { status: 403, message: 'Missing request body' }
}
try {
- const { status, body, metrics, optOutRecipients } = await this.sesWebhookHandler.handleWebhook({
+ const { status, body, metrics, logEntries, optOutRecipients } = await this.sesWebhookHandler.handleWebhook({
body: parseJSON(req.body),
headers: req.headers,
verifySignature: true,
@@ -242,6 +316,22 @@ export class EmailTrackingService {
})
}
+ // Wrapped so a failure here doesn't skip the opt-out processing below.
+ try {
+ await this.trackLogs(
+ (logEntries || []).map((entry) => ({
+ functionId: entry.functionId,
+ invocationId: entry.invocationId,
+ parentRunId: entry.parentRunId,
+ level: entry.level,
+ message: entry.message,
+ }))
+ )
+ } catch (error) {
+ logger.error('[EmailTrackingService] handleSesWebhook: Failed to track logs', { error })
+ emailTrackingErrorsCounter.inc({ error_type: 'track_logs_failed', source: 'ses' })
+ }
+
// Collect all emails to opt out per team, then batch each team's opt-out in one query
const emailsByTeam = new Map<number, string[]>()
for (const { teamId: teamIdStr, emailAddresses } of optOutRecipients || []) {
diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts b/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
index 6e6f4df3c286..2c0c2ad7b5c6 100644
--- a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
@@ -243,8 +243,9 @@ describe('SesWebhookHandler', () => {
},
]
const result = await handler.handleWebhook({ body, headers: {} })
- // No metric recorded for the test send, but the hard bounce still triggers an opt-out.
+ // No metric or log entry recorded for the test send, but the hard bounce still triggers an opt-out.
expect(result.metrics).toEqual([])
+ expect(result.logEntries).toEqual([])
expect(result.optOutRecipients).toEqual([{ teamId: '1', emailAddresses: ['[email protected]'] }])
})
@@ -490,4 +491,185 @@ describe('SesWebhookHandler', () => {
expect(result.status).toBe(200)
expect(result.metrics?.[0].metricName).toBe('email_opened')
})
+
+ describe('log entries', () => {
+ const logCases: { name: string; event: Record<string, any>; level: string; message: string }[] = [
+ {
+ name: 'Bounce permanent',
+ event: {
+ eventType: 'Bounce',
+ mail: baseMail,
+ bounce: {
+ bounceType: 'Permanent',
+ bouncedRecipients: [
+ {
+ emailAddress: '[email protected]',
+ status: '5.1.1',
+ diagnosticCode: 'mailbox does not exist',
+ },
+ ],
+ timestamp: '2025-10-03T12:04:00Z',
+ },
+ },
+ level: 'error',
+ message: '[Action:act789] Permanent bounce to [email protected], mailbox does not exist (5.1.1)',
+ },
+ {
+ name: 'Bounce transient',
+ event: {
+ eventType: 'Bounce',
+ mail: baseMail,
+ bounce: {
+ bounceType: 'Transient',
+ bouncedRecipients: [
+ { emailAddress: '[email protected]', status: '4.1.1', diagnosticCode: 'temp' },
+ ],
+ timestamp: '2025-10-03T12:04:00Z',
+ },
+ },
+ level: 'warn',
+ message: '[Action:act789] Transient bounce to [email protected], temp (4.1.1)',
+ },
+ {
+ name: 'Complaint',
+ event: {
+ eventType: 'Complaint',
+ mail: baseMail,
+ complaint: {
+ complainedRecipients: [{ emailAddress: '[email protected]' }],
+ timestamp: '2025-10-03T12:05:00Z',
+ complaintFeedbackType: 'abuse',
+ },
+ },
+ level: 'warn',
+ message: '[Action:act789] Complaint from [email protected], feedback type: abuse',
+ },
+ {
+ name: 'RenderingFailure',
+ event: {
+ eventType: 'RenderingFailure',
+ mail: baseMail,
+ renderingFailure: { errorMessage: 'bad template', templateName: 'welcome' },
+ },
+ level: 'error',
+ message: '[Action:act789] Rendering failure for template welcome: bad template',
+ },
+ {
+ name: 'Reject',
+ event: { eventType: 'Reject', mail: baseMail, reject: { reason: 'spam' } },
+ level: 'error',
+ message: '[Action:act789] Message rejected by SES: spam',
+ },
+ ]
+
+ it.each(logCases)('emits a $name log entry', async ({ event, level, message }) => {
+ const result = await handler.handleWebhook({ body: [event], headers: {} })
+ expect(result.logEntries).toEqual([
+ expect.objectContaining({ functionId: 'abc123', invocationId: 'inv456', level, message }),
+ ])
+ })
+
+ it.each([
+ { name: 'Open', event: { eventType: 'Open', mail: baseMail, open: { timestamp: '2025-10-03T12:01:00Z' } } },
+ {
+ name: 'Delivery',
+ event: { eventType: 'Delivery', mail: baseMail, delivery: { timestamp: '2025-10-03T12:03:00Z' } },
+ },
+ { name: 'Send', event: { eventType: 'Send', mail: baseMail } },
+ ])('does not emit a log entry for the info-level $name event', async ({ event }) => {
+ const result = await handler.handleWebhook({ body: [event], headers: {} })
+ expect(result.logEntries).toEqual([])
+ })
+
+ it('emits one log entry per bounced recipient', async () => {
+ const body = [
+ {
+ eventType: 'Bounce',
+ mail: baseMail,
+ bounce: {
+ bounceType: 'Permanent',
+ bouncedRecipients: [
+ { emailAddress: '[email protected]', diagnosticCode: 'mailbox full' },
+ { emailAddress: '[email protected]', diagnosticCode: 'mailbox full' },
+ ],
+ timestamp: '2025-10-03T12:04:00Z',
+ },
+ },
+ ]
+ const result = await handler.handleWebhook({ body, headers: {} })
+ expect(result.logEntries?.map((e) => e.message)).toEqual([
+ '[Action:act789] Permanent bounce to [email protected], mailbox full',
+ '[Action:act789] Permanent bounce to [email protected], mailbox full',
+ ])
+ })
+
+ it('does not duplicate the status when SES inlines it inside diagnosticCode', async () => {
+ const body = [
+ {
+ eventType: 'Bounce',
+ mail: baseMail,
+ bounce: {
+ bounceType: 'Permanent',
+ bouncedRecipients: [
+ {
+ emailAddress: '[email protected]',
+ status: '5.1.1',
+ diagnosticCode: 'smtp; 550 5.1.1 user unknown <[email protected]>',
+ },
+ ],
+ timestamp: '2025-10-03T12:04:00Z',
+ },
+ },
+ ]
+ const result = await handler.handleWebhook({ body, headers: {} })
+ expect(result.logEntries?.[0].message).toBe(
+ '[Action:act789] Permanent bounce to [email protected], smtp; 550 5.1.1 user unknown <[email protected]>'
+ )
+ })
+
+ it('drops the [Action:...] prefix when the actionId contains unsafe characters', async () => {
+ // A ph_id whose actionId would close the Action token early and inject an Actor token
+ // must not reach the rich-log viewer with brackets intact.
+ const maliciousInvocation = {
+ ...baseInvocation,
+ state: { actionId: 'act] [Actor:[email protected]' },
+ }
+ const maliciousMail = {
+ ...baseMail,
+ headers: [{ name: TRACKING_CODE_HEADER, value: signer.generate(maliciousInvocation) }],
+ tags: { ph_id: [signer.generateShort(maliciousInvocation)] },
+ }
+ const body = [
+ {
+ eventType: 'Bounce',
+ mail: maliciousMail,
+ bounce: {
+ bounceType: 'Permanent',
+ bouncedRecipients: [{ emailAddress: '[email protected]', diagnosticCode: 'unknown' }],
+ timestamp: '2025-10-03T12:04:00Z',
+ },
+ },
+ ]
+ const result = await handler.handleWebhook({ body, headers: {} })
+ expect(result.logEntries?.[0].message).toBe('Permanent bounce to [email protected], unknown')
+ })
+
+ it('accepts DeliveryDelay without producing a metric or log (so SNS does not retry)', async () => {
+ const body = [
+ {
+ eventType: 'DeliveryDelay',
+ mail: baseMail,
+ deliveryDelay: {
+ delayType: 'MailboxFull',
+ timestamp: '2025-10-03T12:06:00Z',
+ delayedRecipients: [{ emailAddress: '[email protected]' }],
+ },
+ },
+ ]
+ const result = await handler.handleWebhook({ body, headers: {} })
+ expect(result.status).toBe(200)
+ expect(result.metrics).toEqual([])
+ expect(result.logEntries).toEqual([])
+ })
+ })
})
diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.ts b/nodejs/src/cdp/services/messaging/helpers/ses.ts
index c5585f9c1c68..7822f2f9d1aa 100644
--- a/nodejs/src/cdp/services/messaging/helpers/ses.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/ses.ts
@@ -127,7 +127,13 @@ const SesRenderingFailureSchema = SesCommonEventBase.extend({
})
const SesSendEventSchema = SesCommonEventBase.extend({ eventType: z.literal('Send') })
-const SesRejectEventSchema = SesCommonEventBase.extend({ eventType: z.literal('Reject') })
+const SesRejectEventSchema = SesCommonEventBase.extend({
+ eventType: z.literal('Reject'),
+ reject: z.object({ reason: z.string().optional() }).optional(),
+})
+
+// Acknowledged so SNS doesn't retry forever; details aren't surfaced.
+const SesDeliveryDelayEventSchema = SesCommonEventBase.extend({ eventType: z.literal('DeliveryDelay') })
const SesEventRecordSchema = z.union([
SesOpenEventSchema,
@@ -138,6 +144,7 @@ const SesEventRecordSchema = z.union([
SesRenderingFailureSchema,
SesSendEventSchema,
SesRejectEventSchema,
+ SesDeliveryDelayEventSchema,
])
const SesEventBatchSchema = z.array(SesEventRecordSchema)
@@ -156,6 +163,75 @@ const EVENT_TYPE_TO_METRIC_NAME: Partial<Record<SesEventRecord['eventType'], Min
Reject: 'email_failed',
}
+export type SesEventLogLine = {
+ level: 'warn' | 'error'
+ message: string
+}
+
+const MAX_SES_FIELD_LENGTH = 1024
+
+// Strip control chars, neutralize rich-log bracket tokens, and cap length.
+const sanitizeSesField = (value: string, max = MAX_SES_FIELD_LENGTH): string => {
+ const cleaned = value
+ .replace(/[\u0000-\u001f\u007f]/g, ' ')
+ .replace(/\[/g, '(')
+ .replace(/\]/g, ')')
+ return cleaned.length > max ? cleaned.slice(0, max) + '…' : cleaned
+}
+
+// Only warn/error events become log entries. Info-level events (Send, Delivery, Open, Click)
+// are tracked as metrics only - they're analytics signal, not debugging signal.
+export const formatSesEventLogs = (rec: SesEventRecord): SesEventLogLine[] => {
+ switch (rec.eventType) {
+ case 'Bounce': {
+ const bounceType = rec.bounce.bounceType
+ const level: SesEventLogLine['level'] = bounceType === 'Permanent' ? 'error' : 'warn'
+ return rec.bounce.bouncedRecipients.map((r) => {
+ const diag = r.diagnosticCode ? sanitizeSesField(r.diagnosticCode) : ''
+ // SES typically inlines the SMTP status inside diagnosticCode already
+ // (e.g. "smtp; 550 5.1.1 user unknown"), so skip the suffix when present.
+ const statusSuffix = r.status && !diag.includes(r.status) ? ` (${sanitizeSesField(r.status)})` : ''
+ const diagPart = diag ? `, ${diag}` : ''
+ return {
+ level,
+ message: `${bounceType} bounce to ${sanitizeSesField(r.emailAddress)}${diagPart}${statusSuffix}`,
+ }
+ })
+ }
+ case 'Complaint': {
+ const feedback = rec.complaint.complaintFeedbackType
+ ? `, feedback type: ${sanitizeSesField(rec.complaint.complaintFeedbackType)}`
+ : ''
+ return rec.complaint.complainedRecipients.map((r) => ({
+ level: 'warn',
+ message: `Complaint from ${sanitizeSesField(r.emailAddress)}${feedback}`,
+ }))
+ }
+ case 'RenderingFailure': {
+ const tmpl = rec.renderingFailure.templateName
+ ? ` for template ${sanitizeSesField(rec.renderingFailure.templateName)}`
+ : ''
+ return [
+ {
+ level: 'error',
+ message: `Rendering failure${tmpl}: ${sanitizeSesField(rec.renderingFailure.errorMessage)}`,
+ },
+ ]
+ }
+ case 'Reject': {
+ const reason = rec.reject?.reason ? `: ${sanitizeSesField(rec.reject.reason)}` : ''
+ return [
+ {
+ level: 'error',
+ message: `Message rejected by SES${reason}`,
+ },
+ ]
+ }
+ default:
+ return []
+ }
+}
+
export class SesWebhookHandler {
certCache: Record<string, Promise<string> | undefined> = {}
@@ -322,6 +398,15 @@ export class SesWebhookHandler {
properties?: Record<string, any>
timestamp?: string
}[]
+ logEntries?: {
+ functionId?: string
+ invocationId?: string
+ actionId?: string
+ parentRunId?: string
+ teamId?: string
+ level: SesEventLogLine['level']
+ message: string
+ }[]
optOutRecipients?: {
teamId?: string
emailAddresses: string[]
@@ -383,6 +468,15 @@ export class SesWebhookHandler {
properties?: Record<string, any>
timestamp?: string
}[] = []
+ const logEntries: {
+ functionId?: string
+ invocationId?: string
+ actionId?: string
+ parentRunId?: string
+ teamId?: string
+ level: SesEventLogLine['level']
+ message: string
+ }[] = []
const optOutRecipients: {
teamId?: string
emailAddresses: string[]
@@ -448,6 +542,24 @@ export class SesWebhookHandler {
})
}
+ // Allowlist actionId before interpolating into the [Action:…] rich-log token,
+ // since actionId comes from the attacker-influenceable ph_id tag.
+ const safeActionId = actionId && /^[a-zA-Z0-9_-]+$/.test(actionId) ? actionId : undefined
+ // Skip test sends here too (mirrors the metrics gate above) so a "Run test" bounce
+ // doesn't write a misleading failure into the workflow's invocation logs.
+ for (const line of isTest ? [] : formatSesEventLogs(rec)) {
+ const prefix = safeActionId ? `[Action:${safeActionId}] ` : ''
+ logEntries.push({
+ functionId,
+ invocationId,
+ actionId,
+ parentRunId,
+ teamId,
+ level: line.level,
+ message: `${prefix}${line.message}`,
+ })
+ }
+
// Opt out recipients on permanent bounces
if (teamId && rec.eventType === 'Bounce' && rec.bounce.bounceType === 'Permanent') {
const emails = rec.bounce.bouncedRecipients.map((r) => r.emailAddress)
@@ -455,6 +567,6 @@ export class SesWebhookHandler {
}
}
- return { status: 200, body: { ok: true }, metrics, optOutRecipients }
+ return { status: 200, body: { ok: true }, metrics, logEntries, optOutRecipients }
}
}
diff --git a/products/workflows/frontend/Workflows/EmailMetricsSummary.tsx b/products/workflows/frontend/Workflows/EmailMetricsSummary.tsx
index ddf3af7eb60a..e4b5e534a4d9 100644
--- a/products/workflows/frontend/Workflows/EmailMetricsSummary.tsx
+++ b/products/workflows/frontend/Workflows/EmailMetricsSummary.tsx
@@ -6,11 +6,18 @@ import { appMetricsLogic } from 'lib/components/AppMetrics/appMetricsLogic'
import { AppMetricsTrends } from 'lib/components/AppMetrics/AppMetricsTrends'
import { AppMetricSummary } from 'lib/components/AppMetrics/AppMetricSummary'
-import { WORKFLOW_EMAIL_METRICS } from './workflowMetricsSummaryLogic'
+import { EMAIL_METRIC_LOG_FILTERS, EmailMetric, WORKFLOW_EMAIL_METRICS } from './workflowMetricsSummaryLogic'
const EMAIL_METRIC_KEYS = Object.keys(WORKFLOW_EMAIL_METRICS) as (keyof typeof WORKFLOW_EMAIL_METRICS)[]
-export function EmailMetricsSummary({ logicKey }: { logicKey: string }): JSX.Element {
+export function EmailMetricsSummary({
+ logicKey,
+ onMetricClick,
+}: {
+ logicKey: string
+ /** Invoked when a drill-down-able metric tile (e.g. Bounced) is clicked. */
+ onMetricClick?: (metricKey: EmailMetric) => void
+}): JSX.Element {
const { appMetricsTrendsLoading, appMetricsTrends, getSingleTrendSeries } = useValues(appMetricsLogic({ logicKey }))
const emailTrends = useMemo(
@@ -37,6 +44,7 @@ export function EmailMetricsSummary({ logicKey }: { logicKey: string }): JSX.Ele
<div className="flex flex-row gap-2 flex-wrap justify-center">
{EMAIL_METRIC_KEYS.map((key) => {
const metric = WORKFLOW_EMAIL_METRICS[key]
+ const canDrillDown = !!onMetricClick && !!EMAIL_METRIC_LOG_FILTERS[key]
return (
<AppMetricSummary
key={key}
@@ -47,6 +55,8 @@ export function EmailMetricsSummary({ logicKey }: { logicKey: string }): JSX.Ele
previousPeriodTimeSeries={getSingleTrendSeries(key, true)}
color={metric.color}
colorIfZero={getColorVar('muted')}
+ onClick={canDrillDown ? () => onMetricClick(key) : undefined}
+ onClickTooltip={`View invocations with a ${metric.name.toLowerCase()} log entry in this timeframe`}
/>
)
})}
diff --git a/products/workflows/frontend/Workflows/WorkflowMetrics.tsx b/products/workflows/frontend/Workflows/WorkflowMetrics.tsx
index a2b4c2a76710..5c1c8ff677a6 100644
--- a/products/workflows/frontend/Workflows/WorkflowMetrics.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowMetrics.tsx
@@ -1,4 +1,5 @@
import { useActions, useValues } from 'kea'
+import { router } from 'kea-router'
import { useMemo } from 'react'
import { LemonCollapse, LemonSelect, ProfilePicture, Spinner } from '@posthog/lemon-ui'
@@ -11,6 +12,7 @@ import { AppMetricSummary } from 'lib/components/AppMetrics/AppMetricSummary'
import { ListHog } from 'lib/components/hedgehogs'
import { TZLabel } from 'lib/components/TZLabel'
import { dayjs } from 'lib/dayjs'
+import { urls } from 'scenes/urls'
import { batchWorkflowJobsLogic } from './batchWorkflowJobsLogic'
import { EmailMetricsSummary } from './EmailMetricsSummary'
@@ -18,6 +20,7 @@ import { getHogFlowStep } from './hogflows/steps/HogFlowSteps'
import { HogFlowBatchJob } from './hogflows/types'
import { WorkflowLogicProps, workflowLogic } from './workflowLogic'
import { WorkflowMetricsSummary } from './WorkflowMetricsSummary'
+import { type EmailMetric, buildEmailMetricLogSearchParams } from './workflowMetricsSummaryLogic'
const OVERVIEW_OPTION_VALUE = '__workflow_overview__'
@@ -60,7 +63,8 @@ function WorkflowRunMetrics(props: WorkflowLogicProps): JSX.Element {
const { workflow, hogFunctionTemplatesById } = useValues(workflowLogic)
- const { appMetricsTrendsLoading, appMetricsTrends, getSingleTrendSeries, params } = useValues(logic)
+ const { appMetricsTrendsLoading, appMetricsTrends, getSingleTrendSeries, params, getDateRangeAbsolute } =
+ useValues(logic)
const { setParams } = useActions(logic)
const selectedAction = workflow.actions.find((action) => action.id === params.instanceId)
@@ -97,6 +101,15 @@ function WorkflowRunMetrics(props: WorkflowLogicProps): JSX.Element {
[workflow.actions, hogFunctionTemplatesById]
)
+ // Drill an email metric into the logs tab filtered to its log entries over the current window.
+ const onEmailMetricClick = (metricKey: EmailMetric): void => {
+ const { dateFrom, dateTo } = getDateRangeAbsolute()
+ const searchParams = buildEmailMetricLogSearchParams(metricKey, dateFrom.toISOString(), dateTo.toISOString())
+ if (searchParams && props.id) {
+ router.actions.push(urls.workflow(props.id, 'logs'), searchParams)
+ }
+ }
+
return (
<div className="flex flex-col gap-2" data-attr="workflow-metrics">
<div className="flex flex-row gap-2 flex-wrap justify-between">
@@ -121,9 +134,10 @@ function WorkflowRunMetrics(props: WorkflowLogicProps): JSX.Element {
logicKey={logicKey}
id={props.id ?? ''}
onSelectAction={(actionId) => setParams({ ...params, instanceId: actionId })}
+ onMetricClick={onEmailMetricClick}
/>
) : selectedAction?.type === 'function_email' ? (
- <EmailMetricsSummary logicKey={logicKey} />
+ <EmailMetricsSummary logicKey={logicKey} onMetricClick={onEmailMetricClick} />
) : (
<>
<div className="flex flex-row gap-2 flex-wrap justify-center">
diff --git a/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx b/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx
index 4e3616464b4a..39d15f727efc 100644
--- a/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx
@@ -9,6 +9,7 @@ import { AppMetricSummary } from 'lib/components/AppMetrics/AppMetricSummary'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import {
+ type EmailMetric,
WORKFLOW_SUMMARY_METRICS,
type EmailMetricRow,
withDisplayName,
@@ -18,9 +19,15 @@ import {
interface WorkflowMetricsSummaryProps extends WorkflowMetricsSummaryLogicProps {
onSelectAction?: (actionId: string) => void
+ /** Drill a per-email metric into its filtered logs (only bounced/blocked have a log filter). */
+ onMetricClick?: (metricKey: EmailMetric) => void
}
-export function WorkflowMetricsSummary({ onSelectAction, ...props }: WorkflowMetricsSummaryProps): JSX.Element {
+export function WorkflowMetricsSummary({
+ onSelectAction,
+ onMetricClick,
+ ...props
+}: WorkflowMetricsSummaryProps): JSX.Element {
const {
loading,
summaryMetricKeys,
@@ -68,6 +75,34 @@ export function WorkflowMetricsSummary({ onSelectAction, ...props }: WorkflowMet
align: 'right',
render: (_, row) => row.delivered.toLocaleString(),
},
+ {
+ title: 'Bounced',
+ dataIndex: 'bounced',
+ key: 'bounced',
+ align: 'right',
+ render: (_, row) =>
+ onMetricClick && row.bounced > 0 ? (
+ <span className="cursor-pointer text-link" onClick={() => onMetricClick('email_bounced')}>
+ {row.bounced.toLocaleString()}
+ </span>
+ ) : (
+ row.bounced.toLocaleString()
+ ),
+ },
+ {
+ title: 'Blocked',
+ dataIndex: 'blocked',
+ key: 'blocked',
+ align: 'right',
+ render: (_, row) =>
+ onMetricClick && row.blocked > 0 ? (
+ <span className="cursor-pointer text-link" onClick={() => onMetricClick('email_blocked')}>
+ {row.blocked.toLocaleString()}
+ </span>
+ ) : (
+ row.blocked.toLocaleString()
+ ),
+ },
{
title: 'Opened',
dataIndex: 'opened',
@@ -83,7 +118,7 @@ export function WorkflowMetricsSummary({ onSelectAction, ...props }: WorkflowMet
render: (_, row) => row.linkClicked.toLocaleString(),
},
],
- [onSelectAction]
+ [onSelectAction, onMetricClick]
)
return (
diff --git a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts
index 7467aa501f16..ec907ffc8b60 100644
--- a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts
+++ b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts
@@ -15,7 +15,7 @@ import { urls } from 'scenes/urls'
import { defaultDataTableColumns } from '~/queries/nodes/DataTable/utils'
import { DataTableNode, EventsQuery, NodeKind } from '~/queries/schema/schema-general'
-import { ActivityTab, PropertyFilterType, PropertyOperator } from '~/types'
+import { ActivityTab, LogEntryLevel, PropertyFilterType, PropertyOperator } from '~/types'
import { isEmailAction } from './hogflows/steps/types'
import { workflowLogic } from './workflowLogic'
@@ -49,6 +49,8 @@ export type EmailMetricRow = {
sent: number
opened: number
linkClicked: number
+ bounced: number
+ blocked: number
}
export const WORKFLOW_SUMMARY_METRICS: Record<
@@ -150,6 +152,38 @@ export const WORKFLOW_EMAIL_METRICS: Record<
},
}
+// Email metrics whose SES events also write per-invocation log entries (see the SES webhook
+// handler). Clicking the tile drills into the Invocations tab filtered to those log entries.
+// The `search` term matches the start of the log message the handler emits (e.g. "Permanent
+// bounce to …"), so it surfaces every invocation that logged that failure in the timeframe.
+export const EMAIL_METRIC_LOG_FILTERS: Partial<Record<EmailMetric, { search: string; levels: LogEntryLevel[] }>> = {
+ email_bounced: { search: 'bounce', levels: ['WARN', 'ERROR'] },
+ email_blocked: { search: 'Complaint', levels: ['WARN', 'ERROR'] },
+ // email_failed (RenderingFailure + Reject) is intentionally omitted: its two SES events emit
+ // differently-worded messages ("Rendering failure …" vs "Message rejected by SES …") with no
+ // shared substring, and filtering by ERROR level alone would also catch permanent bounces.
+ // A reliable drill-down would need the log writer to emit a stable machine token to match on.
+}
+
+// Build the router search params that point the Invocations (logs) tab at the invocations whose
+// log entries match the given email metric over the metrics view's current timeframe.
+export function buildEmailMetricLogSearchParams(
+ metricKey: EmailMetric,
+ dateFrom: string,
+ dateTo: string
+): Record<string, string | string[]> | null {
+ const filter = EMAIL_METRIC_LOG_FILTERS[metricKey]
+ if (!filter) {
+ return null
+ }
+ return {
+ search: filter.search,
+ levels: filter.levels,
+ date_from: dateFrom,
+ date_to: dateTo,
+ }
+}
+
const SUMMARY_METRIC_KEYS = (Object.keys(WORKFLOW_SUMMARY_METRICS) as WorkflowSummaryMetric[]).filter(
(key) => key !== 'in_progress'
)
@@ -436,6 +470,8 @@ export const workflowMetricsSummaryLogic = kea<workflowMetricsSummaryLogicType>(
sent: totals.email_sent ?? 0,
opened: totals.email_opened ?? 0,
linkClicked: totals.email_link_clicked ?? 0,
+ bounced,
+ blocked,
}
}),
],