: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): send push to the person named in the step's distinct id (#120237)
danazou244ed6349977
diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex 6596c48208cf..27b2a785b8ac 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -1,6 +1,7 @@import { AppMetricsOutput, HogInvocationResultsOutput, LogEntriesOutput } from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'+import { PersonReadRepository } from '~/common/persons/repositories/person-repository'import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'import { UsageIngestionConfig, createUsageIngestionClient, usageReportTeamMatcher } from '~/common/usage-ingestion'import { PostgresRouter } from '~/common/utils/db/postgres'@@ -30,6 +31,7 @@ import { InvocationResultsService } from './services/invocation-results.service'import { HogFunctionManagerService } from './services/managers/hog-function-manager.service'import { HogFunctionTemplateManagerService } from './services/managers/hog-function-template-manager.service'import { IntegrationManagerService } from './services/managers/integration-manager.service'+import { PersonsManagerService } from './services/managers/persons-manager.service'import { RecipientsManagerService } from './services/managers/recipients-manager.service'import { TeamWorkflowsConfigService } from './services/managers/team-workflows-config.service'import { EmailSuppressionService } from './services/messaging/email-suppression.service'@@ -92,6 +94,7 @@ export interface CdpCoreServices {hogInputsService: HogInputsServicehogFunctionTemplateManager: HogFunctionTemplateManagerServicehogFlowFunctionsService: HogFlowFunctionsService+ personsManager: PersonsManagerServicerecipientsManager: RecipientsManagerServicerecipientPreferencesService: RecipientPreferencesServiceemailSuppressionService: EmailSuppressionService@@ -197,6 +200,7 @@ export interface CdpCoreServicesDeps {pubSub: PubSubencryptedFields: EncryptedFieldsteamManager: TeamManager+ personRepository: PersonReadRepositoryintegrationManager: IntegrationManagerService/** Registry of producers backing the CDP outputs (DEFAULT / MSK / Warpstream-ingestion / Warehouse). */cdpProducerRegistry: KafkaProducerRegistry<CdpProducerName>@@ -437,6 +441,7 @@ export function createCdpCoreServices(transientBounceThreshold: config.EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD,})const recipientsManager = new RecipientsManagerService(deps.postgres)+ const personsManager = new PersonsManagerService(deps.teamManager, deps.personRepository, config.SITE_URL)// Per-workflow send pacing rides the SES Valkey pool, which is only populated on pods that// execute email actions — exactly where the limit is enforced. Null elsewhere disables it.const workflowEmailRateLimiter = deps.emailValidationValkey@@ -484,6 +489,7 @@ export function createCdpCoreServices(},// Valkey-only: push is pre-release, so it moved over whole rather than dual-writing.valkeyShadow.writer,+ personsManager,messageAssetsService)@@ -525,7 +531,11 @@ export function createCdpCoreServices(recipientsManager,emailSuppressionService,deps.frequencyCapValkey- ? { teamWorkflowsConfig: teamWorkflowsConfigService, valkey: deps.frequencyCapValkey }+ ? {+ teamWorkflowsConfig: teamWorkflowsConfigService,+ valkey: deps.frequencyCapValkey,+ persons: personsManager,+ }: undefined)// MX verdicts live on the dedicated SES Valkey (same instance as the SES rate@@ -582,6 +592,7 @@ export function createCdpCoreServices(hogInputsService,hogFunctionTemplateManager,hogFlowFunctionsService,+ personsManager,recipientsManager,recipientPreferencesService,emailSuppressionService,diff --git a/nodejs/src/cdp/consumers/cdp-base.consumer.ts b/nodejs/src/cdp/consumers/cdp-base.consumer.tsindex 212e9ca646ee..e99fbd91c9a0 100644--- a/nodejs/src/cdp/consumers/cdp-base.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-base.consumer.ts@@ -1,5 +1,4 @@import { GroupReadRepository } from '~/common/groups/repositories/group-repository.interface'-import { PersonReadRepository } from '~/common/persons/repositories/person-repository'import { RedisV2 } from '~/common/redis/redis-v2'import { QuotaLimiting } from '~/common/services/quota-limiting.service'import { GeoIPService } from '~/common/utils/geoip'@@ -41,7 +40,6 @@ export type CdpConsumerBaseConfig = CdpCoreServicesConfig &Pick<CdpConfig, 'CDP_OVERFLOW_QUEUE_ENABLED'>export interface CdpConsumerBaseDeps extends CdpCoreServicesDeps {- personRepository: PersonReadRepositorygeoipService: GeoIPServicegroupRepository: GroupReadRepositoryquotaLimiting: QuotaLimiting@@ -100,6 +98,7 @@ export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = Cdthis.hogInputsService = services.hogInputsServicethis.hogFunctionTemplateManager = services.hogFunctionTemplateManagerthis.hogFlowFunctionsService = services.hogFlowFunctionsService+ this.personsManager = services.personsManagerthis.recipientsManager = services.recipientsManagerthis.recipientPreferencesService = services.recipientPreferencesServicethis.hogFlowExecutor = services.hogFlowExecutor@@ -113,7 +112,6 @@ export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = Cd// Base-only servicesthis.hogMasker = new HogMaskerService(services.redis, services.valkeyShadow.writer)- this.personsManager = new PersonsManagerService(deps.teamManager, deps.personRepository, config.SITE_URL)this.groupsManager = new GroupsManagerService(deps.teamManager, deps.groupRepository)this.pluginDestinationExecutorService = new LegacyPluginExecutorService(deps.postgres, deps.geoipService)}diff --git a/nodejs/src/cdp/services/messaging/message-assets.service.test.ts b/nodejs/src/cdp/services/messaging/message-assets.service.test.tsindex 8919ec5fbc78..bb93b57053c1 100644--- a/nodejs/src/cdp/services/messaging/message-assets.service.test.ts+++ b/nodejs/src/cdp/services/messaging/message-assets.service.test.ts@@ -39,6 +39,8 @@ const pushParams = (},}) as unknown as CyclotronInvocationQueueParametersSendPushNotificationType+const pushRecipient = { distinctId: 'user-1', personId: 'person-1' }+const invocationWithAction = (id: string, teamId = 7): CyclotronJobInvocationHogFunction => {const invocation = createExampleInvocation({ id, team_id: teamId })invocation.state.actionId = 'email-step'@@ -157,7 +159,12 @@ describe('MessageAssetsService', () => {it('names the person as the recipient, matching how email fills that column', () => {// The Assets tab shows `recipient` as its RECIPIENT column, and for email that is the// address — so a push has to name who it reached, not which providers carried it.- const row = service.buildRowForPush(invocationWithAction('flow-1', 7), pushParams(), ['Firebase', 'APNs'])+ const row = service.buildRowForPush(+ invocationWithAction('flow-1', 7),+ pushParams(),+ ['Firebase', 'APNs'],+ pushRecipient+ )expect(row).not.toBeNull()expect(row!.kind).toBe('push')@@ -177,7 +184,7 @@ describe('MessageAssetsService', () => {// An asset is a snapshot of what a recipient received, so a send that reached nobody has// nothing to show — it would render as an ordinary row with a blank recipient. The attempt// stays visible through the `push_skipped` metric and the run log explaining why.- const row = service.buildRowForPush(invocationWithAction('flow-1'), pushParams(), [])+ const row = service.buildRowForPush(invocationWithAction('flow-1'), pushParams(), [], pushRecipient)expect(row).toBeNull()})@@ -188,7 +195,8 @@ describe('MessageAssetsService', () => {const row = service.buildRowForPush(invocationWithAction('flow-1'),pushParams({ apns: { subtitle: 'Your account is ready' } }),- ['APNs']+ ['APNs'],+ pushRecipient)expect(row!.html).toContain('Your account is ready')@@ -200,7 +208,8 @@ describe('MessageAssetsService', () => {const row = service.buildRowForPush(invocationWithAction('flow-1'),pushParams({ data: { internal_ref: 'super-secret-value' } }),- ['Firebase']+ ['Firebase'],+ pushRecipient)expect(row!.html).not.toContain('super-secret-value')@@ -210,7 +219,8 @@ describe('MessageAssetsService', () => {const row = service.buildRowForPush(invocationWithAction('flow-1'),pushParams({ title: '<img src=x onerror=alert(1)>' }),- ['Firebase']+ ['Firebase'],+ pushRecipient)expect(row!.html).not.toContain('<img src=x')@@ -221,7 +231,7 @@ describe('MessageAssetsService', () => {const invocation = invocationWithAction('flow-1')invocation.state.actionId = undefined- expect(service.buildRowForPush(invocation, pushParams(), ['Firebase'])).toBeNull()+ expect(service.buildRowForPush(invocation, pushParams(), ['Firebase'], pushRecipient)).toBeNull()})})diff --git a/nodejs/src/cdp/services/messaging/message-assets.service.ts b/nodejs/src/cdp/services/messaging/message-assets.service.tsindex 4fb0d62fc361..b3d2a0a1ea4d 100644--- a/nodejs/src/cdp/services/messaging/message-assets.service.ts+++ b/nodejs/src/cdp/services/messaging/message-assets.service.ts@@ -183,7 +183,10 @@ export class MessageAssetsService {buildRowForPush(invocation: CyclotronJobInvocationHogFunction,params: CyclotronInvocationQueueParametersSendPushNotificationType,- platforms: string[]+ platforms: string[],+ // The person whose devices took delivery, which the step's Distinct ID input can point away+ // from the run's own person.+ recipient: { distinctId: string; personId: string | undefined }): MessageAssetRow | null {if (!invocation.state.actionId) {return null@@ -198,7 +201,6 @@ export class MessageAssetsService {if (platforms.length === 0) {return null}- const recipient = params.distinctIdreturn {team_id: invocation.teamId,function_kind: 'hog_flow',@@ -207,11 +209,11 @@ export class MessageAssetsService {invocation_id: invocation.id,action_id: invocation.state.actionId ?? '',kind: 'push',- distinct_id: recipient,- person_id: invocation.state.globals.person?.id ?? '',+ distinct_id: recipient.distinctId,+ person_id: recipient.personId ?? '',// The person, not the providers that carried it, so the Assets tab's RECIPIENT column means// the same thing for push as it does for email. Per-channel outcomes stay in the run log.- recipient,+ recipient: recipient.distinctId,subject: payload.title,status: 'sent',sent_at: isoMicroseconds(new Date()),diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts b/nodejs/src/cdp/services/messaging/push-notification.service.test.tsindex 1dcda525f2f8..e77fcd707b37 100644--- a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts+++ b/nodejs/src/cdp/services/messaging/push-notification.service.test.ts@@ -50,6 +50,8 @@ const createSendPushNotificationInvocation = (} as anyinvocation.state.vmState = { stack: [] } as any+ // The step's Distinct ID input names the run's own person, the template default.+ invocation.state.globals.event.distinct_id = 'test-distinct-id'if (personProperties) {invocation.state.globals.person = {@@ -68,6 +70,7 @@ describe('PushNotificationService', () => {let valkeyStore: Map<string, string>let mockValkeySet: jest.Mocklet mockValkey: any+ let personsManager: { getCyclotronPerson: jest.Mock }const mockTrackedFetch = jest.fn()@@ -117,7 +120,15 @@ describe('PushNotificationService', () => {),} as any- service = new PushNotificationService(integrationManager, encryptedFields, fetchUtils, mockValkey)+ personsManager = { getCyclotronPerson: jest.fn().mockResolvedValue(null) }++ service = new PushNotificationService(+ integrationManager,+ encryptedFields,+ fetchUtils,+ mockValkey,+ personsManager as any+ )})afterEach(() => {@@ -309,6 +320,7 @@ describe('PushNotificationService', () => {encryptedFields,fetchUtils,mockValkey,+ personsManager as any,new MessageAssetsService({ produce: jest.fn() } as any))})@@ -370,6 +382,7 @@ describe('PushNotificationService', () => {encryptedFields,fetchUtils,mockValkey,+ personsManager as any,{buildRowForPush: () => {throw new Error('boom')@@ -603,6 +616,166 @@ describe('PushNotificationService', () => {})})+ describe('recipient named by the step', () => {+ // The run's person is whoever the trigger ran for; the step's Distinct ID input can name+ // someone else (a manual run's person is the clicker, not the app user being tested).+ const runPersonKey = deviceSubscriptionKey('test-project', 'run-person-token')+ const namedPersonKey = deviceSubscriptionKey('test-project', 'named-person-token')++ const namedPerson = (properties: Record<string, any>) => ({+ id: 'named-person-id',+ name: 'Named',+ url: '',+ distinct_id: 'named-user',+ properties,+ })++ const invocationNaming = (distinctId: string): CyclotronJobInvocationHogFunction => {+ const invocation = createSendPushNotificationInvocation({+ [runPersonKey]: encryptedFields.encrypt('run-person-token'),+ })+ ;(invocation.queueParameters as any).distinctId = distinctId+ invocation.hogFunction.template_id = 'template-native-push'+ invocation.state.actionId = 'push'+ return invocation+ }++ const sentTokens = (): string[] =>+ mockTrackedFetch.mock.calls.map((call: any) => parseJSON(call[0].fetchParams.body).message.token)++ const ok = () => ({+ fetchError: null,+ fetchResponse: { status: 200, text: () => Promise.resolve('{}'), dump: () => Promise.resolve() },+ fetchDuration: 10,+ })++ const unregistered = () => ({+ fetchError: null,+ fetchResponse: {+ status: 404,+ text: () =>+ Promise.resolve(+ JSON.stringify({ error: { status: 'NOT_FOUND', details: [{ errorCode: 'UNREGISTERED' }] } })+ ),+ dump: () => Promise.resolve(),+ },+ fetchDuration: 10,+ })++ it('sends to the devices of the person the input names, not the run person', async () => {+ personsManager.getCyclotronPerson.mockResolvedValue(+ namedPerson({ [namedPersonKey]: encryptedFields.encrypt('named-person-token') })+ )+ mockTrackedFetch.mockResolvedValue(ok())++ // Trailing whitespace from the editor must not turn a valid id into an unknown person.+ const result = await service.executeSendPushNotification(invocationNaming('named-user '))++ expect(personsManager.getCyclotronPerson).toHaveBeenCalledWith(1, 'named-user', 'distinct_id', {+ forceFresh: true,+ })+ expect(sentTokens()).toEqual(['named-person-token'])+ expect(result.deliveredToRecipient).toBe(true)+ })++ it.each([+ ['test-distinct-id', 'test-distinct-id'],+ [' test-distinct-id ', 'test-distinct-id'],+ ['', 'test-distinct-id'],+ [' user-42 ', ' user-42 '],+ ])(+ 'reads the run person without a lookup when the input is %j and the run distinct_id is %j',+ async (distinctId, runDistinctId) => {+ mockTrackedFetch.mockResolvedValue(ok())+ const invocation = invocationNaming(distinctId)+ invocation.state.globals.event.distinct_id = runDistinctId++ await service.executeSendPushNotification(invocation)++ expect(personsManager.getCyclotronPerson).not.toHaveBeenCalled()+ expect(sentTokens()).toEqual(['run-person-token'])+ }+ )++ it.each([+ [+ 'a custom destination',+ (invocation: CyclotronJobInvocationHogFunction) => delete invocation.state.actionId,+ ],+ [+ 'a workflow step built on another template',+ (invocation: CyclotronJobInvocationHogFunction) =>+ (invocation.hogFunction.template_id = 'template-webhook'),+ ],+ ])('keeps %s on the run person when it names someone else', async (_, notAPushStep) => {+ mockTrackedFetch.mockResolvedValue(ok())+ const invocation = invocationNaming('named-user')+ notAPushStep(invocation)++ await service.executeSendPushNotification(invocation)++ expect(personsManager.getCyclotronPerson).not.toHaveBeenCalled()+ expect(sentTokens()).toEqual(['run-person-token'])+ })++ it('skips with a warning naming the input when it matches no person', async () => {+ // Falling back to the run person here would notify someone the step did not name.+ const result = await service.executeSendPushNotification(invocationNaming('nobody'))++ expect(mockTrackedFetch).not.toHaveBeenCalled()+ expect(result.error).toBeUndefined()+ expect(result.logs.map((log) => log.message)).toContainEqual(+ expect.stringContaining('No person found for distinct_id: nobody')+ )+ expect(result.metrics).toContainEqual(expect.objectContaining({ metric_name: 'push_skipped', count: 1 }))+ expect(result.deliveredToRecipient).toBe(false)+ })++ it('names the person it checked in the no-token warning', async () => {+ personsManager.getCyclotronPerson.mockResolvedValue(namedPerson({}))++ const result = await service.executeSendPushNotification(invocationNaming('named-user'))++ expect(mockTrackedFetch).not.toHaveBeenCalled()+ expect(result.logs.map((log) => log.message)).toContainEqual(+ 'No active FCM device token found for distinct_id: named-user'+ )+ })++ it('prunes a dead token from the named person and leaves the run snapshot alone', async () => {+ personsManager.getCyclotronPerson.mockResolvedValue(+ namedPerson({ [namedPersonKey]: encryptedFields.encrypt('named-person-token') })+ )+ mockTrackedFetch.mockResolvedValue(unregistered())+ const invocation = invocationNaming('named-user')++ const result = await service.executeSendPushNotification(invocation)++ expect(result.capturedPostHogEvents).toEqual([+ expect.objectContaining({ distinct_id: 'named-user', properties: { $unset: [namedPersonKey] } }),+ ])+ // The snapshot belongs to the run person, whose token is still live.+ expect(result.invocation.state.globals.person?.properties).toHaveProperty(runPersonKey)+ })++ it('reschedules when the person lookup fails, and fails once the retries are spent', async () => {+ personsManager.getCyclotronPerson.mockRejectedValue(new Error('personhog unavailable'))+ const invocation = invocationNaming('named-user')++ const first = await service.executeSendPushNotification(invocation)++ expect(mockTrackedFetch).not.toHaveBeenCalled()+ expect(first.finished).toBe(false)+ expect(first.invocation.queueScheduledAt).toBeDefined()+ expect(first.invocation.queueParameters).toEqual(invocation.queueParameters)+ expect(first.invocation.queueMetadata).toEqual(expect.objectContaining({ tries: 1 }))+ expect(first.metrics).toEqual([])++ invocation.queueMetadata = { tries: 3 } // == maxRetries+ await expect(service.executeSendPushNotification(invocation)).rejects.toThrow('personhog unavailable')+ })+ })+describe('APNS path', () => {const apnsIntegration = {id: 2,@@ -686,7 +859,14 @@ describe('PushNotificationService', () => {])('presents one APNS provider token for %s', async (_name, podCount) => {const pods = Array.from({ length: podCount },- () => new PushNotificationService(integrationManager, encryptedFields, fetchUtils, mockValkey)+ () =>+ new PushNotificationService(+ integrationManager,+ encryptedFields,+ fetchUtils,+ mockValkey,+ personsManager as any+ ))mockTrackedFetch.mockResolvedValue({fetchError: null,@@ -734,7 +914,13 @@ describe('PushNotificationService', () => {return fn({ get: (key: string) => valkeyStore.get(key) ?? null, set: mockValkeySet })}),} as any- const pod = new PushNotificationService(integrationManager, encryptedFields, fetchUtils, flakyValkey)+ const pod = new PushNotificationService(+ integrationManager,+ encryptedFields,+ fetchUtils,+ flakyValkey,+ personsManager as any+ )mockTrackedFetch.mockResolvedValue({fetchError: null,fetchResponse: { status: 200, text: () => Promise.resolve(''), dump: () => Promise.resolve() },@@ -776,7 +962,13 @@ describe('PushNotificationService', () => {return fn({ get: (key: string) => valkeyStore.get(key) ?? null, set: mockValkeySet })}),} as any- const pod = new PushNotificationService(integrationManager, encryptedFields, fetchUtils, flakyValkey)+ const pod = new PushNotificationService(+ integrationManager,+ encryptedFields,+ fetchUtils,+ flakyValkey,+ personsManager as any+ )mockTrackedFetch.mockResolvedValue({fetchError: null,fetchResponse: { status: 200, text: () => Promise.resolve(''), dump: () => Promise.resolve() },@@ -811,7 +1003,8 @@ describe('PushNotificationService', () => {integrationManager,encryptedFields,fetchUtils,- failingValkey+ failingValkey,+ personsManager as any)mockTrackedFetch.mockResolvedValue({fetchError: null,@@ -1121,7 +1314,8 @@ describe('PushNotificationService', () => {integrationManager,encryptedFields,fetchUtils,- mockValkey+ mockValkey,+ personsManager as any)const retried = await otherPod.executeSendPushNotification(rescheduled.invocation)@@ -1140,7 +1334,8 @@ describe('PushNotificationService', () => {integrationManager,encryptedFields,fetchUtils,- mockValkey+ mockValkey,+ personsManager as any).executeSendPushNotification(otherKeyCarried)expect(failed.finished).toBe(true)expect(failed.metrics).toContainEqual(expect.objectContaining({ metric_name: 'push_failed' }))@@ -1156,7 +1351,8 @@ describe('PushNotificationService', () => {integrationManager,encryptedFields,fetchUtils,- mockValkey+ mockValkey,+ personsManager as any).executeSendPushNotification(createSendPushNotificationInvocation({'$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-device-token'),@@ -1215,7 +1411,8 @@ describe('PushNotificationService', () => {integrationManager,encryptedFields,fetchUtils,- mockValkey+ mockValkey,+ personsManager as any).executeSendPushNotification(rescheduled.invocation)expect(retried.finished).toBe(false)@@ -1273,9 +1470,13 @@ describe('PushNotificationService', () => {})it('signs no new tokens for a rejected key while Valkey is down', async () => {- const pod = new PushNotificationService(integrationManager, encryptedFields, fetchUtils, {- useClient: jest.fn(() => null),- } as any)+ const pod = new PushNotificationService(+ integrationManager,+ encryptedFields,+ fetchUtils,+ { useClient: jest.fn(() => null) } as any,+ personsManager as any+ )mockTrackedFetch.mockResolvedValue(apnsResponse(403, 'InvalidProviderToken'))for (let i = 0; i < 3; i++) {diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.ts b/nodejs/src/cdp/services/messaging/push-notification.service.tsindex 616de638f0c7..30bbfac6872d 100644--- a/nodejs/src/cdp/services/messaging/push-notification.service.ts+++ b/nodejs/src/cdp/services/messaging/push-notification.service.ts@@ -17,8 +17,15 @@ import type { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult, Iimport { createAddLogFunction } from '../../utils'import { EncryptedFields } from '../../utils/encryption-utils'import { createInvocationResult } from '../../utils/invocation-utils'-import { DeviceSubscription, getDevicePushSubscriptions } from '../../utils/push-subscription-utils'+import {+ DeviceSubscription,+ NATIVE_PUSH_TEMPLATE_ID,+ getDevicePushSubscriptions,+ pushRecipientOtherThanRunPerson,+ runDistinctIdMatching,+} from '../../utils/push-subscription-utils'import { IntegrationManagerService } from '../managers/integration-manager.service'+import { PersonsManagerService } from '../managers/persons-manager.service'import { MessageAssetsService } from './message-assets.service'import {NormalizedPushError,@@ -48,7 +55,7 @@ const pushNotificationFailedCounter = new Counter({const pushNotificationSkippedCounter = new Counter({name: 'push_notification_skipped_total',- help: 'Push sends not delivered without an outright failure, by platform and reason. no_token = the recipient never registered a device; unregistered = the provider reported the token dead and it was removed.',+ help: 'Push sends not delivered without an outright failure, by platform and reason. no_token = the recipient never registered a device; unregistered = the provider reported the token dead and it was removed; no_person = the distinct id the step named has no person.',labelNames: ['platform', 'reason'],})@@ -236,6 +243,16 @@ function retriableTokenRejection(error: PushSendError): PushSendError {// apnsAcceptedKeys holds a short prefix of each key fingerprint, never key material.type PushQueueMetadata = { tries?: number; apnsAcceptedKeys?: string[] }+// Whose devices a send goes to. `properties` is the person snapshot the tokens are read from, and+// `isRunPerson` says it is the run's own person, so a pruned token has to leave the invocation's+// snapshot as well.+type PushRecipient = {+ distinctId: string+ personId: string | undefined+ properties: Record<string, any> | undefined+ isRunPerson: boolean+}+export type PushNotificationFetchUtils = {trackedFetch: (args: { url: string; fetchParams: FetchOptions; templateId: string; teamId?: number }) => Promise<{fetchError: Error | null@@ -256,6 +273,7 @@ export class PushNotificationService {private encryptedFields: EncryptedFields,private fetchUtils: PushNotificationFetchUtils,private valkey: RedisV2,+ private personsManager: PersonsManagerService,private messageAssetsService?: MessageAssetsService) {}@@ -339,7 +357,41 @@ export class PushNotificationService {const deliveredPlatforms = new Set<string>()// Filled before device failures collapse into one error per channel, so a retry carries every key that works.const apnsAcceptedKeys = new Set(metadata.apnsAcceptedKeys ?? [])+ // Resolved once for the send: every channel reads the same person's tokens.+ let recipient: PushRecipient | null+ try {+ recipient = await this.resolveRecipient(invocation, params)+ } catch (error) {+ // The person service is down or slow. Nothing was sent yet, so retry later instead of dropping the push.+ if (tries >= this.fetchUtils.maxRetries) {+ throw error+ }+ const nextTries = tries + 1+ result.invocation.queueParameters = invocation.queueParameters+ result.invocation.queueMetadata = { ...metadata, tries: nextTries }+ result.invocation.queuePriority = nextTries+ result.invocation.queueScheduledAt = backoffAt(+ this.fetchUtils.backoffBaseMs,+ this.fetchUtils.backoffMaxMs,+ nextTries+ )+ result.finished = false+ addLog(+ 'warn',+ `Could not look up the person for distinct_id: ${params.distinctId.trim()}; retrying (attempt ${nextTries}/${this.fetchUtils.maxRetries}).`+ )+ return result+ }+ if (!recipient) {+ addLog('warn', `No person found for distinct_id: ${params.distinctId.trim()}; push notification skipped.`)+ pushNotificationSkippedCounter.labels({ platform: 'unknown', reason: 'no_person' }).inc()+ }for (const integrationId of integrationIds) {+ // Nobody to read tokens from, so every channel is skipped the way a person with no device is.+ if (!recipient) {+ skippedCount+++ continue+ }try {const integration = await this.integrationManager.get(integrationId)if (!integration || integration.team_id !== invocation.teamId) {@@ -348,9 +400,9 @@ export class PushNotificationService {let sent: booleanif (integration.kind === 'firebase') {- sent = await this.executeFcm(result, params, integration, invocation)+ sent = await this.executeFcm(result, params, integration, invocation, recipient)} else if (integration.kind === 'apns') {- sent = await this.executeApns(result, params, integration, invocation, apnsAcceptedKeys)+ sent = await this.executeApns(result, params, integration, invocation, recipient, apnsAcceptedKeys)} else {throw new Error(`Unsupported push integration kind: ${integration.kind}`)}@@ -437,13 +489,18 @@ export class PushNotificationService {// per-channel run log explaining why.// Skipped for a test send for the same reason the metrics are: the Assets tab should show// what real recipients were sent, not what an editor preview produced.- if (this.messageAssetsService && successCount > 0 && !isTest) {+ if (this.messageAssetsService && recipient && successCount > 0 && !isTest) {// Best-effort: the notification is already delivered by this point, so a capture failure// must not fail the invocation. Throwing here would send the whole batch back for a retry// and deliver every notification in it a second time. Losing an Assets row is the cheaper// outcome, and it is the same trade the flush path already makes on a Kafka failure.try {- const assetRow = this.messageAssetsService.buildRowForPush(invocation, params, [...deliveredPlatforms])+ const assetRow = this.messageAssetsService.buildRowForPush(+ invocation,+ params,+ [...deliveredPlatforms],+ { distinctId: recipient.distinctId, personId: recipient.personId }+ )if (assetRow) {result.messageAssets.push(assetRow)}@@ -467,12 +524,50 @@ export class PushNotificationService {return result}+ // The run's person snapshot is only the recipient when the step's Distinct ID input names the run's+ // own person (the template default). A manual run's person is whoever pressed the button, and a step+ // pointed at someone else has to read that person's tokens, so anything else is looked up fresh:+ // a push cannot be recalled, and a cached read could predate a device that unregistered.+ // Null when the named distinct id has no person, never the run's person in its place: that would+ // notify someone the step did not name.+ private async resolveRecipient(+ invocation: CyclotronJobInvocationHogFunction,+ params: CyclotronInvocationQueueParametersSendPushNotificationType+ ): Promise<PushRecipient | null> {+ const { event, person } = invocation.state.globals+ // Only a workflow push step may name another person: the opt-out and frequency cap checks run there+ // and nowhere else, so other hog code keeps sending to the run's person.+ const isWorkflowPushStep =+ !!invocation.state.actionId && invocation.hogFunction.template_id === NATIVE_PUSH_TEMPLATE_ID+ const distinctId = isWorkflowPushStep+ ? pushRecipientOtherThanRunPerson(params.distinctId, invocation.state.globals)+ : null+ if (!distinctId) {+ return {+ distinctId:+ runDistinctIdMatching(params.distinctId, invocation.state.globals) ??+ (event.distinct_id || person?.distinct_id || ''),+ personId: person?.id,+ properties: person?.properties,+ isRunPerson: true,+ }+ }+ const named = await this.personsManager.getCyclotronPerson(invocation.teamId, distinctId, 'distinct_id', {+ forceFresh: true,+ })+ if (!named) {+ return null+ }+ return { distinctId, personId: named.id, properties: named.properties, isRunPerson: false }+ }+/** Returns true if a notification was handed off to FCM, false if skipped (no device token). */private async executeFcm(result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>,params: CyclotronInvocationQueueParametersSendPushNotificationType,integration: IntegrationType,- invocation: CyclotronJobInvocationHogFunction+ invocation: CyclotronJobInvocationHogFunction,+ recipient: PushRecipient): Promise<boolean> {const addLog = createAddLogFunction(result.logs)@@ -482,11 +577,10 @@ export class PushNotificationService {throw new Error('Firebase integration is missing project_id or access_token')}- const personProperties = invocation.state.globals.person?.properties- const subscriptions = getDevicePushSubscriptions(personProperties, projectId, this.encryptedFields)+ const subscriptions = getDevicePushSubscriptions(recipient.properties, projectId, this.encryptedFields)if (subscriptions.length === 0) {- addLog('warn', `No active FCM device token found for distinct_id: ${params.distinctId}`)+ addLog('warn', `No active FCM device token found for distinct_id: ${recipient.distinctId}`)pushNotificationSkippedCounter.labels({ platform: 'fcm', reason: 'no_token' }).inc()return false}@@ -505,7 +599,7 @@ export class PushNotificationService {if (outcome.sent) {delivered++} else if (outcome.unregistered) {- this.pruneDeviceToken(result, invocation, params.distinctId, subscription.propertyKeys, 'fcm')+ this.pruneDeviceToken(result, invocation, recipient, subscription.propertyKeys, 'fcm')addLog('warn', `FCM: ${outcome.message}`)} else if (outcome.error) {failures.push(outcome.error)@@ -604,6 +698,7 @@ export class PushNotificationService {params: CyclotronInvocationQueueParametersSendPushNotificationType,integration: IntegrationType,invocation: CyclotronJobInvocationHogFunction,+ recipient: PushRecipient,apnsAcceptedKeys: Set<string>): Promise<boolean> {const addLog = createAddLogFunction(result.logs)@@ -616,11 +711,10 @@ export class PushNotificationService {throw new Error('APNS integration is missing required fields: signing_key, key_id, team_id, or bundle_id')}- const personProperties = invocation.state.globals.person?.properties- const subscriptions = getDevicePushSubscriptions(personProperties, bundleId, this.encryptedFields)+ const subscriptions = getDevicePushSubscriptions(recipient.properties, bundleId, this.encryptedFields)if (subscriptions.length === 0) {- addLog('warn', `No active APNS device token found for distinct_id: ${params.distinctId}`)+ addLog('warn', `No active APNS device token found for distinct_id: ${recipient.distinctId}`)pushNotificationSkippedCounter.labels({ platform: 'apns', reason: 'no_token' }).inc()return false}@@ -673,7 +767,7 @@ export class PushNotificationService {delivered++this.rememberApnsKeyAccepted(keyFingerprint)} else if (outcome.unregistered) {- this.pruneDeviceToken(result, invocation, params.distinctId, subscription.propertyKeys, 'apns')+ this.pruneDeviceToken(result, invocation, recipient, subscription.propertyKeys, 'apns')addLog('warn', `APNs: ${outcome.message}`)} else if (outcome.error) {// Only a provider-token rejection depends on whether the key works, so skip the shared read otherwise.@@ -1042,7 +1136,7 @@ export class PushNotificationService {private pruneDeviceToken(result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>,invocation: CyclotronJobInvocationHogFunction,- distinctId: string,+ recipient: PushRecipient,propertyKeys: string[],platform: 'fcm' | 'apns'): void {@@ -1051,21 +1145,25 @@ export class PushNotificationService {result.capturedPostHogEvents.push({team_id: invocation.teamId,event: '$set',- distinct_id: distinctId,+ distinct_id: recipient.distinctId,timestamp: new Date().toISOString(),properties: { $unset: propertyKeys },})- // Drop the keys from this invocation's own snapshot too. A reschedule carries `state` forward- // unchanged, so a retry would read the same dead token, send to it again and queue the $unset- // again. `person` is replaced rather than edited in place because the object can be shared with- // the sibling invocations built from the same event.- const globals = result.invocation.state.globals- if (globals.person?.properties) {- const properties = { ...globals.person.properties }+ // Drop the keys from the recipient read by the rest of this send, and from this invocation's own+ // snapshot when they are the same person. A reschedule carries `state` forward unchanged, so a+ // retry would read the same dead token, send to it again and queue the $unset again. A looked-up+ // recipient is read fresh on the retry instead. `person` is replaced rather than edited in place+ // because the object can be shared with the sibling invocations built from the same event.+ if (recipient.properties) {+ const properties = { ...recipient.properties }for (const propertyKey of propertyKeys) {delete properties[propertyKey]}- globals.person = { ...globals.person, properties }+ recipient.properties = properties+ }+ const globals = result.invocation.state.globals+ if (recipient.isRunPerson && globals.person?.properties) {+ globals.person = { ...globals.person, properties: recipient.properties ?? {} }}pushNotificationTokenPrunedCounter.labels({ platform }).inc()// A dead token is a non-delivery, not a failure to fix. Record it in the reason-labeled skipdiff --git a/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts b/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.tsindex 09324e04647b..96425e584ae5 100644--- a/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts+++ b/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts@@ -609,30 +609,43 @@ describe('RecipientPreferencesService', () => {expect(mockRecipientsManagerGet).not.toHaveBeenCalled()})- it('keys the opt-out on the delivered-to person, not the triggering event', async () => {- // Delivery reads the device token from globals.person, so the opt-out must check that same- // person even when the triggering event distinct_id differs (e.g. a configured inputs.distinctId).- const action = createPushAction('123e4567-e89b-12d3-a456-426614174000', 'marketing')- const invocation = createFunctionStepInvocation(action)- invocation.state.globals.person!.distinct_id = 'delivered-person'- invocation.state.globals.event!.distinct_id = 'trigger-person'-- mockRecipientsManagerGet.mockResolvedValue(- createRecipient('delivered-person', {- '123e4567-e89b-12d3-a456-426614174000': 'OPTED_OUT',- })- )- mockRecipientsManagerGetPreference.mockReturnValue('OPTED_OUT')- mockRecipientsManagerGetAllMarketingMessagingPreference.mockReturnValue('NO_PREFERENCE')+ it.each([+ ['no Distinct ID input', undefined, 'delivered-person', 'function_push'],+ ['the run event distinct_id', 'trigger-person', 'delivered-person', 'function_push'],+ ['another person', ' named-user ', 'named-user', 'function_push'],+ [+ 'another person, from a generic function step on the push template',+ 'named-user',+ 'named-user',+ 'function',+ ],+ ] as const)(+ 'keys the opt-out on the person the push is delivered to, for %s',+ async (_, distinctIdInput, expected, stepType) => {+ const pushAction = createPushAction('123e4567-e89b-12d3-a456-426614174000', 'marketing')+ const action = (stepType === 'function' ? { ...pushAction, type: 'function' } : pushAction) as any+ const invocation = createFunctionStepInvocation(action)+ invocation.state.globals.person!.distinct_id = 'delivered-person'+ invocation.state.globals.event!.distinct_id = 'trigger-person'+ invocation.state.globals.inputs.distinctId = distinctIdInput++ mockRecipientsManagerGet.mockResolvedValue(+ createRecipient(expected, {+ '123e4567-e89b-12d3-a456-426614174000': 'OPTED_OUT',+ })+ )+ mockRecipientsManagerGetPreference.mockReturnValue('OPTED_OUT')+ mockRecipientsManagerGetAllMarketingMessagingPreference.mockReturnValue('NO_PREFERENCE')- const result = await service.shouldSkipAction(invocation, action)+ const result = await service.shouldSkipAction(invocation, action)- expect(result).toBe('opted_out')- expect(mockRecipientsManagerGet).toHaveBeenCalledWith({- teamId: team.id,- identifier: 'delivered-person',- })- })+ expect(result).toBe('opted_out')+ expect(mockRecipientsManagerGet).toHaveBeenCalledWith({+ teamId: team.id,+ identifier: expected,+ })+ }+ )})describe('for other action types', () => {@@ -665,6 +678,7 @@ describe('RecipientPreferencesService', () => {let frequencyCap: { max_messages: number | null; window_days: number | null }let teamWorkflowsConfig: TeamWorkflowsConfigServicelet cappedService: RecipientPreferencesService+ let persons: { getCyclotronPerson: jest.Mock }const emailAction = (categoryType?: 'marketing' | 'transactional'@@ -693,9 +707,11 @@ describe('RecipientPreferencesService', () => {frequencyCap = { max_messages: 2, window_days: 7 }teamWorkflowsConfig = new TeamWorkflowsConfigService(hub.postgres, hub.pubSub)jest.spyOn(teamWorkflowsConfig, 'getFrequencyCap').mockImplementation(() => Promise.resolve(frequencyCap))+ persons = { getCyclotronPerson: jest.fn().mockResolvedValue(null) }cappedService = new RecipientPreferencesService(mockRecipientsManager, mockEmailSuppressionService, {teamWorkflowsConfig,valkey,+ persons,})})@@ -735,6 +751,26 @@ describe('RecipientPreferencesService', () => {expect(await checkAt(start + 25 * hour)).toBe(true)})+ it('counts a push to a named person against that person, not the run person', async () => {+ frequencyCap = { max_messages: 1, window_days: 7 }+ persons.getCyclotronPerson.mockResolvedValue({ id: 'named-person-id' })+ const pushToNamed: Extract<HogFlowAction, { type: 'function_push' }> = {+ id: 'push',+ name: 'Send push',+ description: '',+ type: 'function_push',+ filters: null,+ config: { template_id: 'template-native-push', inputs: { distinctId: { value: 'named-user' } } },+ created_at: Date.now(),+ updated_at: Date.now(),+ }++ expect(await sendAt(pushToNamed, 1_800_000_000_000)).toBe(false)+ expect(await sendAt(pushToNamed, 1_800_000_000_001)).toBe(true)+ expect(persons.getCyclotronPerson).toHaveBeenCalledWith(team.id, 'named-user', 'distinct_id')+ expect(await sendAt(emailAction(), 1_800_000_000_002)).toBe(false)+ })+it.each([['the config lookup',diff --git a/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts b/nodejs/src/cdp/services/messaging/recipient-preferences.service.tsindex 3be0c81408d2..d81061a8a2cb 100644--- a/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts+++ b/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts@@ -3,7 +3,9 @@ import { RedisV2 } from '~/common/redis/redis-v2'import { logger } from '~/common/utils/logger'import { CyclotronJobInvocationHogFunction } from '../../types'+import { NATIVE_PUSH_TEMPLATE_ID, pushRecipientOtherThanRunPerson } from '../../utils/push-subscription-utils'import { workflowStepDispatchKeyFromInvocation } from '../../utils/workflow-step-dispatch-key'+import { PersonsManagerService } from '../managers/persons-manager.service'import { RecipientsManagerService } from '../managers/recipients-manager.service'import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.service'import { EmailSuppressionService } from './email-suppression.service'@@ -48,7 +50,11 @@ export class RecipientPreferencesService {constructor(private recipientsManager: RecipientsManagerService,private emailSuppressionService: EmailSuppressionService,- private frequencyCap?: { teamWorkflowsConfig: TeamWorkflowsConfigService; valkey: RedisV2 }+ private frequencyCap?: {+ teamWorkflowsConfig: TeamWorkflowsConfigService+ valkey: RedisV2+ persons: Pick<PersonsManagerService, 'getCyclotronPerson'>+ }) {}/** Returns true when the person is at the cap. Otherwise records this send against the cap and returns false. */@@ -56,13 +62,8 @@ export class RecipientPreferencesService {invocation: CyclotronJobInvocationHogFunction,action: HogFlowAction): Promise<boolean> {- const personId = invocation.state.globals.person?.id- if (- !this.frequencyCap ||- !personId ||- !this.isSubjectToRecipientPreferences(action) ||- action.config.message_category_type === 'transactional'- ) {+ const messageAction = this.asMessageAction(action)+ if (!this.frequencyCap || !messageAction || messageAction.config.message_category_type === 'transactional') {return false}try {@@ -72,6 +73,10 @@ export class RecipientPreferencesService {if (!max_messages || !window_days) {return false}+ const personId = await this.cappedPersonId(invocation, messageAction, this.frequencyCap.persons)+ if (!personId) {+ return false+ }const capped = await this.frequencyCap.valkey.useClient({ name: 'workflows-frequency-cap', failOpen: true },(client) =>@@ -94,11 +99,28 @@ export class RecipientPreferencesService {}}+ private async cappedPersonId(+ invocation: CyclotronJobInvocationHogFunction,+ action: MessageAction,+ persons: Pick<PersonsManagerService, 'getCyclotronPerson'>+ ): Promise<string | undefined> {+ const { globals } = invocation.state+ const named =+ action.type === 'function_push'+ ? pushRecipientOtherThanRunPerson(globals.inputs?.distinctId, globals)+ : null+ if (!named) {+ return globals.person?.id+ }+ return (await persons.getCyclotronPerson(invocation.teamId, named, 'distinct_id'))?.id+ }+public async shouldSkipAction(invocation: CyclotronJobInvocationHogFunction,- action: HogFlowAction+ hogFlowAction: HogFlowAction): Promise<RecipientSkipReason | null> {- if (!this.isSubjectToRecipientPreferences(action)) {+ const action = this.asMessageAction(hogFlowAction)+ if (!action) {return null}@@ -153,8 +175,15 @@ export class RecipientPreferencesService {}}- private isSubjectToRecipientPreferences(action: HogFlowAction): action is MessageAction {- return ['function_email', 'function_sms', 'function_push'].includes(action.type)+ // A generic function step saved through the API can run the push template, and it then sends like a push step.+ private asMessageAction(action: HogFlowAction): MessageAction | null {+ if (['function_email', 'function_sms', 'function_push'].includes(action.type)) {+ return action as MessageAction+ }+ if (action.type === 'function' && action.config.template_id === NATIVE_PUSH_TEMPLATE_ID) {+ return { ...action, type: 'function_push' } as unknown as MessageAction+ }+ return null}private async isRecipientOptedOutOfAction(@@ -168,12 +197,14 @@ export class RecipientPreferencesService {} else if (action.type === 'function_email') {identifier = invocation.state.globals.inputs?.email?.to?.email} else if (action.type === 'function_push') {- // Push has no email/phone "to" field. Delivery reads the device token from the invocation's- // person (globals.person.properties), so key the opt-out on that same person's distinct_id —- // not the configurable inputs.distinctId or the triggering event — so the recipient we check- // is always the recipient we deliver to. Fall back to the event distinct_id when the person- // has no resolved one.- identifier = invocation.state.globals.person?.distinct_id ?? invocation.state.globals.event?.distinct_id+ // Push has no email/phone "to" field. Key the opt-out on the person the push is delivered to:+ // the person the Distinct ID input names, or the run's person when it names them. Fall back to+ // the event distinct_id when the run's person has no resolved one.+ const { globals } = invocation.state+ identifier =+ pushRecipientOtherThanRunPerson(globals.inputs?.distinctId, globals) ??+ globals.person?.distinct_id ??+ globals.event?.distinct_id}if (!identifier) {diff --git a/nodejs/src/cdp/utils/push-subscription-utils.ts b/nodejs/src/cdp/utils/push-subscription-utils.tsindex ede9048ae4c6..c755b5848750 100644--- a/nodejs/src/cdp/utils/push-subscription-utils.ts+++ b/nodejs/src/cdp/utils/push-subscription-utils.ts@@ -1,7 +1,11 @@import { createHash } from 'crypto'+import { template as nativePushTemplate } from '../templates/_destinations/push/push.template'+import type { HogFunctionInvocationGlobals } from '../types'import { EncryptedFields } from './encryption-utils'+export const NATIVE_PUSH_TEMPLATE_ID = nativePushTemplate.id+export const DEVICE_SUBSCRIPTION_PREFIX = '$device_push_subscription_'/** Upper bound on devices addressed for one person and app in a single send. */@@ -15,6 +19,32 @@ export interface DeviceSubscription {token: string}+// Shared by delivery, the opt-out check and the frequency cap, so all three act on the same person.+export function pushRecipientOtherThanRunPerson(+ distinctIdInput: unknown,+ globals: Pick<HogFunctionInvocationGlobals, 'event' | 'person'>+): string | null {+ const input = typeof distinctIdInput === 'string' ? distinctIdInput : ''+ // Capture keeps surrounding whitespace in a distinct id, so the run's own id must match exactly first.+ const runDistinctId = runDistinctIdMatching(input, globals)+ if (runDistinctId !== undefined) {+ return null+ }+ const distinctId = input.trim()+ // An empty input (a batch run's event has no distinct_id) keeps the run's person.+ return distinctId || null+}++export function runDistinctIdMatching(+ input: string,+ globals: Pick<HogFunctionInvocationGlobals, 'event' | 'person'>+): string | undefined {+ const runDistinctIds = [globals.event?.distinct_id, globals.person?.distinct_id].filter(+ (id): id is string => typeof id === 'string' && id !== ''+ )+ return runDistinctIds.find((id) => id === input) ?? runDistinctIds.find((id) => id === input.trim())+}+/** Person property key holding one device's push token. */export function deviceSubscriptionKey(appIdentifier: string, token: string): string {return `${DEVICE_SUBSCRIPTION_PREFIX}${appIdentifier}:${createHash('sha256')