: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): respect groups in workflow test runs (#61480)
Harley Alexander638ef884e8ed
diff --git a/nodejs/src/cdp/cdp-api.test.ts b/nodejs/src/cdp/cdp-api.test.tsindex 339283955fd8..0c5876cc3608 100644--- a/nodejs/src/cdp/cdp-api.test.ts+++ b/nodejs/src/cdp/cdp-api.test.ts@@ -688,6 +688,83 @@ describe('CDP API', () => {})})+ describe('hogflow invocation groups', () => {+ const resolvedGroup = {+ id: 'org-1',+ type: 'organization',+ index: 0,+ url: 'http://localhost:8000/groups/0/org-1',+ properties: { plan: 'enterprise' },+ }++ const groupGlobals: Partial<HogFunctionInvocationGlobals> = {+ ...globals,+ groups: {},+ event: {+ ...globals.event!,+ properties: { $groups: { organization: 'org-1' } },+ },+ }++ let executeSpy: jest.SpyInstance+ let getGroupsSpy: jest.SpyInstance++ beforeEach(() => {+ executeSpy = jest.spyOn(api['hogFlowExecutor'], 'executeCurrentAction').mockImplementation(((+ invocation: any+ ) =>+ Promise.resolve({+ invocation,+ error: null,+ logs: [],+ execResult: null,+ })) as any)+ getGroupsSpy = jest+ .spyOn(api['groupsManager'], 'getGroupsForEvent')+ .mockResolvedValue({ organization: resolvedGroup })+ })++ afterEach(() => {+ executeSpy.mockRestore()+ getGroupsSpy.mockRestore()+ })++ it('resolves groups from the event when none are provided', async () => {+ const res = await supertest(app)+ .post(`/api/projects/${team.id}/hog_flows/new/invocations`)+ .send({ globals: groupGlobals, mock_async_functions: true, configuration: {} })++ expect(res.status).toEqual(200)+ expect(getGroupsSpy).toHaveBeenCalledWith(+ team.id,+ expect.objectContaining({ $groups: { organization: 'org-1' } }),+ expect.stringContaining(`/project/${team.id}`)+ )+ // Resolved groups flow into filterGlobals so conditional branches can evaluate them+ const invocation = executeSpy.mock.calls[0][0]+ expect(invocation.filterGlobals.group_0).toEqual({ properties: { plan: 'enterprise' } })+ expect(invocation.filterGlobals.$group_0).toEqual('org-1')+ })++ it('does not override groups provided in the payload', async () => {+ const providedGroups = {+ organization: { ...resolvedGroup, id: 'org-provided', properties: { plan: 'startup' } },+ }+ const res = await supertest(app)+ .post(`/api/projects/${team.id}/hog_flows/new/invocations`)+ .send({+ globals: { ...groupGlobals, groups: providedGroups },+ mock_async_functions: true,+ configuration: {},+ })++ expect(res.status).toEqual(200)+ expect(getGroupsSpy).not.toHaveBeenCalled()+ const invocation = executeSpy.mock.calls[0][0]+ expect(invocation.filterGlobals.$group_0).toEqual('org-provided')+ })+ })+describe('batch hogflow invocations', () => {let batchHogFlow: HogFlowlet produceSpy: jest.SpyInstancediff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.tsindex ab81f078232d..c2e27af07dee 100644--- a/nodejs/src/cdp/cdp-api.ts+++ b/nodejs/src/cdp/cdp-api.ts@@ -96,6 +96,7 @@ export class CdpApi {private recipientTokensService: RecipientTokensServiceprivate outputs: CdpOutputsprivate batchExportHogFunctionService: BatchExportHogFunctionService+ private groupsManager: GroupsManagerServiceconstructor(private config: PluginsServerConfig,@@ -130,10 +131,11 @@ export class CdpApi {services.hogFunctionMonitoringService,services.recipientsManager)+ this.groupsManager = new GroupsManagerService(deps.teamManager, deps.groupRepository)this.batchExportHogFunctionService = new BatchExportHogFunctionService(config.SITE_URL,deps.teamManager,- new GroupsManagerService(deps.teamManager, deps.groupRepository),+ this.groupsManager,this.hogFunctionManager,this.hogExecutor,this.hogWatcher,@@ -538,6 +540,17 @@ export class CdpApi {team_id: team.id,}+ // Mirror real execution: resolve groups server-side from the event's $groups so test-run+ // conditionals branch on group properties. Only resolve when the caller didn't supply+ // groups, so hand-edited test payloads are respected.+ if (!globals.groups || Object.keys(globals.groups).length === 0) {+ globals.groups = await this.groupsManager.getGroupsForEvent(+ team.id,+ globals.event.properties,+ `${this.config.SITE_URL ?? 'http://localhost:8000'}/project/${team.id}`+ )+ }+const triggerGlobals: HogFunctionInvocationGlobals = {...globals,project: {diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 5ffb82e05f72..14ca16de8ee9 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -701,6 +701,12 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vie# session auth, so live sizing while editing is unaffected.if self.action == "user_blast_radius":return ["hog_flow:read", "person:read"]+ # A test invocation resolves the event's $groups into real group properties server-side, so a+ # hog_flow:write-only token could branch on group_0.properties and read the returned logs/variables+ # as a group-property oracle. Require group:read on top. The web builder uses session auth, so+ # running tests while editing is unaffected.+ if self.action == "invocations":+ return ["hog_flow:write", "group:read"]return Nonedef get_serializer_class(self) -> type[BaseSerializer]:diff --git a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.test.tsindex 985ca6d28300..52610322c15d 100644--- a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.test.ts+++ b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.test.ts@@ -1,12 +1,110 @@import { expectLogic } from 'kea-test-utils'import { initKeaTests } from '~/test/init'+import { GroupType, GroupTypeIndex } from '~/types'-import { hogFlowEditorTestLogic } from './hogFlowEditorTestLogic'+import {+ createGlobalsFromResponse,+ groupSelectColumns,+ hogFlowEditorTestLogic,+ parseGroupsFromResult,+} from './hogFlowEditorTestLogic'describe('hogFlowEditorTestLogic', () => {let logic: ReturnType<typeof hogFlowEditorTestLogic.build>+ const groupTypes = new Map<GroupTypeIndex, GroupType>([+ [0 as GroupTypeIndex, { group_type: 'organization', group_type_index: 0 } as GroupType],+ [1 as GroupTypeIndex, { group_type: 'project', group_type_index: 1 } as GroupType],+ ])++ describe('groupSelectColumns', () => {+ it('produces one tuple column per group type', () => {+ const columns = groupSelectColumns(groupTypes)+ expect(columns).toHaveLength(2)+ expect(columns[0]).toContain('organization')+ expect(columns[0]).toContain('.key')+ expect(columns[0]).toContain('.properties')+ expect(columns[1]).toContain('project')+ })++ it('returns nothing when there are no group types', () => {+ expect(groupSelectColumns(new Map())).toEqual([])+ })+ })++ describe('parseGroupsFromResult', () => {+ it('maps group tuples to resolved groups with key and properties', () => {+ const result = [+ { uuid: 'e1' },+ { id: 'p1' },+ ['2021-01-01', 0, 'org-1', JSON.stringify({ plan: 'enterprise' }), '2021-01-02'],+ ['2021-01-01', 1, 'proj-1', JSON.stringify({ tier: 'gold' }), '2021-01-02'],+ ]++ const groups = parseGroupsFromResult(result, groupTypes)++ expect(groups.organization).toMatchObject({+ type: 'organization',+ index: 0,+ id: 'org-1',+ properties: { plan: 'enterprise' },+ })+ expect(groups.organization.url).toContain('/groups/0/org-1')+ expect(groups.project).toMatchObject({ id: 'proj-1', properties: { tier: 'gold' } })+ })++ it('aligns columns by position when group type indices are non-contiguous', () => {+ // Only group type index 1 exists (index 0 absent) — column sits at result[2], not result[3]+ const sparseGroupTypes = new Map<GroupTypeIndex, GroupType>([+ [1 as GroupTypeIndex, { group_type: 'project', group_type_index: 1 } as GroupType],+ ])+ const result = [+ { uuid: 'e1' },+ { id: 'p1' },+ ['2021-01-01', 1, 'proj-1', JSON.stringify({ tier: 'gold' }), '2021-01-02'],+ ]++ const groups = parseGroupsFromResult(result, sparseGroupTypes)+ expect(groups.project).toMatchObject({ index: 1, id: 'proj-1', properties: { tier: 'gold' } })+ })++ it('skips group types with no matching group on the event', () => {+ const result = [{ uuid: 'e1' }, { id: 'p1' }, ['2021-01-01', 0, '', '{}', '2021-01-02']]+ expect(parseGroupsFromResult(result, groupTypes)).toEqual({})+ })++ it('falls back to empty properties on malformed JSON', () => {+ const result = [{ uuid: 'e1' }, { id: 'p1' }, ['2021-01-01', 0, 'org-1', 'not json', '2021-01-02']]+ expect(parseGroupsFromResult(result, groupTypes).organization.properties).toEqual({})+ })+ })++ describe('createGlobalsFromResponse groups', () => {+ const event = {+ uuid: 'e1',+ distinct_id: 'd1',+ timestamp: '2021-01-01',+ elements_chain: '',+ event: '$pageview',+ properties: {},+ }++ it('includes the groups passed in', () => {+ const groups = parseGroupsFromResult(+ [event, { id: 'p1', properties: {} }, ['2021-01-01', 0, 'org-1', '{}', '2021-01-02']],+ groupTypes+ )+ const globals = createGlobalsFromResponse(event, { id: 'p1', properties: {} }, 1, 'wf', groups)+ expect(globals.groups?.organization?.id).toEqual('org-1')+ })++ it('defaults groups to an empty object', () => {+ const globals = createGlobalsFromResponse(event, undefined, 1, 'wf')+ expect(globals.groups).toEqual({})+ })+ })+beforeEach(() => {initKeaTests()})diff --git a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.tsindex b1e1d40acd41..50d938d5f12c 100644--- a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts+++ b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts@@ -9,13 +9,16 @@ import api from 'lib/api'import { dayjs } from 'lib/dayjs'import { uuid } from 'lib/utils'+import { groupsModel } from '~/models/groupsModel'import { performQuery } from '~/queries/query'import { EventsQuery, NodeKind } from '~/queries/schema/schema-general'-import { hogql } from '~/queries/utils'+import { escapePropertyAsHogQLIdentifier, hogql } from '~/queries/utils'import {AnyPropertyFilter,CyclotronJobInvocationGlobals,FilterLogicalOperator,+ GroupType,+ GroupTypeIndex,PropertyFilterType,PropertyGroupFilter,PropertyGroupFilterValue,@@ -82,11 +85,53 @@ export const createExampleEvent = (}}+// HogQL tuple columns appended to the events query so we can resolve each group type's+// key + properties for the sample, mirroring real execution which resolves them from $groups.+export const groupSelectColumns = (groupTypes: Map<GroupTypeIndex, GroupType>): string[] => {+ const columns: string[] = []+ groupTypes.forEach((groupType) => {+ const name = escapePropertyAsHogQLIdentifier(groupType.group_type)+ columns.push(`tuple(${name}.created_at, ${name}.index, ${name}.key, ${name}.properties, ${name}.updated_at)`)+ })+ return columns+}++// Parse the group tuples appended by groupSelectColumns (offsets start after event + person).+export const parseGroupsFromResult = (+ result: any[],+ groupTypes: Map<GroupTypeIndex, GroupType>+): NonNullable<CyclotronJobInvocationGlobals['groups']> => {+ const groups: NonNullable<CyclotronJobInvocationGlobals['groups']> = {}+ // Use a positional counter, not the Map key: groupSelectColumns appends columns in iteration+ // order, so column n sits at result[2 + n] regardless of each type's group_type_index.+ let position = 0+ groupTypes.forEach((groupType) => {+ const tuple = result?.[2 + position++]+ if (tuple && Array.isArray(tuple) && tuple[2]) {+ let properties = {}+ try {+ properties = JSON.parse(tuple[3])+ } catch {+ // Ignore malformed properties+ }+ groups[groupType.group_type] = {+ type: groupType.group_type,+ index: tuple[1],+ id: tuple[2],+ url: `${window.location.origin}/groups/${tuple[1]}/${encodeURIComponent(tuple[2])}`,+ properties,+ }+ }+ })+ return groups+}+export const createGlobalsFromResponse = (event: any,person: any,teamId: number,- workflowName?: string | null+ workflowName?: string | null,+ groups: CyclotronJobInvocationGlobals['groups'] = {}): CyclotronJobInvocationGlobals => {const projectUrl = `${window.location.origin}/project/${teamId}`return {@@ -109,7 +154,7 @@ export const createGlobalsFromResponse = (url: `${window.location.origin}/person/${person.id}`,}: undefined,- groups: {},+ groups,project: {id: teamId,name: 'Default project',@@ -132,6 +177,8 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([['workflow', 'workflowSanitized', 'triggerAction'],hogFlowEditorLogic,['selectedNodeId'],+ groupsModel,+ ['groupTypes'],],actions: [hogFlowEditorLogic, ['setSelectedNodeId', 'setAnimatingEdgePair']],})),@@ -268,7 +315,7 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([const query: EventsQuery = {kind: NodeKind.EventsQuery,fixedProperties: [values.matchingFilters],- select: ['*', 'person'],+ select: ['*', 'person', ...groupSelectColumns(values.groupTypes)],after: timeRange,limit: 10,orderBy: ['timestamp DESC'],@@ -321,8 +368,15 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([const event = response.results[resultIndex][0]const person = response.results[resultIndex][1]-- return createGlobalsFromResponse(event, person, values.workflow.team_id, values.workflow.name)+ const groups = parseGroupsFromResult(response.results[resultIndex], values.groupTypes)++ return createGlobalsFromResponse(+ event,+ person,+ values.workflow.team_id,+ values.workflow.name,+ groups+ )} catch (e: any) {if (!e.message?.includes('breakpoint')) {actions.setSampleGlobalsError('Failed to load matching events. Please try again.')@@ -351,7 +405,7 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([],},],- select: ['*', 'person'],+ select: ['*', 'person', ...groupSelectColumns(values.groupTypes)],after: timeRange,limit: 1,orderBy: ['timestamp DESC'],@@ -385,10 +439,17 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([const event = response.results[0][0]const person = response.results[0][1]+ const groups = parseGroupsFromResult(response.results[0], values.groupTypes)actions.setSampleGlobalsError(null)actions.setCanTryExtendedSearch(false)- return createGlobalsFromResponse(event, person, values.workflow.team_id, values.workflow.name)+ return createGlobalsFromResponse(+ event,+ person,+ values.workflow.team_id,+ values.workflow.name,+ groups+ )} catch {actions.setSampleGlobalsError('Failed to load event. Please try again.')return null