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): richer observability for push notifications (#70913)

Daniel Marchukd72a7ebe43fa
diff --git a/nodejs/src/cdp/services/messaging/push-notification-errors.test.ts b/nodejs/src/cdp/services/messaging/push-notification-errors.test.ts
new file mode 100644
index 000000000000..0166588687a1
--- /dev/null
+++ b/nodejs/src/cdp/services/messaging/push-notification-errors.test.ts
@@ -0,0 +1,79 @@
+import { PushFailureReason, normalizeApnsError, normalizeFcmError } from './push-notification-errors'
+
+describe('push notification error normalization', () => {
+ describe('normalizeFcmError', () => {
+ it.each<[string, number | undefined, string | undefined, string | undefined, PushFailureReason, boolean]>([
+ // name, httpStatus, error.status, details.errorCode, expected reason, expected unregistered
+ ['unregistered token (errorCode)', 200, 'NOT_FOUND', 'UNREGISTERED', 'unregistered', true],
+ ['unregistered token (404 + NOT_FOUND)', 404, 'NOT_FOUND', undefined, 'unregistered', true],
+ // A bare 404 with no FCM error body (e.g. a proxy) must NOT prune the token.
+ ['bare 404 without FCM error body', 404, undefined, undefined, 'unknown', false],
+ ['sender id mismatch', 403, 'PERMISSION_DENIED', 'SENDER_ID_MISMATCH', 'auth_error', false],
+ ['third party auth', 401, 'UNAUTHENTICATED', 'THIRD_PARTY_AUTH_ERROR', 'auth_error', false],
+ ['permission denied', 403, 'PERMISSION_DENIED', undefined, 'auth_error', false],
+ ['quota exceeded', 429, 'RESOURCE_EXHAUSTED', 'QUOTA_EXCEEDED', 'rate_limited', false],
+ ['rate limited by status', 429, undefined, undefined, 'rate_limited', false],
+ ['invalid argument', 400, 'INVALID_ARGUMENT', undefined, 'invalid_payload', false],
+ ['internal error', 500, 'INTERNAL', undefined, 'provider_error', false],
+ ['unavailable', 503, 'UNAVAILABLE', undefined, 'provider_error', false],
+ ['unknown', 418, "I'm a teapot", undefined, 'unknown', false],
+ ])('%s', (_name, status, errorStatus, errorCode, expectedReason, expectedUnregistered) => {
+ const body = { error: { status: errorStatus, details: errorCode ? [{ errorCode }] : undefined } }
+ const result = normalizeFcmError(status, body, null)
+ expect(result.reason).toBe(expectedReason)
+ expect(result.unregistered).toBe(expectedUnregistered)
+ expect(result.message.length).toBeGreaterThan(0)
+ })
+
+ it('classifies a missing response (network error)', () => {
+ const result = normalizeFcmError(undefined, undefined, new Error('socket hang up'))
+ expect(result.reason).toBe('network_error')
+ expect(result.unregistered).toBe(false)
+ })
+
+ it('surfaces the raw provider code and prefers the specific detail errorCode', () => {
+ const body = { error: { status: 'INVALID_ARGUMENT', details: [{ errorCode: 'UNREGISTERED' }] } }
+ const result = normalizeFcmError(400, body, null)
+ // The per-message errorCode is more specific than error.status, so it wins.
+ expect(result.reason).toBe('unregistered')
+ expect(result.code).toBe('UNREGISTERED')
+ })
+ })
+
+ describe('normalizeApnsError', () => {
+ it.each<[number | undefined, string | undefined, PushFailureReason, boolean]>([
+ [410, 'Unregistered', 'unregistered', true],
+ [400, 'BadDeviceToken', 'invalid_token', false],
+ [400, 'DeviceTokenNotForTopic', 'invalid_token', false],
+ [403, 'InvalidProviderToken', 'auth_error', false],
+ [403, 'ExpiredProviderToken', 'auth_error', false],
+ [429, 'TooManyRequests', 'rate_limited', false],
+ [413, 'PayloadTooLarge', 'invalid_payload', false],
+ [500, 'InternalServerError', 'provider_error', false],
+ [503, 'ServiceUnavailable', 'provider_error', false],
+ [400, 'SomethingBrandNew', 'unknown', false],
+ ])('status %s reason %s -> %s', (status, reason, expectedReason, expectedUnregistered) => {
+ const result = normalizeApnsError(status, { reason }, null)
+ expect(result.reason).toBe(expectedReason)
+ expect(result.unregistered).toBe(expectedUnregistered)
+ expect(result.code).toBe(reason)
+ expect(result.message.length).toBeGreaterThan(0)
+ })
+
+ it('classifies a missing response (network error)', () => {
+ const result = normalizeApnsError(undefined, undefined, new Error('ECONNRESET'))
+ expect(result.reason).toBe('network_error')
+ })
+ })
+
+ it('maps config problems to error level and transient problems to warn', () => {
+ // A user must fix credentials -> error; a dead token or throttle is expected/transient -> warn.
+ const apnsAuth = normalizeApnsError(403, { reason: 'InvalidProviderToken' }, null)
+ expect(apnsAuth.level).toBe('error')
+ // A config-error message names the provider so the user knows which credentials to check.
+ expect(apnsAuth.message).toContain('APNs')
+ expect(normalizeApnsError(410, { reason: 'Unregistered' }, null).level).toBe('warn')
+ expect(normalizeFcmError(429, {}, null).level).toBe('warn')
+ expect(normalizeFcmError(400, { error: { status: 'INVALID_ARGUMENT' } }, null).level).toBe('error')
+ })
+})
diff --git a/nodejs/src/cdp/services/messaging/push-notification-errors.ts b/nodejs/src/cdp/services/messaging/push-notification-errors.ts
new file mode 100644
index 000000000000..43d90acab337
--- /dev/null
+++ b/nodejs/src/cdp/services/messaging/push-notification-errors.ts
@@ -0,0 +1,183 @@
+import { LogEntryLevel } from '../../types'
+
+export type PushPlatform = 'fcm' | 'apns'
+
+// A normalized, provider-agnostic reason a push send didn't land. Kept to a small, bounded set so it
+// can safely label ops metrics, and so the workflow logs can explain *why* a push failed in plain
+// language instead of dumping a raw FCM/APNs error payload at the user.
+export type PushFailureReason =
+ | 'unregistered' // the token is dead: app uninstalled or token rotated (permanent)
+ | 'invalid_token' // the token is malformed or not valid for this app/topic
+ | 'auth_error' // the integration's credentials were rejected by the provider
+ | 'rate_limited' // the provider is throttling this project/topic
+ | 'invalid_payload' // the provider rejected the message contents
+ | 'provider_error' // a transient server-side failure at the provider (5xx)
+ | 'network_error' // the request never reached the provider
+ | 'unknown'
+
+export type NormalizedPushError = {
+ reason: PushFailureReason
+ // The raw provider code (FCM errorCode/status or APNs reason), for debugging. Undefined if none was returned.
+ code?: string
+ // Whether this means the device token should be removed from the person (a permanent, dead token).
+ unregistered: boolean
+ // Log severity: config problems the user must fix are errors; transient/expected ones are warnings.
+ level: LogEntryLevel
+ // A plain-language explanation for the workflow logs.
+ message: string
+}
+
+// Thrown by a channel send on a terminal failure. Carries the normalized reason, severity, and raw
+// provider code so the caller can log once at the right level and label the failure metric, without
+// re-deriving any of it or double-logging.
+export class PushSendError extends Error {
+ constructor(
+ message: string,
+ public readonly platform: PushPlatform,
+ public readonly reason: PushFailureReason,
+ public readonly level: LogEntryLevel,
+ public readonly code?: string
+ ) {
+ super(message)
+ this.name = 'PushSendError'
+ }
+}
+
+const PLATFORM_LABEL: Record<PushPlatform, string> = { fcm: 'FCM', apns: 'APNs' }
+
+// Config problems a user must fix surface as errors; transient or self-resolving ones as warnings.
+const REASON_LEVEL: Record<PushFailureReason, LogEntryLevel> = {
+ unregistered: 'warn',
+ invalid_token: 'error',
+ auth_error: 'error',
+ rate_limited: 'warn',
+ invalid_payload: 'error',
+ provider_error: 'warn',
+ network_error: 'warn',
+ unknown: 'error',
+}
+
+// The user-facing sentence for each reason. Written to guide the next action, not just state the fault.
+function reasonMessage(platform: PushPlatform, reason: PushFailureReason): string {
+ const provider = PLATFORM_LABEL[platform]
+ switch (reason) {
+ case 'unregistered':
+ return 'The device is no longer reachable. The app was uninstalled or the push token expired, so the token has been removed and will not be retried.'
+ case 'invalid_token':
+ return `${provider} rejected the device token as invalid for this app. Check that the device registered against the same ${platform === 'fcm' ? 'Firebase project' : 'APNs topic (bundle id)'}.`
+ case 'auth_error':
+ return `${provider} rejected the integration credentials. Check the ${platform === 'fcm' ? 'Firebase service account key' : 'APNs signing key, key id, and team id'} in the integration settings.`
+ case 'rate_limited':
+ return `${provider} is rate-limiting this ${platform === 'fcm' ? 'project' : 'topic'}. The notification was not delivered on this attempt.`
+ case 'invalid_payload':
+ return `${provider} rejected the notification contents. Check the title, body, and any custom data on the push step.`
+ case 'provider_error':
+ return `${provider} had a temporary server error and could not accept the notification.`
+ case 'network_error':
+ return `The request to ${provider} could not be completed (network error).`
+ case 'unknown':
+ return `${provider} returned an unexpected error.`
+ }
+}
+
+function build(platform: PushPlatform, reason: PushFailureReason, code: string | undefined): NormalizedPushError {
+ return {
+ reason,
+ code,
+ unregistered: reason === 'unregistered',
+ level: REASON_LEVEL[reason],
+ message: reasonMessage(platform, reason),
+ }
+}
+
+// FCM v1 returns `{ error: { status, message, details: [{ errorCode }] } }`. The per-message `errorCode`
+// in details is the most specific signal; fall back to the canonical `error.status`, then the HTTP status.
+export function normalizeFcmError(
+ status: number | undefined,
+ body: unknown,
+ fetchError: Error | null
+): NormalizedPushError {
+ if (fetchError && !status) {
+ return build('fcm', 'network_error', undefined)
+ }
+
+ const error = (body as any)?.error
+ const errorCode: string | undefined =
+ error?.details?.find?.((d: any) => typeof d?.errorCode === 'string')?.errorCode ?? undefined
+ const canonical: string | undefined = typeof error?.status === 'string' ? error.status : undefined
+ const code = errorCode ?? canonical
+
+ // Only treat this as a dead token when FCM itself says so (the UNREGISTERED errorCode, or the
+ // NOT_FOUND canonical status). A bare HTTP 404 with no FCM error body can come from a proxy or a
+ // misconfigured endpoint, and pruning on that would permanently drop a still-valid device token.
+ if (errorCode === 'UNREGISTERED' || canonical === 'NOT_FOUND') {
+ return build('fcm', 'unregistered', code)
+ }
+ if (errorCode === 'SENDER_ID_MISMATCH' || errorCode === 'THIRD_PARTY_AUTH_ERROR') {
+ return build('fcm', 'auth_error', code)
+ }
+ if (errorCode === 'QUOTA_EXCEEDED' || errorCode === 'MESSAGE_RATE_EXCEEDED' || status === 429) {
+ return build('fcm', 'rate_limited', code)
+ }
+ if (canonical === 'UNAUTHENTICATED' || canonical === 'PERMISSION_DENIED' || status === 401 || status === 403) {
+ return build('fcm', 'auth_error', code)
+ }
+ if (errorCode === 'INVALID_ARGUMENT' || canonical === 'INVALID_ARGUMENT' || status === 400) {
+ return build('fcm', 'invalid_payload', code)
+ }
+ if (status !== undefined && status >= 500) {
+ return build('fcm', 'provider_error', code)
+ }
+ return build('fcm', 'unknown', code)
+}
+
+// APNs returns `{ reason: "..." }` (and a `410` status for unregistered tokens). The reason string is
+// the authoritative signal; the HTTP status backs it up for throttling and server errors.
+export function normalizeApnsError(
+ status: number | undefined,
+ body: unknown,
+ fetchError: Error | null
+): NormalizedPushError {
+ if (fetchError && !status) {
+ return build('apns', 'network_error', undefined)
+ }
+
+ const reason: string | undefined =
+ body && typeof body === 'object' && typeof (body as any).reason === 'string' ? (body as any).reason : undefined
+
+ if (reason === 'Unregistered' || status === 410) {
+ return build('apns', 'unregistered', reason)
+ }
+ if (reason === 'BadDeviceToken' || reason === 'DeviceTokenNotForTopic' || reason === 'MissingDeviceToken') {
+ return build('apns', 'invalid_token', reason)
+ }
+ if (
+ reason === 'InvalidProviderToken' ||
+ reason === 'ExpiredProviderToken' ||
+ reason === 'MissingProviderToken' ||
+ reason === 'TopicDisallowed' ||
+ reason === 'Forbidden'
+ ) {
+ return build('apns', 'auth_error', reason)
+ }
+ if (reason === 'TooManyRequests' || reason === 'TooManyProviderTokenUpdates' || status === 429) {
+ return build('apns', 'rate_limited', reason)
+ }
+ if (
+ reason === 'PayloadTooLarge' ||
+ reason === 'PayloadEmpty' ||
+ reason === 'BadExpirationDate' ||
+ reason === 'BadPriority' ||
+ reason === 'BadTopic'
+ ) {
+ return build('apns', 'invalid_payload', reason)
+ }
+ if (
+ reason === 'InternalServerError' ||
+ reason === 'ServiceUnavailable' ||
+ (status !== undefined && status >= 500)
+ ) {
+ return build('apns', 'provider_error', reason)
+ }
+ return build('apns', 'unknown', reason)
+}
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 2cdc7c573325..6dd85565cb02 100644
--- a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
@@ -160,6 +160,7 @@ describe('PushNotificationService', () => {
expect(result.metrics).toContainEqual(
expect.objectContaining({
+ metric_kind: 'push',
metric_name: 'push_sent',
count: 1,
})
diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.ts b/nodejs/src/cdp/services/messaging/push-notification.service.ts
index bc6055eeecf7..dea4ba36ca24 100644
--- a/nodejs/src/cdp/services/messaging/push-notification.service.ts
+++ b/nodejs/src/cdp/services/messaging/push-notification.service.ts
@@ -1,5 +1,5 @@
import { createHash, createSign } from 'crypto'
-import { Counter } from 'prom-client'
+import { Counter, Histogram } from 'prom-client'
import {
CyclotronInvocationQueueParametersSendPushNotificationType,
@@ -16,6 +16,13 @@ import { EncryptedFields } from '../../utils/encryption-utils'
import { createInvocationResult } from '../../utils/invocation-utils'
import { getDevicePushSubscriptionToken } from '../../utils/push-subscription-utils'
import { IntegrationManagerService } from '../managers/integration-manager.service'
+import {
+ NormalizedPushError,
+ PushPlatform,
+ PushSendError,
+ normalizeApnsError,
+ normalizeFcmError,
+} from './push-notification-errors'
const pushNotificationSentCounter = new Counter({
name: 'push_notification_sent_total',
@@ -29,6 +36,25 @@ const pushNotificationTokenPrunedCounter = new Counter({
labelNames: ['platform'],
})
+const pushNotificationFailedCounter = new Counter({
+ name: 'push_notification_failed_total',
+ help: 'Push notifications that failed to send, by platform and normalized failure reason.',
+ labelNames: ['platform', 'reason'],
+})
+
+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.',
+ labelNames: ['platform', 'reason'],
+})
+
+const pushNotificationSendDurationMs = new Histogram({
+ name: 'push_notification_send_duration_ms',
+ help: 'Duration of a push send request to the provider, by platform.',
+ labelNames: ['platform'],
+ buckets: [10, 25, 50, 100, 200, 500, 1000, 2000, 5000, 10000],
+})
+
// Apple rate-limits new APNs provider tokens (returns 429 TooManyProviderTokenUpdates if refreshed more
// than once every ~20 min per key) and accepts a token for up to 1 hour. Cache the signed JWT in Redis
// keyed by the auth key id so the whole fleet reuses one token per key rather than minting one per send.
@@ -40,6 +66,17 @@ const APNS_JWT_TTL_SECONDS = 45 * 60
// push targets a handful of provider integrations, not thousands.
const MAX_PUSH_CHANNELS = 10
+function stringifyBody(body: unknown): string {
+ return typeof body === 'string' ? body : JSON.stringify(body)
+}
+
+function pushSendError(platform: PushPlatform, err: NormalizedPushError): PushSendError {
+ // Append the raw provider code so the failure surfaced to the hog template stays debuggable, while
+ // the human-readable sentence leads.
+ const message = err.code ? `${err.message} [${err.code}]` : err.message
+ return new PushSendError(message, platform, err.reason, err.level, err.code)
+}
+
export type PushNotificationFetchUtils = {
trackedFetch: (args: { url: string; fetchParams: FetchOptions; templateId: string }) => Promise<{
fetchError: Error | null
@@ -74,7 +111,7 @@ export class PushNotificationService {
team_id: invocation.teamId,
app_source_id: invocation.parentRunId ?? invocation.functionId,
instance_id: invocation.state.actionId || invocation.id,
- metric_kind: 'other',
+ metric_kind: 'push',
metric_name: metricName,
count: 1,
})
@@ -124,7 +161,15 @@ export class PushNotificationService {
} catch (error) {
errorCount++
firstError = firstError ?? error.message
- addLog('error', error.message)
+ if (error instanceof PushSendError) {
+ // The channel already normalized the provider error; log it once here at the reason's
+ // severity and label the failure metric by platform + reason.
+ addLog(error.level, error.message)
+ pushNotificationFailedCounter.labels({ platform: error.platform, reason: error.reason }).inc()
+ } else {
+ addLog('error', error.message)
+ pushNotificationFailedCounter.labels({ platform: 'unknown', reason: 'unknown' }).inc()
+ }
pushMetric('push_failed')
}
}
@@ -163,6 +208,7 @@ export class PushNotificationService {
if (!token) {
addLog('warn', `No active FCM device token found for distinct_id: ${params.distinctId}`)
+ pushNotificationSkippedCounter.labels({ platform: 'fcm', reason: 'no_token' }).inc()
return false
}
@@ -210,27 +256,23 @@ export class PushNotificationService {
}
const status = fetchResponse?.status
+ pushNotificationSendDurationMs.labels({ platform: 'fcm' }).observe(fetchDuration)
if (!fetchResponse || (status && status >= 400)) {
- addLog(
- 'error',
- `FCM send error. Status: ${status ?? '(none)'}. Body: ${typeof body === 'string' ? body : JSON.stringify(body)}. Fetch error: ${fetchError?.message ?? 'none'}`
- )
- // A 404 / UNREGISTERED means FCM no longer knows this token (app uninstalled or token rotated).
- // Prune it and treat the channel as skipped rather than retrying a token that will never work.
- const fcmErrorCode = (body as any)?.error?.details?.find?.((d: any) => d?.errorCode)?.errorCode
- if (status === 404 || fcmErrorCode === 'UNREGISTERED') {
+ const err = normalizeFcmError(status, body, fetchError)
+ // Keep the raw provider response available for deep debugging, at debug level so it doesn't
+ // clutter the workflow log — the user-facing explanation is the normalized message below.
+ addLog('debug', `FCM response ${status ?? '(none)'}: ${stringifyBody(body)}`)
+ if (err.unregistered) {
this.pruneDeviceToken(result, invocation, params.distinctId, projectId, 'fcm')
- addLog('warn', `Removed unregistered FCM token for distinct_id: ${params.distinctId}`)
+ addLog('warn', `FCM: ${err.message}`)
return false
}
- throw new Error(
- `Push notification failed with status ${status ?? '(none)'}.${fetchError ? ` Error: ${fetchError.message}.` : ''}`
- )
+ throw pushSendError('fcm', err)
}
pushNotificationSentCounter.labels({ platform: 'fcm' }).inc()
- addLog('info', `Push notification sent via FCM`)
+ addLog('info', 'Push notification accepted by FCM.')
return true
}
@@ -257,6 +299,7 @@ export class PushNotificationService {
if (!token) {
addLog('warn', `No active APNS device token found for distinct_id: ${params.distinctId}`)
+ pushNotificationSkippedCounter.labels({ platform: 'apns', reason: 'no_token' }).inc()
return false
}
@@ -322,29 +365,23 @@ export class PushNotificationService {
}
const status = fetchResponse?.status
+ pushNotificationSendDurationMs.labels({ platform: 'apns' }).observe(fetchDuration)
if (!fetchResponse || (status && status >= 400)) {
- const reason =
- body && typeof body === 'object' && 'reason' in body ? ` Reason: ${(body as any).reason}.` : ''
- addLog(
- 'error',
- `APNS send error. Status: ${status ?? '(none)'}. Body: ${typeof body === 'string' ? body : JSON.stringify(body)}. Fetch error: ${fetchError?.message ?? 'none'}`
- )
- // 410 Unregistered is Apple's signal that the token is dead (app uninstalled). Prune it and
- // skip rather than retrying. Other 4xx (e.g. BadDeviceToken) can be environment/config issues,
- // so we don't prune on those to avoid dropping a token that is actually valid.
- if (status === 410) {
+ const err = normalizeApnsError(status, body, fetchError)
+ addLog('debug', `APNs response ${status ?? '(none)'}: ${stringifyBody(body)}`)
+ // Apple signals a dead token with 410 / reason "Unregistered". Prune it and skip rather than
+ // retrying a token that will never work; other reasons are surfaced as failures.
+ if (err.unregistered) {
this.pruneDeviceToken(result, invocation, params.distinctId, bundleId, 'apns')
- addLog('warn', `Removed unregistered APNS token for distinct_id: ${params.distinctId}`)
+ addLog('warn', `APNs: ${err.message}`)
return false
}
- throw new Error(
- `Push notification failed with status ${status ?? '(none)'}.${reason}${fetchError ? ` Error: ${fetchError.message}.` : ''}`
- )
+ throw pushSendError('apns', err)
}
pushNotificationSentCounter.labels({ platform: 'apns' }).inc()
- addLog('info', `Push notification sent via APNS`)
+ addLog('info', 'Push notification accepted by APNs.')
return true
}
@@ -450,6 +487,9 @@ export class PushNotificationService {
properties: { $unset: [`$device_push_subscription_${appIdentifier}`] },
})
pushNotificationTokenPrunedCounter.labels({ platform }).inc()
+ // A dead token is a non-delivery, not a failure to fix. Record it in the reason-labeled skip
+ // series too (not just the token-removal counter) so the skip metric accounts for it.
+ pushNotificationSkippedCounter.labels({ platform, reason: 'unregistered' }).inc()
}
private buildFcmMessage(token: string, payload: PushNotificationPayloadType): Record<string, unknown> {