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(cdp): Add hogflow subscription matcher consumer (#57847)

Daniel Marchuk41c3a2014a7a
diff --git a/nodejs/src/capabilities.ts b/nodejs/src/capabilities.ts
index 26662c32a08a..13c2d9ced0f2 100644
--- a/nodejs/src/capabilities.ts
+++ b/nodejs/src/capabilities.ts
@@ -27,6 +27,7 @@ export const CAPABILITIES_CDP_WORKFLOWS: PluginServerCapabilities = {
cdpCyclotronWorkerHogFlow: true,
cdpCyclotronV2Janitor: isDevEnv(),
cdpHogflowScheduler: isDevEnv(),
+ cdpHogflowSubscriptionMatcher: isDevEnv(),
}
/** Realtime Cohorts - precalculated filters and cohort membership */
@@ -133,6 +134,10 @@ export function getPluginServerCapabilities(
return {
cdpPrecalculatedFilters: true,
}
+ case PluginServerMode.cdp_hogflow_subscription_matcher:
+ return {
+ cdpHogflowSubscriptionMatcher: true,
+ }
case PluginServerMode.cdp_cohort_membership:
return {
cdpCohortMembership: true,
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
new file mode 100644
index 000000000000..87b9981df07a
--- /dev/null
+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts
@@ -0,0 +1,781 @@
+import { HogFlow } from '../../schema/hogflow'
+import { parseJSON } from '../../utils/json-parse'
+import { logger } from '../../utils/logger'
+import * as posthogUtils from '../../utils/posthog'
+import { HogFunctionInvocationGlobals } from '../types'
+import * as hogExec from '../utils/hog-exec'
+import { CdpHogflowSubscriptionMatcherConsumer } from './cdp-hogflow-subscription-matcher.consumer'
+
+jest.mock('./cdp-base.consumer', () => {
+ return {
+ CdpConsumerBase: class {
+ constructor() {}
+ async start(): Promise<void> {}
+ },
+ }
+})
+
+jest.mock('../../kafka/consumer', () => ({
+ createKafkaConsumer: jest.fn().mockReturnValue({}),
+}))
+
+jest.mock('pg', () => {
+ const Pool = jest.fn()
+ return { Pool }
+})
+
+type MockRow = {
+ id: string
+ team_id: number
+ function_id: string
+ action_id: string | null
+ distinct_id: string | null
+ person_id: string | null
+ state?: Buffer | null
+}
+
+const eventBytecode = (eventName: string): any[] => ['_H', 1, 32, eventName, 32, 'event', 1, 1, 11]
+
+const makeHogFlow = (overrides: Partial<HogFlow> & { id: string; waitUntil?: boolean }): HogFlow => {
+ const { id, team_id, waitUntil = true, ...rest } = overrides
+ const waitAction = {
+ id: 'wait_node',
+ name: 'Wait',
+ type: 'wait_until_condition',
+ config: {
+ events: [
+ {
+ filters: {
+ bytecode: eventBytecode('wuc_subscribed'),
+ events: [{ id: 'wuc_subscribed', name: 'wuc_subscribed', type: 'events', order: 0 }],
+ },
+ },
+ ],
+ condition: { filters: null },
+ max_wait_duration: '5m',
+ },
+ }
+ return {
+ id,
+ team_id: team_id ?? 1,
+ version: 1,
+ status: 'active',
+ actions: [
+ {
+ id: 'trigger_node',
+ name: 'Trigger',
+ type: 'trigger',
+ config: { type: 'event', filters: {} },
+ },
+ ...(waitUntil ? [waitAction] : []),
+ { id: 'exit_node', name: 'Exit', type: 'exit', config: {} },
+ ],
+ edges: [],
+ conversion: null,
+ ...rest,
+ } as unknown as HogFlow
+}
+
+const makeGlobals = (overrides: Partial<HogFunctionInvocationGlobals>): HogFunctionInvocationGlobals =>
+ ({
+ project: { id: 1, name: 'Test', url: '' },
+ event: {
+ uuid: 'event-uuid',
+ event: 'wuc_subscribed',
+ distinct_id: 'user-1',
+ properties: {},
+ elements_chain: '',
+ timestamp: new Date().toISOString(),
+ url: '',
+ },
+ person: { id: 'person-uuid-1', properties: {}, name: 'User 1', url: '' },
+ ...overrides,
+ }) as HogFunctionInvocationGlobals
+
+interface QueryCall {
+ sql: string
+ params: any[]
+}
+
+class MatcherUnderTest extends CdpHogflowSubscriptionMatcherConsumer {
+ public calls: QueryCall[] = []
+ public findRows: MockRow[] = []
+ public wakeRows: MockRow[] = []
+ public updateRowCount = 0
+
+ constructor() {
+ // Non-empty URL satisfies the constructor's fail-fast guard; the real Pool (mocked
+ // via jest.mock('pg')) is immediately replaced below with a fixture-dispatching fake.
+ super({ CYCLOTRON_NODE_DATABASE_URL: 'postgres://test' } as any, {} as any)
+ // Wire a fake pool that dispatches queries to predefined fixtures.
+ const dispatch = (sql: string, params: any[]): Promise<{ rows: any[]; rowCount: number }> => {
+ if (sql === 'BEGIN' || sql === 'COMMIT' || sql === 'ROLLBACK') {
+ return Promise.resolve({ rows: [], rowCount: 0 })
+ }
+ this.calls.push({ sql, params })
+ if (sql.includes('SELECT id, team_id, function_id')) {
+ return Promise.resolve({ rows: this.findRows, rowCount: this.findRows.length })
+ }
+ if (sql.includes('SELECT id, state FROM cyclotron_jobs')) {
+ return Promise.resolve({ rows: this.wakeRows, rowCount: this.wakeRows.length })
+ }
+ if (sql.startsWith('UPDATE cyclotron_jobs')) {
+ return Promise.resolve({ rows: [], rowCount: this.updateRowCount })
+ }
+ return Promise.resolve({ rows: [], rowCount: 0 })
+ }
+ ;(this as any).cyclotronPool = {
+ query: jest.fn((sql: string, params: any[]) => dispatch(sql, params)),
+ connect: jest.fn(() =>
+ Promise.resolve({
+ query: jest.fn((sql: string, params: any[]) => dispatch(sql, params)),
+ release: jest.fn(),
+ })
+ ),
+ }
+ // Stub hogFlowManager
+ ;(this as any).hogFlowManager = {
+ getHogFlowsForTeams: jest.fn().mockResolvedValue({}),
+ getHogFlowsForTeam: jest.fn().mockResolvedValue([]),
+ }
+ }
+
+ public setHogFlows(map: Record<string, HogFlow>): void {
+ const byTeam: Record<number, HogFlow[]> = {}
+ for (const flow of Object.values(map)) {
+ byTeam[flow.team_id] = byTeam[flow.team_id] ?? []
+ byTeam[flow.team_id].push(flow)
+ }
+ ;(this as any).hogFlowManager.getHogFlowsForTeams.mockResolvedValue(byTeam)
+ ;(this as any).hogFlowManager.getHogFlowsForTeam.mockImplementation((teamId: number) =>
+ Promise.resolve(byTeam[teamId] ?? [])
+ )
+ }
+
+ public async runWake(invocationGlobals: HogFunctionInvocationGlobals[]): Promise<void> {
+ await (this as any).wakeMatchingWorkflows(invocationGlobals)
+ }
+}
+
+const stateBuffer = (state: any): Buffer => Buffer.from(JSON.stringify({ state }))
+
+describe('CdpHogflowSubscriptionMatcherConsumer', () => {
+ let matcher: MatcherUnderTest
+
+ beforeEach(() => {
+ matcher = new MatcherUnderTest()
+ })
+
+ describe('wakeMatchingWorkflows', () => {
+ it('is a no-op when no events have person_id', async () => {
+ await matcher.runWake([
+ makeGlobals({ person: undefined as any, event: { ...makeGlobals({}).event, distinct_id: '' } }),
+ ])
+ expect(matcher.calls).toHaveLength(0)
+ })
+
+ it('passes both distinct_ids and person_ids to the lookup query', async () => {
+ // Need a qualifying hogflow on the team or the team-level early-out skips findParkedJobs.
+ matcher.setHogFlows({ 'flow-1': makeHogFlow({ id: 'flow-1' }) })
+ await matcher.runWake([
+ makeGlobals({}),
+ makeGlobals({
+ event: { ...makeGlobals({}).event, distinct_id: 'user-2', uuid: 'e2' },
+ person: { id: 'person-uuid-2', properties: {}, name: '', url: '' },
+ }),
+ ])
+ const lookup = matcher.calls.find((c) => c.sql.includes('SELECT id, team_id, function_id'))!
+ expect(lookup).not.toBeUndefined()
+ // Params are correlated (team, id) pairs: distinctTeamIds/distinctIds zip row-wise,
+ // and personTeamIds/personIds zip row-wise. Both events are team 1.
+ expect(lookup.params[0]).toEqual([1, 1]) // distinctTeamIds
+ expect(lookup.params[1]).toEqual(['user-1', 'user-2']) // distinctIds
+ expect(lookup.params[2]).toEqual([1, 1]) // personTeamIds
+ expect(lookup.params[3]).toEqual(['person-uuid-1', 'person-uuid-2']) // personIds
+ expect(lookup.params[4]).toEqual(['flow-1']) // functionIds
+ })
+
+ it('correlates team_id with distinct_id so a cross-team pairing is never queried or woken', async () => {
+ // Bug scenario: event A is (team 1, alice), event B is (team 2, bob). A naive
+ // `team_id = ANY([1,2]) AND distinct_id = ANY([alice,bob])` query would also match
+ // a parked job at (team 1, bob) — a team/id combination that no event in the batch
+ // actually carried. The lookup must only ever ask for (team 1, alice) and (team 2, bob).
+ matcher.setHogFlows({
+ 'flow-1': makeHogFlow({ id: 'flow-1', team_id: 1 }),
+ 'flow-2': makeHogFlow({ id: 'flow-2', team_id: 2 }),
+ })
+
+ // Pretend the DB still returned the cross-team false positive (team 1, bob). The
+ // in-memory guard must reject it because no batch event was for (team 1, bob).
+ matcher.findRows = [
+ {
+ id: 'job-cross',
+ team_id: 1,
+ function_id: 'flow-1',
+ action_id: 'wait_node',
+ distinct_id: 'bob',
+ person_id: null,
+ },
+ ]
+ matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer({ currentAction: { id: 'wait_node' } }) }]
+ matcher.updateRowCount = 1
+
+ await matcher.runWake([
+ makeGlobals({
+ project: { id: 1, name: 'T1', url: '' },
+ event: { ...makeGlobals({}).event, distinct_id: 'alice', uuid: 'e1' },
+ person: undefined,
+ }),
+ makeGlobals({
+ project: { id: 2, name: 'T2', url: '' },
+ event: { ...makeGlobals({}).event, distinct_id: 'bob', uuid: 'e2' },
+ person: undefined,
+ }),
+ ])
+
+ // The correlated lookup params zip (team, distinct_id) row-wise: {(1,alice),(2,bob)}.
+ // (1,bob) must not appear — that's the cross-team combination that doesn't exist.
+ const lookup = matcher.calls.find((c) => c.sql.includes('SELECT id, team_id, function_id'))!
+ expect(lookup).not.toBeUndefined()
+ const pairs = lookup.params[0].map((teamId: number, i: number) => `${teamId}:${lookup.params[1][i]}`)
+ expect(pairs).toEqual(['1:alice', '2:bob'])
+ expect(pairs).not.toContain('1:bob')
+ // And the query is genuinely correlated (tuple form), not independent ANY/ANY.
+ expect(lookup.sql).toContain('(team_id, distinct_id) IN (SELECT * FROM unnest($1::int[], $2::text[]))')
+
+ // The stray cross-team candidate is filtered in-memory → no job is woken.
+ const update = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))
+ expect(update).toBeUndefined()
+ })
+
+ it('scopes the lookup to qualifying flows, excluding non-wait flows on the same team', async () => {
+ matcher.setHogFlows({
+ 'flow-1': makeHogFlow({ id: 'flow-1' }),
+ 'flow-2': makeHogFlow({ id: 'flow-2', waitUntil: false }),
+ })
+ await matcher.runWake([makeGlobals({})])
+ const lookup = matcher.calls.find((c) => c.sql.includes('SELECT id, team_id, function_id'))!
+ expect(lookup).not.toBeUndefined()
+ expect(lookup.params[4]).toEqual(['flow-1'])
+ })
+
+ it('skips cyclotron entirely when no team in the batch has a wait_until_condition or conversion goal', async () => {
+ // Default: no hogflows configured → team has nothing the matcher could wake.
+ // The cyclotron lookup must NOT fire.
+ await matcher.runWake([makeGlobals({})])
+ expect(matcher.calls.find((c) => c.sql.includes('SELECT id, team_id, function_id'))).toBeUndefined()
+ })
+
+ it('wakes when the matching event is not the first event in the batch for a distinct_id', async () => {
+ // Two events for the same user in one batch. The first does not match the
+ // wait condition; the second does. The matcher must evaluate both, not just
+ // the first one it indexed.
+ matcher.findRows = [
+ {
+ id: 'job-1',
+ 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': makeHogFlow({ id: 'flow-1' }) })
+
+ await matcher.runWake([
+ makeGlobals({ event: { ...makeGlobals({}).event, event: 'random_event', uuid: 'e1' } }),
+ makeGlobals({ event: { ...makeGlobals({}).event, event: 'wuc_subscribed', uuid: 'e2' } }),
+ ])
+
+ const update = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))
+ expect(update).not.toBeUndefined()
+ expect(update!.params[0]).toEqual(['job-1'])
+ })
+
+ it('wakes a job matched by distinct_id (event-triggered scenario)', async () => {
+ matcher.findRows = [
+ {
+ id: 'job-1',
+ 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': makeHogFlow({ id: 'flow-1' }) })
+
+ await matcher.runWake([makeGlobals({})])
+
+ const update = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))
+ expect(update).not.toBeUndefined()
+ expect(update!.params[0]).toEqual(['job-1'])
+ const newState = parseJSON(update!.params[1][0].toString('utf-8')) as any
+ expect(newState.state.currentAction.eventMatched).toBe(true)
+ // The matching event's name and UUID are persisted so the executor log and the
+ // logs view can pinpoint exactly which event woke the step.
+ expect(newState.state.currentAction.eventMatchedEvent).toBe('wuc_subscribed')
+ expect(newState.state.currentAction.eventMatchedEventUuid).toBe('event-uuid')
+ expect(newState.state.conversionMatched).toBeUndefined()
+ })
+
+ it('logs the hogflow id alongside the action id when wait-step bytecode evaluation throws', async () => {
+ const errorSpy = jest.spyOn(logger, 'error').mockReturnValue(undefined as any)
+ const execSpy = jest.spyOn(hogExec, 'execHog').mockRejectedValue(new Error('boom'))
+ const captureSpy = jest.spyOn(posthogUtils, 'captureException').mockReturnValue(undefined as any)
+
+ try {
+ matcher.findRows = [
+ {
+ id: 'job-1',
+ team_id: 1,
+ function_id: 'flow-1',
+ action_id: 'wait_node',
+ distinct_id: 'user-1',
+ person_id: null,
+ },
+ ]
+ matcher.setHogFlows({ 'flow-1': makeHogFlow({ id: 'flow-1' }) })
+ await matcher.runWake([makeGlobals({})])
+
+ const errorCall = errorSpy.mock.calls.find((c) => c[1] === 'Bytecode evaluation error')
+ expect(errorCall).toBeDefined()
+ expect(errorCall![2]).toMatchObject({ hogFlowId: 'flow-1', actionId: 'wait_node' })
+ expect(captureSpy).toHaveBeenCalledWith(expect.any(Error), {
+ extra: { hogFlowId: 'flow-1', actionId: 'wait_node' },
+ })
+ } finally {
+ errorSpy.mockRestore()
+ execSpy.mockRestore()
+ captureSpy.mockRestore()
+ }
+ })
+
+ it('does not wake when the wait step has events without bytecode (fail-closed)', async () => {
+ // HogFlowSerializer compiles bytecode at save time; a row that reaches the
+ // matcher without bytecode is malformed and must not fall back to event-name
+ // matching, which would silently bypass property filters.
+ matcher.findRows = [
+ {
+ id: 'job-1',
+ 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
+ const flow = makeHogFlow({ id: 'flow-1' })
+ ;(flow.actions as any[])[1].config.events[0].filters.bytecode = []
+ matcher.setHogFlows({ 'flow-1': flow })
+
+ await matcher.runWake([makeGlobals({})])
+
+ const update = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))
+ expect(update).toBeUndefined()
+ })
+
+ it('skips waking a matched job whose state has no currentAction', async () => {
+ matcher.findRows = [
+ {
+ id: 'job-1',
+ team_id: 1,
+ function_id: 'flow-1',
+ action_id: 'wait_node',
+ distinct_id: 'user-1',
+ person_id: null,
+ },
+ ]
+ // State is missing currentAction, so the matcher cannot tag the wake as an
+ // event match. It must skip the job rather than misclassify it as a timeout.
+ matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer({}) }]
+ matcher.updateRowCount = 1
+ matcher.setHogFlows({ 'flow-1': makeHogFlow({ id: 'flow-1' }) })
+
+ await matcher.runWake([makeGlobals({})])
+
+ const update = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))
+ expect(update).toBeUndefined()
+ })
+
+ it('still wakes a job for a conversion match when stepMatched lacks currentAction', async () => {
+ matcher.findRows = [
+ {
+ id: 'job-1',
+ team_id: 1,
+ function_id: 'flow-1',
+ action_id: 'wait_node',
+ distinct_id: 'user-1',
+ person_id: null,
+ },
+ ]
+ // State missing currentAction: we cannot tag eventMatched, but the same incoming
+ // event also satisfies the workflow's conversion goal, which is independent of
+ // currentAction - that wake must still happen.
+ matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer({}) }]
+ matcher.updateRowCount = 1
+ matcher.setHogFlows({
+ 'flow-1': makeHogFlow({
+ id: 'flow-1',
+ conversion: {
+ window_minutes: null,
+ filters: {},
+ bytecode: [],
+ events: [
+ {
+ filters: {
+ events: [{ id: 'wuc_subscribed' }],
+ bytecode: eventBytecode('wuc_subscribed'),
+ },
+ },
+ ],
+ },
+ } as any),
+ })
+
+ await matcher.runWake([makeGlobals({})])
+
+ const update = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))
+ expect(update).not.toBeUndefined()
+ const newState = parseJSON(update!.params[1][0].toString('utf-8')) as any
+ expect(newState.state.conversionMatched).toBe(true)
+ // currentAction is missing in input state, so eventMatched must not have been set
+ expect(newState.state.currentAction).toBeUndefined()
+ })
+
+ it('wakes a job matched by person_id (batch-triggered scenario, distinct_id mismatch)', async () => {
+ matcher.findRows = [
+ {
+ id: 'job-batch',
+ team_id: 1,
+ function_id: 'flow-1',
+ action_id: 'wait_node',
+ distinct_id: null,
+ person_id: 'person-uuid-1',
+ },
+ ]
+ matcher.wakeRows = [
+ {
+ ...matcher.findRows[0],
+ state: stateBuffer({ currentAction: { id: 'wait_node' }, personId: 'person-uuid-1' }),
+ },
+ ]
+ matcher.updateRowCount = 1
+ matcher.setHogFlows({ 'flow-1': makeHogFlow({ id: 'flow-1' }) })
+
+ await matcher.runWake([
+ makeGlobals({
+ event: { ...makeGlobals({}).event, distinct_id: 'fresh-distinct-id' },
+ person: { id: 'person-uuid-1', properties: {}, name: '', url: '' },
+ }),
+ ])
+
+ const update = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))
+ expect(update).not.toBeUndefined()
+ expect(update!.params[0]).toEqual(['job-batch'])
+ })
+
+ it('sets conversionMatched on top-level state when workflow conversion event fires', async () => {
+ const flow = makeHogFlow({
+ id: 'flow-1',
+ 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({ 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'))
+ const newState = parseJSON(update!.params[1][0].toString('utf-8')) as any
+ expect(newState.state.conversionMatched).toBe(true)
+ })
+
+ it('does not wake when neither step filter nor conversion matches', async () => {
+ matcher.findRows = [
+ {
+ id: 'job-1',
+ team_id: 1,
+ function_id: 'flow-1',
+ action_id: 'wait_node',
+ distinct_id: 'user-1',
+ person_id: null,
+ },
+ ]
+ matcher.setHogFlows({ 'flow-1': makeHogFlow({ id: 'flow-1' }) })
+
+ // Event name doesn't match wuc_subscribed (waiter event) nor any conversion
+ await matcher.runWake([makeGlobals({ event: { ...makeGlobals({}).event, event: 'unrelated_event' } })])
+
+ const update = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))
+ expect(update).toBeUndefined()
+ })
+
+ it('skips candidates whose hogflow is not in cache', async () => {
+ matcher.findRows = [
+ {
+ id: 'job-1',
+ team_id: 1,
+ function_id: 'unknown-flow',
+ action_id: 'wait_node',
+ distinct_id: 'user-1',
+ person_id: null,
+ },
+ ]
+ matcher.setHogFlows({})
+
+ await matcher.runWake([makeGlobals({})])
+
+ const update = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))
+ expect(update).toBeUndefined()
+ })
+
+ it('skips wait step that is not a wait_until_condition (and no conversion match)', async () => {
+ const flow = makeHogFlow({ id: 'flow-1' })
+ // Replace the wait node with a delay
+ ;(flow.actions as any[])[1] = { id: 'delay_node', name: 'Delay', type: 'delay', config: {} }
+ matcher.findRows = [
+ {
+ id: 'job-1',
+ team_id: 1,
+ function_id: 'flow-1',
+ action_id: 'delay_node',
+ distinct_id: 'user-1',
+ person_id: null,
+ },
+ ]
+ matcher.setHogFlows({ 'flow-1': flow })
+
+ await matcher.runWake([makeGlobals({})])
+
+ const update = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))
+ expect(update).toBeUndefined()
+ })
+
+ it('returns no candidates when lookup query returns empty', async () => {
+ // Team has a qualifying hogflow, so the team-level early-out doesn't fire and we
+ // do hit cyclotron — but the lookup itself returns no rows, so no UPDATE follows.
+ matcher.findRows = []
+ matcher.setHogFlows({ 'flow-1': makeHogFlow({ id: 'flow-1' }) })
+
+ await matcher.runWake([makeGlobals({})])
+
+ expect(matcher.calls.find((c) => c.sql.includes('SELECT id, team_id, function_id'))).not.toBeUndefined()
+ expect(matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))).toBeUndefined()
+ })
+
+ it('wakes only matching subset when multiple candidates returned', async () => {
+ matcher.findRows = [
+ {
+ id: 'job-match',
+ team_id: 1,
+ function_id: 'flow-1',
+ action_id: 'wait_node',
+ distinct_id: 'user-1',
+ person_id: null,
+ },
+ {
+ id: 'job-nomatch',
+ team_id: 1,
+ function_id: 'flow-no-match',
+ action_id: 'wait_node',
+ distinct_id: 'user-1',
+ person_id: null,
+ },
+ ]
+ matcher.wakeRows = [
+ {
+ id: 'job-match',
+ team_id: 1,
+ function_id: 'flow-1',
+ action_id: 'wait_node',
+ distinct_id: 'user-1',
+ person_id: null,
+ state: stateBuffer({ currentAction: { id: 'wait_node' } }),
+ },
+ ]
+ matcher.updateRowCount = 1
+
+ // flow-no-match waits on a different event name
+ const noMatchFlow = makeHogFlow({ id: 'flow-no-match' })
+ ;(noMatchFlow.actions as any[])[1].config.events[0].filters.bytecode = eventBytecode('something_else')
+ ;(noMatchFlow.actions as any[])[1].config.events[0].filters.events[0].id = 'something_else'
+ ;(noMatchFlow.actions as any[])[1].config.events[0].filters.events[0].name = 'something_else'
+
+ matcher.setHogFlows({
+ 'flow-1': makeHogFlow({ id: 'flow-1' }),
+ 'flow-no-match': noMatchFlow,
+ })
+
+ await matcher.runWake([makeGlobals({})])
+
+ const update = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))
+ expect(update).not.toBeUndefined()
+ expect(update!.params[0]).toEqual(['job-match'])
+ })
+
+ it('propagates processBatch failures through backgroundTask (no swallow)', async () => {
+ // Kafka offsets must not advance past a batch we couldn't match. Otherwise a
+ // transient cyclotron failure silently misses wakeups. The consumer-v2 fatalError
+ // gate then crashes the pod and replays — the SELECT is read-only and the UPDATE
+ // is guarded by `status = 'available'`, so replay is idempotent.
+ const failure = new Error('connection refused')
+ // Need a qualifying hogflow so the team-level early-out doesn't skip the cyclotron
+ // call we want to see fail.
+ matcher.setHogFlows({ 'flow-1': makeHogFlow({ id: 'flow-1' }) })
+ ;(matcher as any).cyclotronPool.query = jest.fn().mockRejectedValue(failure)
+ ;(matcher as any)._parseKafkaBatch = jest.fn().mockResolvedValue([makeGlobals({})])
+
+ let capturedEachBatch: ((messages: any[]) => Promise<any>) | undefined
+ ;(matcher as any).kafkaConsumer = {
+ connect: jest.fn((cb: (messages: any[]) => Promise<any>) => {
+ capturedEachBatch = cb
+ return Promise.resolve()
+ }),
+ }
+
+ await matcher.start()
+ const result = await capturedEachBatch!([{ value: Buffer.from('{}') }])
+
+ await expect(result.backgroundTask).rejects.toBe(failure)
+ })
+
+ it('does not load state for non-matching candidates (projection-only lookup)', async () => {
+ // Two candidates returned, only one matches the wait filter.
+ matcher.findRows = [
+ {
+ id: 'job-match',
+ team_id: 1,
+ function_id: 'flow-1',
+ action_id: 'wait_node',
+ distinct_id: 'user-1',
+ person_id: null,
+ },
+ {
+ id: 'job-nomatch',
+ team_id: 1,
+ function_id: 'flow-no-match',
+ action_id: 'wait_node',
+ distinct_id: 'user-1',
+ person_id: null,
+ },
+ ]
+ matcher.wakeRows = [
+ {
+ id: 'job-match',
+ team_id: 1,
+ function_id: 'flow-1',
+ action_id: 'wait_node',
+ distinct_id: 'user-1',
+ person_id: null,
+ state: stateBuffer({ currentAction: { id: 'wait_node' } }),
+ },
+ ]
+ matcher.updateRowCount = 1
+
+ const noMatchFlow = makeHogFlow({ id: 'flow-no-match' })
+ ;(noMatchFlow.actions as any[])[1].config.events[0].filters.bytecode = eventBytecode('other')
+
+ matcher.setHogFlows({
+ 'flow-1': makeHogFlow({ id: 'flow-1' }),
+ 'flow-no-match': noMatchFlow,
+ })
+
+ await matcher.runWake([makeGlobals({})])
+
+ const stateLoad = matcher.calls.find((c) => c.sql.includes('SELECT id, state FROM cyclotron_jobs'))
+ expect(stateLoad).not.toBeUndefined()
+ // wakeJobs is called with only the matching id; SELECT id, state pulls only that
+ expect(stateLoad!.params[0]).toEqual(['job-match'])
+ })
+ })
+
+ describe('_parseKafkaBatch', () => {
+ const rawMessage = (overrides: Record<string, any>): any => ({
+ value: Buffer.from(
+ JSON.stringify({
+ uuid: 'e-uuid',
+ event: 'wuc_subscribed',
+ team_id: 1,
+ distinct_id: 'user-1',
+ person_id: 'person-uuid-1',
+ timestamp: '2024-01-01 00:00:00.000',
+ properties: '{}',
+ elements_chain: '',
+ ...overrides,
+ })
+ ),
+ })
+
+ beforeEach(() => {
+ ;(matcher as any).deps = {
+ teamManager: {
+ getTeam: jest.fn().mockResolvedValue({ id: 1, name: 'Test', person_display_name_properties: null }),
+ },
+ }
+ ;(matcher as any).config = { SITE_URL: 'http://localhost:8000' }
+ // Team 1 has an actionable (wait_until_condition) flow so events reach conversion.
+ matcher.setHogFlows({ 'flow-1': makeHogFlow({ id: 'flow-1', team_id: 1 }) })
+ })
+
+ it('keeps events with a distinct_id but no person_id, drops events with neither', async () => {
+ // A job can be parked by distinct_id alone (the lookup has a (team_id, distinct_id)
+ // branch), so an event carrying only a distinct_id must still flow into matching.
+ const result = await (matcher as any)._parseKafkaBatch([
+ rawMessage({ person_id: '', distinct_id: 'only-distinct' }),
+ rawMessage({ person_id: '', distinct_id: '' }),
+ rawMessage({ person_id: 'person-uuid-1', distinct_id: 'user-1' }),
+ ])
+
+ const distinctIds = result.map((g: HogFunctionInvocationGlobals) => g.event.distinct_id).sort()
+ expect(distinctIds).toEqual(['only-distinct', 'user-1'])
+
+ // The distinct-only event has no resolved person, which downstream indexing handles.
+ const distinctOnly = result.find(
+ (g: HogFunctionInvocationGlobals) => g.event.distinct_id === 'only-distinct'
+ )!
+ expect(distinctOnly.person).toBeUndefined()
+ })
+
+ it('skips events whose team has no actionable flow before paying for getTeam + conversion', async () => {
+ // Team 2 has no wait_until_condition step and no event conversion goal, so its events
+ // must be dropped via the in-memory cache without ever calling getTeam or converting.
+ const getTeam = (matcher as any).deps.teamManager.getTeam
+
+ const result = await (matcher as any)._parseKafkaBatch([
+ rawMessage({ team_id: 2, distinct_id: 'user-2' }),
+ rawMessage({ team_id: 1, distinct_id: 'user-1' }),
+ ])
+
+ expect(result.map((g: HogFunctionInvocationGlobals) => g.project.id)).toEqual([1])
+ // getTeam is only reached for the actionable team, never for team 2.
+ expect(getTeam).toHaveBeenCalledTimes(1)
+ expect(getTeam).toHaveBeenCalledWith(1)
+ })
+ })
+})
diff --git a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts
new file mode 100644
index 000000000000..f054bf49759e
--- /dev/null
+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts
@@ -0,0 +1,585 @@
+import { Message } from 'node-rdkafka'
+import { Pool } from 'pg'
+import { Counter, Histogram } from 'prom-client'
+
+import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'
+
+import { KAFKA_EVENTS_JSON } from '../../config/kafka-topics'
+import { KafkaConsumerInterface, createKafkaConsumer } from '../../kafka/consumer'
+import { HogFlow, HogFlowAction } from '../../schema/hogflow'
+import { HealthCheckResult, PluginsServerConfig, RawClickHouseEvent } from '../../types'
+import { parseJSON } from '../../utils/json-parse'
+import { logger } from '../../utils/logger'
+import { captureException } from '../../utils/posthog'
+import { HogFlowInvocationContext, HogFunctionInvocationGlobals } from '../types'
+import { convertToHogFunctionInvocationGlobals } from '../utils'
+import { execHog } from '../utils/hog-exec'
+import { convertToHogFunctionFilterGlobal } from '../utils/hog-function-filtering'
+import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'
+import { counterParseError } from './metrics'
+
+const counterHogflowMatcherBytecodeError = new Counter({
+ name: 'cdp_hogflow_matcher_bytecode_error',
+ help: 'A wait_until_condition or conversion-goal filter threw during evaluation. Filter is treated as non-matching, so the workflow falls through to its timeout branch.',
+})
+
+const counterHogflowMatcherCandidatesEvaluated = new Counter({
+ name: 'cdp_hogflow_matcher_candidates_evaluated',
+ help: 'Parked hogflow jobs the matcher loaded from cyclotron and evaluated against a batch.',
+})
+
+const counterHogflowMatcherJobsWoken = new Counter({
+ name: 'cdp_hogflow_matcher_jobs_woken',
+ help: 'Parked hogflow jobs the matcher woke because an incoming event matched.',
+})
+
+// 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({
+ name: 'cdp_hogflow_matcher_find_parked_jobs_seconds',
+ help: 'Duration of the findParkedJobs cyclotron query.',
+ buckets: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5],
+})
+
+const counterHogflowMatcherEventSkipped = new Counter({
+ name: 'cdp_hogflow_matcher_event_skipped',
+ help: 'An incoming event was dropped before matching: no identifiers (distinct_id or person_id), or unknown team.',
+ labelNames: ['reason'],
+})
+
+type ParkedCandidate = {
+ id: string
+ teamId: number
+ functionId: string
+ actionId: string | null
+ distinctId: string | null
+ personId: string | null
+}
+
+type WakeRequest = {
+ id: string
+ stepMatched: boolean
+ conversionMatched: boolean
+ // Name and UUID of the event that matched, so the executor's resume log can surface the
+ // name and the logs view can link to the exact event.
+ eventName?: string
+ eventUuid?: string
+}
+
+type FilterGlobals = ReturnType<typeof convertToHogFunctionFilterGlobal>
+
+// Wakes parked hogflow jobs when an event matches a `wait_until_condition` step
+// or a workflow conversion goal.
+export class CdpHogflowSubscriptionMatcherConsumer<
+ TConfig extends PluginsServerConfig = PluginsServerConfig,
+> extends CdpConsumerBase<TConfig> {
+ protected name = 'CdpHogflowSubscriptionMatcherConsumer'
+ protected kafkaConsumer: KafkaConsumerInterface
+ private cyclotronPool: Pool
+
+ constructor(config: TConfig, deps: CdpConsumerBaseDeps) {
+ super(config, deps)
+ this.kafkaConsumer = createKafkaConsumer({
+ groupId: 'cdp-hogflow-subscription-matcher-consumer',
+ topic: KAFKA_EVENTS_JSON,
+ })
+
+ // The matcher does nothing but read/write cyclotron_jobs, so a missing connection
+ // string means it would silently consume the event stream and wake nothing. Fail
+ // loudly on startup instead of degrading into a healthy-looking no-op.
+ if (!config.CYCLOTRON_NODE_DATABASE_URL) {
+ throw new Error('CdpHogflowSubscriptionMatcherConsumer requires CYCLOTRON_NODE_DATABASE_URL')
+ }
+ this.cyclotronPool = new Pool({
+ connectionString: config.CYCLOTRON_NODE_DATABASE_URL,
+ max: config.CYCLOTRON_NODE_MAX_CONNECTIONS,
+ })
+ }
+
+ public async processBatch(invocationGlobals: HogFunctionInvocationGlobals[]): Promise<void> {
+ if (!invocationGlobals.length) {
+ return
+ }
+ await this.wakeMatchingWorkflows(invocationGlobals)
+ }
+
+ @instrumented('cdpHogflowSubscriptionMatcher.wakeMatchingWorkflows')
+ private async wakeMatchingWorkflows(invocationGlobals: HogFunctionInvocationGlobals[]): Promise<void> {
+ const { teamIds, distinctTeamIds, distinctIds, personTeamIds, personIds, byDistinctId, byPersonId } =
+ indexBatch(invocationGlobals)
+ if (byDistinctId.size === 0 && byPersonId.size === 0) {
+ return
+ }
+
+ // Build the set of actionable flows from the in-memory hogflow cache (same pattern as
+ // cdp-events). Only flows with a wait_until_condition step or an event-based conversion
+ // goal can ever be woken; scoping to them keeps the function_id list in findParkedJobs
+ // small and skips cyclotron entirely when a batch has none.
+ const hogFlowsByTeam = await this.hogFlowManager.getHogFlowsForTeams(teamIds)
+ const hogflows: Record<string, HogFlow> = {}
+ for (const flows of Object.values(hogFlowsByTeam)) {
+ for (const flow of flows) {
+ if (hasWaitUntilOrConversion(flow)) {
+ hogflows[flow.id] = flow
+ }
+ }
+ }
+
+ if (Object.keys(hogflows).length === 0) {
+ return
+ }
+
+ const candidates = await this.findParkedJobs(
+ distinctTeamIds,
+ distinctIds,
+ personTeamIds,
+ personIds,
+ Object.keys(hogflows)
+ )
+ if (candidates.length === 0) {
+ return
+ }
+ counterHogflowMatcherCandidatesEvaluated.inc(candidates.length)
+
+ // Compute filterGlobals once per event; the same event can match many candidates.
+ const filterGlobalsByEvent = new Map<HogFunctionInvocationGlobals, FilterGlobals>()
+ const filterGlobalsFor = (g: HogFunctionInvocationGlobals): FilterGlobals => {
+ let fg = filterGlobalsByEvent.get(g)
+ if (!fg) {
+ fg = convertToHogFunctionFilterGlobal(g)
+ filterGlobalsByEvent.set(g, fg)
+ }
+ return fg
+ }
+
+ const jobsToWake: WakeRequest[] = []
+ for (const candidate of candidates) {
+ const hogflow = hogflows[candidate.functionId]
+ if (!hogflow) {
+ continue
+ }
+
+ const candidateGlobals = collectCandidateGlobals(candidate, byDistinctId, byPersonId)
+ if (candidateGlobals.length === 0) {
+ continue
+ }
+
+ const action = candidate.actionId
+ ? hogflow.actions.find((a: HogFlowAction) => a.id === candidate.actionId)
+ : undefined
+
+ // Any single matching event is enough. Stop early once both flags are set.
+ let stepMatched = false
+ let stepMatchedEventName: string | undefined
+ let stepMatchedEventUuid: string | undefined
+ let conversionMatched = false
+ for (const globals of candidateGlobals) {
+ const filterGlobals = filterGlobalsFor(globals)
+ if (!stepMatched && action?.type === 'wait_until_condition') {
+ if (await this.evaluateWaitUntilCondition(action, filterGlobals, hogflow.id)) {
+ stepMatched = true
+ stepMatchedEventName = globals.event.event
+ stepMatchedEventUuid = globals.event.uuid
+ }
+ }
+ if (!conversionMatched) {
+ conversionMatched = await this.evaluateConversionEvents(hogflow, filterGlobals)
+ }
+ if (stepMatched && conversionMatched) {
+ break
+ }
+ }
+
+ if (stepMatched || conversionMatched) {
+ jobsToWake.push({
+ id: candidate.id,
+ stepMatched,
+ conversionMatched,
+ eventName: stepMatchedEventName,
+ eventUuid: stepMatchedEventUuid,
+ })
+ }
+ }
+
+ if (jobsToWake.length === 0) {
+ return
+ }
+
+ const woken = await this.wakeJobs(jobsToWake)
+ counterHogflowMatcherJobsWoken.inc(woken)
+ logger.info('⚡', 'Woke waiting workflows from event match', {
+ evaluated: candidates.length,
+ matched: jobsToWake.length,
+ woken,
+ })
+ }
+
+ private async evaluateWaitUntilCondition(
+ action: Extract<HogFlowAction, { type: 'wait_until_condition' }>,
+ filterGlobals: FilterGlobals,
+ hogflowId: string
+ ): Promise<boolean> {
+ // `events` and the property-based `condition` are OR'd: a step can wait on either,
+ // and either matching wakes the job. The condition is evaluated on every incoming
+ // event, which is what makes property-based waits event-driven rather than polled.
+ const context = { hogFlowId: hogflowId, actionId: action.id }
+ for (const eventConfig of action.config.events ?? []) {
+ if (await runBytecode(eventConfig.filters?.bytecode, filterGlobals, context)) {
+ return true
+ }
+ }
+ return runBytecode(action.config.condition?.filters?.bytecode, filterGlobals, context)
+ }
+
+ private async evaluateConversionEvents(hogflow: HogFlow, filterGlobals: FilterGlobals): Promise<boolean> {
+ const conversionEvents = hogflow.conversion?.events ?? []
+ const context = { hogFlowId: hogflow.id }
+ for (const eventConfig of conversionEvents) {
+ if (await runBytecode(eventConfig.filters?.bytecode, filterGlobals, context)) {
+ return true
+ }
+ }
+ return false
+ }
+
+ private async findParkedJobs(
+ distinctTeamIds: number[],
+ distinctIds: string[],
+ personTeamIds: number[],
+ personIds: string[],
+ functionIds: string[]
+ ): Promise<ParkedCandidate[]> {
+ // Two index-friendly branches with UNION (dedupes rows that match both keys).
+ // A single OR across distinct_id and person_id often forces Postgres into a
+ // sequential scan; splitting lets each branch hit its own composite index.
+ // Each branch correlates (team_id, id) as a tuple via `unnest(teams, ids)`, which
+ // zips the parallel arrays row-wise — a job only matches when its team and its id
+ // came from the SAME event. Filtering team_id and distinct_id independently with
+ // ANY/ANY would match a job whose team and distinct_id came from two different
+ // events in the batch (a cross-team false-positive candidate). The function_id
+ // filter further scopes to flows the matcher can act on.
+ const stopTimer = histogramHogflowMatcherFindParkedJobs.startTimer()
+ let result
+ try {
+ result = await this.cyclotronPool.query(
+ `SELECT id, team_id, function_id, action_id, distinct_id, person_id
+ FROM cyclotron_jobs
+ WHERE status = 'available'
+ AND queue_name = 'hogflow'
+ 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
+ FROM cyclotron_jobs
+ WHERE status = 'available'
+ AND queue_name = 'hogflow'
+ AND scheduled > NOW()
+ AND function_id = ANY($5::uuid[])
+ AND (team_id, person_id) IN (SELECT * FROM unnest($3::int[], $4::text[]))`,
+ [distinctTeamIds, distinctIds, personTeamIds, personIds, functionIds]
+ )
+ } finally {
+ stopTimer()
+ }
+
+ return result.rows.map((row) => ({
+ id: row.id,
+ teamId: row.team_id,
+ functionId: row.function_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
+ }
+
+ 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 client = await this.cyclotronPool.connect()
+ try {
+ await client.query('BEGIN')
+
+ const stateRows = await client.query(
+ `SELECT id, state FROM cyclotron_jobs
+ WHERE id = ANY($1::uuid[]) AND status = 'available'
+ ORDER BY id
+ FOR UPDATE`,
+ [ids]
+ )
+
+ const requestById = new Map(requests.map((r) => [r.id, r]))
+ const updates: { id: string; state: Buffer }[] = []
+ for (const row of stateRows.rows) {
+ if (!row.state) {
+ continue
+ }
+ const req = requestById.get(row.id)
+ if (!req) {
+ continue
+ }
+ const updated = applyWakeFlags(row.state, req)
+ if (updated) {
+ updates.push({ id: row.id, state: updated })
+ }
+ }
+
+ if (updates.length === 0) {
+ await client.query('COMMIT')
+ return 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'`,
+ [updates.map((u) => u.id), updates.map((u) => u.state)]
+ )
+ await client.query('COMMIT')
+ return result.rowCount ?? 0
+ } catch (err) {
+ await client.query('ROLLBACK').catch(() => {})
+ throw err
+ } finally {
+ client.release()
+ }
+ }
+
+ @instrumented('cdpHogflowSubscriptionMatcher.parseKafkaMessages')
+ public async _parseKafkaBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {
+ const events: HogFunctionInvocationGlobals[] = []
+
+ await Promise.all(
+ messages.map(async (message) => {
+ try {
+ const clickHouseEvent = parseJSON(message.value!.toString()) as RawClickHouseEvent
+ // A job can be parked by distinct_id or person_id, so an event needs at least
+ // one of them to match anything. Drop only events that carry neither.
+ if (!clickHouseEvent.person_id && !clickHouseEvent.distinct_id) {
+ counterHogflowMatcherEventSkipped.labels({ reason: 'no_identifiers' }).inc()
+ return
+ }
+ // The vast majority of events belong to teams with no wait_until_condition
+ // step and no event conversion goal. Bail on those via the in-memory hogflow
+ // cache before paying for getTeam + full globals conversion.
+ const teamHogFlows = await this.hogFlowManager.getHogFlowsForTeam(clickHouseEvent.team_id)
+ if (!teamHogFlows.some(hasWaitUntilOrConversion)) {
+ counterHogflowMatcherEventSkipped.labels({ reason: 'no_actionable_flow' }).inc()
+ return
+ }
+ const team = await this.deps.teamManager.getTeam(clickHouseEvent.team_id)
+ if (!team) {
+ counterHogflowMatcherEventSkipped.labels({ reason: 'no_team' }).inc()
+ return
+ }
+ events.push(convertToHogFunctionInvocationGlobals(clickHouseEvent, team, this.config.SITE_URL))
+ } catch (e) {
+ logger.error('Error parsing message', e)
+ counterParseError.labels({ error: e.message }).inc()
+ }
+ })
+ )
+
+ return events
+ }
+
+ public override async start(): Promise<void> {
+ await super.start()
+ await this.kafkaConsumer.connect(async (messages) => {
+ return await instrumentFn('cdpHogflowSubscriptionMatcher.handleEachBatch', async () => {
+ const invocationGlobals = await this._parseKafkaBatch(messages)
+ // Surface failures to the kafka consumer so the offset doesn't advance past a
+ // batch we couldn't match. The pod will crash and replay; the SELECT is read-only
+ // and the UPDATE (with `status = 'available'` guards) is idempotent, so replay is safe.
+ return { backgroundTask: this.processBatch(invocationGlobals) }
+ })
+ })
+ }
+
+ public override async stop(): Promise<void> {
+ logger.info('💤', `Stopping ${this.name}...`)
+ await this.kafkaConsumer.disconnect()
+ await this.cyclotronPool.end()
+ await super.stop()
+ logger.info('💤', `${this.name} stopped!`)
+ }
+
+ public isHealthy(): HealthCheckResult {
+ return this.kafkaConsumer.isHealthy()
+ }
+}
+
+type IndexedBatch = {
+ teamIds: number[]
+ // Parallel (teamId, id) pair arrays for the correlated lookup (see findParkedJobs).
+ distinctTeamIds: number[]
+ distinctIds: string[]
+ personTeamIds: number[]
+ personIds: string[]
+ byDistinctId: Map<string, HogFunctionInvocationGlobals[]>
+ byPersonId: Map<string, HogFunctionInvocationGlobals[]>
+}
+
+// Skip teams whose hogflows have no wait_until_condition step and no event-based
+// conversion goal — nothing for the matcher to evaluate against.
+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
+}
+
+// Single pass over the batch: dedup distinct/person ids, collect team ids,
+// and bucket every event under all the keys it could match a candidate by.
+function indexBatch(invocationGlobals: HogFunctionInvocationGlobals[]): IndexedBatch {
+ const teamIds = new Set<number>()
+ const distinctTeamIds: number[] = []
+ const distinctIds: string[] = []
+ const personTeamIds: number[] = []
+ const personIds: string[] = []
+ const byDistinctId = new Map<string, HogFunctionInvocationGlobals[]>()
+ const byPersonId = new Map<string, HogFunctionInvocationGlobals[]>()
+
+ for (const globals of invocationGlobals) {
+ const teamId = globals.project.id
+ teamIds.add(teamId)
+
+ const distinctId = globals.event.distinct_id
+ if (distinctId) {
+ const key = `${teamId}:${distinctId}`
+ if (!byDistinctId.has(key)) {
+ distinctTeamIds.push(teamId)
+ distinctIds.push(distinctId)
+ }
+ pushToMap(byDistinctId, key, globals)
+ }
+ const personId = globals.person?.id
+ if (personId) {
+ const key = `${teamId}:${personId}`
+ if (!byPersonId.has(key)) {
+ personTeamIds.push(teamId)
+ personIds.push(personId)
+ }
+ pushToMap(byPersonId, key, globals)
+ }
+ }
+
+ return {
+ teamIds: [...teamIds],
+ distinctTeamIds,
+ distinctIds,
+ personTeamIds,
+ personIds,
+ byDistinctId,
+ byPersonId,
+ }
+}
+
+function pushToMap<K, V>(map: Map<K, V[]>, key: K, value: V): void {
+ const existing = map.get(key)
+ if (existing) {
+ existing.push(value)
+ } else {
+ map.set(key, [value])
+ }
+}
+
+function collectCandidateGlobals(
+ candidate: ParkedCandidate,
+ byDistinctId: Map<string, HogFunctionInvocationGlobals[]>,
+ byPersonId: Map<string, HogFunctionInvocationGlobals[]>
+): HogFunctionInvocationGlobals[] {
+ const seen = new Set<HogFunctionInvocationGlobals>()
+ if (candidate.distinctId) {
+ for (const g of byDistinctId.get(`${candidate.teamId}:${candidate.distinctId}`) ?? []) {
+ seen.add(g)
+ }
+ }
+ if (candidate.personId) {
+ for (const g of byPersonId.get(`${candidate.teamId}:${candidate.personId}`) ?? []) {
+ seen.add(g)
+ }
+ }
+ return [...seen]
+}
+
+// Logged as separate fields on a bytecode error so it's filterable by flow/action.
+// actionId is absent for a conversion goal (not an action).
+type BytecodeContext = { hogFlowId: string; actionId?: string }
+
+// Evaluates a compiled filter against the event. HogFlowSerializer compiles bytecode for
+// every events[].filters at save time, so missing/empty bytecode means a malformed row:
+// we fail closed (return false) rather than falling back to event-name-only matching, which
+// would silently bypass property filters.
+async function runBytecode(
+ bytecode: unknown,
+ filterGlobals: FilterGlobals,
+ context: BytecodeContext
+): Promise<boolean> {
+ if (!Array.isArray(bytecode) || bytecode.length === 0) {
+ return false
+ }
+ try {
+ const result = await execHog(bytecode, { globals: filterGlobals })
+ return result.execResult?.result === true
+ } catch (err) {
+ // A broken filter silently never matches and the workflow falls through to its
+ // timeout branch, which is usually the wrong outcome. Surface loudly so we notice.
+ logger.error('🔴', 'Bytecode evaluation error', { ...context, err })
+ captureException(err, { extra: { ...context } })
+ counterHogflowMatcherBytecodeError.inc()
+ return false
+ }
+}
+
+function applyWakeFlags(stateBuffer: Buffer, req: WakeRequest): Buffer | null {
+ try {
+ const parsed = parseJSON(stateBuffer.toString('utf-8'))
+ const updatedState: HogFlowInvocationContext = { ...parsed.state }
+
+ let applied = false
+ if (req.stepMatched) {
+ if (updatedState.currentAction) {
+ updatedState.currentAction = {
+ ...updatedState.currentAction,
+ eventMatched: true,
+ eventMatchedEvent: req.eventName,
+ eventMatchedEventUuid: req.eventUuid,
+ }
+ applied = 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 })
+ }
+ }
+ if (req.conversionMatched) {
+ updatedState.conversionMatched = true
+ applied = true
+ }
+ if (!applied) {
+ // No flag set - waking the job without one would misclassify as a timeout wake.
+ return null
+ }
+ parsed.state = updatedState
+ return Buffer.from(JSON.stringify(parsed))
+ } catch (err) {
+ logger.warn('Failed to parse state during wake', { jobId: req.id, err })
+ return null
+ }
+}
diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.ts
index 69637ff9d441..ff609381bae2 100644
--- a/nodejs/src/cdp/types.ts
+++ b/nodejs/src/cdp/types.ts
@@ -332,7 +332,19 @@ export type HogFlowInvocationContext = {
id: string
startedAtTimestamp: number
hogFunctionState?: CyclotronJobInvocationHogFunctionContext
+ // Set by the subscription matcher consumer when it wakes a wait_until_condition
+ // job because a matching event arrived (as opposed to a scheduled timeout firing).
+ eventMatched?: boolean
+ // Name of the event that triggered the wake, so the executor can surface
+ // "woken by event: X" in logs instead of echoing the trigger event.
+ eventMatchedEvent?: string
+ // UUID of the exact event that triggered the wake, so the logs view can link to
+ // it precisely (the name alone is ambiguous when a person fires it repeatedly).
+ eventMatchedEventUuid?: string
}
+ // 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
variables?: Record<string, any>
// Sticky counter incremented by the rerun paginator on rehydration. Lets
// the lifecycle row producer derive `attempts` / `is_retry` for hog flows
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.ts
index 4faad207aec8..e86a61087f44 100644
--- a/nodejs/src/common/config.ts
+++ b/nodejs/src/common/config.ts
@@ -23,6 +23,7 @@ export enum PluginServerMode {
cdp_internal_events = 'cdp-internal-events',
cdp_cyclotron_worker = 'cdp-cyclotron-worker',
cdp_precalculated_filters = 'cdp-precalculated-filters',
+ cdp_hogflow_subscription_matcher = 'cdp-hogflow-subscription-matcher',
cdp_cohort_membership = 'cdp-cohort-membership',
cdp_cyclotron_worker_hogflow = 'cdp-cyclotron-worker-hogflow',
cdp_cyclotron_worker_hogflow_legacy_pg = 'cdp-cyclotron-worker-hogflow-legacy-pg',
diff --git a/nodejs/src/schema/hogflow.test.ts b/nodejs/src/schema/hogflow.test.ts
new file mode 100644
index 000000000000..4ed0d598d14f
--- /dev/null
+++ b/nodejs/src/schema/hogflow.test.ts
@@ -0,0 +1,76 @@
+import { HogFlowActionSchema, HogFlowSchema } from './hogflow'
+
+describe('hogflow schema', () => {
+ const commonActionFields = {
+ id: 'action-1',
+ name: 'Wait',
+ description: '',
+ created_at: 0,
+ updated_at: 0,
+ filters: {},
+ }
+
+ describe('wait_until_condition events', () => {
+ const baseConfig = {
+ condition: { filters: {} },
+ max_wait_duration: '5m',
+ }
+
+ it('accepts a wait_until_condition action with an events list', () => {
+ const parsed = HogFlowActionSchema.parse({
+ ...commonActionFields,
+ type: 'wait_until_condition',
+ config: {
+ ...baseConfig,
+ events: [{ filters: { bytecode: ['_H', 1] }, name: 'pricing_viewed' }],
+ },
+ })
+ expect(parsed.type).toBe('wait_until_condition')
+ expect((parsed.config as any).events).toHaveLength(1)
+ })
+
+ it('accepts a wait_until_condition action without an events list (optional)', () => {
+ const parsed = HogFlowActionSchema.parse({
+ ...commonActionFields,
+ type: 'wait_until_condition',
+ config: baseConfig,
+ })
+ expect((parsed.config as any).events).toBeUndefined()
+ })
+ })
+
+ describe('conversion events', () => {
+ const baseHogFlow = {
+ id: 'flow-1',
+ team_id: 1,
+ version: 1,
+ name: 'Test',
+ status: 'active' as const,
+ trigger: { type: 'event' as const, filters: {} },
+ exit_condition: 'exit_only_at_end' as const,
+ actions: [],
+ edges: [],
+ }
+
+ it('accepts a conversion goal with an events list', () => {
+ const parsed = HogFlowSchema.parse({
+ ...baseHogFlow,
+ conversion: {
+ window_minutes: 60,
+ filters: {},
+ bytecode: [],
+ events: [{ filters: { bytecode: ['_H', 1] }, name: 'subscribed' }],
+ },
+ })
+ expect(parsed.conversion?.events).toHaveLength(1)
+ })
+
+ it('accepts a conversion goal without an events list (optional)', () => {
+ const parsed = HogFlowSchema.parse({
+ ...baseHogFlow,
+ conversion: { window_minutes: 60, filters: {}, bytecode: [] },
+ })
+ expect(parsed.conversion?.events).toBeUndefined()
+ })
+ })
+})
diff --git a/nodejs/src/schema/hogflow.ts b/nodejs/src/schema/hogflow.ts
index 2fa98b860d73..9cb639d9863f 100644
--- a/nodejs/src/schema/hogflow.ts
+++ b/nodejs/src/schema/hogflow.ts
@@ -67,7 +67,7 @@ const HogFlowTriggerSchema = z.discriminatedUnion('type', [
}),
])
-const HogFlowActionSchema = z.discriminatedUnion('type', [
+export const HogFlowActionSchema = z.discriminatedUnion('type', [
// Trigger
z.object({
..._commonActionFields,
@@ -118,6 +118,14 @@ const HogFlowActionSchema = z.discriminatedUnion('type', [
filters: z.any(), // type this stronger
name: z.string().optional(), // Custom name for the condition
}),
+ events: z
+ .array(
+ z.object({
+ filters: z.any(),
+ name: z.string().optional(),
+ })
+ )
+ .optional(),
max_wait_duration: z.string(),
}),
}),
@@ -222,6 +230,14 @@ export const HogFlowSchema = z.object({
window_minutes: z.number().nullable(),
filters: z.any(),
bytecode: z.array(z.union([z.string(), z.number()])),
+ events: z
+ .array(
+ z.object({
+ filters: z.any(),
+ name: z.string().optional(),
+ })
+ )
+ .optional(),
})
.optional(),
exit_condition: z.enum([
diff --git a/nodejs/src/server.ts b/nodejs/src/server.ts
index e21e5c46002a..0e6ad6d9f039 100644
--- a/nodejs/src/server.ts
+++ b/nodejs/src/server.ts
@@ -12,6 +12,7 @@ import { CdpCyclotronWorkerHogFlow } from './cdp/consumers/cdp-cyclotron-worker-
import { CdpCyclotronWorker } from './cdp/consumers/cdp-cyclotron-worker.consumer'
import { CdpDatawarehouseEventsConsumer } from './cdp/consumers/cdp-data-warehouse-events.consumer'
import { CdpEventsConsumer } from './cdp/consumers/cdp-events.consumer'
+import { CdpHogflowSubscriptionMatcherConsumer } from './cdp/consumers/cdp-hogflow-subscription-matcher.consumer'
import { CdpInternalEventsConsumer } from './cdp/consumers/cdp-internal-event.consumer'
import { CdpLegacyEventsConsumer } from './cdp/consumers/cdp-legacy-event.consumer'
import { CdpPersonUpdatesConsumer } from './cdp/consumers/cdp-person-updates-consumer'
@@ -93,6 +94,7 @@ export class PluginServer implements NodeServer {
capabilities.cdpPrecalculatedFilters ||
capabilities.cdpCohortMembership ||
capabilities.cdpBatchHogFlow ||
+ capabilities.cdpHogflowSubscriptionMatcher ||
capabilities.cdpRerunWorker
)
// 1. Shared infrastructure (always needed)
@@ -308,6 +310,14 @@ export class PluginServer implements NodeServer {
})
}
+ if (capabilities.cdpHogflowSubscriptionMatcher) {
+ serviceLoaders.push(async () => {
+ const consumer = new CdpHogflowSubscriptionMatcherConsumer(this.config, cdpDeps!)
+ await consumer.start()
+ return consumer.service
+ })
+ }
+
const readyServices = await Promise.all(serviceLoaders.map((loader) => loader()))
this.lifecycle.services.push(...readyServices)
}
diff --git a/nodejs/src/types.ts b/nodejs/src/types.ts
index d2907fb8ef3a..2633902c49ba 100644
--- a/nodejs/src/types.ts
+++ b/nodejs/src/types.ts
@@ -175,6 +175,7 @@ export interface PluginServerCapabilities {
cdpCyclotronV2Janitor?: boolean
cdpRerunWorker?: boolean
cdpHogflowScheduler?: boolean
+ cdpHogflowSubscriptionMatcher?: boolean
recordingApi?: boolean
ingestionV2Testing?: boolean
}
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 0512ff863237..e94aec63f1cd 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -233,6 +233,19 @@ class HogFlowActionSerializer(serializers.Serializer):
serializer.is_valid(raise_exception=True)
condition["filters"] = serializer.validated_data
+ if data.get("type") == "wait_until_condition":
+ wait_events = data.get("config", {}).get("events") or []
+ for event_config in wait_events:
+ filters = event_config.get("filters")
+ if filters is not None:
+ serializer = HogFunctionFiltersSerializer(data=filters, context=self.context)
+ if is_draft:
+ if serializer.is_valid():
+ event_config["filters"] = serializer.validated_data
+ else:
+ serializer.is_valid(raise_exception=True)
+ event_config["filters"] = serializer.validated_data
+
if data.get("type") == "delay":
delay_duration = data.get("config", {}).get("delay_duration")
if not isinstance(delay_duration, str) or not DELAY_DURATION_REGEX.match(delay_duration):
@@ -514,6 +527,23 @@ class HogFlowSerializer(HogFlowMinimalSerializer):
if "bytecode" not in data["conversion"]:
data["conversion"]["bytecode"] = []
+ for event_config in conversion.get("events") or []:
+ event_filters = event_config.get("filters")
+ if event_filters is not None:
+ event_serializer = HogFunctionFiltersSerializer(data=event_filters, context=self.context)
+ if self.context.get("is_draft"):
+ if event_serializer.is_valid():
+ event_config["filters"] = event_serializer.validated_data
+ elif isinstance(event_filters, dict):
+ # Draft with invalid filters: never keep client-supplied bytecode.
+ # Conversion isn't revalidated on a status-only activation, so stored
+ # bytecode would activate unvalidated and the matcher would execute it.
+ # Strip it so the filter fails closed (no bytecode = never matches).
+ event_filters.pop("bytecode", None)
+ else:
+ event_serializer.is_valid(raise_exception=True)
+ event_config["filters"] = event_serializer.validated_data
+
return data
def create(self, validated_data: dict, *args, **kwargs) -> HogFlow:
diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.py
index 0e3d3efc105e..c90c8493323d 100644
--- a/products/workflows/backend/api/test/test_hog_flow.py
+++ b/products/workflows/backend/api/test/test_hog_flow.py
@@ -531,6 +531,166 @@ class TestHogFlowAPI(APIBaseTest):
assert data["code"] == "invalid_input"
assert data["type"] == "validation_error"
+ def test_hog_flow_wait_until_events_filters_bytecode(self):
+ trigger_action = {
+ "id": "trigger_node",
+ "name": "trigger_1",
+ "type": "trigger",
+ "config": {
+ "type": "event",
+ "filters": {
+ "events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}],
+ },
+ },
+ }
+
+ wait_action = {
+ "id": "wait_1",
+ "name": "wait_1",
+ "type": "wait_until_condition",
+ "config": {
+ "condition": {"filters": None},
+ "max_wait_duration": "5m",
+ "events": [
+ {
+ "filters": {
+ "events": [
+ {
+ "id": "subscription created",
+ "name": "subscription created",
+ "type": "events",
+ "order": 0,
+ "properties": [
+ {
+ "key": "plan",
+ "type": "event",
+ "value": ["growth"],
+ "operator": "exact",
+ },
+ ],
+ }
+ ],
+ },
+ },
+ ],
+ },
+ }
+
+ hog_flow = {
+ "name": "Test Flow Wait Events Bytecode",
+ "status": "active",
+ "actions": [trigger_action, wait_action],
+ }
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+ assert response.status_code == 201, response.json()
+
+ events = response.json()["actions"][1]["config"]["events"]
+ assert len(events) == 1
+ filters = events[0]["filters"]
+ assert "bytecode" in filters, filters
+ bytecode = filters["bytecode"]
+ assert "subscription created" in bytecode, bytecode
+ assert "plan" in bytecode, bytecode
+ assert "growth" in bytecode, bytecode
+
+ def test_hog_flow_conversion_events_filters_bytecode(self):
+ trigger_action = {
+ "id": "trigger_node",
+ "name": "trigger_1",
+ "type": "trigger",
+ "config": {
+ "type": "event",
+ "filters": {
+ "events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}],
+ },
+ },
+ }
+
+ hog_flow = {
+ "name": "Test Flow Conversion Events Bytecode",
+ "status": "active",
+ "actions": [trigger_action],
+ "conversion": {
+ "window_minutes": 60,
+ "events": [
+ {
+ "filters": {
+ "events": [
+ {
+ "id": "purchase completed",
+ "name": "purchase completed",
+ "type": "events",
+ "order": 0,
+ "properties": [
+ {
+ "key": "tier",
+ "type": "event",
+ "value": ["enterprise"],
+ "operator": "exact",
+ },
+ ],
+ }
+ ],
+ },
+ },
+ ],
+ },
+ }
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+ assert response.status_code == 201, response.json()
+
+ conversion_events = response.json()["conversion"]["events"]
+ assert len(conversion_events) == 1
+ filters = conversion_events[0]["filters"]
+ assert "bytecode" in filters, filters
+ bytecode = filters["bytecode"]
+ assert "purchase completed" in bytecode, bytecode
+ assert "tier" in bytecode, bytecode
+ assert "enterprise" in bytecode, bytecode
+
+ def test_hog_flow_draft_conversion_event_strips_client_supplied_bytecode(self):
+ # A draft with invalid conversion-event filters must not persist client-supplied
+ # bytecode: conversion is not revalidated on a status-only activation, so it would
+ # otherwise activate unvalidated and the matcher would execute it.
+ trigger_action = {
+ "id": "trigger_node",
+ "name": "trigger_1",
+ "type": "trigger",
+ "config": {
+ "type": "event",
+ "filters": {
+ "events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}],
+ },
+ },
+ }
+
+ hog_flow = {
+ "name": "Test Flow Draft Conversion Bytecode Injection",
+ # No status => draft, so invalid filters are tolerated rather than rejected.
+ "actions": [trigger_action],
+ "conversion": {
+ "window_minutes": 60,
+ "events": [
+ {
+ "filters": {
+ # Invalid source fails serializer validation, so the draft branch
+ # keeps the raw filters - which must not retain the injected bytecode.
+ "source": "not-a-valid-source",
+ "bytecode": ["_H", 1, 32, "injected"],
+ },
+ },
+ ],
+ },
+ }
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+ assert response.status_code == 201, response.json()
+
+ filters = response.json()["conversion"]["events"][0]["filters"]
+ assert "bytecode" not in filters, filters
+
def test_hog_flow_enable_disable(self):
hog_flow, _ = self._create_hog_flow_with_action(
{