:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(workflows): Don't wake on an empty wait_until_condition events entry (#62306)
Daniel Marchuk5166b9c233aa
diff --git a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.tsindex abf0fe85c9a3..8d8b2a742ae0 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@@ -527,6 +527,35 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {expect(newState.state.conversionMatched).toBe(true)})+ it('does not wake on an empty conversion "events" entry (always-true bytecode)', async () => {+ // A conversion entry that targets neither events nor actions compiles to always-true+ // bytecode and would otherwise mark every incoming event as a conversion.+ const flow = makeHogFlow({+ id: 'flow-1',+ conversion: { events: [{ filters: { bytecode: ['_H', 1, 29], events: [] } }] } 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,+ },+ ]+ // Wire the wake path so that IF the empty entry incorrectly matched, an UPDATE would+ // be produced — otherwise this assertion would pass trivially.+ 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: 'unrelated_event' } })])++ const update = matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))+ expect(update).toBeUndefined()+ })+it('does not wake when neither step filter nor conversion matches', async () => {matcher.findRows = [{@@ -547,6 +576,55 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {expect(update).toBeUndefined()})+ it('does not wake on an empty "events to wait for" entry (always-true bytecode)', async () => {+ // An events entry that references no events compiles to always-true bytecode and would+ // otherwise wake the job on any incoming event, bypassing the property condition.+ matcher.findRows = [+ {+ id: 'job-1',+ team_id: 1,+ function_id: 'flow-1',+ action_id: 'wait_node',+ distinct_id: 'user-1',+ person_id: null,+ },+ ]+ // Wire the wake path so that IF the empty entry incorrectly matched, an UPDATE would+ // be produced — otherwise this assertion would pass trivially.+ matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer({ currentAction: { id: 'wait_node' } }) }]+ matcher.updateRowCount = 1+ matcher.setHogFlows({+ 'flow-1': makeHogFlow({+ id: 'flow-1',+ actions: [+ {+ id: 'trigger_node',+ name: 'Trigger',+ type: 'trigger',+ config: { type: 'event', filters: {} },+ },+ {+ id: 'wait_node',+ name: 'Wait',+ type: 'wait_until_condition',+ config: {+ // Empty events entry: bytecode is TRUE (op 29), events list is empty.+ events: [{ filters: { bytecode: ['_H', 1, 29], events: [] } }],+ condition: { filters: null },+ max_wait_duration: '5m',+ },+ },+ { id: 'exit_node', name: 'Exit', type: 'exit', config: {} },+ ],+ } as any),+ })++ 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 = [{diff --git a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.tsindex 87d84cf99416..6f4db0905494 100644--- a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts@@ -230,6 +230,9 @@ export class CdpHogflowSubscriptionMatcherConsumer<// 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 (!hasEventOrActionTarget(eventConfig)) {+ continue+ }if (await runBytecode(eventConfig.filters?.bytecode, filterGlobals, context)) {return true}@@ -241,6 +244,9 @@ export class CdpHogflowSubscriptionMatcherConsumer<const conversionEvents = hogflow.conversion?.events ?? []const context = { hogFlowId: hogflow.id }for (const eventConfig of conversionEvents) {+ if (!hasEventOrActionTarget(eventConfig)) {+ continue+ }if (await runBytecode(eventConfig.filters?.bytecode, filterGlobals, context)) {return true}@@ -442,6 +448,15 @@ type IndexedBatch = {byPersonId: Map<string, HogFunctionInvocationGlobals[]>}+// An "events to wait for" / conversion entry that targets neither events nor actions compiles to+// always-true bytecode (the UI can leave an empty entry behind when the last event is removed), so+// it would match every incoming event. Action-based entries (events empty, actions set) are real+// and must be kept. Shared by the wait_until_condition and conversion evaluators so the rule lives+// in one place.+function hasEventOrActionTarget(eventConfig: { filters?: { events?: unknown[]; actions?: unknown[] } }): boolean {+ return Boolean(eventConfig.filters?.events?.length || eventConfig.filters?.actions?.length)+}+// Skip teams whose hogflows have no wait_until_condition step and no event-based// conversion goal — nothing for the matcher to evaluate against.function hasWaitUntilOrConversion(hogflow: HogFlow): boolean {diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.tsindex f62365a959fe..c294fe12effb 100644--- a/nodejs/src/cdp/workflows-e2e.test.ts+++ b/nodejs/src/cdp/workflows-e2e.test.ts@@ -288,6 +288,15 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)const eventNameFilter = (eventName: string) => ({filters: { events: [{ id: eventName }], bytecode: eventNameBytecode(eventName) },})+ // An action-based wait entry: the editor's Actions picker yields a filter with `actions` set and+ // `events` empty. Django compiles the action's match conditions into bytecode the same way.+ const actionFilter = (eventName: string, actionId: number) => ({+ filters: { actions: [{ id: actionId, type: 'actions' }], events: [], bytecode: eventNameBytecode(eventName) },+ })+ // The state left when the last event is removed from a wait entry in the UI: no events, no+ // actions. Empty filters compile to always-true bytecode (op 29), which must NOT wake on every+ // event. ['_H', 1, 29] is exactly what the Django compiler emits for empty filters.+ const emptyEventFilter = () => ({ filters: { events: [], bytecode: ['_H', 1, 29] } })describe('simple workflow: trigger → function → exit', () => {beforeEach(async () => {@@ -673,6 +682,28 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)expect(mockFetch).toHaveBeenCalledWith('https://example.com/condition-matched', expect.anything())})+ it('wakes a parked job whose wait entry is action-based (events empty, actions + bytecode set)', async () => {+ await createWaitUntilWorkflow({+ // Property condition never matches the trigger event, so the job parks.+ condition: { filters: HOG_FILTERS_EXAMPLES.elements_text_filter.filters },+ // "Events to wait for" entry targets a PostHog Action: filters.events is empty,+ // filters.actions is set, and the compiled bytecode matches the action's event.+ events: [actionFilter('action_wakeup_event', 3)],+ max_wait_duration: '5m',+ })+ await triggerWorkflow(createGlobals())+ await expectParked()++ // The action's underlying event fires — the matcher must wake the job via the action+ // entry even though filters.events is empty.+ await matcher.processBatch([createGlobals({ event: 'action_wakeup_event' })])++ await waitForExpect(() => {+ expect(mockFetch).toHaveBeenCalledTimes(1)+ }, 10000)+ expect(mockFetch).toHaveBeenCalledWith('https://example.com/condition-matched', expect.anything())+ })+it('wakes a parked job when a later event satisfies the property condition', async () => {await createWaitUntilWorkflow({// No events list — only a property-based condition. The matcher evaluates the@@ -731,6 +762,28 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)expect(jobs.every((j: any) => j.status === 'available' && new Date(j.scheduled) > new Date())).toBe(true)expect(mockFetch).not.toHaveBeenCalled()})++ it('does not wake on a completely empty "events to wait for" entry (always-true bytecode)', async () => {+ // The state left when the last event is removed from a wait entry: empty filters compile+ // to always-true bytecode. Inserted directly so it bypasses the serializer strip — this+ // guards the matcher itself, which must NOT fire the workflow on every incoming event.+ await createWaitUntilWorkflow({+ condition: { filters: HOG_FILTERS_EXAMPLES.elements_text_filter.filters },+ events: [emptyEventFilter()],+ max_wait_duration: '5m',+ })+ await triggerWorkflow(createGlobals())+ await expectParked()++ // An unrelated event must not wake the job — the always-true bytecode would otherwise match.+ await matcher.processBatch([createGlobals({ event: 'some_unrelated_event' })])++ // Give the worker room to (incorrectly) pick the job up — it must not.+ await new Promise((resolve) => setTimeout(resolve, 1000))+ const jobs = await queryCyclotronJobs()+ expect(jobs.every((j: any) => j.status === 'available' && new Date(j.scheduled) > new Date())).toBe(true)+ expect(mockFetch).not.toHaveBeenCalled()+ })})describe('wait_until_time_window: window in the future', () => {diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 36ef934c2fe0..c651138707a1 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -69,6 +69,15 @@ logger = structlog.get_logger(__name__)DELAY_DURATION_REGEX = re.compile(r"^\d*\.?\d+[dhm]$")+def _event_config_has_event_or_action(event_config: dict) -> bool:+ # An "events to wait for" / conversion entry that targets neither events nor actions compiles to+ # always-true bytecode and would fire on every incoming event. Action-based entries (events empty,+ # actions set) are real and kept. Shared by the wait_until_condition and conversion strips so the+ # rule lives in one place (mirrors hasEventOrActionTarget in the matcher consumer).+ filters = event_config.get("filters") or {}+ return bool(filters.get("events") or filters.get("actions"))++class BlastRadiusRequestSerializer(serializers.Serializer):filters = serializers.DictField(help_text="Property filters to apply")group_type_index = serializers.IntegerField(@@ -328,6 +337,13 @@ class HogFlowActionSerializer(serializers.Serializer):if data.get("type") == "wait_until_condition":wait_events = data.get("config", {}).get("events") or []+ # Drop "events to wait for" entries that target neither events nor actions. An empty+ # event filter compiles to always-true bytecode, which would wake the job on every+ # incoming event and bypass the property condition. The UI can leave such an entry+ # behind when the last event is removed; "nothing targeted" must mean "nothing wakes+ # this", not "everything". Action-based entries (events empty, actions set) are kept.+ wait_events = [ec for ec in wait_events if _event_config_has_event_or_action(ec)]+ data["config"]["events"] = wait_eventsfor event_config in wait_events:filters = event_config.get("filters")if filters is not None:@@ -644,7 +660,13 @@ class HogFlowSerializer(HogFlowMinimalSerializer):if "bytecode" not in data["conversion"]:data["conversion"]["bytecode"] = []- for event_config in conversion.get("events") or []:+ # Drop conversion "events" entries that target neither events nor actions, for the same+ # always-true reason as the wait_until_condition guard above: an empty entry would mark+ # every incoming event as a conversion. Action-based entries (events empty, actions set)+ # are kept.+ conversion_events = [ec for ec in (conversion.get("events") or []) if _event_config_has_event_or_action(ec)]+ data["conversion"]["events"] = conversion_events+ for event_config in conversion_events:event_filters = event_config.get("filters")if event_filters is not None:event_serializer = HogFunctionFiltersSerializer(data=event_filters, context=self.context)diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex 209e5a1e91f1..d88a0a7f55be 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -14,6 +14,7 @@ from posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.test.fixtures import create_app_metric2+from products.actions.backend.models.action import Actionfrom products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATESfrom products.cohorts.backend.models.cohort import Cohortfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlow@@ -599,6 +600,106 @@ class TestHogFlowAPI(APIBaseTest):assert "plan" in bytecode, bytecodeassert "growth" in bytecode, bytecode+ def test_hog_flow_wait_until_drops_empty_events_entry(self):+ # An "events to wait for" entry that references no events compiles to always-true bytecode,+ # which would wake the job on every incoming event. It must be dropped on save; a real entry+ # alongside it is kept.+ 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": {+ "properties": [{"key": "plan", "type": "person", "value": ["growth"], "operator": "exact"}],+ },+ },+ "max_wait_duration": "5m",+ "events": [+ {"filters": {"events": []}},+ {+ "filters": {+ "events": [+ {+ "id": "subscription created",+ "name": "subscription created",+ "type": "events",+ "order": 0,+ }+ ],+ },+ },+ ],+ },+ }++ hog_flow = {+ "name": "Test Flow Drop Empty Wait Events",+ "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, events+ assert "subscription created" in events[0]["filters"]["bytecode"], events[0]["filters"]++ def test_hog_flow_wait_until_keeps_action_only_entry(self):+ # An "events to wait for" entry can target a PostHog Action instead of an event: filters.actions+ # is set and filters.events is empty. That is a real wait and must be kept (and its bytecode+ # compiled), while a truly-empty entry alongside it is still dropped.+ action = Action.objects.create(team=self.team, name="Played with calculator", steps_json=[{"event": "calc"}])++ 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": []}},+ {"filters": {"actions": [{"id": str(action.id), "type": "actions", "order": 0}], "events": []}},+ ],+ },+ }+ hog_flow = {+ "name": "Test Flow Keep Action Wait Entry",+ "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, events+ assert events[0]["filters"]["actions"] == [{"id": str(action.id), "type": "actions", "order": 0}]+ assert events[0]["filters"]["bytecode"], events[0]["filters"]+def test_hog_flow_conversion_events_filters_bytecode(self):trigger_action = {"id": "trigger_node",@@ -655,6 +756,40 @@ class TestHogFlowAPI(APIBaseTest):assert "tier" in bytecode, bytecodeassert "enterprise" in bytecode, bytecode+ def test_hog_flow_conversion_drops_empty_keeps_action_event(self):+ # Same always-true guard as wait_until: a conversion "events" entry targeting nothing is+ # dropped (it would convert on every event), while an action-based entry is kept and compiled.+ action = Action.objects.create(team=self.team, name="Converted via action", steps_json=[{"event": "converted"}])+ 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 Drop Empty Keep Action",+ "status": "active",+ "actions": [trigger_action],+ "conversion": {+ "window_minutes": 60,+ "events": [+ {"filters": {"events": []}},+ {"filters": {"actions": [{"id": str(action.id), "type": "actions", "order": 0}], "events": []}},+ ],+ },+ }++ 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, conversion_events+ assert conversion_events[0]["filters"]["actions"] == [{"id": str(action.id), "type": "actions", "order": 0}]+ assert conversion_events[0]["filters"]["bytecode"], conversion_events[0]["filters"]+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@@ -680,8 +815,10 @@ class TestHogFlowAPI(APIBaseTest):"events": [{"filters": {- # Invalid source fails serializer validation, so the draft branch+ # A real event target so the entry survives the empty-entry strip. The+ # invalid source still fails serializer validation, so the draft branch# keeps the raw filters - which must not retain the injected bytecode.+ "events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}],"source": "not-a-valid-source","bytecode": ["_H", 1, 32, "injected"],},