: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): emit the versioned email tracking code (#91487)
Daniel Marchuk89093d504883
diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.test.tsindex 0e8dae20bb25..efda6aea12a3 100644--- a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts@@ -90,6 +90,29 @@ describe('EmailTrackingService', () => {expect(extractTarget(addTrackingToEmail(html, invocation, signer))).toBe(expected)})+ // The pixel and redirect URLs are the only tracking carrier for a provider whose opens and+ // clicks we record ourselves, so a version missing here means those engagement metrics never+ // split by version however the send path is configured.+ it('carries the sending version into the pixel and redirect codes', () => {+ const flowInvocation = { ...invocation, hogFlow: { id: 'flow-1', version: 7 } } as any+ const html = '<body><a href="https://example.com/">x</a></body>'++ const out = addTrackingToEmail(html, flowInvocation, signer)+ const codes = [...out.matchAll(/ph_id=([A-Za-z0-9_.-]+)/g)].map((match) => match[1])++ expect(codes).toHaveLength(2) // one redirect, one pixel+ for (const code of codes) {+ expect(signer.parse(code)?.workflowVersion).toBe(7)+ }+ })++ it('mints no version for a hog function send, which has no workflow', () => {+ const out = addTrackingToEmail('<body><a href="https://example.com/">x</a></body>', invocation, signer)+ const code = out.match(/ph_id=([A-Za-z0-9_.-]+)/)![1]++ expect(signer.parse(code)?.workflowVersion).toBeUndefined()+ })+it('skips literal javascript: hrefs', () => {const html = '<body><a href="javascript:alert(1)">x</a></body>'const out = addTrackingToEmail(html, invocation, signer)diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.tsindex 9f80b3051ebe..c26d4b4b197f 100644--- a/nodejs/src/cdp/services/messaging/email-tracking.service.ts+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.ts@@ -3,7 +3,13 @@ import { Counter } from 'prom-client'import express from 'ultimate-express'import { HogFlow } from '~/cdp/schema/hogflow'-import { CyclotronJobInvocationHogFunction, LogEntry, LogEntryLevel, MinimalAppMetric } from '~/cdp/types'+import {+ CyclotronJobInvocationHogFlow,+ CyclotronJobInvocationHogFunction,+ LogEntry,+ LogEntryLevel,+ MinimalAppMetric,+} from '~/cdp/types'import { ModifiedRequest } from '~/common/api/router'import { isDevEnv, isTestEnv } from '~/common/utils/env-utils'import { parseJSON } from '~/common/utils/json-parse'@@ -109,6 +115,16 @@ export const resolveEmailEngagementDistinctId = (return invocation.state?.globals?.event?.distinct_id || undefined}+// The workflow version that is sending this message, for the tracking code minted below. A flow's+// email runs as a hog function invocation built by spreading the flow invocation, so `hogFlow` is+// present at runtime even though the type is the narrower hog function shape. A hog function send+// has none, and its engagement lands in the version-agnostic series alone.+export const resolveEmailSendingVersion = (invocation: CyclotronJobInvocationHogFunction): number | undefined => {+ return 'hogFlow' in invocation+ ? (invocation as unknown as CyclotronJobInvocationHogFlow).hogFlow.version+ : undefined+}+// HTML attribute values arrive entity-encoded (e.g. `&`, `&`). Decode before// percent-encoding for the tracking redirect, otherwise `?a=1&b=2` round-trips// through `target=` as a literal `&` and breaks the destination page's query string.@@ -139,7 +155,10 @@ export const addTrackingToEmail = (// signed header), so embedding distinct_id in the public `ph_id` would be unused — and worse,// a tracked-link click could leak the recipient identifier to the destination via the Referer.const distinctId = isDevEnv() || isTestEnv() ? resolveEmailEngagementDistinctId(invocation) : undefined- const trackingInvocation = { ...invocation, distinctId }+ // The pixel and redirect codes carry the sending version too. SES-attributed opens and clicks+ // read the version off the signed header instead, but a provider we track ourselves has these+ // URLs as its only carrier, and without the version its engagement cannot split by version.+ const trackingInvocation = { ...invocation, distinctId, workflowVersion: resolveEmailSendingVersion(invocation) }const trackingUrl = signer.pixelUrl(trackingInvocation, isTest)// Incremented for every anchor LINK_REGEX matches, including ones that turn out to be opteddiff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.tsindex e0f1e28ac7d5..4361e19081b3 100644--- a/nodejs/src/cdp/services/messaging/email.service.ts+++ b/nodejs/src/cdp/services/messaging/email.service.ts@@ -6,7 +6,6 @@ import { Counter } from 'prom-client'import { CyclotronInvocationQueueParametersEmailType } from '~/cdp/schema/cyclotron'import { HogFlowEmailSendingRateLimit, HogFlowEmailSendingRateLimitSchema } from '~/cdp/schema/hogflow'import {- CyclotronJobInvocationHogFlow,CyclotronJobInvocationHogFunction,CyclotronJobInvocationResult,HogFunctionType,@@ -23,7 +22,11 @@ import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.seimport { RateLimiterService } from '../rate-limiter/rate-limiter.service'import { selectEmailSenderIntegrationId } from './email-sender-selection'import { EmailSuppressionService } from './email-suppression.service'-import { addTrackingToEmail, resolveEmailEngagementDistinctId } from './email-tracking.service'+import {+ addTrackingToEmail,+ resolveEmailEngagementDistinctId,+ resolveEmailSendingVersion,+} from './email-tracking.service'import { mailDevTransport, mailDevWebUrl } from './helpers/maildev'import { maybeAddPreheaderToEmail } from './helpers/preheader'import { EmailTrackingCodeSigner, TRACKING_CODE_HEADER_NAME } from './helpers/tracking-code'@@ -682,12 +685,7 @@ export class EmailService {// Full signed code (with distinct_id + isTest) rides in the header; the short unsigned// carrier (no distinct_id/isTest) goes in the SES EmailTag, guaranteed under the 256-char// tag-value limit. The webhook reads the header first and only falls back to the tag.- // A flow's email runs as a hog function invocation built by spreading the flow invocation, so- // `hogFlow` is present at runtime even though the type is the narrower hog function shape.- const workflowVersion =- 'hogFlow' in result.invocation- ? (result.invocation as unknown as CyclotronJobInvocationHogFlow).hogFlow.version- : undefined+ const workflowVersion = resolveEmailSendingVersion(result.invocation)const trackingCode = this.trackingCodeSigner.generate({ ...result.invocation, distinctId, workflowVersion },isTestdiff --git a/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts b/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.tsindex e43ebc4130dd..e198dfedc763 100644--- a/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts+++ b/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts@@ -254,20 +254,19 @@ describe('email tracking code', () => {})describe('versioned payload rollout', () => {- it('does not emit the marker by default, so pods on the old parser still read new codes', () => {- // Phase one ships the marker-aware parser only. Emitting the marker before the fleet can- // parse it shifts every field for an old pod — functionId becomes the literal marker, the- // flow lookup misses, and the engagement metric is dropped for the whole rolling deploy.- const decoded = Buffer.from(- signer.generate({ functionId: 'fn-1', id: 'inv-2', teamId: 3, workflowVersion: 3 }).split('.')[0],- 'base64'- ).toString('utf8')+ it('emits the marker so the version reaches the engagement webhook', () => {+ // The marker carries the sending version to an open, click or bounce arriving days later.+ const code = signer.generate({ functionId: 'fn-1', id: 'inv-2', teamId: 3, workflowVersion: 3 })+ const decoded = Buffer.from(code.split('.')[0], 'base64').toString('utf8')- expect(decoded.startsWith('fn-1:')).toBe(true)- expect(- signer.parse(signer.generate({ functionId: 'fn-1', id: 'inv-2', teamId: 3, workflowVersion: 3 }))- ?.workflowVersion- ).toBeUndefined()+ expect(decoded.startsWith('v2:fn-1:')).toBe(true)+ expect(signer.parse(code)?.workflowVersion).toBe(3)+ })++ it('leaves the version empty for a send that has none, so hog functions are unchanged', () => {+ const code = signer.generate({ functionId: 'fn-1', id: 'inv-2', teamId: 3 })++ expect(signer.parse(code)?.workflowVersion).toBeUndefined()})})diff --git a/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts b/nodejs/src/cdp/services/messaging/helpers/tracking-code.tsindex df9d971fd0ea..2d211d6fa40e 100644--- a/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts+++ b/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts@@ -94,15 +94,7 @@ export type ParsedTrackingCode = {// layout and no version. It can't collide with a real payload because segment 0 is a UUID.const VERSIONED_PAYLOAD_MARKER = 'v2'-// Phase one of a two-phase rollout: `parse` understands the marker, `generate` does not yet emit it.-// The layouts are only compatible in one direction — a marked code read by a pod still running the-// old parser shifts every field (functionId becomes the literal marker), the flow lookup misses, and-// the engagement metric is dropped. Emitting before the fleet can parse would lose metrics for the-// length of the rolling deploy.-//-// Phase two flips this to `true` in a follow-up, once this parser is everywhere. Until then no-// engagement metric carries a version, and they land in the version-agnostic series alone.-const EMIT_VERSIONED_PAYLOAD = false+const EMIT_VERSIONED_PAYLOAD = true// Generates, signs, verifies and renders email tracking codes. Signing keys and the public// tracking URL are read once in the constructor so callers can be injected with a configureddiff --git a/products/workflows/CONTRIBUTING.md b/products/workflows/CONTRIBUTING.mdindex 758a4ef2b944..45a376779c4a 100644--- a/products/workflows/CONTRIBUTING.md+++ b/products/workflows/CONTRIBUTING.md@@ -334,7 +334,7 @@ Things to know when reading these numbers:- **The version is the one that ran the step, not the one the person entered on.** Live edits reach runs already in flight, so a run that starts on v2 and sends its email after v3 is published attributes the trigger to v2 and the email to v3. Per-version rates are therefore a comparison of what each config did while it was live, not a fixed entry cohort.- **Conversions are the exception: they follow the message, not the step that happened to run.** A conversion can land days after the send, so it can't be attributed at match time — the published version by then may be one that never reached this person. The run carries `flowVersion` in its state, seeded at run start and re-pinned by each email or push step to the version that sent, so a conversion is credited to the same version its `email_sent` was. A run that converts without ever sending keeps the run-start version, and one parked before this shipped has none at all and lands only in the version-agnostic series.- **Engagement metrics carry the sending version, which is not always the live one.** `email_delivered`, `email_opened`, `email_link_clicked`, the bounce metrics and complaints (`email_blocked`) arrive from an SES webhook long after the send, by which time the workflow may have been republished. The version rides on the tracking code minted at send time (`ph_id`, and the `X-PostHog-Tracking-Code` header) rather than being read off the flow when the webhook lands — reading it on arrival would blame the newest version for the previous one's sends. A message whose only surviving carrier is the short SES `EmailTags` value has no version and lands in the version-agnostic series alone.-- **Engagement versions are not flowing yet.** The tracking-code layouts are only compatible in one direction, so the rollout is two-phase: the marker-aware parser ships first, and `generate` starts emitting it only once that parser is everywhere. Emitting early would shift every field for a pod still on the old parser and drop the metric for the length of the rolling deploy. Flip `EMIT_VERSIONED_PAYLOAD` in `nodejs/src/cdp/services/messaging/helpers/tracking-code.ts` to start phase two.+- **Engagement versions only exist for sends made after the marker shipped.** The tracking-code layouts are compatible in one direction only, so this rolled out in two phases: the marker-aware parser first, then `EMIT_VERSIONED_PAYLOAD` once that parser was fleet-wide. Emitting earlier would have shifted every field for a pod still on the old parser and dropped the metric for the length of a rolling deploy. Codes minted before the flip carry no marker, parse under the original layout, and land in the version-agnostic series alone — so engagement rates only split by version from the flip onward.When adding a metric for a hog flow, set `app_source_version` on the `MinimalAppMetric` if you're calling `queueAppMetric` directly.Metrics pushed onto a `result.metrics` array need nothing: `HogFunctionMonitoringService.queueInvocationResults` stamps the version for the whole result.