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.

fix(cdp): Conversion match only wakes a workflow that exits on conversion (#63211)

Daniel Marchuk45a4a2ca7275
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 6b8e57b62310..366562e45879 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
@@ -493,9 +493,10 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {
expect(update!.params[0]).toEqual(['job-batch'])
})
- it('sets conversionMatched on top-level state when workflow conversion event fires', async () => {
+ it('sets conversionMatched and wakes the job when an exit_on_conversion goal fires', async () => {
const flow = makeHogFlow({
id: 'flow-1',
+ exit_condition: 'exit_on_conversion',
conversion: {
events: [
{
@@ -528,6 +529,46 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {
expect(newState.state.conversionMatched).toBe(true)
})
+ 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.
+ const flow = makeHogFlow({
+ id: 'flow-1',
+ 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)
+ // Event matches the conversion goal but not the wait step, so the only thing that could
+ // wake the job is the conversion — which must be suppressed for exit_only_at_end.
+ 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({ currentAction: { id: 'wait_node' } }) }]
+ 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()
+ })
+
it('does not wake on an empty conversion "events" entry (always-true bytecode)', async () => {
// A conversion entry that targets neither events nor actions compiles to always-true
// bytecode and would otherwise mark every incoming event as a conversion.
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 50365ef2e2fa..a6255da1ebbb 100644
--- a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts
@@ -199,7 +199,12 @@ export class CdpHogflowSubscriptionMatcherConsumer<
}
}
- if (stepMatched || conversionMatched) {
+ // 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({
id: candidate.id,
stepMatched,
@@ -467,14 +472,24 @@ function hasEventOrActionTarget(eventConfig: { filters?: { events?: unknown[]; a
return Boolean(eventConfig.filters?.events?.length || eventConfig.filters?.actions?.length)
}
-// Skip teams whose hogflows have no wait_until_condition step and no event-based
-// conversion goal — nothing for the matcher to evaluate against.
+// Whether a workflow exits when its conversion goal is met. Only then does the matcher wake a
+// parked job on a conversion match (so it can exit early); otherwise the conversion goal is
+// measurement-only and must not perturb the job's progression.
+function exitsOnConversion(hogflow: HogFlow): boolean {
+ return (
+ hogflow.exit_condition === 'exit_on_conversion' ||
+ hogflow.exit_condition === 'exit_on_trigger_not_matched_or_conversion'
+ )
+}
+
+// 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.
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
+ return Array.isArray(conversionEvents) && conversionEvents.length > 0 && exitsOnConversion(hogflow)
}
// Single pass over the batch: dedup distinct/person ids, collect team ids,
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
index 02940d66c040..3ddc9134c19f 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
@@ -284,6 +284,15 @@ export class HogFlowExecutorService {
)
}
}
+ // 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
+ // conversion event just fired"), so consume it: clear it after reading so a later, unrelated
+ // resume (e.g. after a subsequent delay) can't re-trigger an exit from a stale flag.
+ if (invocation.state.conversionMatched) {
+ conversionMatch = true
+ invocation.state.conversionMatched = false
+ }
switch (hogFlow.exit_condition) {
case 'exit_on_trigger_not_matched':
diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.ts
index a2c03a580f9a..b74fa6d9082d 100644
--- a/nodejs/src/cdp/workflows-e2e.test.ts
+++ b/nodejs/src/cdp/workflows-e2e.test.ts
@@ -216,12 +216,18 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)
/** Same as createWorkflow but returns the full HogFlow object (useful for hand-built invocations) */
async function createWorkflowFlow(
workflow: Parameters<FixtureHogFlowBuilder['withWorkflow']>[0],
- opts?: { name?: string }
+ opts?: { name?: string; conversion?: HogFlow['conversion']; exitCondition?: HogFlow['exit_condition'] }
): Promise<HogFlow> {
const builder = new FixtureHogFlowBuilder().withTeamId(team.id).withStatus('active').withWorkflow(workflow)
if (opts?.name) {
builder.withName(opts.name)
}
+ if (opts?.conversion) {
+ builder.withConversion(opts.conversion)
+ }
+ if (opts?.exitCondition) {
+ builder.withExitCondition(opts.exitCondition)
+ }
const flow = builder.build()
await insertHogFlow(hub.postgres, flow)
return flow
@@ -828,6 +834,88 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)
}, 10000)
expect(mockFetch).toHaveBeenCalledWith('https://example.com/condition-matched', expect.anything())
})
+
+ it('does not run the next step early when a conversion event fires during a delay', async () => {
+ // trigger -> delay -> fetch, with an event-based conversion goal used only for
+ // measurement (exit_only_at_end). A conversion event arriving while the job is parked
+ // in the delay must NOT wake it and run the fetch ~5 minutes early.
+ 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()
+
+ // The conversion event fires during the delay — it must not pull the job out early.
+ await matcher.processBatch([createGlobals({ event: 'conversion_event' })])
+
+ // Give the worker room to (incorrectly) resume the job — it must stay parked, no fetch.
+ await new Promise((resolve) => setTimeout(resolve, 1000))
+ const jobs = await queryCyclotronJobs()
+ expect(jobs.every((j: any) => j.status === 'available' && new Date(j.scheduled) > new Date())).toBe(true)
+ expect(mockFetch).not.toHaveBeenCalled()
+ })
+
+ it('exits the workflow when an exit_on_conversion goal fires during a delay', async () => {
+ // Same shape, but the workflow exits on conversion. The conversion event during the delay
+ // SHOULD resume the job — to exit it early — but must still not run the next step (fetch).
+ 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_on_conversion',
+ conversion: {
+ window_minutes: 60,
+ filters: [],
+ bytecode: [],
+ events: [eventNameFilter('conversion_event')],
+ } as any,
+ }
+ )
+ await triggerWorkflow(createGlobals())
+ await expectParked()
+
+ // The conversion event fires during the delay — the workflow must exit early.
+ await matcher.processBatch([createGlobals({ event: 'conversion_event' })])
+
+ await waitForExpect(async () => {
+ const jobs = await queryCyclotronJobs()
+ expect(jobs.some((j: any) => ['completed', 'failed', 'canceled'].includes(j.status))).toBe(true)
+ }, 10000)
+ // Exited on conversion — the after-delay step never ran.
+ expect(mockFetch).not.toHaveBeenCalled()
+ })
})
describe('wait_until_time_window: window in the future', () => {