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(workflows): stamp open-tracking correlation ids into push payloads (#75716)

Daniel Marchuk52c2d6712d1e
diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts b/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
index 1406c7a90eec..059b65c85325 100644
--- a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
@@ -185,6 +185,92 @@ describe('PushNotificationService', () => {
expect(result.metrics).not.toContainEqual(expect.objectContaining({ metric_name: 'push_sent' }))
})
+ it('stamps workflow, action and invocation ids into the data payload so opens can be attributed', async () => {
+ // An open is captured on the device, so these ids riding along in the payload are the only
+ // way the resulting event can be tied back to the workflow and step that sent it.
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_test-project': encryptedFields.encrypt('device-token-123'),
+ })
+ invocation.state.actionId = 'push-step'
+ mockTrackedFetch.mockResolvedValue({
+ fetchError: null,
+ fetchResponse: {
+ status: 200,
+ text: () => Promise.resolve('{}'),
+ dump: () => Promise.resolve(),
+ },
+ fetchDuration: 10,
+ })
+
+ await service.executeSendPushNotification(invocation)
+
+ const body = parseJSON(mockTrackedFetch.mock.calls[0][0].fetchParams.body)
+ // Nested under the single `posthog` key, JSON-encoded: that is the only entry the SDKs read,
+ // and FCM's `data` map only accepts string values. Sibling keys would be silently ignored.
+ expect(parseJSON(body.message.data.posthog)).toEqual({
+ workflow_id: invocation.functionId,
+ action_id: 'push-step',
+ invocation_id: invocation.id,
+ })
+ })
+
+ it('carries the batch run id so a batch push open divides against its sends', async () => {
+ // A batch run attributes its send metrics to the batch job, not the workflow
+ // (`parentRunId ?? functionId`). Without the same id on the open, sends would be counted
+ // against the batch and opens against the workflow, and the open rate wouldn't divide.
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_test-project': encryptedFields.encrypt('device-token-123'),
+ })
+ invocation.state.actionId = 'push-step'
+ invocation.parentRunId = 'batch-job-1'
+ mockTrackedFetch.mockResolvedValue({
+ fetchError: null,
+ fetchResponse: {
+ status: 200,
+ text: () => Promise.resolve('{}'),
+ dump: () => Promise.resolve(),
+ },
+ fetchDuration: 10,
+ })
+
+ const result = await service.executeSendPushNotification(invocation)
+
+ const body = parseJSON(mockTrackedFetch.mock.calls[0][0].fetchParams.body)
+ expect(parseJSON(body.message.data.posthog)).toEqual({
+ workflow_id: invocation.functionId,
+ action_id: 'push-step',
+ invocation_id: invocation.id,
+ parent_run_id: 'batch-job-1',
+ })
+ // The same id the send metric is filed under, so the two are comparable.
+ expect(result.metrics).toContainEqual(
+ expect.objectContaining({ metric_name: 'push_sent', app_source_id: 'batch-job-1' })
+ )
+ })
+
+ it('does not let a custom data key shadow the correlation payload', async () => {
+ // `data` is customer-controlled. If a custom key could win, opens would be attributed to
+ // whatever workflow the sender named, so the reserved key has to be applied last.
+ const invocation = createSendPushNotificationInvocation({
+ '$device_push_subscription_test-project': encryptedFields.encrypt('device-token-123'),
+ })
+ ;(invocation.queueParameters as any).payload.data = { posthog: 'not-the-real-workflow' }
+ mockTrackedFetch.mockResolvedValue({
+ fetchError: null,
+ fetchResponse: {
+ status: 200,
+ text: () => Promise.resolve('{}'),
+ dump: () => Promise.resolve(),
+ },
+ fetchDuration: 10,
+ })
+
+ await service.executeSendPushNotification(invocation)
+
+ const body = parseJSON(mockTrackedFetch.mock.calls[0][0].fetchParams.body)
+ expect(parseJSON(body.message.data.posthog).workflow_id).toBe(invocation.functionId)
+ })
+
describe('message asset capture', () => {
let serviceWithAssets: PushNotificationService
diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.ts b/nodejs/src/cdp/services/messaging/push-notification.service.ts
index 5fc2b4258cd4..7adc0ac58c7b 100644
--- a/nodejs/src/cdp/services/messaging/push-notification.service.ts
+++ b/nodejs/src/cdp/services/messaging/push-notification.service.ts
@@ -104,6 +104,38 @@ function backoffAt(baseMs: number, maxMs: number, tries: number): DateTime {
return DateTime.utc().plus({ milliseconds: delay })
}
+// Correlation ids stamped into every notification's data payload. An open happens on the device, so the
+// SDK is the only thing that can observe it; these ride along in the payload and come back on the
+// captured open event, which is what lets an open be attributed to the workflow and step that sent it.
+// Without them an open is only ever a global count.
+//
+// The key and the shape are fixed by the mobile SDKs: both read the single `posthog` entry out of the
+// notification payload and re-emit each of its keys as `$notification_<key>` on `$push_notification_opened`.
+// Nothing outside that entry is read, so these ids have to be nested under it rather than sent as
+// sibling keys.
+const PUSH_CORRELATION_KEY = 'posthog'
+
+// Serialized rather than nested as an object because FCM's `data` map only accepts string values. Both
+// SDKs parse this entry from either a dictionary or a JSON string, on either delivery route, so one
+// encoding covers FCM and direct APNs.
+function pushCorrelationData(invocation: CyclotronJobInvocationHogFunction): Record<string, string> {
+ const correlation: Record<string, string> = {
+ workflow_id: invocation.functionId,
+ invocation_id: invocation.id,
+ }
+ // Absent for a push sent outside a workflow step, where there is no step to attribute an open to.
+ if (invocation.state.actionId) {
+ correlation.action_id = invocation.state.actionId
+ }
+ // Send metrics are attributed to `parentRunId ?? functionId`, so a batch run counts its sends
+ // against the batch job rather than the workflow. An open has to be attributable the same way or
+ // the two don't divide into a rate — which is why the email tracking code carries this id too.
+ if (invocation.parentRunId) {
+ correlation.parent_run_id = invocation.parentRunId
+ }
+ return { [PUSH_CORRELATION_KEY]: JSON.stringify(correlation) }
+}
+
function pushSendError(platform: PushPlatform, err: NormalizedPushError, retryAfterMs?: number): PushSendError {
// Append the raw provider code so the failure surfaced to the hog template stays debuggable, while
// the human-readable sentence leads.
@@ -142,7 +174,17 @@ export class PushNotificationService {
throw new Error('Bad invocation')
}
- const params = invocation.queueParameters as CyclotronInvocationQueueParametersSendPushNotificationType
+ const queueParams = invocation.queueParameters as CyclotronInvocationQueueParametersSendPushNotificationType
+ // Stamp the correlation ids last so they win over any custom `data` key of the same name. The
+ // enriched copy is local: `invocation.queueParameters` stays untouched, so a reschedule re-derives
+ // these rather than persisting them onto the job.
+ const params: CyclotronInvocationQueueParametersSendPushNotificationType = {
+ ...queueParams,
+ payload: {
+ ...queueParams.payload,
+ data: { ...(queueParams.payload?.data ?? {}), ...pushCorrelationData(invocation) },
+ },
+ }
const result = createInvocationResult<CyclotronJobInvocationHogFunction>(invocation, {}, { finished: true })
const addLog = createAddLogFunction(result.logs)