: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(workflows): add push_opened metric and Metrics tab tile (#76995)
Daniel Marchuk73c7d774755f
diff --git a/nodejs/src/cdp/consumers/cdp-events-consumer.test.ts b/nodejs/src/cdp/consumers/cdp-events-consumer.test.tsindex cc43d3682f5b..d3e6642b921d 100644--- a/nodejs/src/cdp/consumers/cdp-events-consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-events-consumer.test.ts@@ -1159,4 +1159,38 @@ describe('hog flow processing', () => {expect(globals.groups).toEqual({})})})++ describe('push open tracking', () => {+ it('emits a push_opened app-metric for a $push_notification_opened event, attributed to its workflow', async () => {+ const flow = await _insertHogFlow(hub.postgres, new FixtureHogFlowBuilder().withTeamId(team.id).build())++ const globals = createHogExecutionGlobals({+ project: { id: team.id } as any,+ event: {+ uuid: 'push-open-uuid',+ event: '$push_notification_opened',+ properties: {+ $notification_workflow_id: flow.id,+ $notification_invocation_id: 'inv-open-1',+ $notification_action_id: 'push_step_1',+ },+ } as any,+ })++ const { backgroundTask } = await processor.processBatch([globals])+ await backgroundTask++ const pushOpened = mockProducerObserver+ .getProducedKafkaMessagesForTopic('clickhouse_app_metrics2_test')+ .filter((m: any) => m.value.metric_name === 'push_opened')+ expect(pushOpened).toHaveLength(1)+ expect(pushOpened[0].value).toMatchObject({+ app_source: 'hog_flow',+ app_source_id: flow.id,+ instance_id: 'push_step_1',+ metric_name: 'push_opened',+ count: 1,+ })+ })+ })})diff --git a/nodejs/src/cdp/consumers/cdp-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-events.consumer.tsindex 1096cc15b854..e9064e92b1e7 100644--- a/nodejs/src/cdp/consumers/cdp-events.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-events.consumer.ts@@ -15,6 +15,7 @@ import { JobQueue } from '../services/job-queue/job-queue.interface'import { CyclotronJobInvocation, HogFunctionInvocationGlobals, HogFunctionTypeType } from '../types'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'import { counterParseError } from './metrics'+import { PUSH_NOTIFICATION_OPENED_EVENT, buildPushOpenedMetric } from './push-open-tracking'export class CdpEventsConsumer<TConfig extends PluginsServerConfig = PluginsServerConfig,@@ -99,6 +100,10 @@ export class CdpEventsConsumer<this.invocationResultsService.invocationResultsRowsService.queueLifecycleRow(invocation, 'running')}+ // Turn any $push_notification_opened events in this batch into `push_opened` app-metrics. Queued+ // here (synchronously) so the monitoring flush in the background task below picks them up.+ await this.trackPushNotificationOpens(invocationGlobals)+return {// This is all IO so we can set them off in the background and start processing the next batchbackgroundTask: Promise.all([@@ -124,6 +129,37 @@ export class CdpEventsConsumer<}}+ // Resolve each $push_notification_opened event's workflow and queue its push_opened app-metric.+ // The attribution + spoof guard live in buildPushOpenedMetric (pure + unit-tested).+ private async trackPushNotificationOpens(globals: HogFunctionInvocationGlobals[]): Promise<void> {+ const opens = globals.filter((g) => g.event.event === PUSH_NOTIFICATION_OPENED_EVENT)+ if (!opens.length) {+ return+ }+ // Match each open's workflow id against the flows its own team owns, which the hog flow pipeline+ // already loaded for this batch (warm by-team cache). Resolving against that bounded, team-owned+ // set rather than looking up the client-supplied id directly keeps a spoofed id from hitting+ // Postgres or polluting the shared by-id cache with negative entries. Best-effort: a lookup+ // failure here must not abort the batch (that would stall all event processing and force a replay).+ try {+ const teamIds = Array.from(new Set(opens.map((g) => g.project.id)))+ const flowsByTeam = await this.hogFlowManager.getHogFlowsForTeams(teamIds)+ for (const g of opens) {+ const workflowId = g.event.properties['$notification_workflow_id']+ if (typeof workflowId !== 'string') {+ continue+ }+ const flow = (flowsByTeam[g.project.id] ?? []).find((f) => f.id === workflowId) ?? null+ const metric = buildPushOpenedMetric(g.event.properties, g.project.id, flow)+ if (metric) {+ this.hogFunctionMonitoringService.queueAppMetric(metric, 'hog_flow')+ }+ }+ } catch (error) {+ logger.error('[CdpEventsConsumer] Failed to track push notification opens', { error })+ }+ }+@instrumented('cdpConsumer.handleEachBatch.parseKafkaMessages')public async _parseKafkaBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {const events: HogFunctionInvocationGlobals[] = []diff --git a/nodejs/src/cdp/consumers/push-open-tracking.test.ts b/nodejs/src/cdp/consumers/push-open-tracking.test.tsnew file mode 100644index 000000000000..c5b0291b5d24--- /dev/null+++ b/nodejs/src/cdp/consumers/push-open-tracking.test.ts@@ -0,0 +1,59 @@+import { buildPushOpenedMetric } from './push-open-tracking'++describe('buildPushOpenedMetric', () => {+ const flow = { id: 'wf-1', team_id: 1 }+ const props = {+ $notification_workflow_id: 'wf-1',+ $notification_invocation_id: 'inv-1',+ $notification_action_id: 'action-1',+ }++ it('builds a push_opened metric attributed to the workflow and action', () => {+ expect(buildPushOpenedMetric(props, 1, flow)).toEqual({+ team_id: 1,+ app_source_id: 'wf-1',+ instance_id: 'action-1',+ metric_name: 'push_opened',+ metric_kind: 'push',+ count: 1,+ })+ })++ it('attributes a batch open to its parent run so it divides against the batch send', () => {+ const metric = buildPushOpenedMetric({ ...props, $notification_parent_run_id: 'batch-9' }, 1, flow)+ expect(metric?.app_source_id).toBe('batch-9')+ })++ it('falls back to the invocation id for instance_id when there is no action id', () => {+ const metric = buildPushOpenedMetric(+ { $notification_workflow_id: 'wf-1', $notification_invocation_id: 'inv-1' },+ 1,+ flow+ )+ expect(metric?.instance_id).toBe('inv-1')+ })++ it('leaves instance_id undefined when both action and invocation ids are empty strings', () => {+ // Empty strings must fall through to undefined, not be used as the instance_id.+ const metric = buildPushOpenedMetric(+ { $notification_workflow_id: 'wf-1', $notification_action_id: '', $notification_invocation_id: '' },+ 1,+ flow+ )+ expect(metric?.instance_id).toBeUndefined()+ })++ it('does not count an event whose workflow belongs to another team', () => {+ // Guards against a spoofed $push_notification_opened inflating a different team's metrics: the+ // captured event's team (2) does not own the resolved workflow (team 1).+ expect(buildPushOpenedMetric(props, 2, flow)).toBeNull()+ })++ it('does not count an event whose workflow does not resolve to a hog flow', () => {+ expect(buildPushOpenedMetric(props, 1, null)).toBeNull()+ })++ it('does not count an event missing the workflow id', () => {+ expect(buildPushOpenedMetric({ $notification_invocation_id: 'inv-1' }, 1, flow)).toBeNull()+ })+})diff --git a/nodejs/src/cdp/consumers/push-open-tracking.ts b/nodejs/src/cdp/consumers/push-open-tracking.tsnew file mode 100644index 000000000000..08aa7343954c--- /dev/null+++ b/nodejs/src/cdp/consumers/push-open-tracking.ts@@ -0,0 +1,40 @@+import type { MinimalAppMetric } from '../types'++// Push opens arrive as this captured event, emitted by the mobile SDKs when a user taps a+// notification. Its `$notification_*` properties carry the ids stamped into the push payload at send.+export const PUSH_NOTIFICATION_OPENED_EVENT = '$push_notification_opened'++// Build the `push_opened` app-metric for one $push_notification_opened event, or null if it should not+// count. The event is client-emitted (spoofable), so it only counts when its $notification_workflow_id+// resolves to a hog flow on the *same* team that captured the event — a spoofed event can't inflate+// another team's metrics. Attribution mirrors the send metric (parentRunId ?? workflowId /+// actionId ?? invocationId) so Sent and Opened divide into a rate under the same app_source_id.+export function buildPushOpenedMetric(+ properties: Record<string, unknown>,+ teamId: number,+ hogFlow: { id: string; team_id: number } | null+): MinimalAppMetric | null {+ const workflowId = properties['$notification_workflow_id']+ if (typeof workflowId !== 'string') {+ return null+ }+ if (!hogFlow || hogFlow.team_id !== teamId) {+ return null+ }+ const parentRunId = properties['$notification_parent_run_id']+ const actionId = properties['$notification_action_id']+ const invocationId = properties['$notification_invocation_id']+ return {+ team_id: hogFlow.team_id,+ app_source_id: typeof parentRunId === 'string' && parentRunId ? parentRunId : workflowId,+ instance_id:+ typeof actionId === 'string' && actionId+ ? actionId+ : typeof invocationId === 'string' && invocationId+ ? invocationId+ : undefined,+ metric_name: 'push_opened',+ metric_kind: 'push',+ count: 1,+ }+}diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex 8241c2859f15..c267f15f73fe 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -249,6 +249,7 @@ export type MinimalAppMetric = {| 'push_sent'| 'push_failed'| 'push_skipped'+ | 'push_opened'| 'quota_limited'| 'conversion'| 'exited_workflow_changed'diff --git a/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx b/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsxindex 435dadb0644c..26ce524953f1 100644--- a/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx+++ b/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx@@ -181,6 +181,7 @@ export function WorkflowMetricsSummary({{ title: 'Sent', key: 'sent', align: 'right', render: (_, row) => row.sent.toLocaleString() },{ title: 'Skipped', key: 'skipped', align: 'right', render: (_, row) => row.skipped.toLocaleString() },{ title: 'Failed', key: 'failed', align: 'right', render: (_, row) => row.failed.toLocaleString() },+ { title: 'Opened', key: 'opened', align: 'right', render: (_, row) => row.opened.toLocaleString() },...(onSelectAction? [{diff --git a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.test.ts b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.test.tsindex b5142873de4e..5e25a0a53f44 100644--- a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.test.ts+++ b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.test.ts@@ -200,17 +200,17 @@ describe('buildEmailMetricRows', () => {})describe('buildPushMetricRows', () => {- it('maps sent/skipped/failed per action and defaults missing totals to 0', () => {+ it('maps sent/skipped/failed/opened per action and defaults missing totals to 0', () => {const rows = buildPushMetricRows([{ id: 'p1', name: 'Reminder' },{ id: 'p2', name: 'Promo' },],- { p1: { push_sent: 50, push_skipped: 20, push_failed: 3 } }+ { p1: { push_sent: 50, push_skipped: 20, push_failed: 3, push_opened: 12 } })expect(rows).toEqual([- { id: 'p1', push: 'Reminder', sent: 50, skipped: 20, failed: 3 },- { id: 'p2', push: 'Promo', sent: 0, skipped: 0, failed: 0 },+ { id: 'p1', push: 'Reminder', sent: 50, skipped: 20, failed: 3, opened: 12 },+ { id: 'p2', push: 'Promo', sent: 0, skipped: 0, failed: 0, opened: 0 },])})})diff --git a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.tsindex 508a07ff46a7..b96151e6ee8b 100644--- a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts+++ b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts@@ -48,7 +48,7 @@ export type EmailMetric =| 'email_spam'| 'email_untracked'-export type PushMetric = 'push_sent' | 'push_skipped' | 'push_failed'+export type PushMetric = 'push_sent' | 'push_skipped' | 'push_failed' | 'push_opened'export type PushMetricRow = {id: string@@ -56,6 +56,7 @@ export type PushMetricRow = {sent: numberskipped: numberfailed: number+ opened: number}export type EmailMetricRow = {@@ -261,6 +262,13 @@ export const WORKFLOW_PUSH_METRICS: Record<color: METRIC_COLORS['Failed'],metricNames: ['push_failed'],},+ push_opened: {+ name: 'Opened',+ description:+ 'Total number of push notifications a recipient opened, captured by the mobile SDK when the user taps the notification. Requires the SDK open-tracking integration in your app.',+ color: METRIC_COLORS['Opened'],+ metricNames: ['push_opened'],+ },}// How each drillable email metric maps onto the Invocations tab. Each SES event also writes a@@ -316,7 +324,7 @@ const EMAIL_METRICS: EmailMetric[] = ['email_untracked',]-const PUSH_METRICS: PushMetric[] = ['push_sent', 'push_skipped', 'push_failed']+const PUSH_METRICS: PushMetric[] = ['push_sent', 'push_skipped', 'push_failed', 'push_opened']export interface WorkflowMetricsSummaryLogicProps {logicKey: string@@ -1363,6 +1371,7 @@ export function buildPushMetricRows(sent: totals.push_sent ?? 0,skipped: totals.push_skipped ?? 0,failed: totals.push_failed ?? 0,+ opened: totals.push_opened ?? 0,}})}