: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): make wait-for-event steps testable in the editor test panel (#68963)
Harley Alexander34ddd7b8eab0
diff --git a/nodejs/src/cdp/cdp-api.test.ts b/nodejs/src/cdp/cdp-api.test.tsindex 7ba597f35482..4af94ace0d46 100644--- a/nodejs/src/cdp/cdp-api.test.ts+++ b/nodejs/src/cdp/cdp-api.test.ts@@ -784,6 +784,59 @@ describe('CDP API', () => {})})+ describe('hogflow wait_until_condition test invocations', () => {+ // Matches events whose name equals `eventName` - same shape the serializer compiles+ // for an "events to wait for" entry.+ const eventBytecode = (eventName: string): any[] => ['_H', 1, 32, eventName, 32, 'event', 1, 1, 11]++ const waitFlowConfiguration = {+ name: 'Wait flow',+ actions: [+ { id: 'trigger_node', name: 'Trigger', type: 'trigger', config: { type: 'event', filters: {} } },+ {+ id: 'wait_node',+ name: 'Wait',+ type: 'wait_until_condition',+ config: {+ events: [+ {+ filters: {+ bytecode: eventBytecode('follow_up'),+ events: [{ id: 'follow_up', name: 'follow_up', type: 'events', order: 0 }],+ },+ },+ ],+ condition: { filters: null },+ max_wait_duration: '5m',+ },+ },+ { id: 'exit_node', name: 'Exit', type: 'exit', config: {} },+ ],+ edges: [+ { from: 'wait_node', to: 'exit_node', type: 'branch', index: 0 },+ { from: 'wait_node', to: 'exit_node', type: 'continue' },+ ],+ }++ it.each([+ ['matching', 'follow_up', 'exit_node'],+ ['non-matching', 'some_other_event', 'wait_node'],+ ])('a %s test event resolves the wait step correctly', async (_, eventName, expectedNextActionId) => {+ const res = await supertest(app)+ .post(`/api/projects/${team.id}/hog_flows/new/invocations`)+ .send({+ globals: { ...globals, event: { ...globals.event!, event: eventName } },+ mock_async_functions: true,+ configuration: waitFlowConfiguration,+ current_action_id: 'wait_node',+ })++ expect(res.status).toEqual(200)+ expect(res.body.status).toEqual('success')+ expect(res.body.nextActionId).toEqual(expectedNextActionId)+ })+ })+describe('batch hogflow invocations', () => {let batchHogFlow: HogFlowdiff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.tsindex a9d287fb5067..a119bb07ab54 100644--- a/nodejs/src/cdp/cdp-api.ts+++ b/nodejs/src/cdp/cdp-api.ts@@ -25,6 +25,7 @@ import {import { HogTransformerService, createHogTransformerService } from './hog-transformations/hog-transformer.service'import { RerunJobManager } from './rerun/rerun-job.manager'import { RerunRequest } from './rerun/rerun-job.types'+import { HogFlowAction } from './schema/hogflow'import { BatchExportHogFunctionService, NotFoundError, ParseError } from './services/batch-export-hog-function.service'import type { CyclotronV2JobProducer } from './services/cyclotron-v2'import { HogExecutorExecuteAsyncOptions, HogExecutorService, MAX_ASYNC_STEPS } from './services/hog-executor.service'@@ -35,6 +36,7 @@ import {} from './services/hogflows/batch-resolver.types'import { HogFlowExecutorService, createHogFlowInvocation } from './services/hogflows/hogflow-executor.service'import { HogFlowManagerService } from './services/hogflows/hogflow-manager.service'+import { matchesWaitUntilCondition } from './services/hogflows/hogflow-utils'import { InvocationResultsService } from './services/invocation-results.service'import { JobQueue } from './services/job-queue/job-queue.interface'import { GroupsManagerService } from './services/managers/groups-manager.service'@@ -588,6 +590,35 @@ export class CdpApi {: undefinedconst logs: MinimalLogEntry[] = []++ // In production a wait_until_condition step's "events to wait for" are evaluated by the+ // subscription matcher against incoming events (never by the executor), so a plain+ // executeCurrentAction could not advance past one. Simulate the matcher here: when the+ // supplied test event matches, tag the invocation the same way a real match would, and+ // the handler advances to the next step.+ const currentAction: HogFlowAction | undefined = current_action_id+ ? compoundConfiguration.actions?.find((a: HogFlowAction) => a.id === current_action_id)+ : undefined+ if (currentAction?.type === 'wait_until_condition' && invocation.state.currentAction) {+ const matched = await matchesWaitUntilCondition(currentAction, filterGlobals, {+ hogFlowId: isNewHogFlow ? 'new' : id,+ actionId: currentAction.id,+ })+ if (matched) {+ invocation.state.currentAction.eventMatched = true+ invocation.state.currentAction.eventMatchedEvent = globals.event.event+ invocation.state.currentAction.eventMatchedEventUuid = globals.event.uuid+ invocation.state.currentAction.eventMatchedEventTimestamp = globals.event.timestamp+ }+ logs.push({+ level: 'info',+ timestamp: DateTime.now(),+ message: matched+ ? `Test event '${globals.event.event}' matched the wait conditions`+ : `Test event '${globals.event.event}' did not match the wait conditions - the workflow would continue waiting`,+ })+ }+const options: HogExecutorExecuteAsyncOptions = buildHogExecutorAsyncOptions(mock_async_functions, logs)options.sendEmailsInline = trueconst result = await this.hogFlowExecutor.executeCurrentAction(invocation, { hogExecutorOptions: options })diff --git a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.tsindex 4633f8d2d542..e8a07fdc0e67 100644--- a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts@@ -14,14 +14,17 @@ import { UUIDT } from '~/common/utils/utils'import { ClickHousePerson, HealthCheckResult, PluginsServerConfig, RawClickHouseEvent, Team } from '../../types'import { CdpInternalEventSchema } from '../schema'-import { isEvaluableCondition } from '../services/hogflows/hogflow-utils'+import {+ hasEventOrActionTarget,+ matchesWaitUntilCondition,+ runFilterBytecode,+} from '../services/hogflows/hogflow-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'@@ -33,11 +36,6 @@ import { counterParseError } from './metrics'// 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.',-})-const counterHogflowMatcherCandidatesEvaluated = new Counter({name: 'cdp_hogflow_matcher_candidates_evaluated',help: 'Parked hogflow jobs the matcher loaded from cyclotron and evaluated against a batch.',@@ -270,7 +268,12 @@ export class CdpHogflowSubscriptionMatcherConsumer<for (const globals of candidateGlobals) {const filterGlobals = filterGlobalsFor(globals)if (!stepMatched && action?.type === 'wait_until_condition') {- if (await this.evaluateWaitUntilCondition(action, filterGlobals, hogflow.id)) {+ if (+ await matchesWaitUntilCondition(action, filterGlobals, {+ hogFlowId: hogflow.id,+ actionId: action.id,+ })+ ) {stepMatched = truestepMatchedEventName = globals.event.eventstepMatchedEventUuid = globals.event.uuid@@ -327,32 +330,6 @@ export class CdpHogflowSubscriptionMatcherConsumer<})}- 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 (!hasEventOrActionTarget(eventConfig)) {- continue- }- if (await runBytecode(eventConfig.filters?.bytecode, filterGlobals, context)) {- return true- }- }- // An empty condition compiles to always-true bytecode, which would wake the job on the next- // event of any kind. Only evaluate the condition when it has a real compiled filter;- // otherwise the wait relies on its `events` / the step timeout.- if (!isEvaluableCondition(action.config.condition)) {- return false- }- 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 }@@ -360,7 +337,7 @@ export class CdpHogflowSubscriptionMatcherConsumer<if (!hasEventOrActionTarget(eventConfig)) {continue}- if (await runBytecode(eventConfig.filters?.bytecode, filterGlobals, context)) {+ if (await runFilterBytecode(eventConfig.filters?.bytecode, filterGlobals, context)) {return true}}@@ -758,15 +735,6 @@ 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)-}-// Whether a workflow exits when its conversion goal is met. Only then does the matcher wake a// parked job on a conversion match (so it can exit early); otherwise the conversion goal is// measurement-only and must not perturb the job's progression.@@ -863,35 +831,6 @@ function collectCandidateGlobals(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- }-}-type MatchOutcome = { state: Buffer; wake: boolean; countConversion: boolean }// Applies a batch match to a parked job's state. Returns the new state plus whether the job shoulddiff --git a/nodejs/src/cdp/services/hogflows/hogflow-utils.ts b/nodejs/src/cdp/services/hogflows/hogflow-utils.tsindex 5de355b30153..3ac99c4efd7e 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-utils.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-utils.ts@@ -1,9 +1,12 @@import { DateTime } from 'luxon'-import { Summary } from 'prom-client'+import { Counter, Summary } from 'prom-client'import { HogFlow, HogFlowAction } from '~/cdp/schema/hogflow'-import { CyclotronJobInvocationHogFlow, CyclotronJobInvocationResult } from '~/cdp/types'+import { CyclotronJobInvocationHogFlow, CyclotronJobInvocationResult, HogFunctionFilterGlobals } from '~/cdp/types'+import { execHog } from '~/cdp/utils/hog-exec'import { filterFunctionInstrumented } from '~/cdp/utils/hog-function-filtering'+import { logger } from '~/common/utils/logger'+import { captureException } from '~/common/utils/posthog'export const findActionById = (hogFlow: HogFlow, id: string): HogFlowAction => {const action = hogFlow.actions.find((action) => action.id === id)@@ -131,6 +134,78 @@ export function isEvaluableCondition(condition?: {)}+const counterHogflowFilterBytecodeError = 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.',+})++// 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).+export type HogFlowBytecodeContext = { hogFlowId: string; actionId?: string }++// 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.+export function hasEventOrActionTarget(eventConfig: {+ filters?: { events?: unknown[]; actions?: unknown[] }+}): boolean {+ return Boolean(eventConfig.filters?.events?.length || eventConfig.filters?.actions?.length)+}++// 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.+export async function runFilterBytecode(+ bytecode: unknown,+ filterGlobals: HogFunctionFilterGlobals,+ context: HogFlowBytecodeContext+): 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 } })+ counterHogflowFilterBytecodeError.inc()+ return false+ }+}++// `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.+// Used by the subscription matcher in production and by the test-invocation endpoint+// to simulate a matcher wake against a supplied event.+export async function matchesWaitUntilCondition(+ action: Extract<HogFlowAction, { type: 'wait_until_condition' }>,+ filterGlobals: HogFunctionFilterGlobals,+ context: HogFlowBytecodeContext+): Promise<boolean> {+ for (const eventConfig of action.config.events ?? []) {+ if (!hasEventOrActionTarget(eventConfig)) {+ continue+ }+ if (await runFilterBytecode(eventConfig.filters?.bytecode, filterGlobals, context)) {+ return true+ }+ }+ // An empty condition compiles to always-true bytecode, which would wake the job on the next+ // event of any kind. Only evaluate the condition when it has a real compiled filter;+ // otherwise the wait relies on its `events` / the step timeout.+ if (!isEvaluableCondition(action.config.condition)) {+ return false+ }+ return runFilterBytecode(action.config.condition?.filters?.bytecode, filterGlobals, context)+}+const DELAY_ACTION_TYPES: HogFlowAction['type'][] = ['delay', 'wait_until_condition', 'wait_until_time_window']export function hasDelayActions(actions: HogFlowAction[]): boolean {