: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): track conversions as a metric in the metrics tab (#65897)
Daniel Marchuk20ce9edc3555
diff --git a/frontend/src/lib/components/AppMetrics/AppMetricSummary.tsx b/frontend/src/lib/components/AppMetrics/AppMetricSummary.tsxindex e86adbc9e82f..387910fc3c5c 100644--- a/frontend/src/lib/components/AppMetrics/AppMetricSummary.tsx+++ b/frontend/src/lib/components/AppMetrics/AppMetricSummary.tsx@@ -19,6 +19,8 @@ export type AppMetricSummaryProps = {previousPeriodTimeSeries?: AppMetricsTimeSeriesResponse | nullloading?: booleanhideIfZero?: boolean+ /** Optional content rendered at the bottom of the card, e.g. a deep-link to the underlying data. */+ footer?: JSX.Element | null}export function AppMetricSummary({@@ -30,6 +32,7 @@ export function AppMetricSummary({colorIfZero,loading,hideIfZero = false,+ footer,}: AppMetricSummaryProps): JSX.Element | null {const total = useMemo(() => {if (!timeSeries) {@@ -123,6 +126,7 @@ export function AppMetricSummary({)}</div></div>+ {footer ? <div className="mt-2 text-xs text-center">{footer}</div> : null}</div>)}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.tsindex 785f03a192e6..8146bc30e6a0 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@@ -29,6 +29,7 @@ type MockRow = {id: stringteam_id: numberfunction_id: string+ parent_run_id?: string | nullaction_id: string | nulldistinct_id: string | nullperson_id: string | null@@ -139,6 +140,27 @@ class MatcherUnderTest extends CdpHogflowSubscriptionMatcherConsumer {getHogFlowsForTeams: jest.fn().mockResolvedValue({}),getHogFlowsForTeam: jest.fn().mockResolvedValue([]),}+ // CdpConsumerBase is mocked out in these tests, so the monitoring service it normally+ // provides is absent. Stub it so the matcher can queue/flush the `conversion` app metric.+ ;(this as any).hogFunctionMonitoringService = {+ queueAppMetric: jest.fn(),+ flush: jest.fn().mockResolvedValue(undefined),+ }+ // Likewise stub the captured-events service used to emit $workflows_conversion events.+ ;(this as any).invocationResultsService = {+ capturedEventsService: {+ queueEvent: jest.fn().mockResolvedValue(undefined),+ flush: jest.fn().mockResolvedValue(undefined),+ },+ }+ }++ public get queueAppMetricMock(): jest.Mock {+ return (this as any).hogFunctionMonitoringService.queueAppMetric+ }++ public get queueConversionEventMock(): jest.Mock {+ return (this as any).invocationResultsService.capturedEventsService.queueEvent}public setHogFlows(map: Record<string, HogFlow>): void {@@ -429,13 +451,14 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {},]// State missing currentAction: we cannot tag eventMatched, but the same incoming- // event also satisfies the workflow's conversion goal, which is independent of+ // event also satisfies the workflow's exit-on-conversion goal, which is independent of// currentAction - that wake must still happen.matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer({}) }]matcher.updateRowCount = 1matcher.setHogFlows({'flow-1': makeHogFlow({id: 'flow-1',+ exit_condition: 'exit_on_conversion',conversion: {window_minutes: null,filters: {},@@ -458,6 +481,7 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {expect(update).not.toBeUndefined()const newState = parseJSON(update!.params[1][0].toString('utf-8')) as anyexpect(newState.state.conversionMatched).toBe(true)+ expect(newState.state.conversionCounted).toBe(true)// currentAction is missing in input state, so eventMatched must not have been setexpect(newState.state.currentAction).toBeUndefined()})@@ -525,15 +549,41 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {await matcher.runWake([makeGlobals({ event: { ...makeGlobals({}).event, event: 'wuc_cancelled' } })])- const update = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))- const newState = parseJSON(update!.params[1][0].toString('utf-8')) as any+ // exit_on_conversion wakes the job: a `SET scheduled = NOW()` UPDATE is issued.+ const wake = matcher.calls.find(+ (c) => c.sql.startsWith('UPDATE cyclotron_jobs') && c.sql.includes('SET scheduled = NOW()')+ )+ expect(wake).not.toBeUndefined()+ const newState = parseJSON(wake!.params[1][0].toString('utf-8')) as anyexpect(newState.state.conversionMatched).toBe(true)+ expect(newState.state.conversionCounted).toBe(true)+ // 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 }),+ 'hog_flow'+ )+ // ...and emitted once as a billable $workflows_conversion event for the converting person.+ expect(matcher.queueConversionEventMock).toHaveBeenCalledTimes(1)+ expect(matcher.queueConversionEventMock).toHaveBeenCalledWith(+ expect.objectContaining({+ team_id: 1,+ event: '$workflows_conversion',+ distinct_id: 'user-1',+ properties: expect.objectContaining({+ $workflow_id: 'flow-1',+ $workflow_conversion_type: 'event',+ $workflow_conversion_event: 'wuc_cancelled',+ }),+ })+ )})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- // delay short). The conversion event matches but no UPDATE is produced.+ // delay short). The conversion still counts once, persisted via a state-only UPDATE that+ // leaves `scheduled` untouched.const flow = makeHogFlow({id: 'flow-1',exit_condition: 'exit_only_at_end',@@ -566,8 +616,174 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {await matcher.runWake([makeGlobals({ event: { ...makeGlobals({}).event, event: 'wuc_cancelled' } })])+ // No wake: no `SET scheduled = NOW()` UPDATE is issued.+ const wake = matcher.calls.find(+ (c) => c.sql.startsWith('UPDATE cyclotron_jobs') && c.sql.includes('SET scheduled = NOW()')+ )+ expect(wake).toBeUndefined()+ // But a state-only `SET state = u.state` UPDATE persists conversionCounted.+ const stateOnly = matcher.calls.find(+ (c) =>+ c.sql.startsWith('UPDATE cyclotron_jobs') &&+ c.sql.includes('SET state = u.state') &&+ !c.sql.includes('scheduled')+ )+ expect(stateOnly).not.toBeUndefined()+ const newState = parseJSON(stateOnly!.params[1][0].toString('utf-8')) as any+ expect(newState.state.conversionCounted).toBe(true)+ expect(newState.state.conversionMatched).toBeUndefined()+ // ...and the conversion is counted once (measurement-only).+ expect(matcher.queueAppMetricMock).toHaveBeenCalledTimes(1)+ expect(matcher.queueAppMetricMock).toHaveBeenCalledWith(+ expect.objectContaining({ app_source_id: 'flow-1', metric_name: 'conversion', count: 1 }),+ 'hog_flow'+ )+ })++ it('counts a conversion (without waking) for a conversion-only flow that has no wait step', async () => {+ // Broadened gating: a flow whose only actionable feature is an event-based conversion goal+ // (no wait_until_condition) is now evaluated regardless of exit condition, so the metric is+ // tracked. exit_only_at_end means it must not be woken.+ const flow = makeHogFlow({+ id: 'flow-1',+ waitUntil: false,+ exit_condition: 'exit_only_at_end',+ 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: null,+ distinct_id: 'user-1',+ person_id: null,+ },+ ]+ matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer({}) }]+ matcher.updateRowCount = 1+ matcher.setHogFlows({ 'flow-1': flow })++ await matcher.runWake([makeGlobals({ event: { ...makeGlobals({}).event, event: 'wuc_cancelled' } })])++ // No wake, but a state-only UPDATE persists conversionCounted.+ const wake = matcher.calls.find(+ (c) => c.sql.startsWith('UPDATE cyclotron_jobs') && c.sql.includes('SET scheduled = NOW()')+ )+ expect(wake).toBeUndefined()+ const stateOnly = matcher.calls.find(+ (c) =>+ c.sql.startsWith('UPDATE cyclotron_jobs') &&+ c.sql.includes('SET state = u.state') &&+ !c.sql.includes('scheduled')+ )+ expect(stateOnly).not.toBeUndefined()+ expect(matcher.queueAppMetricMock).toHaveBeenCalledTimes(1)+ expect(matcher.queueAppMetricMock).toHaveBeenCalledWith(+ expect.objectContaining({ app_source_id: 'flow-1', metric_name: 'conversion', count: 1 }),+ 'hog_flow'+ )+ })++ it('does not re-count or update a conversion already counted this run (per-run dedup)', async () => {+ // The parked job's state already carries conversionCounted: true (the run converted via a+ // property change, or an earlier matcher pass). A matching conversion event must be a+ // no-op: no metric, no UPDATE. The FOR UPDATE read sees the persisted flag and skips.+ const flow = makeHogFlow({+ id: 'flow-1',+ waitUntil: false,+ exit_condition: 'exit_only_at_end',+ 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: null,+ distinct_id: 'user-1',+ person_id: null,+ },+ ]+ matcher.wakeRows = [+ {+ ...matcher.findRows[0],+ state: stateBuffer({ currentAction: { id: 'wait_node' }, conversionCounted: true }),+ },+ ]+ matcher.updateRowCount = 1+ matcher.setHogFlows({ 'flow-1': flow })++ await matcher.runWake([makeGlobals({ event: { ...makeGlobals({}).event, event: 'wuc_cancelled' } })])+const update = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))expect(update).toBeUndefined()+ expect(matcher.queueAppMetricMock).not.toHaveBeenCalled()+ })++ it('attributes a conversion to the batch parent_run_id when set', async () => {+ // Batch-workflow jobs carry a parent_run_id (the batch job). The emitted conversion metric+ // must key app_source_id by that run id, not the function id, so it lands under the batch.+ const flow = makeHogFlow({+ id: 'flow-1',+ waitUntil: false,+ exit_condition: 'exit_only_at_end',+ 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',+ parent_run_id: 'batch-run-1',+ action_id: null,+ distinct_id: 'user-1',+ person_id: null,+ },+ ]+ matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer({}) }]+ matcher.updateRowCount = 1+ matcher.setHogFlows({ 'flow-1': flow })++ await matcher.runWake([makeGlobals({ event: { ...makeGlobals({}).event, event: 'wuc_cancelled' } })])++ expect(matcher.queueAppMetricMock).toHaveBeenCalledTimes(1)+ expect(matcher.queueAppMetricMock).toHaveBeenCalledWith(+ expect.objectContaining({+ app_source_id: 'batch-run-1',+ instance_id: 'flow-1',+ metric_name: 'conversion',+ count: 1,+ }),+ 'hog_flow'+ )})it('does not wake on an empty conversion "events" entry (always-true bytecode)', async () => {diff --git a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.tsindex 6edca2bb6d10..eddb87f6b9b5 100644--- a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts@@ -5,6 +5,7 @@ import { Counter, Histogram } from 'prom-client'import { HogFlow, HogFlowAction } from '~/cdp/schema/hogflow'import { KAFKA_EVENTS_JSON } from '~/common/config/kafka-topics'import { KafkaConsumerInterface, RdKafkaConsumerConfig, createKafkaConsumer } from '~/common/kafka/consumer'+import { InternalCaptureEvent } from '~/common/services/internal-capture'import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'import { parseJSON } from '~/common/utils/json-parse'import { logger } from '~/common/utils/logger'@@ -12,7 +13,7 @@ import { captureException } from '~/common/utils/posthog'import { HealthCheckResult, PluginsServerConfig, RawClickHouseEvent } from '../../types'import { isEvaluableCondition } from '../services/hogflows/hogflow-utils'-import { HogFlowInvocationContext, HogFunctionInvocationGlobals } from '../types'+import { HogFlowInvocationContext, HogFunctionInvocationGlobals, MinimalAppMetric } from '../types'import { convertToHogFunctionInvocationGlobals } from '../utils'import { execHog } from '../utils/hog-exec'import { convertToHogFunctionFilterGlobal } from '../utils/hog-function-filtering'@@ -34,6 +35,11 @@ const counterHogflowMatcherJobsWoken = new Counter({help: 'Parked hogflow jobs the matcher woke because an incoming event matched.',})+const counterHogflowMatcherConversionsCounted = new Counter({+ name: 'cdp_hogflow_matcher_conversions_counted',+ help: 'Event-based conversions counted by the matcher (deduped to once per run via conversionCounted).',+})+// Latency of the cyclotron lookup for parked jobs. Watch this for cyclotron-node// read pressure as the wait-until-event feature ramps.const histogramHogflowMatcherFindParkedJobs = new Histogram({@@ -52,21 +58,37 @@ type ParkedCandidate = {id: stringteamId: numberfunctionId: string+ parentRunId: string | nullactionId: string | nulldistinctId: string | nullpersonId: string | null}-type WakeRequest = {+// A parked job the matcher needs to act on this batch: either resume it (stepMatched, or a+// conversion match on an exit-on-conversion flow) and/or count its conversion once. Carries the+// fields needed to emit the `conversion` metric without re-reading the hogflow.+type MatchedJob = {id: string+ teamId: number+ functionId: string+ parentRunId: string | nullstepMatched: booleanconversionMatched: boolean+ exitsOnConversion: boolean// Name, UUID and timestamp of the matched event, so the resume log can name it and link to it.eventName?: stringeventUuid?: stringeventTimestamp?: string+ // Distinct id + name/uuid of the event that satisfied the conversion goal, so the matcher can+ // emit the `$workflows_conversion` PostHog event for the converting person.+ conversionDistinctId?: string+ conversionEventName?: string+ conversionEventUuid?: string}+// Payload for capturedEventsService.queueEvent — a resolved PostHog capture event minus the token.+type CapturedConversionEvent = { team_id: number } & Omit<InternalCaptureEvent, 'team_token'>+type FilterGlobals = ReturnType<typeof convertToHogFunctionFilterGlobal>// Wakes parked hogflow jobs when an event matches a `wait_until_condition` step@@ -107,7 +129,24 @@ export class CdpHogflowSubscriptionMatcherConsumer<if (!invocationGlobals.length) {return}- await this.wakeMatchingWorkflows(invocationGlobals)+ try {+ await this.wakeMatchingWorkflows(invocationGlobals)+ } finally {+ // Flush any `conversion` metrics and `$workflows_conversion` events queued during matching.+ // Best-effort: a flush failure must not crash the batch (which would replay the event+ // offsets). flush() is a no-op when nothing was queued, so it's safe to call unconditionally.+ await instrumentFn({ key: 'cdp.background_task.monitoring_flush', sendException: false }, async () => {+ try {+ await Promise.all([+ this.hogFunctionMonitoringService.flush(),+ this.invocationResultsService.capturedEventsService.flush(),+ ])+ } catch (err) {+ logger.error('⚠️', 'Failed to flush hogflow matcher app metrics/events', { err })+ captureException(err)+ }+ })+ }}@instrumented('cdpHogflowSubscriptionMatcher.wakeMatchingWorkflows')@@ -159,7 +198,7 @@ export class CdpHogflowSubscriptionMatcherConsumer<return fg}- const jobsToWake: WakeRequest[] = []+ const matchedJobs: MatchedJob[] = []for (const candidate of candidates) {const hogflow = hogflows[candidate.functionId]if (!hogflow) {@@ -181,6 +220,9 @@ export class CdpHogflowSubscriptionMatcherConsumer<let stepMatchedEventUuid: string | undefinedlet stepMatchedEventTimestamp: string | undefinedlet conversionMatched = false+ let conversionDistinctId: string | undefined+ let conversionEventName: string | undefined+ let conversionEventUuid: string | undefinedfor (const globals of candidateGlobals) {const filterGlobals = filterGlobalsFor(globals)if (!stepMatched && action?.type === 'wait_until_condition') {@@ -191,41 +233,53 @@ export class CdpHogflowSubscriptionMatcherConsumer<stepMatchedEventTimestamp = globals.event.timestamp}}- if (!conversionMatched) {- conversionMatched = await this.evaluateConversionEvents(hogflow, filterGlobals)+ if (!conversionMatched && (await this.evaluateConversionEvents(hogflow, filterGlobals))) {+ conversionMatched = true+ // Remember who converted (and via which event) so we can emit $workflows_conversion.+ conversionDistinctId = globals.event.distinct_id+ conversionEventName = globals.event.event+ conversionEventUuid = globals.event.uuid}if (stepMatched && conversionMatched) {break}}- // A matched wait step always resumes the job. A conversion match only wakes the job when- // the workflow is configured to exit on conversion — then the resumed job exits early via- // `shouldExitEarly`. For any other exit condition a conversion goal is measurement-only,- // so waking would just pull a parked job (e.g. one sitting in a delay) forward and run its- // next step early. `conversionMatched` is still surfaced so the executor can act on it.- if (stepMatched || (conversionMatched && exitsOnConversion(hogflow))) {- jobsToWake.push({+ // Collect a job when its wait step matched OR a conversion matched. Conversion matches are+ // collected even on measurement-only (non-exit) flows: processMatchedJobs reads the job's+ // state under FOR UPDATE to count the conversion exactly once per run (and surface it to+ // the executor for exit-on-conversion flows). The wake-vs-count-only decision is made there.+ if (stepMatched || conversionMatched) {+ matchedJobs.push({id: candidate.id,+ teamId: candidate.teamId,+ functionId: candidate.functionId,+ parentRunId: candidate.parentRunId,stepMatched,conversionMatched,+ exitsOnConversion: exitsOnConversion(hogflow),eventName: stepMatchedEventName,eventUuid: stepMatchedEventUuid,eventTimestamp: stepMatchedEventTimestamp,+ conversionDistinctId,+ conversionEventName,+ conversionEventUuid,})}}- if (jobsToWake.length === 0) {+ if (matchedJobs.length === 0) {return}- const woken = await this.wakeJobs(jobsToWake)+ const { woken, conversionsCounted } = await this.processMatchedJobs(matchedJobs)counterHogflowMatcherJobsWoken.inc(woken)- logger.info('⚡', 'Woke waiting workflows from event match', {+ counterHogflowMatcherConversionsCounted.inc(conversionsCounted)+ logger.info('⚡', 'Processed waiting workflows from event match', {evaluated: candidates.length,- matched: jobsToWake.length,+ matched: matchedJobs.length,woken,+ conversionsCounted,})}@@ -295,14 +349,14 @@ export class CdpHogflowSubscriptionMatcherConsumer<let resulttry {result = await this.cyclotronPool.query(- `SELECT id, team_id, function_id, action_id, distinct_id, person_id+ `SELECT id, team_id, function_id, parent_run_id, action_id, distinct_id, person_idFROM cyclotron_jobsWHERE status = 'available'AND scheduled > NOW()AND function_id = ANY($5::uuid[])AND (team_id, distinct_id) IN (SELECT * FROM unnest($1::int[], $2::text[]))UNION- SELECT id, team_id, function_id, action_id, distinct_id, person_id+ SELECT id, team_id, function_id, parent_run_id, action_id, distinct_id, person_idFROM cyclotron_jobsWHERE status = 'available'AND scheduled > NOW()@@ -318,24 +372,25 @@ export class CdpHogflowSubscriptionMatcherConsumer<id: row.id,teamId: row.team_id,functionId: row.function_id,+ parentRunId: row.parent_run_id,actionId: row.action_id,distinctId: row.distinct_id,personId: row.person_id,}))}- private async wakeJobs(requests: WakeRequest[]): Promise<number> {- if (requests.length === 0) {- return 0+ private async processMatchedJobs(matched: MatchedJob[]): Promise<{ woken: number; conversionsCounted: number }> {+ if (matched.length === 0) {+ return { woken: 0, conversionsCounted: 0 }}- const ids = requests.map((r) => r.id)- // The state read-modify-write must be atomic: two matcher instances waking the- // same job (one stepMatched, one conversionMatched) would otherwise both read the- // original state and the later UPDATE would drop the earlier flag. SELECT ... FOR- // UPDATE inside a transaction serializes them — the second waker blocks, then reads- // our committed state and merges its flag on top. ORDER BY id keeps lock acquisition- // order consistent across instances so concurrent batches can't deadlock.+ const ids = matched.map((m) => m.id)+ // The state read-modify-write must be atomic: two matcher instances acting on the same job+ // would otherwise both read the original state and the later UPDATE would drop the earlier+ // flag — and both would count the same conversion. SELECT ... FOR UPDATE inside a transaction+ // serializes them: the second instance blocks, then reads our committed `conversionCounted`+ // and skips the duplicate. ORDER BY id keeps lock acquisition order consistent across+ // instances so concurrent batches can't deadlock.const client = await this.cyclotronPool.connect()try {await client.query('BEGIN')@@ -348,38 +403,97 @@ export class CdpHogflowSubscriptionMatcherConsumer<[ids])- const requestById = new Map(requests.map((r) => [r.id, r]))- const updates: { id: string; state: Buffer }[] = []+ const matchedById = new Map(matched.map((m) => [m.id, m]))+ // Woken jobs get `scheduled = NOW()`; count-only jobs (measurement-only conversions on+ // non-exit flows) get a state write that leaves `scheduled` untouched, so we persist+ // `conversionCounted` without pulling a parked job forward.+ const wakeUpdates: { id: string; state: Buffer }[] = []+ const stateOnlyUpdates: { id: string; state: Buffer }[] = []+ const conversionMetrics: MinimalAppMetric[] = []+ const conversionEvents: CapturedConversionEvent[] = []for (const row of stateRows.rows) {if (!row.state) {continue}- const req = requestById.get(row.id)- if (!req) {+ const m = matchedById.get(row.id)+ if (!m) {+ continue+ }+ const outcome = applyMatchToState(row.state, m)+ if (!outcome) {continue}- const updated = applyWakeFlags(row.state, req)- if (updated) {- updates.push({ id: row.id, state: updated })+ if (outcome.countConversion) {+ conversionMetrics.push({+ team_id: m.teamId,+ // Key by the run id so batch-workflow conversions land under the batch job+ // (parentRunId), matching how the executor records property-based conversions.+ app_source_id: m.parentRunId ?? m.functionId,+ instance_id: m.functionId,+ metric_kind: 'other',+ metric_name: 'conversion',+ count: 1,+ })+ // Emit the same billable $workflows_conversion event as the executor's property+ // path, so event-based conversions also power insights/cohorts. Needs a+ // distinct_id to attribute to a person.+ if (m.conversionDistinctId) {+ conversionEvents.push({+ team_id: m.teamId,+ event: '$workflows_conversion',+ distinct_id: m.conversionDistinctId,+ timestamp: new Date().toISOString(),+ properties: {+ $workflow_id: m.functionId,+ $workflow_conversion_type: 'event',+ $workflow_conversion_event: m.conversionEventName,+ $workflow_conversion_event_uuid: m.conversionEventUuid,+ },+ })+ }+ }+ if (outcome.wake) {+ wakeUpdates.push({ id: row.id, state: outcome.state })+ } else {+ stateOnlyUpdates.push({ id: row.id, state: outcome.state })}}- if (updates.length === 0) {- await client.query('COMMIT')- return 0+ let woken = 0+ if (wakeUpdates.length > 0) {+ const result = await client.query(+ `UPDATE cyclotron_jobs cj+ SET scheduled = NOW(), state = u.state+ FROM (+ SELECT unnest($1::uuid[]) AS id, unnest($2::bytea[]) AS state+ ) u+ WHERE cj.id = u.id AND cj.status = 'available'`,+ [wakeUpdates.map((u) => u.id), wakeUpdates.map((u) => u.state)]+ )+ woken = result.rowCount ?? 0}+ if (stateOnlyUpdates.length > 0) {+ await client.query(+ `UPDATE cyclotron_jobs cj+ SET state = u.state+ FROM (+ SELECT unnest($1::uuid[]) AS id, unnest($2::bytea[]) AS state+ ) u+ WHERE cj.id = u.id AND cj.status = 'available'`,+ [stateOnlyUpdates.map((u) => u.id), stateOnlyUpdates.map((u) => u.state)]+ )+ }+ await client.query('COMMIT')- const result = await client.query(- `UPDATE cyclotron_jobs cj- SET scheduled = NOW(), state = u.state- FROM (- SELECT unnest($1::uuid[]) AS id, unnest($2::bytea[]) AS state- ) u- WHERE cj.id = u.id AND cj.status = 'available'`,- [updates.map((u) => u.id), updates.map((u) => u.state)]+ // Queue metrics/events only after the dedup write commits: if the transaction rolled back,+ // the run is still uncounted in state, so a retry must be free to count it (no double-count).+ for (const metric of conversionMetrics) {+ this.hogFunctionMonitoringService.queueAppMetric(metric, 'hog_flow')+ }+ await Promise.all(+ conversionEvents.map((event) => this.invocationResultsService.capturedEventsService.queueEvent(event)))- await client.query('COMMIT')- return result.rowCount ?? 0+ return { woken, conversionsCounted: conversionMetrics.length }} catch (err) {await client.query('ROLLBACK').catch(() => {})throw err@@ -483,13 +597,15 @@ function exitsOnConversion(hogflow: HogFlow): boolean {}// Skip teams whose hogflows have nothing the matcher can act on: no wait_until_condition step, and-// no event-based conversion goal that the workflow exits on.+// no event-based conversion goal. Event conversions are evaluated regardless of exit condition so+// the `conversion` metric is tracked even for flows that don't exit on conversion — only the *wake*+// decision (in wakeMatchingWorkflows) still depends on exitsOnConversion.function hasWaitUntilOrConversion(hogflow: HogFlow): boolean {if (hogflow.actions.some((a: HogFlowAction) => a.type === 'wait_until_condition')) {return true}const conversionEvents = hogflow.conversion?.events- return Array.isArray(conversionEvents) && conversionEvents.length > 0 && exitsOnConversion(hogflow)+ return Array.isArray(conversionEvents) && conversionEvents.length > 0}// Single pass over the batch: dedup distinct/person ids, collect team ids,@@ -595,42 +711,67 @@ async function runBytecode(}}-function applyWakeFlags(stateBuffer: Buffer, req: WakeRequest): Buffer | null {+type MatchOutcome = { state: Buffer; wake: boolean; countConversion: boolean }++// 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+// when nothing changed (e.g. the conversion was already counted and there's no wake to apply).+function applyMatchToState(stateBuffer: Buffer, m: MatchedJob): MatchOutcome | null {try {const parsed = parseJSON(stateBuffer.toString('utf-8'))const updatedState: HogFlowInvocationContext = { ...parsed.state }- let applied = false- if (req.stepMatched) {+ let changed = false+ let wake = false+ let countConversion = false++ // Count each run's conversion at most once, regardless of exit condition. The same flag is+ // set by the executor's property-based path, so a run is counted once whether it converts via+ // a property change or a conversion event — and repeated conversion events no longer inflate+ // the count for measurement-only (non-exit) flows.+ if (m.conversionMatched && !updatedState.conversionCounted) {+ updatedState.conversionCounted = true+ changed = true+ countConversion = true+ }++ // A matched wait_until_condition step resumes the job, tagged so the resume reads as an event+ // match rather than a timeout.+ if (m.stepMatched) {if (updatedState.currentAction) {updatedState.currentAction = {...updatedState.currentAction,eventMatched: true,- eventMatchedEvent: req.eventName,- eventMatchedEventUuid: req.eventUuid,- eventMatchedEventTimestamp: req.eventTimestamp,+ eventMatchedEvent: m.eventName,+ eventMatchedEventUuid: m.eventUuid,+ eventMatchedEventTimestamp: m.eventTimestamp,}- applied = true+ changed = true+ wake = true} else {- // A parked wait_until_condition job should always carry its current action.- // Without it we cannot tag the wake as an event match - skip the flag and- // continue, since conversionMatched is independent of currentAction and may- // still apply.- logger.warn('Skipping eventMatched: no currentAction in state', { jobId: req.id })+ // A parked wait_until_condition job should always carry its current action. Without it+ // we cannot tag the wake as an event match - skip the flag and continue, since the+ // conversion handling above is independent of currentAction and may still apply.+ logger.warn('Skipping eventMatched: no currentAction in state', { jobId: m.id })}}- if (req.conversionMatched) {++ // Only exit-on-conversion flows resume on a conversion match (so shouldExitEarly can exit).+ // For any other exit condition the conversion is measurement-only: we persist conversionCounted+ // above but must not reschedule, or we'd pull a parked job (e.g. one in a delay) forward.+ if (m.conversionMatched && m.exitsOnConversion) {updatedState.conversionMatched = true- applied = true+ changed = true+ wake = true}- if (!applied) {- // No flag set - waking the job without one would misclassify as a timeout wake.++ if (!changed) {return null}parsed.state = updatedState- return Buffer.from(JSON.stringify(parsed))+ return { state: Buffer.from(JSON.stringify(parsed)), wake, countConversion }} catch (err) {- logger.warn('Failed to parse state during wake', { jobId: req.id, err })+ logger.warn('Failed to parse state during match', { jobId: m.id, err })return null}}diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.tsindex d1063fa364d5..9ca4348ebd22 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts@@ -678,7 +678,8 @@ describe('Hogflow Executor', () => {)const result2 = await executor.execute(invocation2)expect(result2.finished).toBe(true)- expect(result2.metrics.map((m) => m.metric_name)).toEqual(['early_exit'])+ // The property-based conversion is also counted on the exit path+ expect(result2.metrics.map((m) => m.metric_name)).toEqual(['early_exit', 'conversion'])expect(result2.logs.map((log) => log.message)).toMatchInlineSnapshot(`["Workflow exited early due to exit condition: exit_on_conversion ([Person:person_id|John Doe] matches conversion filters)",@@ -793,7 +794,8 @@ describe('Hogflow Executor', () => {const result2 = await executor.execute(invocation2)expect(result2.finished).toBe(true)- expect(result2.metrics.map((m) => m.metric_name)).toEqual(['early_exit'])+ // The property-based conversion is also counted on the exit path+ expect(result2.metrics.map((m) => m.metric_name)).toEqual(['early_exit', 'conversion'])expect(result2.logs.map((log) => log.message)).toMatchInlineSnapshot(`["Workflow exited early due to exit condition: exit_on_trigger_not_matched_or_conversion ([Person:person_id|John Doe] matches conversion filters)",@@ -801,6 +803,102 @@ describe('Hogflow Executor', () => {`)})+ it('counts a property-based conversion without exiting when exit condition is exit_only_at_end', async () => {+ hogFlow.exit_condition = 'exit_only_at_end'+ hogFlow.conversion = {+ filters: [{ key: '$browser', type: 'person', value: ['Chrome'], operator: 'exact' }],+ bytecode: ['_H', 1, 32, 'Chrome', 32, '$browser', 32, 'properties', 32, 'person', 1, 3, 11],+ window_minutes: null,+ }++ const invocation = createExampleHogFlowInvocation(+ hogFlow,+ {+ event: {+ ...createHogExecutionGlobals().event,+ event: '$pageview',+ properties: { name: 'John Doe', $current_url: 'https://posthog.com' },+ },+ },+ { properties: { $browser: 'Chrome' } }+ )++ const result = await executor.execute(invocation)+ // The run completes normally (no early exit) but the conversion is counted exactly once+ expect(result.finished).toBe(true)+ expect(result.metrics.map((m) => m.metric_name)).toEqual([+ 'conversion',+ 'fetch',+ 'billable_invocation',+ 'succeeded',+ 'succeeded',+ ])+ expect(result.metrics.filter((m) => m.metric_name === 'conversion')).toHaveLength(1)+ expect(invocation.state.conversionCounted).toBe(true)+ // The conversion is also surfaced as a billable $workflows_conversion event exactly once.+ const conversionEvents = result.capturedPostHogEvents.filter((e) => e.event === '$workflows_conversion')+ expect(conversionEvents).toHaveLength(1)+ expect(conversionEvents[0]).toMatchObject({+ distinct_id: 'distinct_id',+ properties: { $workflow_id: hogFlow.id, $workflow_conversion_type: 'property' },+ })+ })++ it('does not re-count a property-based conversion on a resume that already counted', async () => {+ hogFlow.exit_condition = 'exit_only_at_end'+ hogFlow.conversion = {+ filters: [{ key: '$browser', type: 'person', value: ['Chrome'], operator: 'exact' }],+ bytecode: ['_H', 1, 32, 'Chrome', 32, '$browser', 32, 'properties', 32, 'person', 1, 3, 11],+ window_minutes: null,+ }++ const invocation = createExampleHogFlowInvocation(+ hogFlow,+ {+ event: {+ ...createHogExecutionGlobals().event,+ event: '$pageview',+ properties: { name: 'John Doe', $current_url: 'https://posthog.com' },+ },+ },+ { properties: { $browser: 'Chrome' } }+ )+ // Simulate a prior step in this run having already counted the conversion+ invocation.state.conversionCounted = true++ const result = await executor.execute(invocation)+ expect(result.finished).toBe(true)+ expect(result.metrics.map((m) => m.metric_name)).not.toContain('conversion')+ })++ it('does not count event-based conversions in the executor (counted by the matcher)', async () => {+ hogFlow.exit_condition = 'exit_only_at_end'+ // Event-based conversion goal: no property filters/bytecode, so the executor's+ // property path never matches. The matcher flags the run via conversionMatched.+ hogFlow.conversion = {+ filters: [],+ bytecode: [],+ window_minutes: null,+ events: [{ filters: { bytecode: ['_H', 1, 29] } }],+ }++ const invocation = createExampleHogFlowInvocation(hogFlow, {+ event: {+ ...createHogExecutionGlobals().event,+ event: '$pageview',+ properties: { name: 'John Doe', $current_url: 'https://posthog.com' },+ },+ })+ invocation.state.conversionMatched = true++ const result = await executor.execute(invocation)+ expect(result.finished).toBe(true)+ // No conversion metric from the executor; the flag is consumed, not double-counted+ expect(result.metrics.map((m) => m.metric_name)).not.toContain('conversion')+ expect(invocation.state.conversionMatched).toBe(false)+ expect(invocation.state.conversionCounted).toBeUndefined()+ })+describe('on_error handling', () => {let hogFlow: HogFlowbeforeEach(async () => {diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.tsindex 6ff46b77679b..c063ece5f1df 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts@@ -177,7 +177,7 @@ export class HogFlowExecutorService {const capturedPostHogEvents: HogFunctionCapturedEvent[] = []const warehouseWebhookPayloads: WarehouseWebhookPayload[] = []- const earlyExitResult = await this.shouldExitEarly(invocation)+ const earlyExitResult = await this.shouldExitEarly(invocation, metrics, capturedPostHogEvents)if (earlyExitResult) {return earlyExitResult}@@ -265,7 +265,9 @@ export class HogFlowExecutorService {* Determines if the invocation should exit early based on the hogflow's exit condition*/private async shouldExitEarly(- invocation: CyclotronJobInvocationHogFlow+ invocation: CyclotronJobInvocationHogFlow,+ metrics: MinimalAppMetric[],+ capturedPostHogEvents: HogFunctionCapturedEvent[]): Promise<CyclotronJobInvocationResult<CyclotronJobInvocationHogFlow> | null> {let earlyExitResult: CyclotronJobInvocationResult<CyclotronJobInvocationHogFlow> | null = null@@ -302,6 +304,41 @@ export class HogFlowExecutorService {)}}+ // Count property-based conversions here, regardless of exit condition, so the metric is+ // meaningful even for flows that don't exit on conversion. Captured before the event-flag+ // override below: event-based conversions are counted by the subscription matcher, so the+ // executor must only emit for the property path or exit-on-conversion event flows double-count.+ // Guarded once-per-run by `conversionCounted` since shouldExitEarly runs on every resume.+ const propertyConversionMatched = conversionMatch === true+ let conversionMetric: MinimalAppMetric | null = null+ let conversionEvent: HogFunctionCapturedEvent | null = null+ if (propertyConversionMatched && !invocation.state.conversionCounted) {+ invocation.state.conversionCounted = true+ conversionMetric = {+ team_id: hogFlow.team_id,+ app_source_id: invocation.parentRunId ?? hogFlow.id,+ instance_id: hogFlow.id,+ metric_kind: 'other',+ metric_name: 'conversion',+ count: 1,+ }+ // Also surface the conversion as a billable PostHog event so it can power insights and+ // cohorts (mirrors the $workflows_email_* engagement events). Event-based conversions are+ // emitted by the subscription matcher, so this only fires for the property path.+ const distinctId = invocation.state.event?.distinct_id+ if (distinctId) {+ conversionEvent = {+ team_id: hogFlow.team_id,+ event: '$workflows_conversion',+ distinct_id: distinctId,+ timestamp: new Date().toISOString(),+ properties: {+ $workflow_id: hogFlow.id,+ $workflow_conversion_type: 'property',+ },+ }+ }+ }// Event-based conversion goals are evaluated by the subscription matcher (against the live// event stream), which flags the job when the conversion event fires. The property-based// check above can't see those, so honor the flag here. It is a one-shot signal ("the@@ -354,6 +391,16 @@ export class HogFlowExecutorService {})}+ // Route the conversion metric/event onto whichever result is actually flushed: the early-exit+ // result when we exit, otherwise the caller's arrays (which become result.metrics /+ // result.capturedPostHogEvents once the run continues and finishes).+ if (conversionMetric) {+ ;(earlyExitResult?.metrics ?? metrics).push(conversionMetric)+ }+ if (conversionEvent) {+ ;(earlyExitResult?.capturedPostHogEvents ?? capturedPostHogEvents).push(conversionEvent)+ }+return earlyExitResult}diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex c0bb5ae58512..eaf450944769 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -240,6 +240,7 @@ export type MinimalAppMetric = {| 'email_spam'| 'email_unsubscribed'| 'quota_limited'+ | 'conversion'count: number}@@ -364,6 +365,11 @@ export type HogFlowInvocationContext = {// Set by the subscription matcher consumer when an incoming event matched the// workflow's event-based conversion goals. shouldExitEarly reads and clears it.conversionMatched?: boolean+ // Once-per-run guard for the property-based conversion metric. Executor-owned:+ // shouldExitEarly runs on every resume, so without this a persistently-true+ // conversion filter would emit a `conversion` metric on every step. Event-based+ // conversions are counted by the matcher and never touch this flag.+ conversionCounted?: booleanvariables?: Record<string, any>// Sticky counter incremented by the rerun paginator on rehydration. Lets// the lifecycle row producer derive `attempts` / `is_retry` for hog flowsdiff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.tsindex 8dad82122a10..51a3bea16990 100644--- a/nodejs/src/cdp/workflows-e2e.test.ts+++ b/nodejs/src/cdp/workflows-e2e.test.ts@@ -1008,6 +1008,62 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)// Exited on conversion — the after-delay step never ran.expect(mockFetch).not.toHaveBeenCalled()})++ it('counts an event-based conversion exactly once per run even when the event fires repeatedly', async () => {+ // Regression guard for conversion over-counting on measurement-only flows. The run stays+ // parked in the delay (exit_only_at_end), and the conversion event fires across three+ // separate matcher batches. The matcher must record exactly ONE `conversion` metric for+ // the run (deduped via conversionCounted), and must never wake the job.+ await createWorkflowFlow(+ {+ actions: {+ trigger: trigger(),+ delay: { type: 'delay', config: { delay_duration: '5m' } },+ after_delay: fetchAction('https://example.com/after-delay'),+ exit: exitAction(),+ },+ edges: [+ { from: 'trigger', to: 'delay', type: 'continue' },+ { from: 'delay', to: 'after_delay', type: 'continue' },+ { from: 'after_delay', to: 'exit', type: 'continue' },+ ],+ },+ {+ exitCondition: 'exit_only_at_end',+ conversion: {+ window_minutes: 60,+ filters: [],+ bytecode: [],+ events: [eventNameFilter('conversion_event')],+ } as any,+ }+ )+ await triggerWorkflow(createGlobals())+ await expectParked()++ const conversionCount = (): number =>+ mockProducerObserver+ .getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)+ .filter((m: any) => m.value.metric_name === 'conversion')+ .reduce((sum: number, m: any) => sum + m.value.count, 0)++ // First match counts the conversion once.+ await matcher.processBatch([createGlobals({ event: 'conversion_event' })])+ await waitForExpect(() => {+ expect(conversionCount()).toBe(1)+ }, 5000)++ // The same conversion event firing again must NOT increment the count — the run already converted.+ await matcher.processBatch([createGlobals({ event: 'conversion_event' })])+ await matcher.processBatch([createGlobals({ event: 'conversion_event' })])+ await new Promise((resolve) => setTimeout(resolve, 500))+ expect(conversionCount()).toBe(1)++ // Measurement-only: the run stays parked and the after-delay step never runs early.+ const jobs = await queryCyclotronJobs()+ expect(jobs.every((j: any) => j.status === 'available' && new Date(j.scheduled) > new Date())).toBe(true)+ expect(mockFetch).not.toHaveBeenCalled()+ })})describe('wait_until_time_window: window in the future', () => {diff --git a/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx b/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsxindex c5b8a6287c49..4e3616464b4a 100644--- a/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx+++ b/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx@@ -1,7 +1,7 @@import { useValues } from 'kea'import { useMemo } from 'react'-import { LemonLabel, LemonTable, LemonTableColumns, SpinnerOverlay } from '@posthog/lemon-ui'+import { LemonLabel, LemonTable, LemonTableColumns, Link, SpinnerOverlay } from '@posthog/lemon-ui'import { getColorVar } from 'lib/colors'import { AppMetricsTrends } from 'lib/components/AppMetrics/AppMetricsTrends'@@ -26,12 +26,17 @@ export function WorkflowMetricsSummary({ onSelectAction, ...props }: WorkflowMetsummaryMetricKeys,metricNameBySummaryMetric,getSingleTrendSeries,- getExitNodeSingleTrendSeries,+ getCompletedSingleTrendSeries,inProgressTotal,inProgressTotalLoading,workflowSummaryTrends,emailMetricsRows,emailTotalsByActionIdLoading,+ conversionRate,+ conversionStats,+ conversionStatsLoading,+ convertedUsersUrl,+ hasConversionGoal,} = useValues(workflowMetricsSummaryLogic(props))const emailMetricsColumns: LemonTableColumns<EmailMetricRow> = useMemo(@@ -103,16 +108,19 @@ export function WorkflowMetricsSummary({ onSelectAction, ...props }: WorkflowMet</div></div>{summaryMetricKeys.map((summaryMetric) => {+ if (summaryMetric === 'converted' && !hasConversionGoal) {+ return null+ }const metric = WORKFLOW_SUMMARY_METRICS[summaryMetric]const metricName = metricNameBySummaryMetric[summaryMetric]const timeSeries =summaryMetric === 'completed'- ? withDisplayName(getExitNodeSingleTrendSeries('succeeded'), metric.name)+ ? withDisplayName(getCompletedSingleTrendSeries('succeeded'), metric.name): withDisplayName(getSingleTrendSeries(metricName), metric.name)const previousPeriodTimeSeries =summaryMetric === 'completed'- ? withDisplayName(getExitNodeSingleTrendSeries('succeeded', true), metric.name)+ ? withDisplayName(getCompletedSingleTrendSeries('succeeded', true), metric.name): withDisplayName(getSingleTrendSeries(metricName, true), metric.name)return (@@ -125,9 +133,41 @@ export function WorkflowMetricsSummary({ onSelectAction, ...props }: WorkflowMetpreviousPeriodTimeSeries={previousPeriodTimeSeries}color={metric.color}colorIfZero={getColorVar('muted')}+ footer={+ summaryMetric === 'converted' &&+ !conversionStatsLoading &&+ conversionStats.conversions > 0 ? (+ <Link to={convertedUsersUrl}>View converted users</Link>+ ) : null+ }/>)})}+ {hasConversionGoal && (+ <div className="flex flex-1 flex-col relative border rounded p-3 bg-surface-primary min-w-[16rem]">+ <div className="flex flex-col h-full">+ <LemonLabel info="Share of started workflow runs that recorded a conversion (Converted ÷ Started) over the selected date range.">+ Conversion rate+ </LemonLabel>+ <div className="flex flex-1 items-center justify-center">+ {conversionStatsLoading ? (+ <SpinnerOverlay />+ ) : conversionStats.started === 0 ? (+ <LemonLabel className="text-muted text-md mb-2">No workflows started</LemonLabel>+ ) : (+ <div className="text-6xl text-muted-foreground mb-2">+ {`${(Math.min(conversionRate, 1) * 100).toFixed(1)}%`}+ </div>+ )}+ </div>+ {!conversionStatsLoading && conversionStats.conversions > 0 && (+ <Link to={convertedUsersUrl} className="text-xs text-center">+ View converted users+ </Link>+ )}+ </div>+ </div>+ )}</div><LemonTablediff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsxindex 1a2a3c739c42..f252a7117b21 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx@@ -7,6 +7,7 @@ import {IconBolt,IconButton,IconClock,+ IconInfo,IconLeave,IconPeople,IconPlusSmall,@@ -783,9 +784,12 @@ function ConversionGoalSection(): JSX.Element {return (<div className="flex flex-col py-2 w-full">- <span className="flex gap-1">+ <span className="flex gap-1 items-center"><IconTarget className="text-lg" /><span className="text-md font-semibold">Conversion goal (optional)</span>+ <Tooltip title="When a conversion goal is set, each conversion is sent as a billable $workflows_conversion event (with the workflow id and conversion type). You can build insights and cohorts from it, and it counts toward your event usage.">+ <IconInfo className="text-secondary" />+ </Tooltip></span><p>Define what a user must do to be considered converted. All conditions must be met for the user to bediff --git a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.tsindex bba2564e096b..7467aa501f16 100644--- a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts+++ b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts@@ -1,5 +1,6 @@import { afterMount, connect, kea, key, listeners, path, props, selectors } from 'kea'import { loaders } from 'kea-loaders'+import { combineUrl } from 'kea-router'import { getColorVar } from 'lib/colors'import {@@ -10,12 +11,27 @@ import {type AppMetricsTotalsResponse,} from 'lib/components/AppMetrics/appMetricsLogic'import { dayjs } from 'lib/dayjs'+import { urls } from 'scenes/urls'++import { defaultDataTableColumns } from '~/queries/nodes/DataTable/utils'+import { DataTableNode, EventsQuery, NodeKind } from '~/queries/schema/schema-general'+import { ActivityTab, PropertyFilterType, PropertyOperator } from '~/types'import { isEmailAction } from './hogflows/steps/types'-import { EXIT_NODE_ID, workflowLogic } from './workflowLogic'+import { workflowLogic } from './workflowLogic'import type { workflowMetricsSummaryLogicType } from './workflowMetricsSummaryLogicType'-export type WorkflowSummaryMetric = 'started' | 'in_progress' | 'persons_messaged' | 'completed'+// Each conversion is emitted as a `$workflows_conversion` PostHog event carrying `$workflow_id`, so+// "View converted users" deep-links to the events explorer scoped to this workflow and date range.+const CONVERSION_EVENT = '$workflows_conversion'++// The run-level "succeeded" metric is emitted once per run that finishes successfully, with an+// empty instance_id — for ANY terminal path, including early exits (e.g. exiting on conversion).+// Filtering on it (rather than the exit node's succeeded) makes "Completed" count converted /+// early-exited runs too, and keeps "In progress" from treating those finished runs as still live.+const RUN_LEVEL_INSTANCE_ID = ''++export type WorkflowSummaryMetric = 'started' | 'in_progress' | 'persons_messaged' | 'completed' | 'converted'export type EmailMetric =| 'email_sent'| 'email_delivered'@@ -65,10 +81,17 @@ export const WORKFLOW_SUMMARY_METRICS: Record<completed: {name: 'Completed',description:- 'Total number of workflow runs completed. This may include runs that began before the selected date range but completed within it.',+ 'Total number of workflow runs that finished — whether they reached the end of the workflow or exited early (for example, by meeting the conversion goal on an exit-on-conversion workflow). This may include runs that began before the selected date range but finished within it.',color: getColorVar('success'),metricNames: ['succeeded'],},+ converted: {+ name: 'Converted',+ description:+ 'Total number of conversions recorded for this workflow. A conversion is counted when a person matches the workflow’s conversion goal (property- or event-based), regardless of whether the workflow is set to exit on conversion.',+ color: getColorVar('purple'),+ metricNames: ['conversion'],+ },}export const WORKFLOW_EMAIL_METRICS: Record<@@ -166,21 +189,21 @@ export const workflowMetricsSummaryLogic = kea<workflowMetricsSummaryLogicType>('getDateRangeAbsolute',],appMetricsLogic({- logicKey: `workflow-exit-node-completed-${props.appSourceId ?? props.id}`,+ logicKey: `workflow-completed-${props.appSourceId ?? props.id}`,loadOnMount: true,loadOnChanges: true,forceParams: {appSource: 'hog_flow',appSourceId: props.appSourceId ?? props.id,- instanceId: EXIT_NODE_ID,+ instanceId: RUN_LEVEL_INSTANCE_ID,metricName: 'succeeded',breakdownBy: 'metric_name' as const,},}),[- 'appMetricsTrendsLoading as exitNodeCompletedLoading',- 'appMetricsTrends as exitNodeCompletedTrends',- 'getSingleTrendSeries as getExitNodeSingleTrendSeries',+ 'appMetricsTrendsLoading as completedLoading',+ 'appMetricsTrends as completedTrends',+ 'getSingleTrendSeries as getCompletedSingleTrendSeries',],],actions: [appMetricsLogic({ logicKey: props.logicKey }), ['setParams', 'loadAppMetricsTrendsSuccess']],@@ -208,6 +231,37 @@ export const workflowMetricsSummaryLogic = kea<workflowMetricsSummaryLogicType>(},},],+ conversionStats: [+ { conversions: 0, started: 0 } as {+ conversions: number+ started: number+ },+ {+ loadConversionStats: async (_, breakpoint) => {+ await breakpoint(10)+ const timezone = values.currentTeam?.timezone ?? 'UTC'+ const dateRange = values.getDateRangeAbsolute()+ const baseRequest: AppMetricsTotalsRequest = {+ appSource: values.params.appSource,+ appSourceId: values.params.appSourceId,+ breakdownBy: ['metric_name'],+ dateFrom: dateRange.dateFrom.toISOString(),+ dateTo: dateRange.dateTo.toISOString(),+ metricName: ['conversion'],+ }+ // The two totals have no data dependency, so fetch them in parallel.+ const [conversionResponse, startedResponse] = await Promise.all([+ loadAppMetricsTotals(baseRequest, timezone),+ loadAppMetricsTotals({ ...baseRequest, metricName: ['triggered'] }, timezone),+ ])+ await breakpoint(10)++ const conversions = Object.values(conversionResponse).reduce((sum, r) => sum + r.total, 0)+ const started = Object.values(startedResponse).reduce((sum, r) => sum + r.total, 0)+ return { conversions, started }+ },+ },+ ],inProgressTotal: [0,{@@ -226,12 +280,12 @@ export const workflowMetricsSummaryLogic = kea<workflowMetricsSummaryLogicType>(const triggeredResponse = await loadAppMetricsTotals(request, timezone)await breakpoint(10)- const exitRequest: AppMetricsTotalsRequest = {+ const completedRequest: AppMetricsTotalsRequest = {...request,- instanceId: EXIT_NODE_ID,+ instanceId: RUN_LEVEL_INSTANCE_ID,metricName: ['succeeded'],}- const completedResponse = await loadAppMetricsTotals(exitRequest, timezone)+ const completedResponse = await loadAppMetricsTotals(completedRequest, timezone)await breakpoint(10)const triggered = Object.values(triggeredResponse).reduce((sum, r) => sum + r.total, 0)@@ -243,9 +297,9 @@ export const workflowMetricsSummaryLogic = kea<workflowMetricsSummaryLogicType>(})),selectors({loading: [- (s) => [s.appMetricsTrendsLoading, s.exitNodeCompletedLoading],- (appMetricsTrendsLoading: boolean, exitNodeCompletedLoading: boolean) =>- appMetricsTrendsLoading || exitNodeCompletedLoading,+ (s) => [s.appMetricsTrendsLoading, s.completedLoading],+ (appMetricsTrendsLoading: boolean, completedLoading: boolean) =>+ appMetricsTrendsLoading || completedLoading,],emailActions: [(s) => [s.workflow], (workflow) => workflow.actions.filter(isEmailAction)],@@ -267,6 +321,55 @@ export const workflowMetricsSummaryLogic = kea<workflowMetricsSummaryLogicType>(],summaryMetricKeys: [() => [], (): WorkflowSummaryMetric[] => SUMMARY_METRIC_KEYS],++ conversionRate: [+ (s) => [s.conversionStats],+ ({ conversions, started }): number => (started > 0 ? conversions / started : 0),+ ],++ // Only surface the conversion tiles when a goal is actually configured — without one the+ // backend never emits conversion metrics/events, so the tiles would always read empty.+ hasConversionGoal: [+ (s) => [s.workflow],+ (workflow): boolean => {+ const filters = workflow.conversion?.filters+ const hasPropertyGoal = Array.isArray(filters) && filters.length > 0+ const hasEventGoal = (workflow.conversion?.events?.length ?? 0) > 0+ return hasPropertyGoal || hasEventGoal+ },+ ],++ convertedUsersUrl: [+ (s) => [s.getDateRangeAbsolute, (_, p: WorkflowMetricsSummaryLogicProps) => p.id],+ (getDateRangeAbsolute, id): string => {+ const { dateFrom, dateTo } = getDateRangeAbsolute()+ const source: EventsQuery = {+ kind: NodeKind.EventsQuery,+ select: defaultDataTableColumns(NodeKind.EventsQuery),+ orderBy: ['timestamp DESC'],+ event: CONVERSION_EVENT,+ after: dateFrom.toISOString(),+ before: dateTo.toISOString(),+ properties: [+ {+ type: PropertyFilterType.Event,+ key: '$workflow_id',+ operator: PropertyOperator.Exact,+ value: id,+ },+ ],+ }+ const query: DataTableNode = {+ kind: NodeKind.DataTableNode,+ full: true,+ source,+ propertiesViaUrl: true,+ showSavedQueries: true,+ showPersistentColumnConfigurator: true,+ }+ return combineUrl(urls.activity(ActivityTab.ExploreEvents), {}, { q: query }).url+ },+ ],}),// Separate block so these selectors can reference emailActions and metricNameBySummaryMetric via `s`@@ -274,23 +377,23 @@ export const workflowMetricsSummaryLogic = kea<workflowMetricsSummaryLogicType>(workflowSummaryTrends: [(s) => [s.appMetricsTrends,- s.exitNodeCompletedTrends,+ s.completedTrends,s.metricNameBySummaryMetric,- s.getExitNodeSingleTrendSeries,+ s.getCompletedSingleTrendSeries,],(appMetricsTrends,- exitNodeCompletedTrends,+ completedTrends,metricNameBySummaryMetric,- getExitNodeSingleTrendSeries+ getCompletedSingleTrendSeries): AppMetricsTimeSeriesResponse | null => {- if (!appMetricsTrends && !exitNodeCompletedTrends) {+ if (!appMetricsTrends && !completedTrends) {return null}- const labels = appMetricsTrends?.labels ?? exitNodeCompletedTrends?.labels ?? []+ const labels = appMetricsTrends?.labels ?? completedTrends?.labels ?? []const completedValues =- getExitNodeSingleTrendSeries('succeeded')?.series[0]?.values ??+ getCompletedSingleTrendSeries('succeeded')?.series[0]?.values ??Array.from({ length: labels.length }, () => 0)return {@@ -341,20 +444,22 @@ export const workflowMetricsSummaryLogic = kea<workflowMetricsSummaryLogicType>(afterMount(({ actions }) => {actions.loadEmailTotals({})actions.loadInProgressTotal({})+ actions.loadConversionStats({})}),listeners(({ actions, values, props }) => ({setParams: () => {- // Sync date/interval params to the exit node logic- const exitNodeLogic = appMetricsLogic({- logicKey: `workflow-exit-node-completed-${props.appSourceId ?? props.id}`,+ // Sync date/interval params to the completed (run-level succeeded) logic+ const completedLogic = appMetricsLogic({+ logicKey: `workflow-completed-${props.appSourceId ?? props.id}`,})- exitNodeLogic.actions.setParams({+ completedLogic.actions.setParams({interval: values.params.interval,dateFrom: values.params.dateFrom,dateTo: values.params.dateTo,})actions.loadEmailTotals({})+ actions.loadConversionStats({})},})),])