Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(workflows): wake parked wait conditions from person and internal event streams (#65949)

Daniel Marchuk5b03c275df19
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts
index de9ec23e5a9e..f4fdecfdc9c0 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts
@@ -94,6 +94,14 @@ export class CdpCyclotronWorkerHogFlow extends CdpCyclotronWorker {
hogFlowInvocationState.event.distinct_id = person.distinct_id
}
+ // Persist the resolved person UUID into state so a re-parked wait keeps its person_id
+ // even when a later re-resolution transiently misses. clickhouse_person wakes match on
+ // person_id only, so a wait parked with person_id = null could never be woken by a
+ // person-property change — it would depend entirely on the polling backstop.
+ if (person?.id && !hogFlowInvocationState.personId) {
+ hogFlowInvocationState.personId = person.id
+ }
+
const filterGlobals = convertToHogFunctionFilterGlobal({
event: hogFlowInvocationState.event,
person: person ?? undefined,
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts
index 1aac9d7db1b9..9c75d4ece93f 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts
@@ -356,6 +356,20 @@ describe('CdpCyclotronWorkerHogFlow', () => {
expect(results[0].invocation.filterGlobals?.person?.id).toBe(personUuid)
})
+ it('persists the resolved person UUID into state so a re-parked wait keeps its person_id', async () => {
+ const results = (await processor.processInvocations(
+ invocations
+ )) as CyclotronJobInvocationResult<CyclotronJobInvocationHogFlow>[]
+
+ // invocation1 (distinct_A_1) resolves to Person A 1 — its UUID is written back into
+ // state.personId, so a later re-park keeps person_id even if re-resolution transiently misses.
+ // clickhouse_person wakes match on person_id only, so this is what lets a person-property
+ // change wake the wait without relying on the polling backstop.
+ expect(results[0].invocation.state.personId).toBe('dd3d6f80-60ad-45c3-bd61-e2300f2ba7e1')
+ // invocation4 (missing_person) resolves to nothing — no person_id to persist.
+ expect(results[3].invocation.state.personId).toBeUndefined()
+ })
+
it('should skip invocations when workflow is disabled after being queued', async () => {
const hogFlow = hogFlows[0]
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 8146bc30e6a0..090693bbe5d0 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
@@ -17,7 +17,13 @@ jest.mock('./cdp-base.consumer', () => {
})
jest.mock('~/common/kafka/consumer', () => ({
- createKafkaConsumer: jest.fn().mockReturnValue({}),
+ // Fresh stub per call: the matcher now constructs three consumers (events, person, internal
+ // events), and start()/stop()/isHealthy() touch all of them.
+ createKafkaConsumer: jest.fn(() => ({
+ connect: jest.fn().mockResolvedValue(undefined),
+ disconnect: jest.fn().mockResolvedValue(undefined),
+ isHealthy: jest.fn(),
+ })),
}))
jest.mock('pg', () => {
@@ -1188,6 +1194,140 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {
})
})
+ describe('_parsePersonBatch', () => {
+ const rawPerson = (overrides: Record<string, any>): any => ({
+ value: Buffer.from(
+ JSON.stringify({
+ id: 'person-uuid-1',
+ team_id: 1,
+ properties: JSON.stringify({ plan: 'enterprise' }),
+ is_deleted: 0,
+ timestamp: '2024-01-01 00:00:00.000',
+ ...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' }
+ matcher.setHogFlows({ 'flow-1': makeHogFlow({ id: 'flow-1', team_id: 1 }) })
+ })
+
+ it('maps a person mutation to $person_updated globals keyed on person_id only', async () => {
+ const result = await (matcher as any)._parsePersonBatch([rawPerson({})])
+
+ expect(result).toHaveLength(1)
+ const globals = result[0] as HogFunctionInvocationGlobals
+ expect(globals.event.event).toBe('$person_updated')
+ // distinct_id is empty so indexBatch keys this only on person_id, never adding a spurious
+ // (team_id, distinct_id) lookup.
+ expect(globals.event.distinct_id).toBe('')
+ expect(globals.person?.id).toBe('person-uuid-1')
+ expect(globals.person?.properties).toEqual({ plan: 'enterprise' })
+ })
+
+ it('skips deleted persons, persons with no id, and persons whose team has no actionable flow', async () => {
+ const getTeam = (matcher as any).deps.teamManager.getTeam
+
+ const result = await (matcher as any)._parsePersonBatch([
+ rawPerson({ is_deleted: 1 }),
+ rawPerson({ id: '' }),
+ rawPerson({ team_id: 2 }), // team 2 has no wait_until_condition flow
+ rawPerson({}),
+ ])
+
+ // Only the valid person for the actionable team survives.
+ expect(result.map((g: HogFunctionInvocationGlobals) => g.person?.id)).toEqual(['person-uuid-1'])
+ // The firehose early-out means getTeam is only paid for the surviving person.
+ expect(getTeam).toHaveBeenCalledTimes(1)
+ expect(getTeam).toHaveBeenCalledWith(1)
+ })
+
+ it('skips a person whose team cannot be loaded', async () => {
+ ;(matcher as any).deps.teamManager.getTeam = jest.fn().mockResolvedValue(null)
+
+ const result = await (matcher as any)._parsePersonBatch([rawPerson({})])
+
+ expect(result).toEqual([])
+ })
+ })
+
+ describe('_parseInternalEventsBatch', () => {
+ const rawInternalEvent = (
+ overrides: { team_id?: number; event?: Record<string, any>; person?: any } = {}
+ ): any => ({
+ value: Buffer.from(
+ JSON.stringify({
+ team_id: overrides.team_id ?? 1,
+ event: {
+ uuid: 'evt-uuid-1',
+ event: '$insight_alert_firing',
+ distinct_id: 'distinct-1',
+ properties: {},
+ timestamp: '2024-01-01T00:00:00Z',
+ ...overrides.event,
+ },
+ ...(overrides.person !== undefined ? { person: overrides.person } : {}),
+ })
+ ),
+ })
+
+ 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' }
+ matcher.setHogFlows({ 'flow-1': makeHogFlow({ id: 'flow-1', team_id: 1 }) })
+ })
+
+ it('maps an internal event to globals keyed on distinct_id', async () => {
+ const result = await (matcher as any)._parseInternalEventsBatch([rawInternalEvent()])
+
+ expect(result).toHaveLength(1)
+ const globals = result[0] as HogFunctionInvocationGlobals
+ expect(globals.event.event).toBe('$insight_alert_firing')
+ expect(globals.event.distinct_id).toBe('distinct-1')
+ })
+
+ it('skips events with no identifiers and no-flow teams, but keeps a person-only event', async () => {
+ const result = await (matcher as any)._parseInternalEventsBatch([
+ rawInternalEvent({ event: { distinct_id: '' } }), // no distinct_id and no person
+ rawInternalEvent({ team_id: 2 }), // team 2 has no actionable flow
+ rawInternalEvent({ event: { distinct_id: '' }, person: { id: 'person-1', properties: {} } }),
+ ])
+
+ // Only the person-only event for the actionable team survives — matched later by person_id.
+ expect(result).toHaveLength(1)
+ expect((result[0] as HogFunctionInvocationGlobals).person?.id).toBe('person-1')
+ })
+
+ it('skips an event whose team cannot be loaded', async () => {
+ ;(matcher as any).deps.teamManager.getTeam = jest.fn().mockResolvedValue(null)
+
+ const result = await (matcher as any)._parseInternalEventsBatch([rawInternalEvent()])
+
+ expect(result).toEqual([])
+ })
+
+ it('drops a malformed message (schema parse failure) without throwing', async () => {
+ const result = await (matcher as any)._parseInternalEventsBatch([
+ { value: Buffer.from(JSON.stringify({ team_id: 1 })) }, // missing required `event`
+ rawInternalEvent(),
+ ])
+
+ // The bad message is dropped; the valid one still parses.
+ expect(result).toHaveLength(1)
+ expect((result[0] as HogFunctionInvocationGlobals).event.event).toBe('$insight_alert_firing')
+ })
+ })
+
// The full combination matrix lives here (mocked pg, ~ms each) rather than in the E2E suite:
// it exercises the same wake decision the matcher makes for every events/property/action shape.
describe('wake matrix: events / property / action combinations', () => {
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 eddb87f6b9b5..4633f8d2d542 100644
--- a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts
@@ -3,23 +3,36 @@ import { Pool } from 'pg'
import { Counter, Histogram } from 'prom-client'
import { HogFlow, HogFlowAction } from '~/cdp/schema/hogflow'
-import { KAFKA_EVENTS_JSON } from '~/common/config/kafka-topics'
+import { KAFKA_CDP_INTERNAL_EVENTS, KAFKA_EVENTS_JSON, KAFKA_PERSON } 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'
import { captureException } from '~/common/utils/posthog'
+import { UUIDT } from '~/common/utils/utils'
-import { HealthCheckResult, PluginsServerConfig, RawClickHouseEvent } from '../../types'
+import { ClickHousePerson, HealthCheckResult, PluginsServerConfig, RawClickHouseEvent, Team } from '../../types'
+import { CdpInternalEventSchema } from '../schema'
import { isEvaluableCondition } from '../services/hogflows/hogflow-utils'
-import { HogFlowInvocationContext, HogFunctionInvocationGlobals, MinimalAppMetric } from '../types'
-import { convertToHogFunctionInvocationGlobals } from '../utils'
+import { CyclotronPerson, HogFlowInvocationContext, HogFunctionInvocationGlobals, MinimalAppMetric } from '../types'
+import {
+ convertInternalEventToHogFunctionInvocationGlobals,
+ convertToHogFunctionInvocationGlobals,
+ getPersonDisplayName,
+} 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'
+// A waker only needs signals that arrive after a job parks, never history. auto.offset.reset=latest
+// makes a fresh consumer group start at the tip instead of replaying the (unconsumable at prod
+// volume) topic backlog. Once the group has committed offsets, both consumer impls resume from them
+// regardless of this value — so steady-state recovery is committed-offset resume; latest only governs
+// the first bootstrap and offset-loss edge cases (covered by the deferred lag alerting follow-up).
+const startAtLatest = { ['auto.offset.reset' as keyof RdKafkaConsumerConfig]: 'latest' as never }
+
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.',
@@ -45,9 +58,14 @@ const counterHogflowMatcherConversionsCounted = new Counter({
const histogramHogflowMatcherFindParkedJobs = new Histogram({
name: 'cdp_hogflow_matcher_find_parked_jobs_seconds',
help: 'Duration of the findParkedJobs cyclotron query.',
+ labelNames: ['stream'],
buckets: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5],
})
+// Which Kafka stream a batch came from. Labels the find_parked_jobs metric so the person and
+// internal-event query load is distinguishable from the events firehose on the shared cyclotron DB.
+type WakeSource = 'events' | 'person' | 'internal_events'
+
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.',
@@ -98,19 +116,38 @@ export class CdpHogflowSubscriptionMatcherConsumer<
> extends CdpConsumerBase<TConfig> {
protected name = 'CdpHogflowSubscriptionMatcherConsumer'
protected kafkaConsumer: KafkaConsumerInterface
+ // clickhouse_person carries non-event person-property changes (the precalculated topic only
+ // emits a per-condition match boolean, not the full property set the wait bytecode needs).
+ private personKafkaConsumer: KafkaConsumerInterface
+ // cdp_internal_events carries CDP-generated signals (e.g. $insight_alert_firing,
+ // $activity_log_entry_created) that bypass the public capture pipeline and never reach the
+ // analytics events topic. (Email engagement events, by contrast, flow through capture to
+ // clickhouse_events_json and are already covered by the events stream.)
+ private internalEventsKafkaConsumer: KafkaConsumerInterface
private cyclotronPool: Pool
constructor(config: TConfig, deps: CdpConsumerBaseDeps) {
super(config, deps)
- // A waker only needs events that arrive after a job parks, never history, so start at the
- // head: auto.offset.reset=latest makes a fresh consumer group begin at the tip instead of
- // replaying the clickhouse_events_json backlog (unconsumable at prod volume).
this.kafkaConsumer = createKafkaConsumer(
{
groupId: 'cdp-hogflow-subscription-matcher-consumer',
topic: KAFKA_EVENTS_JSON,
},
- { ['auto.offset.reset' as keyof RdKafkaConsumerConfig]: 'latest' as never }
+ startAtLatest
+ )
+ this.personKafkaConsumer = createKafkaConsumer(
+ {
+ groupId: 'cdp-hogflow-subscription-matcher-person-consumer',
+ topic: KAFKA_PERSON,
+ },
+ startAtLatest
+ )
+ this.internalEventsKafkaConsumer = createKafkaConsumer(
+ {
+ groupId: 'cdp-hogflow-subscription-matcher-internal-events-consumer',
+ topic: KAFKA_CDP_INTERNAL_EVENTS,
+ },
+ startAtLatest
)
// The matcher does nothing but read/write cyclotron_jobs, so a missing connection
@@ -125,12 +162,15 @@ export class CdpHogflowSubscriptionMatcherConsumer<
})
}
- public async processBatch(invocationGlobals: HogFunctionInvocationGlobals[]): Promise<void> {
+ public async processBatch(
+ invocationGlobals: HogFunctionInvocationGlobals[],
+ source: WakeSource = 'events'
+ ): Promise<void> {
if (!invocationGlobals.length) {
return
}
try {
- await this.wakeMatchingWorkflows(invocationGlobals)
+ await this.wakeMatchingWorkflows(invocationGlobals, source)
} 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
@@ -150,7 +190,10 @@ export class CdpHogflowSubscriptionMatcherConsumer<
}
@instrumented('cdpHogflowSubscriptionMatcher.wakeMatchingWorkflows')
- private async wakeMatchingWorkflows(invocationGlobals: HogFunctionInvocationGlobals[]): Promise<void> {
+ private async wakeMatchingWorkflows(
+ invocationGlobals: HogFunctionInvocationGlobals[],
+ source: WakeSource = 'events'
+ ): Promise<void> {
const { teamIds, distinctTeamIds, distinctIds, personTeamIds, personIds, byDistinctId, byPersonId } =
indexBatch(invocationGlobals)
if (byDistinctId.size === 0 && byPersonId.size === 0) {
@@ -180,7 +223,8 @@ export class CdpHogflowSubscriptionMatcherConsumer<
distinctIds,
personTeamIds,
personIds,
- Object.keys(hogflows)
+ Object.keys(hogflows),
+ source
)
if (candidates.length === 0) {
return
@@ -328,7 +372,8 @@ export class CdpHogflowSubscriptionMatcherConsumer<
distinctIds: string[],
personTeamIds: number[],
personIds: string[],
- functionIds: string[]
+ functionIds: string[],
+ source: WakeSource
): 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
@@ -345,7 +390,7 @@ export class CdpHogflowSubscriptionMatcherConsumer<
// dedicated queue, the following wait parks on that queue, so a queue_name='hogflow'
// filter would silently miss it. function_id already scopes to hogflow jobs, and
// waking the job (scheduled = NOW()) lets whichever worker owns that queue resume it.
- const stopTimer = histogramHogflowMatcherFindParkedJobs.startTimer()
+ const stopTimer = histogramHogflowMatcherFindParkedJobs.startTimer({ stream: source })
let result
try {
result = await this.cyclotronPool.query(
@@ -540,29 +585,165 @@ export class CdpHogflowSubscriptionMatcherConsumer<
return events
}
+ @instrumented('cdpHogflowSubscriptionMatcher.parsePersonMessages')
+ public async _parsePersonBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {
+ const events: HogFunctionInvocationGlobals[] = []
+
+ await Promise.all(
+ messages.map(async (message) => {
+ try {
+ const data = parseJSON(message.value!.toString()) as ClickHousePerson
+ // A deleted person can never satisfy a wait — skip tombstones.
+ if (data.is_deleted) {
+ return
+ }
+ // Parked waits are matched by person_id (the job's person.id), so a person
+ // mutation needs an id to wake anything.
+ if (!data.id) {
+ counterHogflowMatcherEventSkipped.labels({ reason: 'no_identifiers' }).inc()
+ return
+ }
+ // clickhouse_person is a firehose; bail before getTeam + JSON parse for teams
+ // with no flow the matcher can act on.
+ const teamHogFlows = await this.hogFlowManager.getHogFlowsForTeam(data.team_id)
+ if (!teamHogFlows.some(hasWaitUntilOrConversion)) {
+ counterHogflowMatcherEventSkipped.labels({ reason: 'no_actionable_flow' }).inc()
+ return
+ }
+ const team = await this.deps.teamManager.getTeam(data.team_id)
+ if (!team) {
+ counterHogflowMatcherEventSkipped.labels({ reason: 'no_team' }).inc()
+ return
+ }
+ events.push(convertClickhousePersonToWakeGlobals(data, team, this.config.SITE_URL))
+ } catch (e) {
+ logger.error('Error parsing person message', e)
+ counterParseError.labels({ error: e.message }).inc()
+ }
+ })
+ )
+
+ return events
+ }
+
+ @instrumented('cdpHogflowSubscriptionMatcher.parseInternalEventMessages')
+ public async _parseInternalEventsBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {
+ const events: HogFunctionInvocationGlobals[] = []
+
+ await Promise.all(
+ messages.map(async (message) => {
+ try {
+ const parsed = CdpInternalEventSchema.parse(parseJSON(message.value!.toString()))
+ if (!parsed.event.distinct_id && !parsed.person?.id) {
+ counterHogflowMatcherEventSkipped.labels({ reason: 'no_identifiers' }).inc()
+ return
+ }
+ const teamHogFlows = await this.hogFlowManager.getHogFlowsForTeam(parsed.team_id)
+ if (!teamHogFlows.some(hasWaitUntilOrConversion)) {
+ counterHogflowMatcherEventSkipped.labels({ reason: 'no_actionable_flow' }).inc()
+ return
+ }
+ const team = await this.deps.teamManager.getTeam(parsed.team_id)
+ if (!team) {
+ counterHogflowMatcherEventSkipped.labels({ reason: 'no_team' }).inc()
+ return
+ }
+ events.push(convertInternalEventToHogFunctionInvocationGlobals(parsed, team, this.config.SITE_URL))
+ } catch (e) {
+ logger.error('Error parsing internal event 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) }
- })
- })
+ // Surface failures to each 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. All three streams
+ // funnel into the same input-agnostic wakeMatchingWorkflows via processBatch.
+ await Promise.all([
+ this.kafkaConsumer.connect(async (messages) => {
+ return await instrumentFn('cdpHogflowSubscriptionMatcher.handleEachBatch', async () => {
+ return { backgroundTask: this.processBatch(await this._parseKafkaBatch(messages), 'events') }
+ })
+ }),
+ this.personKafkaConsumer.connect(async (messages) => {
+ return await instrumentFn('cdpHogflowSubscriptionMatcher.handlePersonBatch', async () => {
+ return { backgroundTask: this.processBatch(await this._parsePersonBatch(messages), 'person') }
+ })
+ }),
+ this.internalEventsKafkaConsumer.connect(async (messages) => {
+ return await instrumentFn('cdpHogflowSubscriptionMatcher.handleInternalEventsBatch', async () => {
+ return {
+ backgroundTask: this.processBatch(
+ await this._parseInternalEventsBatch(messages),
+ 'internal_events'
+ ),
+ }
+ })
+ }),
+ ])
}
public override async stop(): Promise<void> {
logger.info('💤', `Stopping ${this.name}...`)
- await this.kafkaConsumer.disconnect()
+ await Promise.all([
+ this.kafkaConsumer.disconnect(),
+ this.personKafkaConsumer.disconnect(),
+ this.internalEventsKafkaConsumer.disconnect(),
+ ])
await this.cyclotronPool.end()
await super.stop()
logger.info('💤', `${this.name} stopped!`)
}
public isHealthy(): HealthCheckResult {
- return this.kafkaConsumer.isHealthy()
+ // Unhealthy if any stream is unhealthy: with polling gone, a stalled stream means dropped wakes.
+ const results = [
+ this.kafkaConsumer.isHealthy(),
+ this.personKafkaConsumer.isHealthy(),
+ this.internalEventsKafkaConsumer.isHealthy(),
+ ]
+ return results.find((r) => r.status !== 'ok') ?? results[0]
+ }
+}
+
+// Person mutations arrive on clickhouse_person with the full current property set but no triggering
+// analytics event. We synthesize a `$person_updated` event so wakeMatchingWorkflows can run a wait's
+// property condition against the new person.properties. Event-name `events` entries never match this
+// synthetic event name, which is correct: a person change should only satisfy property-based waits.
+function convertClickhousePersonToWakeGlobals(
+ data: ClickHousePerson,
+ team: Team,
+ siteUrl: string
+): HogFunctionInvocationGlobals {
+ const projectUrl = `${siteUrl}/project/${team.id}`
+ const properties = parseJSON(data.properties) as Record<string, any>
+ const person: CyclotronPerson = {
+ id: data.id,
+ properties,
+ name: getPersonDisplayName(team, data.id, properties),
+ url: `${projectUrl}/person/${encodeURIComponent(data.id)}`,
+ }
+ return {
+ project: { id: team.id, name: team.name, url: projectUrl },
+ event: {
+ uuid: new UUIDT().toString(),
+ event: '$person_updated',
+ // Empty so indexBatch only keys this on person_id. A person mutation has no triggering
+ // distinct_id, and using the person UUID here would add a spurious (team_id, distinct_id)
+ // lookup that matches a job only if its distinct_id happened to equal the UUID.
+ distinct_id: '',
+ properties: {},
+ timestamp: data.timestamp,
+ url: person.url,
+ elements_chain: '',
+ },
+ person,
}
}
diff --git a/nodejs/src/cdp/services/hogflows/actions/conditional_branch.test.ts b/nodejs/src/cdp/services/hogflows/actions/conditional_branch.test.ts
index b13a79dabd24..32f15ab457e0 100644
--- a/nodejs/src/cdp/services/hogflows/actions/conditional_branch.test.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/conditional_branch.test.ts
@@ -8,7 +8,10 @@ import { CyclotronJobInvocationHogFlow } from '~/cdp/types'
import { createInvocationResult } from '~/cdp/utils/invocation-utils'
import { findActionById, findActionByType } from '../hogflow-utils'
-import { ConditionalBranchHandler, checkConditions } from './conditional_branch'
+import { ConditionalBranchHandler, checkConditions, counterHogflowWaitPollOnlyAdvance } from './conditional_branch'
+
+const pollOnlyAdvanceCount = async (): Promise<number> =>
+ (await counterHogflowWaitPollOnlyAdvance.get()).values[0]?.value ?? 0
describe('action.conditional_branch', () => {
let invocation: CyclotronJobInvocationHogFlow
@@ -201,6 +204,7 @@ describe('action.conditional_branch', () => {
startedAtTimestamp: DateTime.utc().toMillis(),
}
handler = new ConditionalBranchHandler()
+ counterHogflowWaitPollOnlyAdvance.reset()
})
it('advances to the matched branch and clears eventMatched', async () => {
@@ -248,5 +252,89 @@ describe('action.conditional_branch', () => {
expect(result.scheduledAt).toBeDefined()
expect(result.nextAction).toBeUndefined()
})
+
+ it('re-parks a wait_until_condition on the 10-minute cap (polling retained as backstop)', async () => {
+ // Polling is kept for now: a wait_until_condition re-parks on the 10-minute cap and
+ // re-checks its condition, even though the subscription matcher also wakes it early on a
+ // matching signal. A 30-minute wait therefore schedules ~10 minutes out, not ~30.
+ waitAction.config.max_wait_duration = '30m'
+
+ const result = await handler.execute({
+ invocation: waitInvocation,
+ action: waitAction,
+ result: createInvocationResult(waitInvocation),
+ })
+
+ expect(result.scheduledAt).toEqual(DateTime.utc().plus({ minutes: 10 }))
+ })
+
+ it('marks the wait as re-parked when its condition does not match', async () => {
+ // The default condition does not match, so the wait re-parks and records that it has
+ // polled at least once — without counting a poll-only advance.
+ const result = await handler.execute({
+ invocation: waitInvocation,
+ action: waitAction,
+ result: createInvocationResult(waitInvocation),
+ })
+
+ expect(result.scheduledAt).toBeDefined()
+ expect(waitInvocation.state.currentAction!.pollReparked).toBe(true)
+ expect(await pollOnlyAdvanceCount()).toBe(0)
+ })
+
+ it('counts a poll-only advance when a re-parked wait matches on a later re-check', async () => {
+ // Evaluable event-name filter that matches the example invocation's `test` event.
+ waitAction.config.condition = {
+ filters: {
+ bytecode: ['_H', 1, 32, 'test', 32, 'event', 1, 1, 11],
+ events: [{ id: 'test', name: 'test', type: 'events', order: 0 }],
+ },
+ }
+ // The wait already re-parked at least once and the matcher did not wake it: the periodic
+ // re-check is what found the condition true.
+ waitInvocation.state.currentAction!.pollReparked = true
+
+ const result = await handler.execute({
+ invocation: waitInvocation,
+ action: waitAction,
+ result: createInvocationResult(waitInvocation),
+ })
+
+ expect(result.nextAction).toEqual(findActionById(waitInvocation.hogFlow, 'matched_target'))
+ expect(await pollOnlyAdvanceCount()).toBe(1)
+ })
+
+ it('does not count an evaluate-on-entry match (the wait never re-parked)', async () => {
+ // Evaluable event-name filter that matches the example invocation's `test` event.
+ waitAction.config.condition = {
+ filters: {
+ bytecode: ['_H', 1, 32, 'test', 32, 'event', 1, 1, 11],
+ events: [{ id: 'test', name: 'test', type: 'events', order: 0 }],
+ },
+ }
+ // pollReparked is unset: the condition was already true on entry, which polling did not catch.
+
+ const result = await handler.execute({
+ invocation: waitInvocation,
+ action: waitAction,
+ result: createInvocationResult(waitInvocation),
+ })
+
+ expect(result.nextAction).toEqual(findActionById(waitInvocation.hogFlow, 'matched_target'))
+ expect(await pollOnlyAdvanceCount()).toBe(0)
+ })
+
+ it('does not count a matcher (eventMatched) wake as poll-only', async () => {
+ waitInvocation.state.currentAction!.pollReparked = true
+ waitInvocation.state.currentAction!.eventMatched = true
+
+ await handler.execute({
+ invocation: waitInvocation,
+ action: waitAction,
+ result: createInvocationResult(waitInvocation),
+ })
+
+ expect(await pollOnlyAdvanceCount()).toBe(0)
+ })
})
})
diff --git a/nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts b/nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts
index 70dd58277ef3..094cf8751d32 100644
--- a/nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts
@@ -1,4 +1,5 @@
import { DateTime } from 'luxon'
+import { Counter } from 'prom-client'
import { HogFlowAction } from '~/cdp/schema/hogflow'
import { CyclotronJobInvocationHogFlow } from '~/cdp/types'
@@ -10,6 +11,15 @@ import { calculatedScheduledAt } from './delay'
const DEFAULT_WAIT_DURATION_SECONDS = 10 * 60
+// Increments only when the 10-minute polling re-check advances a wait_until_condition that the
+// subscription matcher did NOT wake (and not an evaluate-on-entry match). This is the decisive
+// signal for removing the poll: while it sits at ~0 across teams for a sustained window, the
+// person/event/internal streams cover every wake and polling is provably redundant.
+export const counterHogflowWaitPollOnlyAdvance = new Counter({
+ name: 'cdp_hogflow_wait_poll_only_advance',
+ help: 'wait_until_condition advanced via the polling re-check, not the subscription matcher — a wake the streams missed.',
+})
+
export class ConditionalBranchHandler implements ActionHandler {
async execute({
invocation,
@@ -47,9 +57,21 @@ export class ConditionalBranchHandler implements ActionHandler {
}
)
+ const isWait = action.type === 'wait_until_condition'
+
if (conditionResult.scheduledAt) {
+ // Record that this wait has re-parked at least once, so a later condition match is
+ // attributable to the polling re-check rather than an evaluate-on-entry match.
+ if (isWait && invocation.state.currentAction) {
+ invocation.state.currentAction.pollReparked = true
+ }
return { scheduledAt: conditionResult.scheduledAt, result: { conditionResult } }
} else if (conditionResult.nextAction) {
+ // Poll-only advance: a wait whose condition matched on a re-check (not via the matcher's
+ // eventMatched short-circuit above, and not on entry). This is the wake the streams missed.
+ if (isWait && invocation.state.currentAction?.pollReparked === true) {
+ counterHogflowWaitPollOnlyAdvance.inc()
+ }
return { nextAction: conditionResult.nextAction, result: { conditionResult } }
}
@@ -81,7 +103,9 @@ export async function checkConditions(
}
if (action.config.delay_duration) {
- // Calculate the scheduledAt based on the delay duration - max we will wait for is 10 minutes which means we check every 10 minutes until the condition is met
+ // Re-park on the 10-minute cap so the condition is re-checked by polling. The subscription
+ // matcher also wakes the job early on a matching signal, but polling is kept as the backstop
+ // for now; removing it is a follow-up once the matcher streams are proven in production.
const scheduledAt = calculatedScheduledAt(
action.config.delay_duration,
invocation.state.currentAction?.startedAtTimestamp,
diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.ts
index 1daa137b8e9e..a925e64d6f17 100644
--- a/nodejs/src/cdp/types.ts
+++ b/nodejs/src/cdp/types.ts
@@ -364,6 +364,11 @@ export type HogFlowInvocationContext = {
// debug line *and clears the flag* so any subsequent actions on the same dequeue
// (the email handler's `nextAction: exit`, etc.) log normally.
routingOnlyReschedule?: boolean
+ // Set when a wait_until_condition re-parks on its polling interval. Lets the handler
+ // attribute a later condition match to the periodic poll (vs evaluate-on-entry) and emit
+ // the cdp_hogflow_wait_poll_only_advance metric — the signal that proves whether the poll
+ // ever catches a wake the subscription streams missed, gating its eventual removal.
+ pollReparked?: boolean
}
// Set by the subscription matcher consumer when an incoming event matched the
// workflow's event-based conversion goals. shouldExitEarly reads and clears it.
diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.ts
index 43edcaa06027..1c76267d9c8f 100644
--- a/nodejs/src/cdp/workflows-e2e.test.ts
+++ b/nodejs/src/cdp/workflows-e2e.test.ts
@@ -376,6 +376,13 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)
// bytecode (op 29). Unlike an events entry, the executor evaluates the condition on entry, so
// without the guard this fires the wait immediately. Mirrors the serializer's compiled shape.
const emptyConditionFilters = () => ({ bytecode: ['_H', 1, 29], properties: [] })
+ // A wait CONDITION on a person property: `person.properties[key] == value`. Mirrors the bytecode
+ // Django compiles for a single person-property equality filter. Used to prove that a person
+ // mutation (no analytics event) can satisfy a parked condition wait.
+ const personPropertyConditionFilters = (key: string, value: string): any => ({
+ bytecode: ['_H', 1, 32, value, 32, key, 32, 'properties', 32, 'person', 1, 3, 11],
+ properties: [{ key, value, type: 'person', operator: 'exact' }],
+ })
describe('simple workflow: trigger → function → exit', () => {
beforeEach(async () => {
@@ -1025,6 +1032,103 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)
expect(mockFetch).not.toHaveBeenCalled()
})
+ it('wakes a parked condition wait on a person-property change with no analytics event', async () => {
+ // The core of removing the 10-minute poll: a property change that produces no analytics
+ // event (only a clickhouse_person mutation) must still wake the wait. The matcher's
+ // person stream synthesizes a $person_updated globals carrying the new person.properties,
+ // which the wait's property condition then matches.
+ await createWaitUntilWorkflow({
+ // Person-property condition only — never satisfied by the trigger event, so it parks.
+ condition: { filters: personPropertyConditionFilters('plan', 'enterprise') },
+ max_wait_duration: '5m',
+ })
+ // person is not persisted in the job state — the worker re-resolves it from the person store
+ // on dequeue (CyclotronPerson.id = person.uuid). Without a resolvable person the re-parked job
+ // stores person_id = null and the person-stream matcher can never find it. Production resolves
+ // person_id during ingestion before the job parks; mirror that so the parked job carries
+ // person_id = 'uuid' — the same id the clickhouse_person mutation below targets. The resolved
+ // person has no `plan`, so the condition still fails on entry and the job parks as expected.
+ mockPersonRepo.fetchPersonsByDistinctIds.mockResolvedValue([
+ {
+ id: '1',
+ uuid: 'uuid',
+ team_id: team.id,
+ properties: { email: '[email protected]' },
+ properties_last_updated_at: {},
+ properties_last_operation: null,
+ created_at: DateTime.utc(),
+ version: 1,
+ is_identified: true,
+ is_user_id: null,
+ last_seen_at: null,
+ distinct_id: 'distinct_id',
+ },
+ ])
+ await triggerWorkflow(createGlobals())
+ await expectParked()
+
+ // A clickhouse_person mutation for that person — the person now matches `plan=enterprise`.
+ // No analytics event is involved; this comes straight off the person topic.
+ const personMessage = {
+ value: Buffer.from(
+ JSON.stringify({
+ id: 'uuid',
+ team_id: team.id,
+ properties: JSON.stringify({ email: '[email protected]', plan: 'enterprise' }),
+ is_deleted: 0,
+ is_identified: 1,
+ created_at: '2024-09-03 09:00:00.000',
+ timestamp: '2024-09-03 09:00:00.000',
+ version: 2,
+ })
+ ),
+ }
+ const personGlobals = await matcher._parsePersonBatch([personMessage as any])
+ await matcher.processBatch(personGlobals)
+
+ await waitForExpect(() => {
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ }, 10000)
+ expect(mockFetch).toHaveBeenCalledWith('https://example.com/condition-matched', expect.anything())
+ })
+
+ it('wakes a parked wait from a cdp_internal_events signal with no analytics event', async () => {
+ // CDP-generated signals (e.g. $insight_alert_firing) arrive on cdp_internal_events and never
+ // hit the analytics events topic. The matcher parses them via _parseInternalEventsBatch and
+ // wakes parked waits whose "events to wait for" name the signal, matched by distinct_id.
+ await createWaitUntilWorkflow({
+ // Property condition never matches the trigger event, so the job parks until the signal.
+ condition: { filters: HOG_FILTERS_EXAMPLES.elements_text_filter.filters },
+ events: [eventNameFilter('$insight_alert_firing')],
+ max_wait_duration: '5m',
+ })
+ await triggerWorkflow(createGlobals())
+ await expectParked()
+
+ // A raw cdp_internal_events message for this person's distinct_id — no analytics event.
+ const internalEventMessage = {
+ value: Buffer.from(
+ JSON.stringify({
+ team_id: team.id,
+ event: {
+ uuid: new UUIDT().toString(),
+ event: '$insight_alert_firing',
+ distinct_id: 'distinct_id',
+ properties: {},
+ timestamp: '2024-09-03T09:00:00Z',
+ },
+ })
+ ),
+ }
+ const internalGlobals = await matcher._parseInternalEventsBatch([internalEventMessage as any])
+ await matcher.processBatch(internalGlobals)
+
+ await waitForExpect(() => {
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ }, 10000)
+ expect(mockFetch).toHaveBeenCalledWith('https://example.com/condition-matched', expect.anything())
+ })
+
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
diff --git a/products/workflows/frontend/Workflows/hogflows/filters/HogFlowFilters.tsx b/products/workflows/frontend/Workflows/hogflows/filters/HogFlowFilters.tsx
index ea2074115950..c004838dd8e4 100644
--- a/products/workflows/frontend/Workflows/hogflows/filters/HogFlowFilters.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/filters/HogFlowFilters.tsx
@@ -44,6 +44,11 @@ export type HogFlowFiltersProps = {
setFilters: (filters: HogFlowAction['filters']) => void
typeKey?: string
buttonCopy?: string
+ // Drop group-property filters from the taxonomy. The subscription matcher wakes parked
+ // wait_until_condition jobs from person- and event-keyed signals only; a group-property change
+ // has no such key, so a group-based wait could never be woken and would only ever time out.
+ // Used by wait conditions to keep them constrained to matcher-observable signals.
+ excludeGroupProperties?: boolean
// When filtering rows of a data warehouse table, pass the selected table's columns so they appear
// as suggestions and resolve their distinct values.
schemaColumns?: DatabaseSchemaField[]
@@ -53,7 +58,13 @@ export type HogFlowFiltersProps = {
/**
* Standard components wherever we do conditional matching to support whatever we know the hogflow engine supports
*/
-export function HogFlowEventFilters({ filters, setFilters, typeKey, buttonCopy }: HogFlowFiltersProps): JSX.Element {
+export function HogFlowEventFilters({
+ filters,
+ setFilters,
+ typeKey,
+ buttonCopy,
+ excludeGroupProperties,
+}: HogFlowFiltersProps): JSX.Element {
const shouldShowInternalEvents = useFeatureFlag('WORKFLOWS_INTERNAL_EVENT_FILTERS')
const sampleGlobals = useSampleGlobals()
const { groupsTaxonomicTypes } = useValues(groupsModel)
@@ -73,7 +84,7 @@ export function HogFlowEventFilters({ filters, setFilters, typeKey, buttonCopy }
TaxonomicFilterGroupType.EventFeatureFlags,
TaxonomicFilterGroupType.Elements,
TaxonomicFilterGroupType.PersonProperties,
- ...groupsTaxonomicTypes,
+ ...(excludeGroupProperties ? [] : groupsTaxonomicTypes),
TaxonomicFilterGroupType.HogQLExpression,
]
if (shouldShowInternalEvents) {
@@ -110,6 +121,7 @@ export function HogFlowPropertyFilters({
filtersKey,
filters,
setFilters,
+ excludeGroupProperties,
schemaColumns,
dataWarehouseTableName,
}: HogFlowFiltersProps): JSX.Element {
@@ -141,7 +153,7 @@ export function HogFlowPropertyFilters({
TaxonomicFilterGroupType.EventProperties,
TaxonomicFilterGroupType.EventFeatureFlags,
TaxonomicFilterGroupType.PersonProperties,
- ...groupsTaxonomicTypes,
+ ...(excludeGroupProperties ? [] : groupsTaxonomicTypes),
TaxonomicFilterGroupType.HogQLExpression,
TaxonomicFilterGroupType.EventMetadata,
]
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepWaitUntilCondition.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepWaitUntilCondition.tsx
index 6243a6247d1f..83d624c06144 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/StepWaitUntilCondition.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepWaitUntilCondition.tsx
@@ -58,6 +58,7 @@ export function StepWaitUntilConditionConfiguration({
}
typeKey="workflow-wait-until-event"
buttonCopy="Add event"
+ excludeGroupProperties
/>
</div>
@@ -96,6 +97,7 @@ export function StepWaitUntilConditionConfiguration({
partialSetWorkflowActionConfig(action.id, { condition: { ...condition, filters } })
}
typeKey="workflow-wait-until-condition"
+ excludeGroupProperties
/>
</div>