: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
fix(workflows): count people instead of events for broadcast opens and clicks (#129330)
Daniel Marchuk8b0f43355319
diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.tsindex 604149a1ce58..3b926ed56ab1 100644--- a/nodejs/src/cdp/cdp-api.ts+++ b/nodejs/src/cdp/cdp-api.ts@@ -294,7 +294,8 @@ export class CdpApi {services.teamWorkflowsConfigService,new EmailTrackingCodeSigner(config.ENCRYPTION_SALT_KEYS, config.CDP_EMAIL_TRACKING_URL),services.emailSuppressionService,- services.emailStatusService+ services.emailStatusService,+ services.redis)this.groupsManager = new GroupsManagerService(deps.teamManager, deps.groupRepository)this.batchExportHogFunctionService = new BatchExportHogFunctionService(diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.test.tsindex 1a6ea76fb6e1..5fde24b4382a 100644--- a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts@@ -446,6 +446,78 @@ describe('EmailTrackingService', () => {})})+ it('counts a large audience, where most new people do not change the HyperLogLog', async () => {+ const parentRunId = new UUIDT().toString()+ const service = api['emailTrackingService'] as any+ let opened = 0+ for (let index = 0; index < 5000; index++) {+ const added = await service.newEngagedPeople(parentRunId, `person-${index}`, 'email_opened', 'ses')+ opened += added[0]?.count ?? 0+ }+ expect(opened).toBeGreaterThan(4900)+ expect(opened).toBeLessThan(5100)+ })++ it('still records the open when Redis stalls', async () => {+ const parentRunId = new UUIDT().toString()+ const service = api['emailTrackingService'] as any+ jest.spyOn(service.engagementRedis, 'useClient').mockReturnValue(new Promise(() => {}))+ const code = signer.generate({+ functionId: hogFunction.id,+ id: new UUIDT().toString(),+ teamId: team.id,+ parentRunId,+ })++ const response = await supertest(app).get(`/public/m/pixel?ph_id=${code}`)++ expect(response.status).toBe(200)+ await waitForExpect(() => {+ const names = mockProducerObserver+ .getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)+ .filter(({ value }) => value.app_source_id === parentRunId)+ .map(({ value }) => value.metric_name)+ expect(names).toEqual(['email_opened'])+ })+ })++ it('counts a person once per run however often they open or click', async () => {+ const parentRunId = new UUIDT().toString()+ const phId = (id: string): string =>+ signer.generate({+ functionId: hogFunction.id,+ id,+ teamId: team.id,+ parentRunId,+ })+ const first = phId(new UUIDT().toString())+ const second = phId(new UUIDT().toString())++ for (const code of [first, first, second]) {+ await supertest(app).get(`/public/m/pixel?ph_id=${code}`)+ }+ await supertest(app).get(`/public/m/redirect?ph_id=${first}&target=https://example.com`)+ await supertest(app).get(`/public/m/redirect?ph_id=${first}&target=https://example.com`)++ await waitForExpect(() => {+ const counts: Record<string, number> = {}+ for (const { value } of mockProducerObserver.getProducedKafkaMessagesForTopic(+ KAFKA_APP_METRICS_2+ )) {+ if (value.app_source_id === parentRunId) {+ counts[value.metric_name as string] =+ (counts[value.metric_name as string] ?? 0) + (value.count as number)+ }+ }+ expect(counts).toEqual({+ email_opened: 3,+ email_opened_by_person: 2,+ email_link_clicked: 2,+ email_clicked_by_person: 1,+ })+ })+ })+it('should return a 200 even if the tracking code is invalid', async () => {const res = await supertest(app).get(`/public/m/pixel?ph_id=invalid-tracking-code`)expect(res.status).toBe(200)diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.tsindex 4e6cfc312e01..736a4a901b80 100644--- a/nodejs/src/cdp/services/messaging/email-tracking.service.ts+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.ts@@ -12,6 +12,7 @@ import {MinimalAppMetric,} from '~/cdp/types'import { ModifiedRequest } from '~/common/api/router'+import { RedisV2 } from '~/common/redis/redis-v2'import { isDevEnv, isTestEnv } from '~/common/utils/env-utils'import { parseJSON } from '~/common/utils/json-parse'import { logger } from '~/common/utils/logger'@@ -89,6 +90,29 @@ const emailTrackingLogSkipsCounter = new Counter({labelNames: ['reason', 'source'],})+const ENGAGEMENT_PERSON_METRICS: Partial<Record<MinimalAppMetric['metric_name'], MinimalAppMetric['metric_name'][]>> = {+ email_opened: ['email_opened_by_person'],+ email_link_clicked: ['email_opened_by_person', 'email_clicked_by_person'],+}+// An open after this counts its person again. Almost all opens and clicks come in the first days.+const ENGAGEMENT_PEOPLE_TTL_SECONDS = 30 * 24 * 60 * 60+// A slow Redis costs a person count, never an open or click webhook.+const ENGAGEMENT_REDIS_TIMEOUT_MS = 500+// PFADD returns 0 for many new people once a HyperLogLog fills, so the growth of PFCOUNT is what counts. Each pair of+// keys is a HyperLogLog and the total already reported. Returns how much each total grew.+const ENGAGEMENT_PEOPLE_SCRIPT = `+local grew = {}+for index = 1, #KEYS, 2 do+ redis.call('PFADD', KEYS[index], ARGV[1])+ local total = redis.call('PFCOUNT', KEYS[index])+ local reported = tonumber(redis.call('GET', KEYS[index + 1]) or '0')+ redis.call('SET', KEYS[index + 1], math.max(total, reported), 'EX', ARGV[2])+ redis.call('EXPIRE', KEYS[index], ARGV[2])+ grew[#grew + 1] = math.max(total - reported, 0)+end+return grew+`+// 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.@@ -294,7 +318,8 @@ export class EmailTrackingService {private teamWorkflowsConfigService: TeamWorkflowsConfigService,private trackingCodeSigner: EmailTrackingCodeSigner,private emailSuppressionService: EmailSuppressionService,- private emailStatusService: EmailStatusService | null = null+ private emailStatusService: EmailStatusService | null = null,+ private engagementRedis: RedisV2 | null = null) {const allowedTopicArns = (process.env.SES_ALLOWED_SNS_TOPIC_ARNS ?? '').split(',')this.sesWebhookHandler = new SesWebhookHandler(this.trackingCodeSigner, allowedTopicArns)@@ -401,6 +426,27 @@ export class EmailTrackingService {hogFlow ? 'hog_flow' : 'hog_function')+ if (parentRunId) {+ for (const { metric, count } of await this.newEngagedPeople(+ parentRunId,+ invocationId,+ metricName,+ source+ )) {+ this.hogFunctionMonitoringService.queueAppMetric(+ {+ team_id: teamId,+ app_source_id: parentRunId,+ instance_id: instanceIdOverride || actionId || invocationId,+ metric_name: metric,+ metric_kind: 'email',+ count,+ },+ hogFlow ? 'hog_flow' : 'hog_function'+ )+ }+ }+const eventName = METRIC_NAME_TO_EVENT_NAME[metricName]if (eventName && distinctId && (await this.teamWorkflowsConfigService.shouldCaptureEngagementEvents(teamId))) {await this.capturedEventsService.queueEvent({@@ -661,6 +707,48 @@ export class EmailTrackingService {return Object.fromEntries(ids.map((id) => [id, onReplica[id] ?? onPrimary[id] ?? null]))}+ // How many people this open or click adds to each per-person metric of its run. One email goes to one person, so+ // the email's invocation id stands for the person. A click also counts as an open, because the open pixel is often+ // blocked. A HyperLogLog stays small for any audience and is about 1% off. When Redis fails, the counts read low.+ private async newEngagedPeople(+ parentRunId: string,+ invocationId: string,+ metricName: MinimalAppMetric['metric_name'],+ source: 'direct' | 'ses'+ ): Promise<{ metric: MinimalAppMetric['metric_name']; count: number }[]> {+ const metrics = ENGAGEMENT_PERSON_METRICS[metricName]+ if (!metrics || !this.engagementRedis) {+ return []+ }+ const keys = metrics.flatMap((metric) => {+ const key = `@posthog/email-engagement-people/{${parentRunId}}/${metric}`+ return [key, `${key}/reported`]+ })+ let timer: NodeJS.Timeout | undefined+ const grew = await Promise.race([+ this.engagementRedis.useClient(+ { name: 'email-engagement-people', failOpen: true },+ (client) =>+ client.eval(+ ENGAGEMENT_PEOPLE_SCRIPT,+ keys.length,+ ...keys,+ invocationId,+ ENGAGEMENT_PEOPLE_TTL_SECONDS+ ) as Promise<number[]>+ ),+ new Promise<null>((resolve) => {+ timer = setTimeout(() => resolve(null), ENGAGEMENT_REDIS_TIMEOUT_MS)+ }),+ ])+ clearTimeout(timer)+ if (!grew) {+ emailTrackingErrorsCounter.inc({ error_type: 'engagement_people_not_counted', source })+ return []+ }+ return metrics.map((metric, index) => ({ metric, count: grew[index] })).filter(({ count }) => count > 0)+ }+private parseTrackingParams(query: Record<string, any>): {functionId?: stringinvocationId?: stringdiff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex 1839c58db50d..cdc33a294c9c 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -257,6 +257,8 @@ export type MinimalAppMetric = {| 'email_opened'| 'email_link_clicked'| 'email_link_clicked_by_link'+ | 'email_opened_by_person'+ | 'email_clicked_by_person'| 'email_bounced'| 'email_bounced_hard'| 'email_bounced_transient'diff --git a/products/workflows/frontend/Broadcasts/BroadcastPerformance.tsx b/products/workflows/frontend/Broadcasts/BroadcastPerformance.tsxindex 9628bcd20f28..2d254c22a3e3 100644--- a/products/workflows/frontend/Broadcasts/BroadcastPerformance.tsx+++ b/products/workflows/frontend/Broadcasts/BroadcastPerformance.tsx@@ -14,7 +14,7 @@ import { BroadcastSendActivity } from './BroadcastSendActivity'import { BroadcastSendErrorAction, BroadcastSendErrorBanner } from './BroadcastSendErrorBanner'function share(part: number, whole: number): string {- return whole > 0 ? percentage(part / whole, 1) : '-'+ return whole > 0 ? percentage(Math.min(part / whole, 1), 1) : '-'}export function BroadcastPerformance({@@ -65,12 +65,17 @@ export function BroadcastPerformance({: [{ label: 'Opened', part: stats.opened, whole: stats.trackedSends },{ label: 'Clicked', part: stats.clicked, whole: stats.trackedSends },- { label: 'Clicked to opened', part: stats.clicked, whole: stats.opened },+ ...(stats.engagementCountsPeople+ ? [{ label: 'Clicked to opened', part: stats.clicked, whole: stats.opened }]+ : []),]),...(hasGoal ? [{ label: 'Converted', part: stats.converted, whole: stats.sent }] : []),]const footnote = [trackingOff ? null : 'Opens and clicks are counted against sends with tracking on.',+ !trackingOff && !stats.engagementCountsPeople+ ? 'This send counts every open and click, so one person can count more than once.'+ : null,hasGoal ? 'Conversions are counted against all sends.' : null,].filter(Boolean)diff --git a/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx b/products/workflows/frontend/Broadcasts/BroadcastsTable.tsxindex 40afc2df7f97..56680606e8e6 100644--- a/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx+++ b/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx@@ -18,6 +18,7 @@ import type { HogFlowMinimalApi } from 'products/workflows/frontend/generated/apimport { EmailMetricsIncidentBanner } from '../EmailMetricsIncidentBanner'import { archiveDisabledReason, manageDisabledReason } from './broadcastLifecycle'+import { emailEngagement } from './broadcastPerformanceLogic'import { BroadcastsEmptyState } from './BroadcastsEmptyState'import {BROADCASTS_PAGE_SIZE,@@ -128,7 +129,17 @@ export function BroadcastsTable(): JSX.Element {if (!details?.totals) {return <span className="text-muted">…</span>}- return <span>{humanFriendlyNumber(details.totals[metric] ?? 0)}</span>+ const engagement =+ metric === 'email_opened' ? 'opened' : metric === 'email_link_clicked' ? 'clicked' : null+ return (+ <span>+ {humanFriendlyNumber(+ engagement+ ? emailEngagement(details.totals, engagement, details.latestBatchJob?.created_at)+ : (details.totals[metric] ?? 0)+ )}+ </span>+ )},})),createdByColumn() as LemonTableColumns<HogFlowMinimalApi>[number],diff --git a/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.test.ts b/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.test.tsindex dfe229c27b8c..79778dd0a772 100644--- a/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.test.ts+++ b/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.test.ts@@ -105,6 +105,55 @@ describe('broadcastPerformanceLogic', () => {})+ it.each([+ {+ name: 'a send that counted people',+ runStartedAt: '2026-11-10T22:28:56Z',+ totals: [+ [10, 'email_sent'],+ [5, 'email_opened'],+ [8, 'email_link_clicked'],+ [4, 'email_opened_by_person'],+ [1, 'email_clicked_by_person'],+ ],+ expected: { opened: 4, clicked: 1, engagementCountsPeople: true },+ },+ {+ name: 'an older send that only counted events',+ runStartedAt: '2026-10-19T22:28:56Z',+ totals: [+ [10, 'email_sent'],+ [5, 'email_opened'],+ [8, 'email_link_clicked'],+ ],+ expected: { opened: 5, clicked: 8, engagementCountsPeople: false },+ },+ {+ name: 'an older send with a late open',+ runStartedAt: '2026-10-19T22:28:56Z',+ totals: [+ [10, 'email_sent'],+ [5, 'email_opened'],+ [8, 'email_link_clicked'],+ [1, 'email_opened_by_person'],+ ],+ expected: { opened: 5, clicked: 8, engagementCountsPeople: false },+ },+ ])('reports opens and clicks for $name', async ({ runStartedAt, totals, expected }) => {+ jest.spyOn(api, 'queryHogQL').mockImplementation(+ async (query) =>+ ({ results: String(query).includes('email_link_clicked_by_link') ? [] : totals }) as HogQLQueryResponse+ )+ const logic = broadcastPerformanceLogic({+ runId: `run-${totals.length}-${expected.opened}`,+ runStartedAt,+ })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadTotalsSuccess'])+ expect(logic.values.stats).toMatchObject(expected)+ })+it('does not report tracking off before anything was sent', async () => {jest.spyOn(api, 'queryHogQL').mockResolvedValue({ results: [] } as unknown as HogQLQueryResponse)const logic = broadcastPerformanceLogic({ runId: 'run-2', runStartedAt: '2026-10-19T22:28:56Z' })diff --git a/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.ts b/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.tsindex 1d6ae222d940..291df34755fa 100644--- a/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.ts+++ b/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.ts@@ -33,17 +33,48 @@ export interface BroadcastPerformanceStats {unsubscribed: number/** Sends with open and click tracking, the denominator for engagement rates. */trackedSends: number+ /** False for sends from before people were counted, where opened and clicked count every event. */+ engagementCountsPeople: boolean/** Recipients who met the broadcast's goal. */converted: number/** Push only: people with no device registered for the app. */skipped: number}+// Runs that started before this date counted events. A late open on one adds a per-person count that covers only itself.+const ENGAGEMENT_PEOPLE_COUNTED_SINCE = dayjs('2026-11-06T00:00:00Z')++/** Whether opened and clicked count people for this run, rather than every event. */+export function countsEngagedPeople(totals: Record<string, number>, runStartedAt: string | null | undefined): boolean {+ if (!runStartedAt || dayjs(runStartedAt).isBefore(ENGAGEMENT_PEOPLE_COUNTED_SINCE)) {+ return false+ }+ // Events with no per-person count mean Redis was unavailable, so the events are the better number.+ return !!(+ totals.email_opened_by_person ||+ totals.email_clicked_by_person ||+ (!totals.email_opened && !totals.email_link_clicked)+ )+}++export function emailEngagement(+ totals: Record<string, number>,+ kind: 'opened' | 'clicked',+ runStartedAt: string | null | undefined+): number {+ if (countsEngagedPeople(totals, runStartedAt)) {+ return (kind === 'opened' ? totals.email_opened_by_person : totals.email_clicked_by_person) ?? 0+ }+ return (kind === 'opened' ? totals.email_opened : totals.email_link_clicked) ?? 0+}+const TOTALS_METRICS = ['email_sent','email_delivered','email_opened','email_link_clicked',+ 'email_opened_by_person',+ 'email_clicked_by_person','email_bounced','email_blocked','email_failed',@@ -156,7 +187,8 @@ export interface broadcastPerformanceLogicMeta {__keaTypeGenInternalSelectorTypes: {stats: (totals: Record<string, number> | null,- arg: BroadcastChannel | undefined+ arg: BroadcastChannel | undefined,+ arg2: string) => BroadcastPerformanceStats | nullsendCounts: (totals: Record<string, number> | null,@@ -276,10 +308,15 @@ export const broadcastPerformanceLogic = kea<broadcastPerformanceLogicType>([}),selectors({stats: [- (s) => [s.totals, (_, props: BroadcastPerformanceLogicProps) => props.channel],+ (s) => [+ s.totals,+ (_, props: BroadcastPerformanceLogicProps) => props.channel,+ (_, props: BroadcastPerformanceLogicProps) => props.runStartedAt,+ ],(totals: Record<string, number> | null,- channel: BroadcastChannel | undefined+ channel: BroadcastChannel | undefined,+ runStartedAt: string): BroadcastPerformanceStats | null => {if (!totals) {return null@@ -296,6 +333,7 @@ export const broadcastPerformanceLogic = kea<broadcastPerformanceLogicType>([markedAsSpam: 0,failed: totals.push_failed ?? 0,trackedSends: pushSent,+ engagementCountsPeople: true,converted: totals.conversion ?? 0,skipped: totals.push_skipped ?? 0,unsubscribed: 0,@@ -305,8 +343,9 @@ export const broadcastPerformanceLogic = kea<broadcastPerformanceLogicType>([return {sent,delivered: totals.email_delivered ?? 0,- opened: totals.email_opened ?? 0,- clicked: totals.email_link_clicked ?? 0,+ opened: emailEngagement(totals, 'opened', runStartedAt),+ clicked: emailEngagement(totals, 'clicked', runStartedAt),+ engagementCountsPeople: countsEngagedPeople(totals, runStartedAt),bounced: totals.email_bounced ?? 0,// Spam complaints are stored under email_blocked.markedAsSpam: totals.email_blocked ?? 0,