: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): reload the test panel sample event when trigger filters change (#102689)
Daniel Marchuk0064c762611a
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.test.tsindex 961a7679161d..8a938a4be67d 100644--- a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.test.ts+++ b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.test.ts@@ -2,12 +2,16 @@ import { MOCK_DEFAULT_ORGANIZATION, MOCK_GROUP_TYPES } from 'lib/api.mock'import { expectLogic } from 'kea-test-utils'+import { performWideEventsQueryInTwoPhases } from 'scenes/hog-functions/sampleEventsQuery'+import { useAvailableFeatures } from '~/mocks/features'import { useMocks } from '~/mocks/jest'import { groupsModel } from '~/models/groupsModel'import { initKeaTests } from '~/test/init'import { AvailableFeature, GroupType, GroupTypeIndex, OrganizationType } from '~/types'+import { workflowLogic } from '../../../workflowLogic'+import { hogFlowEditorLogic } from '../../hogFlowEditorLogic'import { encodeSlackFilters } from '../../registry/triggers/slackTriggerFilters'import { createExampleEventForTrigger } from '../../testEventFactory'import {@@ -17,6 +21,11 @@ import {parseGroupsFromResult,} from './hogFlowEditorTestLogic'+jest.mock('scenes/hog-functions/sampleEventsQuery', () => ({+ ...jest.requireActual('scenes/hog-functions/sampleEventsQuery'),+ performWideEventsQueryInTwoPhases: jest.fn(),+}))+// Mounting hogFlowEditorTestLogic mounts workflowLogic, whose afterMount loads the hog// flow; without a valid fixture the editor's resetFlowFromHogFlow crashes and logs.const WORKFLOW_FIXTURE = {@@ -261,7 +270,246 @@ describe('hogFlowEditorTestLogic', () => {beforeEach(() => {initKeaTests()- useMocks({ get: { '/api/environments/:team_id/hog_flows/:id/': WORKFLOW_FIXTURE } })+ useMocks({+ get: { '/api/environments/:team_id/hog_flows/:id/': WORKFLOW_FIXTURE },+ // The editor autosaves, so a test that waits long enough reaches the save handler.+ // Echo the body back, or the saved edit is reverted by the response.+ patch: {+ '/api/environments/:team_id/hog_flows/:id/': async ({ request }) => [+ 200,+ { ...WORKFLOW_FIXTURE, ...((await request.json()) as Record<string, any>) },+ ],+ },+ })+ // clearMocks keeps implementations, so a test that installs one would otherwise hand it+ // to every test that runs after it.+ ;(performWideEventsQueryInTwoPhases as jest.Mock).mockReset()+ })++ describe('sample event follows the trigger filters', () => {+ it('reloads the sample event when the trigger filters change', async () => {+ // The panel fetched once on mount, so editing the trigger filters left the tester running+ // against an event that no longer matched the filters on screen.+ logic = hogFlowEditorTestLogic({ id: 'test-workflow' })+ logic.mount()+ const flowLogic = workflowLogic({ id: 'test-workflow' })+ hogFlowEditorLogic({ id: 'test-workflow' }).actions.setMode('test')++ // Consume the load that mounting always does, so the assertion below can only pass on a+ // second one. Without this the test passes even when nothing reacts to the filters.+ await expectLogic(logic).toDispatchActions(['loadSampleGlobals'])++ const before = logic.values.matchingFilters++ await expectLogic(logic, () => {+ flowLogic.actions.setWorkflowValue(+ 'actions',+ WORKFLOW_FIXTURE.actions.map((action) =>+ action.id === 'trigger_node'+ ? {+ ...action,+ config: {+ type: 'event',+ filters: { events: [{ id: '$pageview', type: 'events', properties: [] }] },+ },+ }+ : action+ )+ )+ }).toDispatchActions(['loadSampleGlobals'])++ expect(logic.values.matchingFilters).not.toEqual(before)+ })++ it('reloads the sample event for a trigger that follows an event picked by name', async () => {+ // The by-name selector renders only for a trigger this panel cannot query, so the+ // picked name outlives that trigger. It must not stop the panel from following the+ // filters once the trigger is one the panel does query.+ logic = hogFlowEditorTestLogic({ id: 'test-workflow' })+ logic.mount()+ const flowLogic = workflowLogic({ id: 'test-workflow' })+ hogFlowEditorLogic({ id: 'test-workflow' }).actions.setMode('test')++ const setTriggerConfig = (config: Record<string, any>): void => {+ flowLogic.actions.setWorkflowValue(+ 'actions',+ WORKFLOW_FIXTURE.actions.map((action) =>+ action.id === 'trigger_node' ? { ...action, config } : action+ )+ )+ }++ // Consume the load that mounting always does, so the assertion below can only pass on+ // a later one.+ await expectLogic(logic).toDispatchActions(['loadSampleGlobals'])+ await expectLogic(flowLogic).toDispatchActions(['loadWorkflowSuccess'])++ setTriggerConfig({ type: 'webhook', filters: {} })+ logic.actions.loadSampleEventByName({ eventName: '$pageview' })+ expect(logic.values.lastSearchedEventName).toEqual('$pageview')++ await expectLogic(logic, () => {+ setTriggerConfig({+ type: 'event',+ filters: { events: [{ id: 'user logged in', type: 'events', properties: [] }] },+ })+ }).toDispatchActions(['loadSampleGlobals'])+ })++ it('follows the test-account toggle, in the reload and in the query', async () => {+ // The live trigger folds the team's test-account filters in, so a sample that ignores+ // the toggle can be an event the trigger would reject.+ const queryMock = performWideEventsQueryInTwoPhases as jest.Mock+ queryMock.mockReset()+ queryMock.mockImplementation(async () => ({ results: [] }))++ logic = hogFlowEditorTestLogic({ id: 'test-workflow' })+ logic.mount()+ const flowLogic = workflowLogic({ id: 'test-workflow' })+ hogFlowEditorLogic({ id: 'test-workflow' }).actions.setMode('test')+ await expectLogic(logic).toDispatchActions(['loadSampleGlobalsSuccess'])++ expect(queryMock.mock.calls[0][0].filterTestAccounts).toBe(false)+ queryMock.mockClear()++ await expectLogic(logic, () => {+ flowLogic.actions.setWorkflowValue(+ 'actions',+ WORKFLOW_FIXTURE.actions.map((action) =>+ action.id === 'trigger_node'+ ? { ...action, config: { type: 'event', filters: { filter_test_accounts: true } } }+ : action+ )+ )+ }).toDispatchActions(['loadSampleGlobals'])+ await expectLogic(logic).toDispatchActions(['loadSampleGlobalsSuccess'])++ expect(logic.values.shouldFilterTestAccounts).toBe(true)+ expect(queryMock.mock.calls[0][0].filterTestAccounts).toBe(true)+ })++ it('holds the reload until the test tab opens', async () => {+ // The build tab mounts this panel for its output mapping, so a filter edit there must+ // not spend a query on someone who never opens the tester.+ const queryMock = performWideEventsQueryInTwoPhases as jest.Mock+ queryMock.mockReset()+ queryMock.mockImplementation(async () => ({ results: [] }))++ logic = hogFlowEditorTestLogic({ id: 'test-workflow' })+ logic.mount()+ const flowLogic = workflowLogic({ id: 'test-workflow' })+ hogFlowEditorLogic({ id: 'test-workflow' }).actions.setMode('build')+ await expectLogic(logic).toDispatchActions(['loadSampleGlobalsSuccess'])+ queryMock.mockClear()++ await expectLogic(logic, () => {+ flowLogic.actions.setWorkflowValue(+ 'actions',+ WORKFLOW_FIXTURE.actions.map((action) =>+ action.id === 'trigger_node'+ ? { ...action, config: { type: 'event', filters: { filter_test_accounts: true } } }+ : action+ )+ )+ }).toDispatchActions(['markSampleGlobalsStale'])+ expect(queryMock).not.toHaveBeenCalled()++ await expectLogic(logic, () => {+ hogFlowEditorLogic({ id: 'test-workflow' }).actions.setMode('test')+ }).toDispatchActions(['loadSampleGlobals', 'loadSampleGlobalsSuccess'])++ expect(queryMock).toHaveBeenCalledTimes(1)+ expect(queryMock.mock.calls[0][0].filterTestAccounts).toBe(true)+ })++ it('keeps the newest sample event when an older query answers last', async () => {+ // Two loads overlap and the first query answers second. The stale answer must be+ // discarded, or the panel shows an event the current filters never asked for.+ const eventRow = (uuid: string): any[] => [+ { uuid, event: '$pageview', distinct_id: 'd1', properties: {}, timestamp: '2026-05-01T00:00:00Z' },+ { id: 'p1', properties: {} },+ ]+ let releaseStale: (() => void) | undefined+ const queryMock = performWideEventsQueryInTwoPhases as jest.Mock+ queryMock.mockReset()+ queryMock+ .mockImplementationOnce(+ async () =>+ await new Promise((resolve) => {+ releaseStale = () => resolve({ results: [eventRow('stale-event')] })+ })+ )+ .mockImplementation(async () => ({ results: [eventRow('fresh-event')] }))++ logic = hogFlowEditorTestLogic({ id: 'test-workflow' })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadSampleGlobals'])+ while (!releaseStale) {+ await new Promise((resolve) => setTimeout(resolve, 20))+ }++ logic.actions.loadSampleGlobals({})+ await expectLogic(logic).toDispatchActions(['loadSampleGlobalsSuccess'])+ expect(logic.values.sampleGlobals?.event?.uuid).toEqual('fresh-event')++ releaseStale!()+ await new Promise((resolve) => setTimeout(resolve, 50))++ expect(logic.values.sampleGlobals?.event?.uuid).toEqual('fresh-event')+ })++ it('keeps the newest sample event when an older query fails last', async () => {+ // The same overlap, but the older query fails for a real reason. Its failure belongs to+ // a load nobody is waiting for, so it must neither clear the event nor raise an error.+ const eventRow = (uuid: string): any[] => [+ { uuid, event: '$pageview', distinct_id: 'd1', properties: {}, timestamp: '2026-05-01T00:00:00Z' },+ { id: 'p1', properties: {} },+ ]+ let failStale: (() => void) | undefined+ const queryMock = performWideEventsQueryInTwoPhases as jest.Mock+ queryMock.mockReset()+ queryMock+ .mockImplementationOnce(+ async () =>+ await new Promise((_resolve, reject) => {+ failStale = () => reject(new Error('query failed'))+ })+ )+ .mockImplementation(async () => ({ results: [eventRow('fresh-event')] }))++ logic = hogFlowEditorTestLogic({ id: 'test-workflow' })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadSampleGlobals'])+ while (!failStale) {+ await new Promise((resolve) => setTimeout(resolve, 20))+ }++ logic.actions.loadSampleGlobals({})+ await expectLogic(logic).toDispatchActions(['loadSampleGlobalsSuccess'])+ expect(logic.values.sampleGlobals?.event?.uuid).toEqual('fresh-event')++ failStale!()+ await new Promise((resolve) => setTimeout(resolve, 50))++ expect(logic.values.sampleGlobals?.event?.uuid).toEqual('fresh-event')+ expect(logic.values.sampleGlobalsError).toBeNull()+ })++ it('still reports a failure that no later load supersedes', async () => {+ const queryMock = performWideEventsQueryInTwoPhases as jest.Mock+ queryMock.mockReset()+ queryMock.mockImplementation(async () => {+ throw new Error('query failed')+ })++ logic = hogFlowEditorTestLogic({ id: 'test-workflow' })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadSampleGlobals', 'setSampleGlobalsError'])+ expect(logic.values.sampleGlobalsError).toEqual('Failed to load matching events. Please try again.')+ })})describe('groupTypesForTest gating on group_analytics', () => {diff --git a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.tsindex 7712d45384a8..8d99583b6056 100644--- a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts+++ b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts@@ -1,8 +1,22 @@import { deepEqual as equal } from 'fast-equals'-import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import {+ MakeLogicType,+ actions,+ afterMount,+ connect,+ isBreakpoint,+ kea,+ key,+ listeners,+ path,+ props,+ reducers,+ selectors,+} from 'kea'import { forms } from 'kea-forms'import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'import { loaders } from 'kea-loaders'+import { subscriptions } from 'kea-subscriptions'import { lemonToast } from '@posthog/lemon-ui'@@ -28,6 +42,7 @@ import {import { WorkflowLogicProps, workflowLogic } from '../../../workflowLogic'import type { TriggerAction } from '../../../workflowLogic'import { hogFlowEditorLogic } from '../../hogFlowEditorLogic'+import type { HogFlowEditorMode } from '../../hogFlowEditorLogic'import { isSlackMessageTriggerConfig } from '../../registry/triggers/slackTriggerFilters'import { HogflowTestResult } from '../../steps/types'import { createExampleEvent, createExampleEventForTrigger } from '../../testEventFactory'@@ -130,6 +145,7 @@ export const createGlobalsFromResponse = (export interface hogFlowEditorTestLogicValues {groupsEnabled: boolean // groupsAccessLogicgroupTypes: Map<GroupTypeIndex, GroupType> // groupsModel+ mode: HogFlowEditorMode // hogFlowEditorLogicselectedNodeId: string | null // hogFlowEditorLogictriggerAction: TriggerAction | null // workflowLogicworkflow: HogFlow // workflowLogic@@ -149,6 +165,8 @@ export interface hogFlowEditorTestLogicValues {sampleGlobals: CyclotronJobInvocationGlobals | nullsampleGlobalsError: string | nullsampleGlobalsLoading: boolean+ sampleGlobalsStale: boolean+ shouldFilterTestAccounts: booleanshouldLoadSampleGlobals: booleanshowTestInvocationErrors: booleantestInvocation: HogflowTestInvocation@@ -228,9 +246,15 @@ export interface hogFlowEditorTestLogicActions {extendedSearch: boolean | undefined}}+ markSampleGlobalsStale: () => {+ value: true+ }receiveExampleGlobals: (globals: object | null) => {globals: object | null}+ reloadSampleGlobalsOrDefer: () => {+ value: true+ }resetAccumulatedVariables: () => {value: true}@@ -438,6 +462,135 @@ export interface hogFlowEditorTestLogicMeta {groupsEnabled: boolean,groupTypes: Map<GroupTypeIndex, GroupType>) => Map<GroupTypeIndex, GroupType>+ shouldFilterTestAccounts: (+ triggerAction:+ | ({+ config:+ | {+ type: 'schedule'+ }+ | {+ filters: {+ all_roles_unassigned?: boolean | undefined+ assigned_to_user_ids?: number[] | undefined+ assignment_status?: 'all' | 'assigned' | 'unassigned' | undefined+ audience_type?: 'accounts' | 'persons' | undefined+ properties: any[]+ tag_names?: string[] | undefined+ }+ type: 'batch'+ }+ | {+ filters: {+ actions?: any[] | undefined+ events?: any[] | undefined+ filter_test_accounts?: boolean | undefined+ properties?: any[] | undefined+ }+ type: 'event'+ }+ | {+ filters: {+ events: any[]+ properties?: any[] | undefined+ source: 'internal-events'+ }+ type: 'internal-event'+ }+ | {+ filters: {+ properties?: any[] | undefined+ }+ key_property?: string | undefined+ table_name: string+ type: 'data-warehouse-table'+ }+ | {+ filters: {+ properties?: any[] | undefined+ }+ key_property?: string | undefined+ table_name: string+ type: 'data-warehouse-view'+ }+ | {+ inputs: Record<+ string,+ {+ bytecode?: any+ order?: number | undefined+ secret?: boolean | undefined+ templating?: 'hog' | 'liquid' | undefined+ value: any+ }+ >+ template_id: string+ template_uuid?: string | undefined+ type: 'manual'+ }+ | {+ inputs: Record<+ string,+ {+ bytecode?: any+ order?: number | undefined+ secret?: boolean | undefined+ templating?: 'hog' | 'liquid' | undefined+ value: any+ }+ >+ template_id: string+ template_uuid?: string | undefined+ type: 'tracking_pixel'+ }+ | {+ inputs: Record<+ string,+ {+ bytecode?: any+ order?: number | undefined+ secret?: boolean | undefined+ templating?: 'hog' | 'liquid' | undefined+ value: any+ }+ >+ template_id: string+ template_uuid?: string | undefined+ type: 'webhook'+ }+ created_at?: number | undefined+ description: string+ filters?:+ | {+ actions?: any[] | undefined+ events?: any[] | undefined+ properties?: any[] | undefined+ }+ | null+ | undefined+ id: string+ name: string+ on_error?: 'abort' | 'continue' | null | undefined+ output_variable?:+ | {+ key: string+ label?: string | null | undefined+ result_path?: string | null | undefined+ spread?: boolean | null | undefined+ }+ | {+ key: string+ label?: string | null | undefined+ result_path?: string | null | undefined+ spread?: boolean | null | undefined+ }[]+ | null+ | undefined+ type: 'trigger'+ updated_at?: number | undefined+ } & Record<string, unknown>)+ | null+ ) => booleanmatchingFilters: (triggerAction:| ({@@ -587,7 +740,7 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([workflowLogic(props),['workflow', 'workflowSanitized', 'triggerAction'],hogFlowEditorLogic,- ['selectedNodeId'],+ ['selectedNodeId', 'mode'],groupsModel,['groupTypes'],groupsAccessLogic,@@ -597,6 +750,8 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([})),actions({setTestResult: (testResult: HogflowTestResult | null) => ({ testResult }),+ reloadSampleGlobalsOrDefer: true,+ markSampleGlobalsStale: true,setTestResultMode: (mode: 'raw' | 'diff') => ({ mode }),loadSampleGlobals: (payload?: { eventId?: string; extendedSearch?: boolean }) => ({eventId: payload?.eventId,@@ -631,6 +786,13 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([setTestResultMode: (_, { mode }) => mode,},],+ sampleGlobalsStale: [+ false,+ {+ markSampleGlobalsStale: () => true,+ loadSampleGlobals: () => false,+ },+ ],sampleGlobalsError: [null as string | null,{@@ -715,10 +877,14 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([sampleGlobals: [null as CyclotronJobInvocationGlobals | null,{- loadSampleGlobals: async ({ extendedSearch }) => {+ loadSampleGlobals: async ({ extendedSearch }, breakpoint) => {if (!values.shouldLoadSampleGlobals) {return null}+ // Editing a filter changes these on every keystroke. Waiting here collapses a+ // burst into one query and drops any earlier load still in flight, so the event+ // shown is the one the current filters asked for.+ await breakpoint(300)try {// Use extended or standard search range@@ -728,6 +894,7 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([const query: EventsQuery = {kind: NodeKind.EventsQuery,fixedProperties: [values.matchingFilters],+ filterTestAccounts: values.shouldFilterTestAccounts,select: ['*', 'person', ...groupSelectColumns(values.groupTypesForTest)],after: timeRange,limit: 10,@@ -739,6 +906,9 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([}const response = await performWideEventsQueryInTwoPhases(query)+ // The wait above only collapses calls still queued. A response that lands after a+ // newer load started must not overwrite that load's result.+ breakpoint()if (!response?.results?.[0]) {// No matching events found@@ -791,9 +961,15 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([groups)} catch (e: any) {- if (!e.message?.includes('breakpoint')) {- actions.setSampleGlobalsError('Failed to load matching events. Please try again.')+ // A superseded load must not resolve at all, whether it was cancelled or it+ // failed. Either way, returning here would set the sample event to null over+ // the result of the load that replaced it, and raise an error about a load+ // nobody is waiting for.+ if (isBreakpoint(e)) {+ throw e}+ breakpoint()+ actions.setSampleGlobalsError('Failed to load matching events. Please try again.')return null}},@@ -891,6 +1067,17 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([(groupsEnabled: boolean, groupTypes: Map<GroupTypeIndex, GroupType>): Map<GroupTypeIndex, GroupType> =>groupsEnabled ? groupTypes : new Map(),],+ // The trigger honours this at runtime, so the sample has to as well, or the panel offers an+ // event from a test account that the live trigger would reject.+ shouldFilterTestAccounts: [+ (s) => [s.triggerAction],+ (triggerAction: null | import('../../../workflowLogic').TriggerAction): boolean => {+ if (!triggerAction || triggerAction.config.type !== 'event') {+ return false+ }+ return !!triggerAction.config.filters?.filter_test_accounts+ },+ ],// TODO(workflows): DRY up matchingFilters with implementation in hogFunctionConfigurationLogicmatchingFilters: [(s) => [s.triggerAction],@@ -1028,6 +1215,13 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([},})),listeners(({ values, actions }) => ({+ reloadSampleGlobalsOrDefer: () => {+ if (values.mode === 'test') {+ actions.loadSampleGlobals()+ return+ }+ actions.markSampleGlobalsStale()+ },setTestResult: ({ testResult }) => {if (testResult?.nextActionId && values.selectedNodeId) {actions.setAnimatingEdgePair(values.selectedNodeId, testResult.nextActionId)@@ -1052,6 +1246,36 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([},})),+ subscriptions(({ actions, values }) => ({+ // Build mounts this panel too, because the output mapping UI reads the sample event. A+ // reload there would spend a query for someone who may never open Test, so it waits.+ mode: (mode, previousMode) => {+ if (mode !== 'test' || mode === previousMode || !values.sampleGlobalsStale) {+ return+ }+ actions.loadSampleGlobals()+ },+ shouldFilterTestAccounts: (value, previousValue) => {+ if (previousValue === undefined || value === previousValue || !values.shouldLoadSampleGlobals) {+ return+ }+ actions.reloadSampleGlobalsOrDefer()+ },+ matchingFilters: (filters, previousFilters) => {+ // The panel renders the pick-an-event-by-name selector only while this is false, so+ // returning here is what leaves a deliberate pick alone.+ if (previousFilters === undefined || !values.shouldLoadSampleGlobals) {+ return+ }+ // The selector rebuilds on any workflow edit, so compare the filters themselves rather+ // than the object identity, or an unrelated change to a step would refetch the event.+ if (JSON.stringify(filters) === JSON.stringify(previousFilters)) {+ return+ }+ actions.reloadSampleGlobalsOrDefer()+ },+ })),+afterMount(({ actions, values }) => {// If we can load actual events (i.e., trigger is configured), load them automaticallyif (values.shouldLoadSampleGlobals) {