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): attribute run metrics and conversions to a version (#75100)

Daniel Marchuk9e925324f965
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.test.ts
index 5f75d23585eb..7fd8629bc847 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.test.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.test.ts
@@ -12,6 +12,7 @@ describe('buildAccountHogFlowInvocation', () => {
parentRunId: 'batch-job-1',
team,
hogFlowId: 'flow-1',
+ flowVersion: 4,
externalId: 'acme-1',
groupType: 'customer',
defaultVariables: { greeting: 'hi' },
@@ -28,6 +29,9 @@ describe('buildAccountHogFlowInvocation', () => {
// The stamp is what the hogflow worker trusts when the live trigger has been
// edited to a person audience while these children were still queued.
expect(state.accountAudience).toBe(true)
+ // Account broadcasts convert long after the send, so the run has to carry the version
+ // that sent or the conversion is credited to whatever is published by then.
+ expect(state.flowVersion).toBe(4)
expect(state.variables).toEqual({ greeting: 'hi' })
expect(invocation.parentRunId).toEqual('batch-job-1')
expect(invocation.queue).toEqual('hogflow')
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts
index 2aea5d78d540..97f24d1e75ec 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts
@@ -271,6 +271,7 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServe
parentRunId: state.batchJobId,
team,
hogFlowId: hogFlow.id,
+ flowVersion: hogFlow.version,
externalId: id,
groupType: page.accountGroupType ?? '',
defaultVariables,
@@ -280,6 +281,7 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServe
parentRunId: state.batchJobId,
team,
hogFlowId: hogFlow.id,
+ flowVersion: hogFlow.version,
personId: id,
defaultVariables,
})
@@ -472,6 +474,7 @@ export function buildAccountHogFlowInvocation(params: {
parentRunId: string
team: Team
hogFlowId: string
+ flowVersion: number
externalId: string
groupType: string
defaultVariables: Record<string, unknown>
@@ -492,6 +495,9 @@ export function buildAccountHogFlowInvocation(params: {
accountAudience: true,
actionStepCount: 0,
variables: params.defaultVariables,
+ // Same reason as createHogFlowInvocation: a broadcast's conversions arrive long after
+ // the send, so they attribute to the version that sent, not the one live by then.
+ flowVersion: params.flowVersion,
} as any,
teamId: params.team.id,
functionId: params.hogFlowId,
@@ -510,6 +516,7 @@ function buildHogFlowInvocation(params: {
parentRunId: string
team: Team
hogFlowId: string
+ flowVersion: number
personId: string
defaultVariables: Record<string, unknown>
}): CyclotronJobInvocation {
@@ -528,6 +535,9 @@ function buildHogFlowInvocation(params: {
personId: params.personId,
actionStepCount: 0,
variables: params.defaultVariables,
+ // Same reason as createHogFlowInvocation: a broadcast's conversions arrive days after
+ // the send, so they have to attribute to the version that sent, not the one live then.
+ flowVersion: params.flowVersion,
} as any,
teamId: params.team.id,
functionId: params.hogFlowId,
diff --git a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts
index 99b5b56e2296..f48195b0de36 100644
--- a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts
+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts
@@ -553,7 +553,12 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {
person_id: null,
},
]
- matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer({ currentAction: { id: 'wait_node' } }) }]
+ matcher.wakeRows = [
+ {
+ ...matcher.findRows[0],
+ state: stateBuffer({ currentAction: { id: 'wait_node' }, flowVersion: 1 }),
+ },
+ ]
matcher.updateRowCount = 1
matcher.setHogFlows({ 'flow-1': flow })
@@ -570,7 +575,12 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {
// The conversion is also counted as a metric exactly once.
expect(matcher.queueAppMetricMock).toHaveBeenCalledTimes(1)
expect(matcher.queueAppMetricMock).toHaveBeenCalledWith(
- expect.objectContaining({ app_source_id: 'flow-1', metric_name: 'conversion', count: 1 }),
+ expect.objectContaining({
+ app_source_id: 'flow-1',
+ metric_name: 'conversion',
+ count: 1,
+ app_source_version: { id: expect.any(String), version: 1 },
+ }),
'hog_flow'
)
// ...and emitted once as a billable $workflows_conversion event for the converting person.
@@ -582,6 +592,7 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {
distinct_id: 'user-1',
properties: expect.objectContaining({
$workflow_id: 'flow-1',
+ $workflow_version: 1,
$workflow_conversion_type: 'event',
$workflow_conversion_event: 'wuc_cancelled',
}),
@@ -589,6 +600,70 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {
)
})
+ // The whole point of the versioned series: "did conversion rate drop after we changed the
+ // email?" is only answerable if a conversion is credited to the version that sent to that
+ // person. Reading it off the freshly loaded flow credits whatever is live when they convert,
+ // so a broadcast under v1 followed by a republish silently moves all of v1's conversions to v2.
+ it.each([
+ {
+ name: 'the version the run started under, not the one live at conversion time',
+ parkedState: { currentAction: { id: 'wait_node' }, flowVersion: 1 },
+ expectedVersion: { id: 'flow-1', version: 1 },
+ expectedEventVersion: 1,
+ },
+ {
+ name: 'no version at all when the run predates the stamp',
+ parkedState: { currentAction: { id: 'wait_node' } },
+ expectedVersion: undefined,
+ expectedEventVersion: undefined,
+ },
+ ])('attributes a conversion to $name', async ({ parkedState, expectedVersion, expectedEventVersion }) => {
+ // The published flow has moved on to v2 since this run started.
+ const flow = makeHogFlow({
+ id: 'flow-1',
+ version: 2,
+ exit_condition: 'exit_on_conversion',
+ conversion: {
+ events: [
+ {
+ filters: {
+ bytecode: eventBytecode('wuc_cancelled'),
+ events: [{ id: 'wuc_cancelled', name: 'wuc_cancelled', type: 'events', order: 0 }],
+ },
+ },
+ ],
+ } as any,
+ } as any)
+ matcher.findRows = [
+ {
+ id: 'job-c',
+ team_id: 1,
+ function_id: 'flow-1',
+ action_id: 'wait_node',
+ distinct_id: 'user-1',
+ person_id: null,
+ },
+ ]
+ matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer(parkedState) }]
+ matcher.updateRowCount = 1
+ matcher.setHogFlows({ 'flow-1': flow })
+
+ await matcher.runWake([makeGlobals({ event: { ...makeGlobals({}).event, event: 'wuc_cancelled' } })])
+
+ expect(matcher.queueAppMetricMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metric_name: 'conversion',
+ app_source_version: expectedVersion,
+ }),
+ 'hog_flow'
+ )
+ expect(matcher.queueConversionEventMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ properties: expect.objectContaining({ $workflow_version: expectedEventVersion }),
+ })
+ )
+ })
+
it('does not wake on a conversion match when the workflow does not exit on conversion', async () => {
// A conversion goal on an `exit_only_at_end` workflow is measurement-only: the conversion
// event must NOT wake/resume the job (which would run its next step early, e.g. cut a
@@ -778,7 +853,7 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {
person_id: null,
},
]
- matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer({}) }]
+ matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer({ flowVersion: 2 }) }]
matcher.updateRowCount = 1
matcher.setHogFlows({ 'flow-1': flow })
@@ -791,6 +866,10 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {
instance_id: 'flow-1',
metric_name: 'conversion',
count: 1,
+ // The run id keys app_source_id, but the versioned mirror keys on the flow —
+ // otherwise every batch run mints its own key and a broadcast's versions never
+ // aggregate.
+ app_source_version: { id: 'flow-1', version: 2 },
}),
'hog_flow'
)
diff --git a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts
index fd39cb4f341c..1cf8762a0c0b 100644
--- a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts
@@ -507,6 +507,13 @@ export class CdpHogflowSubscriptionMatcherConsumer<
metric_kind: 'other',
metric_name: 'conversion',
count: 1,
+ // Omitted rather than defaulted when the run predates the stamp: the
+ // conversion then lands only in the version-agnostic series, which is
+ // better than crediting it to a version that never sent to this person.
+ app_source_version:
+ outcome.flowVersion !== undefined
+ ? { id: m.functionId, version: outcome.flowVersion }
+ : undefined,
})
// Emit the same billable $workflows_conversion event as the executor's property
// path, so event-based conversions also power insights/cohorts. Needs a
@@ -519,6 +526,7 @@ export class CdpHogflowSubscriptionMatcherConsumer<
timestamp: new Date().toISOString(),
properties: {
$workflow_id: m.functionId,
+ $workflow_version: outcome.flowVersion,
$workflow_conversion_type: 'event',
$workflow_conversion_event: m.conversionEventName,
$workflow_conversion_event_uuid: m.conversionEventUuid,
@@ -1122,7 +1130,11 @@ function rewriteStatePersonId(
}
}
-type MatchOutcome = { state: Buffer; wake: boolean; countConversion: boolean }
+// `flowVersion` is the version the run *started* under, read out of the parked job's own state.
+// It is deliberately not taken from the freshly loaded flow: a conversion arriving after a
+// republish belongs to the version whose message the person received. Undefined for runs parked
+// before the stamp existed.
+type MatchOutcome = { state: Buffer; wake: boolean; countConversion: boolean; flowVersion?: number }
// Applies a batch match to a parked job's state. Returns the new state plus whether the job should
// be woken (`scheduled = NOW()`) and whether its conversion should be counted this run. Returns null
@@ -1180,7 +1192,12 @@ function applyMatchToState(stateBuffer: Buffer, m: MatchedJob): MatchOutcome | n
return null
}
parsed.state = updatedState
- return { state: Buffer.from(JSON.stringify(parsed)), wake, countConversion }
+ return {
+ state: Buffer.from(JSON.stringify(parsed)),
+ wake,
+ countConversion,
+ flowVersion: updatedState.flowVersion,
+ }
} catch (err) {
logger.warn('Failed to parse state during match', { jobId: m.id, err })
return null
diff --git a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.test.ts b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.test.ts
index 28d3baccc92d..bb12b16ac5e1 100644
--- a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.test.ts
+++ b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.test.ts
@@ -26,7 +26,12 @@ function makeHogFlowInvocation(hogFlowId = 'flow-1', overrides: { billable_actio
functionId: hogFlowId,
queue: 'hogflow',
queuePriority: 0,
- hogFlow: { id: hogFlowId, name: 'test flow', billable_action_types: overrides.billable_action_types ?? [] },
+ hogFlow: {
+ id: hogFlowId,
+ name: 'test flow',
+ version: 5,
+ billable_action_types: overrides.billable_action_types ?? [],
+ },
state: { event: { uuid: 'evt-1' } },
person: undefined,
} as any
@@ -105,7 +110,12 @@ describe('HogFlowInvocationPipeline', () => {
expect(result).toEqual([inv])
expect(hogFunctionMonitoringService.queueAppMetrics).toHaveBeenCalledWith(
- expect.arrayContaining([expect.objectContaining({ metric_name: 'triggered' })]),
+ expect.arrayContaining([
+ expect.objectContaining({
+ metric_name: 'triggered',
+ app_source_version: { id: expect.any(String), version: 5 },
+ }),
+ ]),
'hog_flow'
)
})
diff --git a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts
index 58dbb1ca97da..0fb8cf95f888 100644
--- a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts
+++ b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts
@@ -10,7 +10,13 @@ import { KeyedRateLimitRequest, KeyedRateLimiterService } from '../../common/ser
import { QuotaLimiting } from '../../common/services/quota-limiting.service'
import { CdpValkeyShadowPools } from '../cdp-services'
import { counterRateLimited } from '../consumers/metrics'
-import { CyclotronJobInvocation, HogFunctionInvocationGlobals, LogEntry, MinimalAppMetric } from '../types'
+import {
+ CyclotronJobInvocation,
+ CyclotronJobInvocationHogFlow,
+ HogFunctionInvocationGlobals,
+ LogEntry,
+ MinimalAppMetric,
+} from '../types'
import { mirrorCompare } from '../utils/mirror-call'
import { HogFlowExecutorService } from './hogflows/hogflow-executor.service'
import { HogFlowManagerService } from './hogflows/hogflow-manager.service'
@@ -124,7 +130,7 @@ export class HogFlowInvocationPipeline {
(primary, mirror) =>
primary.every(([, result], index) => result.isRateLimited === mirror[index]?.[1].isRateLimited)
)
- const validInvocations: CyclotronJobInvocation[] = []
+ const validInvocations: CyclotronJobInvocationHogFlow[] = []
await Promise.all(
possibleInvocations.map(async (item, index) => {
@@ -139,6 +145,7 @@ export class HogFlowInvocationPipeline {
metric_kind: 'failure',
metric_name: 'rate_limited',
count: 1,
+ app_source_version: { id: item.hogFlow.id, version: item.hogFlow.version },
},
'hog_flow'
)
@@ -191,6 +198,7 @@ export class HogFlowInvocationPipeline {
metric_kind: 'failure',
metric_name: 'disabled_permanently',
count: 1,
+ app_source_version: { id: item.hogFlow.id, version: item.hogFlow.version },
},
'hog_flow'
)
@@ -214,6 +222,7 @@ export class HogFlowInvocationPipeline {
metric_kind: 'other',
metric_name: 'masked',
count: 1,
+ app_source_version: { id: item.hogFlow.id, version: item.hogFlow.version },
})),
'hog_flow'
)
@@ -227,6 +236,7 @@ export class HogFlowInvocationPipeline {
metric_kind: 'other',
metric_name: 'triggered',
count: 1,
+ app_source_version: { id: item.hogFlow.id, version: item.hogFlow.version },
})
})
diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
index fead0331f932..99ce5886fcb3 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts
@@ -500,6 +500,41 @@ describe('HogFunctionHandler', () => {
}
)
+ // Live edits reach runs already in flight, so a run that entered on one version can send its
+ // message under a newer one. The conversion belongs to the version whose message the person
+ // received — the same version `email_sent` is counted under — so a send re-pins the attribution
+ // version. A non-message step must leave it alone.
+ it.each([
+ { billingType: 'email' as const, expected: 3 },
+ { billingType: 'push' as const, expected: 3 },
+ { billingType: 'fetch' as const, expected: 1 },
+ ])(
+ 'a completed $billingType step leaves the attribution version at $expected',
+ async ({ billingType, expected }) => {
+ const handler = new HogFunctionHandler(
+ mockHogFlowFunctionsService,
+ mockRecipientPreferencesService,
+ mockEmailValidationService,
+ billingType
+ )
+ // The run entered on v1; v3 is what is live now and what this step executes under.
+ const republished = {
+ ...invocation,
+ hogFlow: { ...invocation.hogFlow, version: 3 },
+ state: { ...invocation.state, flowVersion: 1 },
+ }
+
+ const invocationResult = createInvocationResult<CyclotronJobInvocationHogFlow>(republished, {
+ queue: 'hog',
+ queuePriority: 0,
+ })
+
+ await handler.execute({ invocation: republished, action, result: invocationResult })
+
+ expect(invocationResult.invocation.state.flowVersion).toBe(expected)
+ }
+ )
+
it('should not emit a billable_invocation metric if function is not finished', async () => {
// Mock the executeWithAsyncFunctions to return a non-finished result
jest.spyOn(mockHogFlowFunctionsService, 'executeWithAsyncFunctions').mockResolvedValueOnce({
diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
index 948dc9cefa44..a6479faa3db6 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
@@ -95,6 +95,15 @@ export class HogFunctionHandler implements ActionHandler {
invocation: functionResult.invocation,
billingMetricType: this.hogFlowActionBillingType,
})
+
+ // Re-pin the attribution version to the one that actually sent. Live edits reach runs
+ // already in flight, so a run that entered on v2 can send its email after v3 is
+ // published — and the conversion belongs to the version whose message the person
+ // received, which is also the version `email_sent` was counted under. Leaving the
+ // run-start stamp here would split a rate across two versions.
+ if (this.hogFlowActionBillingType === 'email' || this.hogFlowActionBillingType === 'push') {
+ result.invocation.state.flowVersion = invocation.hogFlow.version
+ }
}
return {
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
index e23303c64aeb..397cd06b7b94 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
@@ -1484,7 +1484,11 @@ describe('Hogflow Executor', () => {
expect(conversionEvents).toHaveLength(1)
expect(conversionEvents[0]).toMatchObject({
distinct_id: 'distinct_id',
- properties: { $workflow_id: hogFlow.id, $workflow_conversion_type: 'property' },
+ properties: {
+ $workflow_id: hogFlow.id,
+ $workflow_version: hogFlow.version,
+ $workflow_conversion_type: 'property',
+ },
})
})
@@ -2090,6 +2094,15 @@ describe('Hogflow Executor', () => {
// Should not match because email contains @posthog.com
expect(result.invocations).toHaveLength(0)
+ // These metrics are queued straight by the pipeline, not via an invocation result, so they
+ // need the version stamped here or a trigger change that filters everyone out is invisible
+ // in the per-version series.
+ expect(result.metrics).toEqual([
+ expect.objectContaining({
+ metric_name: 'filtered',
+ app_source_version: { id: hogFlow.id, version: hogFlow.version },
+ }),
+ ])
})
it('should allow external users without @posthog.com email', async () => {
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
index fd3ba983eb29..bdc875fcb7b9 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
@@ -84,9 +84,16 @@ export function createHogFlowInvocation(
event: globals.event,
actionStepCount: 0,
variables: mergedVariables,
+ // Seeded at run start and persisted with the state, because the flow itself isn't: the
+ // job is re-loaded by functionId on every resume, so by the time a conversion lands the
+ // manager may be serving a newer version. A message step re-pins this to the version
+ // that actually sent (see HogFunctionHandler); until then this is the best answer.
+ flowVersion: hogFlow.version,
},
teamId: hogFlow.team_id,
- functionId: hogFlow.id, // TODO: Include version?
+ // The version lives on `state.flowVersion` rather than here — functionId is the cyclotron
+ // lookup key and re-loads the current flow by design.
+ functionId: hogFlow.id,
hogFlow,
person: globals.person, // This is outside of state as we don't persist it
groups: globals.groups, // Same as person: in-memory only (test path); real execution re-resolves on dequeue
@@ -180,8 +187,16 @@ export class HogFlowExecutorService {
filterGlobals,
})
- // Add any generated metrics and logs to our collections
- metrics.push(...filterResults.metrics)
+ // Add any generated metrics and logs to our collections. These are queued straight by the
+ // pipeline rather than riding an invocation result, so the workflow version is stamped here
+ // — otherwise `filtered` would be missing from the per-version series, and a trigger change
+ // that filters everyone out would look identical to no traffic at all.
+ metrics.push(
+ ...filterResults.metrics.map((metric) => ({
+ ...metric,
+ app_source_version: { id: hogFlow.id, version: hogFlow.version },
+ }))
+ )
logs.push(...filterResults.logs)
if (!filterResults.match) {
@@ -375,6 +390,7 @@ export class HogFlowExecutorService {
timestamp: new Date().toISOString(),
properties: {
$workflow_id: hogFlow.id,
+ $workflow_version: hogFlow.version,
$workflow_conversion_type: 'property',
},
}
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-quota-limiting.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-quota-limiting.test.ts
index 5f71ee6309a0..af7364ca6af9 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-quota-limiting.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-quota-limiting.test.ts
@@ -182,6 +182,7 @@ describe('HogFlow Quota Limiting', () => {
actions: [],
trigger: { type: 'event' },
billable_action_types: [],
+ version: 4,
} as unknown as HogFlow,
} as CyclotronJobInvocationHogFlow
@@ -244,6 +245,7 @@ describe('HogFlow Quota Limiting', () => {
metric_kind: 'failure',
metric_name: 'quota_limited',
count: 1,
+ app_source_version: { id: expect.any(String), version: 4 },
},
'hog_flow'
)
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-quota-limiting.ts b/nodejs/src/cdp/services/hogflows/hogflow-quota-limiting.ts
index a0a00f0e6af9..54fcedc99c5d 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-quota-limiting.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-quota-limiting.ts
@@ -81,6 +81,7 @@ export async function shouldBlockHogFlowDueToQuota(
metric_kind: 'failure',
metric_name: 'quota_limited',
count: 1,
+ app_source_version: { id: item.hogFlow.id, version: item.hogFlow.version },
},
'hog_flow'
)
diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts
index 0e05920d1b21..56a5ff6e2df3 100644
--- a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts
@@ -286,16 +286,19 @@ describe('EmailTrackingService', () => {
const postBounce = async ({
functionId,
parentRunId,
+ workflowVersion,
}: {
functionId: string
parentRunId?: string
+ workflowVersion?: number
}): Promise<supertest.Response> => {
- const trackingCode = signer.generate({
- functionId,
- id: invocationId,
- teamId: team.id,
- parentRunId,
- })
+ // Third arg opts into the versioned payload, which `generate` won't emit by default
+ // until phase two of the rollout — see EMIT_VERSIONED_PAYLOAD in tracking-code.ts.
+ const trackingCode = signer.generate(
+ { functionId, id: invocationId, teamId: team.id, parentRunId, workflowVersion },
+ false,
+ workflowVersion !== undefined
+ )
const sesRecord = {
eventType: 'Bounce',
mail: {
@@ -377,6 +380,31 @@ describe('EmailTrackingService', () => {
expect(logs).toHaveLength(0)
})
+ it('attributes the bounce to the version that sent it, not the version live when it lands', async () => {
+ // The workflow has been republished since the send. Reading the version off the flow
+ // manager here would blame v5 for v2's bounce — which is precisely the comparison
+ // ("did the new version bounce more?") the versioned series exists to answer.
+ const hogFlow = await insertHogFlow(hub.postgres, {
+ ...new FixtureHogFlowBuilder().withTeamId(team.id).build(),
+ version: 5,
+ })
+
+ const res = await postBounce({ functionId: hogFlow.id, workflowVersion: 2 })
+ expect(res.status).toBe(200)
+
+ await waitForExpect(() => {
+ const metrics = mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ const versioned = metrics.filter((m) => m.value.app_source === 'hog_flow_version')
+ // Permanent bounces emit the rollup plus the hard-only sub-metric, so both mirror.
+ expect(versioned.map((m) => m.value.app_source_id)).toEqual([`${hogFlow.id}/2`, `${hogFlow.id}/2`])
+ // Mirrored, not moved — the version-agnostic series every existing reader uses
+ // still carries the same two rows.
+ expect(
+ metrics.filter((m) => m.value.app_source === 'hog_flow').map((m) => m.value.metric_name)
+ ).toEqual(['email_bounced', 'email_bounced_hard'])
+ })
+ })
+
it('keys the log entry under parentRunId for batch-triggered runs', async () => {
const hogFlow = await insertHogFlow(
hub.postgres,
diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.ts
index 84e4652a9a79..06e8136633d2 100644
--- a/nodejs/src/cdp/services/messaging/email-tracking.service.ts
+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.ts
@@ -159,6 +159,7 @@ export class EmailTrackingService {
source,
properties,
timestamp,
+ workflowVersion,
}: {
functionId?: string
invocationId?: string
@@ -169,6 +170,7 @@ export class EmailTrackingService {
source: 'direct' | 'ses'
properties?: Record<string, unknown>
timestamp?: string
+ workflowVersion?: number
}): Promise<void> {
if (!functionId || !invocationId) {
logger.error('[EmailTrackingService] trackMetric: Invalid custom ID', {
@@ -209,6 +211,11 @@ export class EmailTrackingService {
metric_name: metricName,
metric_kind: 'email',
count: 1,
+ // The version comes off the tracking code minted at send time, never from `hogFlow`
+ // above — that's the currently published version, which for an engagement event
+ // arriving after a republish would blame the new version for the old one's sends.
+ app_source_version:
+ hogFlow && workflowVersion !== undefined ? { id: hogFlow.id, version: workflowVersion } : undefined,
},
hogFlow ? 'hog_flow' : 'hog_function'
)
@@ -223,6 +230,7 @@ export class EmailTrackingService {
properties: {
$workflow_id: appSourceId,
$workflow_action_id: actionId,
+ ...(workflowVersion !== undefined ? { $workflow_version: workflowVersion } : {}),
...properties,
},
})
@@ -334,6 +342,7 @@ export class EmailTrackingService {
source: 'ses',
properties: metric.properties,
timestamp: metric.timestamp,
+ workflowVersion: metric.workflowVersion,
})
}
@@ -399,6 +408,7 @@ export class EmailTrackingService {
actionId?: string
parentRunId?: string
distinctId?: string
+ workflowVersion?: number
} {
// Support both combined ph_id format and legacy separate params
if (query.ph_id) {
@@ -412,6 +422,7 @@ export class EmailTrackingService {
actionId: parsed?.actionId,
parentRunId: parsed?.parentRunId,
distinctId: parsed?.distinctId,
+ workflowVersion: parsed?.workflowVersion,
}
}
return {
diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.ts
index e5a85cd27d09..d4452c40a522 100644
--- a/nodejs/src/cdp/services/messaging/email.service.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.ts
@@ -5,6 +5,7 @@ import { Counter } from 'prom-client'
import { CyclotronInvocationQueueParametersEmailType } from '~/cdp/schema/cyclotron'
import {
+ CyclotronJobInvocationHogFlow,
CyclotronJobInvocationHogFunction,
CyclotronJobInvocationResult,
IntegrationType,
@@ -512,7 +513,16 @@ 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.
- const trackingCode = this.trackingCodeSigner.generate({ ...result.invocation, distinctId }, isTest)
+ // 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 trackingCode = this.trackingCodeSigner.generate(
+ { ...result.invocation, distinctId, workflowVersion },
+ isTest
+ )
const shortTrackingCode = this.trackingCodeSigner.generateShort(result.invocation)
const htmlBody = params.html
diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.ts b/nodejs/src/cdp/services/messaging/helpers/ses.ts
index 6699724b4424..2c633e1ff25a 100644
--- a/nodejs/src/cdp/services/messaging/helpers/ses.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/ses.ts
@@ -419,6 +419,7 @@ export class SesWebhookHandler {
metricName: MinimalAppMetric['metric_name']
properties?: Record<string, any>
timestamp?: string
+ workflowVersion?: number
}[]
logEntries?: {
functionId?: string
@@ -516,6 +517,7 @@ export class SesWebhookHandler {
metricName: MinimalAppMetric['metric_name']
properties?: Record<string, any>
timestamp?: string
+ workflowVersion?: number
}[] = []
const logEntries: {
functionId?: string
@@ -555,7 +557,8 @@ export class SesWebhookHandler {
if (parsedCode) {
trackingCodeFormatCounter.inc({ format: parsedCode.format, source: 'ses' })
}
- const { functionId, invocationId, teamId, actionId, parentRunId, distinctId, isTest } = parsedCode || {}
+ const { functionId, invocationId, teamId, actionId, parentRunId, distinctId, isTest, workflowVersion } =
+ parsedCode || {}
if (!functionId && !invocationId) {
logger.error('[SesWebhookHandler] handleWebhook: No functionId or invocationId found', { rec })
@@ -599,6 +602,7 @@ export class SesWebhookHandler {
metricName,
properties,
timestamp,
+ workflowVersion,
})
// email_bounced stays the catch-all rollup; each bounce additionally emits a
@@ -616,6 +620,7 @@ export class SesWebhookHandler {
metricName: BOUNCE_TYPE_TO_METRIC_NAME[rec.bounce.bounceType],
properties,
timestamp,
+ workflowVersion,
})
}
}
diff --git a/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts b/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts
index 04a30470c82b..e43ebc4130dd 100644
--- a/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts
@@ -196,6 +196,53 @@ describe('email tracking code', () => {
format: 'unsigned',
},
},
+ {
+ // The version sits immediately before the greedy distinctId tail, so a distinctId
+ // containing colons is where an off-by-one in the split would surface — either the
+ // version leaks into distinctId or distinctId loses its leading segment.
+ name: 'roundtrips the workflow version alongside a colon-bearing distinctId',
+ encoded: signer.generate(
+ {
+ functionId: 'fn-1',
+ id: 'inv-2',
+ teamId: 3,
+ state: { actionId: 'act-5' },
+ distinctId: 'urn:user:42',
+ workflowVersion: 3,
+ },
+ false,
+ true
+ ),
+ expected: {
+ functionId: 'fn-1',
+ invocationId: 'inv-2',
+ teamId: '3',
+ actionId: 'act-5',
+ parentRunId: undefined,
+ isTest: false,
+ distinctId: 'urn:user:42',
+ workflowVersion: 3,
+ format: 'signed',
+ },
+ },
+ {
+ // Security: same rule as distinct_id above — a version is only honored from a signed
+ // code, so a forged one can't pin another version's engagement metrics onto a chosen
+ // version. The unsigned tag carrier never mints a version, so nothing legitimate is lost.
+ name: 'ignores a workflow version on an unsigned (forged) code',
+ encoded: encodeRaw('v2:fn-1:inv-2:3:act-5:batch-4::9:'),
+ expected: {
+ functionId: 'fn-1',
+ invocationId: 'inv-2',
+ teamId: '3',
+ actionId: 'act-5',
+ parentRunId: 'batch-4',
+ isTest: false,
+ distinctId: undefined,
+ workflowVersion: undefined,
+ format: 'unsigned',
+ },
+ },
{
name: 'returns null when the encoded string is empty',
encoded: '',
@@ -206,6 +253,24 @@ 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')
+
+ expect(decoded.startsWith('fn-1:')).toBe(true)
+ expect(
+ signer.parse(signer.generate({ functionId: 'fn-1', id: 'inv-2', teamId: 3, workflowVersion: 3 }))
+ ?.workflowVersion
+ ).toBeUndefined()
+ })
+ })
+
describe('signed tracking codes', () => {
it('emits codes with a `.` separator when signing keys are configured', () => {
const code = signer.generate({ functionId: 'fn', id: 'inv', teamId: 1 })
diff --git a/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts b/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts
index 876635e7febc..df9d971fd0ea 100644
--- a/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts
@@ -51,6 +51,11 @@ export type TrackingInvocation = Pick<CyclotronJobInvocationHogFunction, 'functi
parentRunId?: string | null
state?: { actionId?: string }
distinctId?: string
+ // Version of the workflow config that sent this email. Engagement metrics (delivered, opened,
+ // bounced, complaints) arrive from SES long after the send, by which time the workflow may have
+ // been republished — so the sending version has to travel with the message rather than being
+ // looked up on arrival. Absent for hog function sends, which have no version.
+ workflowVersion?: number
}
export type TrackingCodeFormat = 'signed' | 'unsigned'
@@ -78,9 +83,27 @@ export type ParsedTrackingCode = {
parentRunId?: string
isTest: boolean
distinctId?: string
+ workflowVersion?: number
format: TrackingCodeFormat
}
+// Leading segment marking a payload that carries the `workflowVersion` field. The payload is
+// positional and `distinctId` is the greedy trailing segment, so a new field can't just be appended
+// without shifting distinctId out from under codes minted before it existed — and opens and clicks
+// arrive for weeks after a send. The marker lets both layouts coexist: no marker means the original
+// 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
+
// 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 configured
// instance (see cdp-services.ts) instead of reaching into global config — and tests can pass
@@ -137,12 +160,18 @@ export class EmailTrackingCodeSigner {
try {
const decoded = fromBase64UrlSafe(payloadB64)
+ const segments = decoded.split(':')
+ const isVersioned = segments[0] === VERSIONED_PAYLOAD_MARKER
+ const fields = isVersioned ? segments.slice(1) : segments
// distinctId is the trailing segment and may itself contain colons, so rejoin everything past it.
- const [functionId, invocationId, teamId, actionId, parentRunId, isTest, ...distinctIdParts] =
- decoded.split(':')
+ const [functionId, invocationId, teamId, actionId, parentRunId, isTest] = fields
+ const distinctIdParts = fields.slice(isVersioned ? 7 : 6)
if (!functionId || !invocationId) {
return null
}
+ // Signed-only for the same reason as distinct_id below: `generate` always signs, and the
+ // unsigned tag carrier never mints a version, so a version on an unsigned code is forged.
+ const workflowVersion = isVersioned && format === 'signed' ? Number.parseInt(fields[6], 10) : Number.NaN
return {
functionId,
invocationId,
@@ -150,6 +179,9 @@ export class EmailTrackingCodeSigner {
actionId: actionId || undefined,
parentRunId: parentRunId || undefined,
isTest: isTest === '1',
+ // Empty for hog function sends, which have no version.
+ workflowVersion:
+ Number.isInteger(workflowVersion) && workflowVersion >= 1 ? workflowVersion : undefined,
// Only trust distinct_id from a signed code — the HMAC is its integrity guarantee. The
// legitimate unsigned tag never carries a distinct_id, so an unsigned code with one is
// forged; honoring it would let a crafted ph_id inject engagement events for any team.
@@ -167,15 +199,26 @@ export class EmailTrackingCodeSigner {
// Full tracking code, HMAC-signed when a signing key is configured. Rides in the custom MIME
// header and the pixel/link URLs — carriers with no length cap — and the signature lets the
// public tracking endpoint reject forged `ph_id` values.
- generate(invocation: TrackingInvocation, isTest = false): string {
+ generate(invocation: TrackingInvocation, isTest = false, emitVersionedPayload = EMIT_VERSIONED_PAYLOAD): string {
const actionId = invocation.state?.actionId ?? ''
const parentRunId = invocation.parentRunId ?? ''
const distinctId = invocation.distinctId ?? ''
+ const workflowVersion = typeof invocation.workflowVersion === 'number' ? String(invocation.workflowVersion) : ''
// isTest marks sends from the editor's "Run test" so the SES webhook can skip recording their
// metrics — keeping test traffic out of the production Metrics tab. distinctId is appended last
// because it may contain colons; it attributes engagement events.
+ const fields = [
+ invocation.functionId,
+ invocation.id,
+ invocation.teamId,
+ actionId,
+ parentRunId,
+ isTest ? '1' : '',
+ ]
const payload = toBase64UrlSafe(
- `${invocation.functionId}:${invocation.id}:${invocation.teamId}:${actionId}:${parentRunId}:${isTest ? '1' : ''}:${distinctId}`
+ emitVersionedPayload
+ ? [VERSIONED_PAYLOAD_MARKER, ...fields, workflowVersion, distinctId].join(':')
+ : [...fields, distinctId].join(':')
)
if (this.signingKeys.length === 0) {
// Fail closed (#62624): a deployment with no signing key must never mint unsigned tracking
@@ -194,8 +237,10 @@ export class EmailTrackingCodeSigner {
// Unsigned tracking code for the SES `EmailTags` carrier. Omitting the signature keeps the
// value short enough to stay within the 256-char tag cap; the tag arrives via the SNS webhook,
// which is already integrity-protected by SNS signing, so it does not need its own signature.
- // This is a legacy backwards-compat carrier only — new fields (e.g. isTest, distinctId) live on
- // the signed code in generate, which the webhook reads first.
+ // This is a legacy backwards-compat carrier only — new fields (e.g. isTest, distinctId,
+ // workflowVersion) live on the signed code in generate, which the webhook reads first. A message
+ // that only has this carrier therefore has no version, and its engagement metrics land in the
+ // version-agnostic series alone rather than being attributed to a guess.
generateShort(invocation: TrackingInvocation): string {
const actionId = invocation.state?.actionId ?? ''
const parentRunId = invocation.parentRunId ?? ''
diff --git a/nodejs/src/cdp/services/monitoring/hog-function-monitoring.service.test.ts b/nodejs/src/cdp/services/monitoring/hog-function-monitoring.service.test.ts
new file mode 100644
index 000000000000..8b850fba40d2
--- /dev/null
+++ b/nodejs/src/cdp/services/monitoring/hog-function-monitoring.service.test.ts
@@ -0,0 +1,118 @@
+import { APP_METRICS_OUTPUT, LOG_ENTRIES_OUTPUT } from '~/common/outputs'
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+import { parseJSON } from '~/common/utils/json-parse'
+
+import { MetricLogSource, MinimalAppMetric } from '../../types'
+import { HogFunctionMonitoringService, MonitoringOutput } from './hog-function-monitoring.service'
+
+describe('HogFunctionMonitoringService', () => {
+ let service: HogFunctionMonitoringService
+ let queueMessagesMock: jest.Mock<Promise<void>, [any[]]>
+
+ beforeEach(() => {
+ queueMessagesMock = jest.fn().mockResolvedValue(undefined)
+ const fakeOutput = {
+ produce: jest.fn().mockResolvedValue(undefined),
+ queueMessages: queueMessagesMock,
+ checkHealth: jest.fn().mockResolvedValue(undefined),
+ checkTopicExists: jest.fn().mockResolvedValue(undefined),
+ } as any
+ service = new HogFunctionMonitoringService(
+ new IngestionOutputs<MonitoringOutput>({
+ [APP_METRICS_OUTPUT]: fakeOutput,
+ [LOG_ENTRIES_OUTPUT]: fakeOutput,
+ })
+ )
+ })
+
+ async function flushedRows(): Promise<Record<string, unknown>[]> {
+ await service.flush()
+ return (queueMessagesMock.mock.calls[0]?.[0] ?? []).map(
+ (m: { value: Buffer }) => parseJSON(m.value.toString()) as Record<string, unknown>
+ )
+ }
+
+ function metric(overrides: Partial<MinimalAppMetric> = {}): MinimalAppMetric {
+ return {
+ team_id: 1,
+ app_source_id: 'flow-1',
+ instance_id: 'action-1',
+ metric_kind: 'success',
+ metric_name: 'succeeded',
+ count: 1,
+ ...overrides,
+ }
+ }
+
+ it('mirrors a versioned hog flow metric under hog_flow_version, keyed by version', async () => {
+ service.queueAppMetric(metric({ app_source_version: { id: 'flow-1', version: 3 } }), 'hog_flow')
+
+ const rows = await flushedRows()
+ expect(rows).toEqual([
+ expect.objectContaining({ app_source: 'hog_flow', app_source_id: 'flow-1', instance_id: 'action-1' }),
+ expect.objectContaining({
+ app_source: 'hog_flow_version',
+ app_source_id: 'flow-1/3',
+ instance_id: 'action-1',
+ }),
+ ])
+ // The version is a routing hint, not a column — a stray field breaks the app_metrics2 Kafka table.
+ expect(rows.every((row) => !('app_source_version' in row))).toBe(true)
+ })
+
+ const unmirroredCases: { name: string; source: MetricLogSource; overrides: Partial<MinimalAppMetric> }[] = [
+ { name: 'no version', source: 'hog_flow', overrides: {} },
+ { name: 'an undefined version', source: 'hog_flow', overrides: { app_source_version: undefined } },
+ {
+ // A flow loaded without its `version` column: the id is there but the version isn't.
+ name: 'a version-less flow',
+ source: 'hog_flow',
+ overrides: { app_source_version: { id: 'flow-1', version: undefined as unknown as number } },
+ },
+ {
+ name: 'a versioned hog function',
+ source: 'hog_function',
+ overrides: { app_source_version: { id: 'flow-1', version: 3 } },
+ },
+ ]
+
+ it.each(unmirroredCases)('writes only the version-agnostic row for $name', async ({ source, overrides }) => {
+ service.queueAppMetric(metric(overrides), source)
+
+ const rows = await flushedRows()
+ expect(rows).toHaveLength(1)
+ expect(rows[0].app_source).toBe(source)
+ })
+
+ it('keeps versions apart when the same metric is counted on either side of a publish', async () => {
+ service.queueAppMetric(metric({ app_source_version: { id: 'flow-1', version: 2 }, count: 5 }), 'hog_flow')
+ service.queueAppMetric(metric({ app_source_version: { id: 'flow-1', version: 3 }, count: 2 }), 'hog_flow')
+
+ const rows = await flushedRows()
+ const byId = Object.fromEntries(rows.map((row) => [`${row.app_source}:${row.app_source_id}`, row.count]))
+ // The version-agnostic row aggregates both, so per-version reads and total reads agree.
+ expect(byId).toEqual({
+ 'hog_flow:flow-1': 7,
+ 'hog_flow_version:flow-1/2': 5,
+ 'hog_flow_version:flow-1/3': 2,
+ })
+ })
+ it('keys the versioned row by the flow, not the batch run its metrics are grouped under', async () => {
+ // Batch-triggered runs put the run id in `app_source_id` so per-run views group correctly.
+ // Keying the mirror off that would mint a fresh id every run, so a broadcast's versions would
+ // never aggregate across its runs and the documented `<flow id>/<version>` read would miss them.
+ service.queueAppMetric(
+ metric({ app_source_id: 'batch-run-1', app_source_version: { id: 'flow-1', version: 3 } }),
+ 'hog_flow'
+ )
+ service.queueAppMetric(
+ metric({ app_source_id: 'batch-run-2', app_source_version: { id: 'flow-1', version: 3 } }),
+ 'hog_flow'
+ )
+
+ const rows = await flushedRows()
+ expect(rows.filter((row) => row.app_source === 'hog_flow_version')).toEqual([
+ expect.objectContaining({ app_source_id: 'flow-1/3', count: 2 }),
+ ])
+ })
+})
diff --git a/nodejs/src/cdp/services/monitoring/hog-function-monitoring.service.ts b/nodejs/src/cdp/services/monitoring/hog-function-monitoring.service.ts
index d6a5907a3bd5..d9189b7641b4 100644
--- a/nodejs/src/cdp/services/monitoring/hog-function-monitoring.service.ts
+++ b/nodejs/src/cdp/services/monitoring/hog-function-monitoring.service.ts
@@ -8,6 +8,7 @@ import { logger } from '~/common/utils/logger'
import { captureException } from '~/common/utils/posthog'
import {
+ CyclotronJobInvocationHogFlow,
CyclotronJobInvocationHogFunction,
CyclotronJobInvocationResult,
LogEntry,
@@ -36,6 +37,19 @@ const hogFunctionMonitoringPendingMessages = new Gauge({
export type MonitoringOutput = AppMetricsOutput | LogEntriesOutput
+// `app_metrics2` has no version column, and it can't gain one: it's an AggregatingMergeTree whose sort
+// key is its aggregation key, so a new dimension would have to join the ORDER BY and re-key existing
+// parts. Instead, every hog flow metric that knows its workflow version is written twice — once under
+// `hog_flow` (the version-agnostic series everything already reads) and once under this app source with
+// the version appended to the flow id. Same instance_id/kind/name semantics on both, so a
+// version-scoped read is the existing query with two substituted parameters.
+export const HOG_FLOW_VERSION_APP_SOURCE = 'hog_flow_version'
+
+// This key format is the contract for anything that reads the versioned series — see
+// "Metrics and version attribution" in products/workflows/CONTRIBUTING.md. Always the flow id, never
+// the run id the version-agnostic series uses for batch runs.
+export const versionedAppSourceId = (flowId: string, version: number): string => `${flowId}/${version}`
+
// Check if the result is of type CyclotronJobInvocationHogFunction
export const isHogFunctionResult = (
result: CyclotronJobInvocationResult
@@ -43,6 +57,12 @@ export const isHogFunctionResult = (
return 'hogFunction' in result.invocation
}
+export const isHogFlowResult = (
+ result: CyclotronJobInvocationResult
+): result is CyclotronJobInvocationResult<CyclotronJobInvocationHogFlow> => {
+ return 'hogFlow' in result.invocation
+}
+
export class HogFunctionMonitoringService {
queuedLogMessages: LogEntrySerialized[] = []
@@ -96,6 +116,21 @@ export class HogFunctionMonitoringService {
metric_name: metric.metric_name,
count: metric.count,
})
+
+ // Guarded on the type rather than truthiness: a flow loaded without its `version` column would
+ // otherwise key every mirrored row under a literal `.../undefined`.
+ if (source === 'hog_flow' && typeof metric.app_source_version?.version === 'number') {
+ this.appMetricsAggregator.queue({
+ team_id: metric.team_id,
+ app_source: HOG_FLOW_VERSION_APP_SOURCE,
+ // Deliberately not `metric.app_source_id` — see `app_source_version` on MinimalAppMetric.
+ app_source_id: versionedAppSourceId(metric.app_source_version.id, metric.app_source_version.version),
+ instance_id: metric.instance_id,
+ metric_kind: metric.metric_kind,
+ metric_name: metric.metric_name,
+ count: metric.count,
+ })
+ }
}
queueAppMetrics(metrics: MinimalAppMetric[], source: MetricLogSource) {
@@ -122,6 +157,13 @@ export class HogFunctionMonitoringService {
const logSourceId = result.invocation.parentRunId
? result.invocation.parentRunId
: result.invocation.functionId
+ // Stamped here rather than at each of the ~10 sites that push onto `result.metrics`
+ // (executor, action handlers, billing). The workflow is re-read from the manager on every
+ // dequeue, so this is the version that actually executed the step — a run started on v2
+ // that reaches its email step after v3 is published attributes that step to v3.
+ const appSourceVersion = isHogFlowResult(result)
+ ? { id: result.invocation.hogFlow.id, version: result.invocation.hogFlow.version }
+ : undefined
this.queueLogs(
result.logs.map((logEntry) => ({
@@ -135,7 +177,12 @@ export class HogFunctionMonitoringService {
)
if (result.metrics) {
- this.queueAppMetrics(result.metrics, source)
+ this.queueAppMetrics(
+ appSourceVersion !== undefined
+ ? result.metrics.map((metric) => ({ app_source_version: appSourceVersion, ...metric }))
+ : result.metrics,
+ source
+ )
}
if (result.finished || result.error) {
@@ -153,6 +200,7 @@ export class HogFunctionMonitoringService {
metric_kind: result.error ? 'failure' : 'success',
metric_name: result.error ? 'failed' : 'succeeded',
count: 1,
+ app_source_version: appSourceVersion,
},
source
)
diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.ts
index df79279873d3..8241c2859f15 100644
--- a/nodejs/src/cdp/types.ts
+++ b/nodejs/src/cdp/types.ts
@@ -254,6 +254,15 @@ export type MinimalAppMetric = {
| 'exited_workflow_changed'
| 'redirected_workflow_changed'
count: number
+ // Key parts for the mirrored version-scoped row: the flow and the `version` of the HogFlow row that
+ // actually executed the step. Not columns on `app_metrics2` — the monitoring service consumes these
+ // to key a row under the `hog_flow_version` app source, and never forwards them to Kafka. Absent
+ // means this metric only lands in the version-agnostic series.
+ //
+ // `id` is carried rather than reusing `app_source_id` because that field is substituted with
+ // `parentRunId` for batch-triggered runs, so per-run views group by the run. A per-version rollup
+ // has to key on the flow itself, or a broadcast's metrics never aggregate across its runs.
+ app_source_version?: { id: string; version: number }
}
export type AppMetricType = MinimalAppMetric & {
@@ -359,6 +368,13 @@ export type HogFlowInvocationContext = {
// applied; the matcher rejects any repoint whose version isn't strictly greater, so an out-of-order
// older move can't rewind the wait onto an obsolete person.
personIdRepointVersion?: number
+ // Version this run's conversions attribute to: the one that sent the last message, or the one
+ // the run started under if it hasn't sent yet. Never the currently published version — a
+ // conversion arriving after a republish belongs to the version whose message the person
+ // actually received, not whatever happens to be live when they convert.
+ // Absent on runs parked before this was introduced — those attribute to no version at all
+ // rather than to a wrong one.
+ flowVersion?: number
actionStepCount: number
currentAction?: {
id: string
diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.ts
index 194d4bbd1f8c..12be70c7ebff 100644
--- a/nodejs/src/cdp/workflows-e2e.test.ts
+++ b/nodejs/src/cdp/workflows-e2e.test.ts
@@ -397,8 +397,10 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)
})
describe('simple workflow: trigger → function → exit', () => {
+ let workflowId: string
+
beforeEach(async () => {
- await createWorkflow({
+ workflowId = await createWorkflow({
actions: {
trigger: trigger(),
function_1: fetchAction('https://example.com/webhook'),
@@ -426,7 +428,9 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)
// Verify metrics were produced to Kafka
await waitForExpect(() => {
- const metrics = mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ const metrics = mockProducerObserver
+ .getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter((m: any) => m.value.app_source === 'hog_flow')
expect(metrics.length).toBeGreaterThanOrEqual(1)
}, 5000)
@@ -436,6 +440,24 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)
expect(logs.length).toBeGreaterThanOrEqual(1)
}, 5000)
})
+
+ it('mirrors every metric of the run under the workflow version that produced it', async () => {
+ await triggerWorkflow(globals)
+
+ const namesFor = (appSource: string, appSourceId: string): string[] =>
+ mockProducerObserver
+ .getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter((m: any) => m.value.app_source === appSource && m.value.app_source_id === appSourceId)
+ .map((m: any) => m.value.metric_name)
+ .sort()
+
+ // The version-scoped series has to carry the whole run, not just the run-level outcome —
+ // a per-version step funnel is only readable if every step's metric is mirrored.
+ await waitForExpect(() => {
+ expect(namesFor('hog_flow', workflowId)).toContain('succeeded')
+ expect(namesFor('hog_flow_version', `${workflowId}/1`)).toEqual(namesFor('hog_flow', workflowId))
+ }, 10000)
+ })
})
describe('delay workflow: trigger → delay → function → exit', () => {
@@ -742,6 +764,7 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)
await waitForExpect(() => {
const metricNames = mockProducerObserver
.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter((m: any) => m.value.app_source === 'hog_flow')
.map((m: any) => m.value.metric_name)
expect(metricNames).toContain('exited_workflow_changed')
expect(metricNames).not.toContain('failed')
@@ -1671,6 +1694,7 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)
const conversionCount = (): number =>
mockProducerObserver
.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter((m: any) => m.value.app_source === 'hog_flow')
.filter((m: any) => m.value.metric_name === 'conversion')
.reduce((sum: number, m: any) => sum + m.value.count, 0)
@@ -2508,6 +2532,7 @@ describe('Workflows E2E (email queue)', () => {
const sumCounts = (filter: (m: any) => boolean) =>
mockProducerObserver
.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter((m: any) => m.value.app_source === 'hog_flow')
.filter(filter)
.reduce((sum: number, m: any) => sum + m.value.count, 0)
@@ -2579,6 +2604,7 @@ describe('Workflows E2E (email queue)', () => {
const sumCounts = (filter: (m: any) => boolean) =>
mockProducerObserver
.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter((m: any) => m.value.app_source === 'hog_flow')
.filter(filter)
.reduce((sum: number, m: any) => sum + m.value.count, 0)
@@ -2792,6 +2818,7 @@ describe('Workflows E2E (email queue)', () => {
const sumCounts = (filter: (m: any) => boolean) =>
mockProducerObserver
.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter((m: any) => m.value.app_source === 'hog_flow')
.filter(filter)
.reduce((sum: number, m: any) => sum + m.value.count, 0)
@@ -2900,6 +2927,7 @@ describe('Workflows E2E (email queue)', () => {
const sumCounts = (filter: (m: any) => boolean) =>
mockProducerObserver
.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter((m: any) => m.value.app_source === 'hog_flow')
.filter(filter)
.reduce((sum: number, m: any) => sum + m.value.count, 0)
@@ -3011,6 +3039,7 @@ describe('Workflows E2E (email queue)', () => {
const sumCounts = (filter: (m: any) => boolean) =>
mockProducerObserver
.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter((m: any) => m.value.app_source === 'hog_flow')
.filter(filter)
.reduce((sum: number, m: any) => sum + m.value.count, 0)
expect(sumCounts((m) => m.value.metric_name === 'email_sent')).toBe(1)
@@ -3103,6 +3132,7 @@ describe('Workflows E2E (email queue)', () => {
const emailsSent = () =>
mockProducerObserver
.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter((m: any) => m.value.app_source === 'hog_flow')
.filter((m: any) => m.value.metric_name === 'email_sent')
.reduce((sum: number, m: any) => sum + m.value.count, 0)
@@ -3212,6 +3242,7 @@ describe('Workflows E2E (email queue)', () => {
await waitForExpect(() => {
const emailSentCount = mockProducerObserver
.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter((m: any) => m.value.app_source === 'hog_flow')
.filter((m: any) => m.value.metric_name === 'email_sent')
.reduce((sum: number, m: any) => sum + m.value.count, 0)
expect(emailSentCount).toBe(1)
@@ -3318,6 +3349,7 @@ describe('Workflows E2E (email queue)', () => {
await waitForExpect(() => {
const emailSentCount = mockProducerObserver
.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter((m: any) => m.value.app_source === 'hog_flow')
.filter((m: any) => m.value.metric_name === 'email_sent')
.reduce((sum: number, m: any) => sum + m.value.count, 0)
expect(emailSentCount).toBe(3)
@@ -3464,6 +3496,7 @@ describe('Workflows E2E (email queue)', () => {
await waitForExpect(() => {
const emailSentCount = mockProducerObserver
.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)
+ .filter((m: any) => m.value.app_source === 'hog_flow')
.filter((m: any) => m.value.metric_name === 'email_sent')
.reduce((sum: number, m: any) => sum + m.value.count, 0)
expect(emailSentCount).toBe(1)
diff --git a/products/workflows/CONTRIBUTING.md b/products/workflows/CONTRIBUTING.md
index 09be9559d987..758a4ef2b944 100644
--- a/products/workflows/CONTRIBUTING.md
+++ b/products/workflows/CONTRIBUTING.md
@@ -301,6 +301,47 @@ Existing example:
- `posthog_assignee` type defined in nodejs/src/cdp/templates/\_destinations/posthog_conversations/posthog-update-ticket.template.ts
- Renderer in products/conversations/frontend/components/Assignee/CyclotronJobInputAssignee.tsx
+## Metrics and version attribution
+
+Workflow metrics live in the ClickHouse `app_metrics2` table, written by the CDP workers.
+Every hog flow metric is written **twice**:
+
+- `app_source: 'hog_flow'`, `app_source_id: '<flow id>'` — all versions combined. What the UI reads.
+- `app_source: 'hog_flow_version'`, `app_source_id: '<flow id>/<version>'` — only the version whose config produced the metric.
+
+`instance_id`, `metric_kind` and `metric_name` mean the same thing in both series, so a version-scoped read is the version-agnostic query with `app_source` and `app_source_id` swapped.
+`app_metrics2` can't hold the version in a column of its own — it's an AggregatingMergeTree whose sort key is its aggregation key, so a new dimension would have to join the ORDER BY and re-key existing parts.
+
+The versioned series is always keyed by the **flow**, even where the version-agnostic series is not.
+Batch and broadcast runs put the run id in `app_source_id` so per-run views group by the run, but a per-version rollup has to key on the flow itself — otherwise every run of a broadcast mints a fresh key and its versions never aggregate.
+So `hog_flow` reads stay exactly as they are, and `hog_flow_version` is always `<flow id>/<version>`.
+
+Nothing reads the versioned series yet.
+`/metrics` and `/metrics/totals` always return the version-agnostic one, and adding a filter to them is the natural next step.
+Until then, query it directly in HogQL, where the table is exposed as `app_metrics` (the HogQL name maps to the `app_metrics2` table; raw ClickHouse separately has a deprecated v1 table literally named `app_metrics`):
+
+```sql
+SELECT metric_name, sum(count)
+FROM app_metrics
+WHERE app_source = 'hog_flow_version' AND app_source_id = '<flow id>/3'
+GROUP BY metric_name
+```
+
+Conversions carry the version as a `$workflow_version` property on the `$workflows_conversion` event, so version comparisons work in insights and cohorts too.
+
+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.
+
+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.
+For anything emitted after the run has ended — a webhook, a callback — the version has to come from whatever the message carried, never from a fresh lookup of the workflow.
+
+Building a version picker? The list of versions that have metrics is `{flow.version} ∪ {revision versions}`, not just the revisions endpoint. A workflow that has never been edited has zero `HogFlowRevision` rows but still reports metrics under `<flow id>/1`.
+
## Common pitfalls
- **Forgot the side-effect import**: triggers/actions must be imported by their `index.ts`, and async functions must be imported by nodejs/src/cdp/async-functions/index.ts.