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(flags): count mode 2 flag calls in destination and workflow estimates (#121813)

Phil Haack0e973285bbcb
diff --git a/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx b/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx
index a644b8f95e69..16e406fc89df 100644
--- a/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx
+++ b/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx
@@ -17,6 +17,7 @@ import {
FEATURE_FLAG_CALLED_EVENT,
reachesPastFlagEvaluationsRetention,
readsFlagEvaluationsTable,
+ storesFlagCallsOutsideEvents,
} from 'scenes/feature-flags/flagEvaluationsTable'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene } from 'scenes/sceneTypes'
@@ -24,7 +25,6 @@ import { filterTestAccountsDefaultsLogic } from 'scenes/settings/environment/fil
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
-import { FlagEvaluationsModeEnumApi } from '~/generated/core/api.schemas'
import { getDefaultEventsQueryForTeam } from '~/queries/nodes/DataTable/defaultEventsQuery'
import { performQuery } from '~/queries/query'
import { DataTableNode, EventsQuery, Node, ProductKey } from '~/queries/schema/schema-general'
@@ -34,8 +34,6 @@ import { ActivityTab, Breadcrumb } from '~/types'
import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import type { TeamPublicType, TeamType } from '../../../types'
-const FLAG_EVALUATIONS_ONLY_MODE = FlagEvaluationsModeEnumApi.Number2
-
export type FlagCallsNote = 'stored-separately' | 'retention'
// Mirrors EventsQueryRunner._list_table, which reads flag_evaluations only for a list of nothing but flag calls.
@@ -141,7 +139,7 @@ export const eventsSceneLogic = kea<eventsSceneLogicType>([
// A reload after the user clears the event runs the check again, because the URL then holds the cleared lookup.
nameFlagCallLookup: async ({ query }, breakpoint) => {
if (
- values.currentTeam?.flag_evaluations_mode !== FLAG_EVALUATIONS_ONLY_MODE ||
+ !storesFlagCallsOutsideEvents(values.currentTeam) ||
!isDataTableNode(query) ||
!isEventsQuery(query.source) ||
!isUnnamedEventLookup(query.source)
@@ -198,9 +196,7 @@ export const eventsSceneLogic = kea<eventsSceneLogicType>([
return null
}
if (!listsOnlyFlagCalls(query.source)) {
- return currentTeam?.flag_evaluations_mode === FLAG_EVALUATIONS_ONLY_MODE
- ? 'stored-separately'
- : null
+ return storesFlagCallsOutsideEvents(currentTeam) ? 'stored-separately' : null
}
const { after } = query.source
// The runner reads a missing start as the last 24 hours. The retention window covers that range.
diff --git a/frontend/src/scenes/feature-flags/flagEvaluationsTable.ts b/frontend/src/scenes/feature-flags/flagEvaluationsTable.ts
index 9983ea7be0dd..e03008c9a620 100644
--- a/frontend/src/scenes/feature-flags/flagEvaluationsTable.ts
+++ b/frontend/src/scenes/feature-flags/flagEvaluationsTable.ts
@@ -12,11 +12,17 @@ export const FLAG_EVALUATIONS_TABLE = 'posthog.flag_evaluations'
export const FEATURE_FLAG_CALLED_EVENT = '$feature_flag_called'
const EVENTS_MODE = FlagEvaluationsModeEnumApi.Number0
+const FLAG_EVALUATIONS_ONLY_MODE = FlagEvaluationsModeEnumApi.Number2
export function readsFlagEvaluationsTable(team: TeamPublicType | TeamType | null): boolean {
return (team?.flag_evaluations_mode ?? EVENTS_MODE) !== EVENTS_MODE
}
+/** Whether ingestion writes the team's flag calls to flag_evaluations instead of `events`. */
+export function storesFlagCallsOutsideEvents(team: TeamPublicType | TeamType | null): boolean {
+ return team?.flag_evaluations_mode === FLAG_EVALUATIONS_ONLY_MODE
+}
+
/**
* How long a row stays in flag_evaluations. The events table keeps $feature_flag_called forever.
* Keep it equal to FLAG_EVALUATIONS_TTL_DAYS in posthog/models/flag_evaluations/sql.py.
diff --git a/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.test.ts b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.test.ts
index 305f7ff48835..9af3e7ba6ed7 100644
--- a/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.test.ts
+++ b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.test.ts
@@ -1,13 +1,28 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
import { expectLogic } from 'kea-test-utils'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { ApiError } from 'lib/api-error'
+import { teamLogic } from 'scenes/teamLogic'
+import { FlagEvaluationsModeEnumApi } from '~/generated/core/api.schemas'
+import { performQuery } from '~/queries/query'
+import { NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
-import { CyclotronJobFiltersType, HogFunctionTemplateType, HogFunctionType } from '~/types'
-
+import {
+ CyclotronJobFilterEvents,
+ CyclotronJobFiltersType,
+ HogFunctionTemplateType,
+ HogFunctionType,
+ PropertyFilterType,
+ PropertyOperator,
+} from '~/types'
+
+import { FLAG_CALLS_NOT_LOADABLE } from '../filters/flagCallsMatching'
+import { performWideEventsQueryInTwoPhases } from '../sampleEventsQuery'
import { hogFunctionConfigurationLogic, sanitizeInputs } from './hogFunctionConfigurationLogic'
jest.mock('lib/api', () => ({
@@ -20,6 +35,16 @@ jest.mock('lib/api', () => ({
},
}))
+jest.mock('~/queries/query', () => ({
+ ...jest.requireActual('~/queries/query'),
+ performQuery: jest.fn(),
+}))
+
+jest.mock('../sampleEventsQuery', () => ({
+ ...jest.requireActual('../sampleEventsQuery'),
+ performWideEventsQueryInTwoPhases: jest.fn(),
+}))
+
// the mock api object
const mockApi = api.hogFunctions as jest.Mocked<typeof api.hogFunctions>
@@ -349,4 +374,113 @@ describe('hogFunctionConfigurationLogic', () => {
expect(mockApi.update).not.toHaveBeenCalled()
})
})
+
+ describe('a destination on feature flag calls', () => {
+ const FLAG_CALLED: CyclotronJobFilterEvents = {
+ id: '$feature_flag_called',
+ name: '$feature_flag_called',
+ type: 'events',
+ order: 0,
+ properties: [
+ {
+ key: '$feature_flag',
+ value: 'my-flag',
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Event,
+ },
+ ],
+ }
+ const PAGEVIEW: CyclotronJobFilterEvents = { id: '$pageview', name: '$pageview', type: 'events', order: 1 }
+ const NO_MATCH_IN_30_DAYS =
+ 'No events match these filters in the last 30 days. Showing an example $pageview event instead.'
+
+ function mountOnMode(
+ mode: FlagEvaluationsModeEnumApi,
+ events: CyclotronJobFilterEvents[] = [FLAG_CALLED]
+ ): void {
+ mockApi.getTemplate.mockReturnValue(Promise.resolve({ ...HOG_TEMPLATE, filters: { events } }))
+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, flag_evaluations_mode: mode })
+ logic = hogFunctionConfigurationLogic({ templateId: 'test' })
+ logic.mount()
+ }
+
+ beforeEach(() => {
+ initKeaTests()
+ ;(performQuery as jest.Mock).mockReset()
+ ;(performQuery as jest.Mock).mockImplementation(async (query) =>
+ query.kind === NodeKind.EventsQuery
+ ? {
+ results: [
+ ['2026-10-16', 700],
+ ['2026-10-17', 3],
+ ],
+ }
+ : {
+ results: [
+ {
+ data: [0, 500, 0],
+ count: 500,
+ labels: ['15-Oct-2026', '16-Oct-2026', '17-Oct-2026'],
+ days: ['2026-10-15', '2026-10-16', '2026-10-17'],
+ },
+ ],
+ }
+ )
+ ;(performWideEventsQueryInTwoPhases as jest.Mock).mockReset()
+ ;(performWideEventsQueryInTwoPhases as jest.Mock).mockResolvedValue({ results: [] })
+ })
+
+ // Mode 1 still writes flag calls to events, so only mode 2 adds the flag_evaluations count.
+ it.each([
+ ['events', FlagEvaluationsModeEnumApi.Number0, 500, [0, 0, 0]],
+ ['read flag evaluations', FlagEvaluationsModeEnumApi.Number1, 500, [0, 0, 0]],
+ ['flag evaluations only', FlagEvaluationsModeEnumApi.Number2, 1203, [0, 200, 0]],
+ ])('estimates the calls it would receive on the %s mode', async (_name, mode, count, highVolume) => {
+ mountOnMode(mode)
+ await expectLogic(logic).toDispatchActions(['loadTemplateSuccess', 'sparklineQueryChangedSuccess'])
+
+ expect(logic.values.sparkline?.count).toEqual(count)
+ expect(logic.values.sparkline?.data.find(({ name }) => name === 'High volume')?.values).toEqual(highVolume)
+ })
+
+ it.each([
+ [
+ 'events mode',
+ FlagEvaluationsModeEnumApi.Number0,
+ [FLAG_CALLED],
+ NO_MATCH_IN_30_DAYS,
+ '$pageview',
+ undefined,
+ ],
+ // The example flag call names the flag that the destination filters on, so a test run passes the filters.
+ [
+ 'flag evaluations only mode',
+ FlagEvaluationsModeEnumApi.Number2,
+ [FLAG_CALLED],
+ `${FLAG_CALLS_NOT_LOADABLE} Showing an example $feature_flag_called event instead.`,
+ '$feature_flag_called',
+ 'my-flag',
+ ],
+ // A pageview can still match, so the notice about flag calls does not apply.
+ [
+ 'flag evaluations only mode with a pageview matcher',
+ FlagEvaluationsModeEnumApi.Number2,
+ [FLAG_CALLED, PAGEVIEW],
+ NO_MATCH_IN_30_DAYS,
+ '$pageview',
+ undefined,
+ ],
+ ])('explains a missing test event on the %s', async (_name, mode, events, message, exampleEvent, flagKey) => {
+ mountOnMode(mode, events)
+ await expectLogic(logic).toDispatchActions(['loadTemplateSuccess'])
+
+ await expectLogic(logic, () => {
+ logic.actions.loadSampleGlobals()
+ }).toDispatchActions(['loadSampleGlobalsSuccess'])
+
+ expect(logic.values.sampleGlobalsError).toEqual(message)
+ expect(logic.values.sampleGlobals?.event.event).toEqual(exampleEvent)
+ expect(logic.values.sampleGlobals?.event.properties.$feature_flag).toEqual(flagKey)
+ })
+ })
})
diff --git a/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx
index 2b31bf8d82e5..5d979834eedf 100644
--- a/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx
+++ b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx
@@ -34,6 +34,7 @@ import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { uuid } from 'lib/utils/dom'
import { addProductIntent } from 'lib/utils/product-intents'
+import { FEATURE_FLAG_CALLED_EVENT } from 'scenes/feature-flags/flagEvaluationsTable'
import { projectLogic } from 'scenes/projectLogic'
import { buildSurveyExampleInvocationGlobals } from 'scenes/surveys/utils'
import { teamLogic } from 'scenes/teamLogic'
@@ -43,7 +44,6 @@ import { userLogic } from 'scenes/userLogic'
import { deleteFromTree, refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'
import { groupsModel } from '~/models/groupsModel'
import { defaultDataTableColumns } from '~/queries/nodes/DataTable/utils'
-import { performQuery } from '~/queries/query'
import {
DataTableNode,
EventsNode,
@@ -86,7 +86,14 @@ import { asDisplay } from 'products/persons/frontend/person-utils'
import type { GroupType, GroupTypeIndex, HogFunctionMappingTemplateType, ProjectType } from '../../../types'
import type { TeamPublicType, TeamType } from '../../../types'
-import { matchingFiltersToPropertyGroup } from '../filters/matchingFilters'
+import {
+ FLAG_CALLS_NOT_LOADABLE,
+ exampleFlagCall,
+ flagCallsOutsideEventsFilters,
+ matchesOnlyFlagCallsOutsideEvents,
+ performTrendsQueryWithFlagCalls,
+} from '../filters/flagCallsMatching'
+import { MatchingFiltersInput, matchingFiltersToPropertyGroup } from '../filters/matchingFilters'
import { performWideEventsQueryInTwoPhases } from '../sampleEventsQuery'
import { eventToHogFunctionContextId } from '../sub-templates/sub-templates'
import { SAMPLE_GLOBALS_CONTEXTS } from './sampleGlobalsContexts'
@@ -99,6 +106,7 @@ export interface HogFunctionConfigurationLogicProps {
}
export const EVENT_VOLUME_DAILY_WARNING_THRESHOLD = 1000
+const SPARKLINE_DAYS = 7
const UNSAVED_CONFIGURATION_TTL = 1000 * 60 * 5
export const HOG_CODE_SIZE_LIMIT = 100 * 1024 // 100KB to match backend limit
@@ -369,6 +377,7 @@ export interface hogFunctionConfigurationLogicValues {
eventsDataTableNode: DataTableNode | null
exampleInvocationGlobals: CyclotronJobInvocationGlobals
filtersContainPersonProperties: boolean
+ flagCallsOutsideEvents: PropertyGroupFilter | null
hasGroupsAddon: boolean
hasHadSubmissionErrors: boolean
hogFunction: HogFunctionType | null
@@ -390,6 +399,7 @@ export interface hogFunctionConfigurationLogicValues {
logicProps: HogFunctionConfigurationLogicProps
mappingTemplates: HogFunctionMappingTemplateType[]
matchingFilters: PropertyGroupFilter
+ matchingFiltersInput: MatchingFiltersInput | null
mightDropEvents: boolean
newFilters: CyclotronJobFiltersType | null
newHogCode: string | null
@@ -622,23 +632,23 @@ export interface hogFunctionConfigurationLogicActions {
sparklineQueryChangedSuccess: (
sparkline:
| {
- count: any
+ count: number
data: {
color: string
name: string
values: number[]
}[]
- labels: any
+ labels: string[]
warning: string | undefined
}
| {
- count: any
+ count: number
data: {
color: string
name: string
values: number[]
}[]
- labels: any
+ labels: string[]
warning?: undefined
}
| null,
@@ -648,23 +658,23 @@ export interface hogFunctionConfigurationLogicActions {
) => {
sparkline:
| {
- count: any
+ count: number
data: {
color: string
name: string
values: number[]
}[]
- labels: any
+ labels: string[]
warning: string | undefined
}
| {
- count: any
+ count: number
data: {
color: string
name: string
values: number[]
}[]
- labels: any
+ labels: string[]
warning?: undefined
}
| null
@@ -766,10 +776,16 @@ export interface hogFunctionConfigurationLogicMeta {
exampleInvocationGlobals: CyclotronJobInvocationGlobals,
configuration: HogFunctionConfigurationType
) => CyclotronJobInvocationGlobalsWithInputs
- matchingFilters: (
+ matchingFiltersInput: (
configuration: HogFunctionConfigurationType,
useMapping: number | true | undefined
- ) => PropertyGroupFilter
+ ) => MatchingFiltersInput | null
+ matchingFilters: (matchingFiltersInput: MatchingFiltersInput | null) => PropertyGroupFilter
+ flagCallsOutsideEvents: (
+ matchingFiltersInput: MatchingFiltersInput | null,
+ sourceUsesEvents: boolean,
+ currentTeam: TeamPublicType | TeamType | null
+ ) => PropertyGroupFilter | null
filtersContainPersonProperties: (configuration: HogFunctionConfigurationType) => boolean
sourceUsesEvents: (configuration: HogFunctionConfigurationType, type: HogFunctionTypeType) => boolean
sparklineQuery: (
@@ -1096,10 +1112,17 @@ export const hogFunctionConfigurationLogic = kea<hogFunctionConfigurationLogicTy
} else {
await breakpoint(1000)
}
- const result = await performQuery(sparklineQuery)
+ const {
+ data: dataValues,
+ count,
+ labels,
+ } = await performTrendsQueryWithFlagCalls(
+ sparklineQuery,
+ values.flagCallsOutsideEvents,
+ SPARKLINE_DAYS
+ )
breakpoint()
- const dataValues: number[] = result?.results?.[0]?.data ?? []
const showVolumeWarning = TYPES_WITH_VOLUME_WARNING.includes(values.type)
if (showVolumeWarning) {
@@ -1123,7 +1146,7 @@ export const hogFunctionConfigurationLogic = kea<hogFunctionConfigurationLogicTy
color: 'warning',
},
]
- return { data, count: result?.results?.[0]?.count, labels: result?.results?.[0]?.labels }
+ return { data, count, labels }
}
// For transformations, just show the raw values without warning thresholds
const data = [
@@ -1135,8 +1158,8 @@ export const hogFunctionConfigurationLogic = kea<hogFunctionConfigurationLogicTy
]
return {
data,
- count: result?.results?.[0]?.count,
- labels: result?.results?.[0]?.labels,
+ count,
+ labels,
warning:
values.type === 'transformation'
? 'Historical volume may not reflect future volume after transformation is applied.'
@@ -1171,8 +1194,15 @@ export const hogFunctionConfigurationLogic = kea<hogFunctionConfigurationLogicTy
if (!values.lastEventQuery) {
return values.sampleGlobals
}
- const errorMessage =
- 'No events match these filters in the last 30 days. Showing an example $pageview event instead.'
+ const matchers = values.matchingFiltersInput ?? {}
+ const flagCallsNotLoadable = matchesOnlyFlagCallsOutsideEvents(values.currentTeam, matchers)
+ // A test run applies the destination filters, so a flag call destination needs a flag call example.
+ const fallbackGlobals = flagCallsNotLoadable
+ ? exampleFlagCall(values.exampleInvocationGlobals, matchers)
+ : values.exampleInvocationGlobals
+ const errorMessage = flagCallsNotLoadable
+ ? `${FLAG_CALLS_NOT_LOADABLE} Showing an example ${FEATURE_FLAG_CALLED_EVENT} event instead.`
+ : 'No events match these filters in the last 30 days. Showing an example $pageview event instead.'
try {
await breakpoint(values.sampleGlobals === null ? 10 : 1000)
let response = await performWideEventsQueryInTwoPhases({
@@ -1233,7 +1263,7 @@ export const hogFunctionConfigurationLogic = kea<hogFunctionConfigurationLogicTy
if (!isBreakpoint(e)) {
actions.setSampleGlobalsError(e.message ?? errorMessage)
}
- return values.exampleInvocationGlobals
+ return fallbackGlobals
}
},
},
@@ -1608,28 +1638,15 @@ export const hogFunctionConfigurationLogic = kea<hogFunctionConfigurationLogicTy
}
},
],
- matchingFilters: [
+ // Null when the function uses mappings and has none, because it then matches no event.
+ matchingFiltersInput: [
(s) => [s.configuration, s.useMapping],
(
configuration: HogFunctionConfigurationType,
useMapping: number | true | undefined
- ): PropertyGroupFilter => {
- // We're using mappings, but none are provided, so match zero events.
+ ): MatchingFiltersInput | null => {
if (useMapping && !configuration.mappings?.length) {
- return {
- type: FilterLogicalOperator.And,
- values: [
- {
- type: FilterLogicalOperator.And,
- values: [
- {
- type: PropertyFilterType.HogQL,
- key: 'false',
- },
- ],
- },
- ],
- }
+ return null
}
// Copied before the mappings are merged in: these arrays are the form's own state.
@@ -1647,14 +1664,51 @@ export const hogFunctionConfigurationLogic = kea<hogFunctionConfigurationLogicTy
}
}
- return matchingFiltersToPropertyGroup({
+ return {
events: allPossibleEventFilters,
actions: allPossibleActionFilters,
properties: configuration.filters?.properties,
- })
+ }
+ },
+ { resultEqualityCheck: equal },
+ ],
+ matchingFilters: [
+ (s) => [s.matchingFiltersInput],
+ (matchingFiltersInput: MatchingFiltersInput | null): PropertyGroupFilter => {
+ if (!matchingFiltersInput) {
+ return {
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: PropertyFilterType.HogQL,
+ key: 'false',
+ },
+ ],
+ },
+ ],
+ }
+ }
+
+ return matchingFiltersToPropertyGroup(matchingFiltersInput)
},
{ resultEqualityCheck: equal },
],
+ // Filters for the matched flag calls that `events` does not hold, or null when there are none.
+ flagCallsOutsideEvents: [
+ (s) => [s.matchingFiltersInput, s.sourceUsesEvents, s.currentTeam],
+ (
+ matchingFiltersInput: MatchingFiltersInput | null,
+ sourceUsesEvents: boolean,
+ currentTeam: TeamPublicType | TeamType | null
+ ): PropertyGroupFilter | null =>
+ matchingFiltersInput && sourceUsesEvents
+ ? flagCallsOutsideEventsFilters(currentTeam, matchingFiltersInput)
+ : null,
+ { resultEqualityCheck: equal },
+ ],
filtersContainPersonProperties: [
(s) => [s.configuration],
@@ -1709,7 +1763,7 @@ export const hogFunctionConfigurationLogic = kea<hogFunctionConfigurationLogicTy
properties: matchingFilters,
interval: 'day',
dateRange: {
- date_from: '-7d',
+ date_from: `-${SPARKLINE_DAYS}d`,
},
trendsFilter: {
display: ChartDisplayType.ActionsBar,
diff --git a/frontend/src/scenes/hog-functions/filters/flagCallsMatching.test.ts b/frontend/src/scenes/hog-functions/filters/flagCallsMatching.test.ts
new file mode 100644
index 000000000000..18faafeb2ada
--- /dev/null
+++ b/frontend/src/scenes/hog-functions/filters/flagCallsMatching.test.ts
@@ -0,0 +1,66 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import { FlagEvaluationsModeEnumApi } from '~/generated/core/api.schemas'
+import { CyclotronJobFilterPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
+
+import {
+ flagCallsOutsideEventsFilters,
+ matchesOnlyFlagCallsOutsideEvents,
+ withFlagCallCounts,
+} from './flagCallsMatching'
+import { MatchingFiltersInput, matchingFiltersToPropertyGroup } from './matchingFilters'
+
+const FLAG_CALLED = { id: '$feature_flag_called', name: '$feature_flag_called', type: 'events' as const, order: 0 }
+const PAGEVIEW = { id: '$pageview', name: '$pageview', type: 'events' as const, order: 1 }
+const ALL_EVENTS = { id: '', name: 'All events', type: 'events' as const, order: 2 }
+const ACTION = { id: '12', name: 'Signed up', type: 'actions' as const, order: 3 }
+const GLOBAL_PROPERTY = {
+ key: '$browser',
+ value: 'Chrome',
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Event,
+} as CyclotronJobFilterPropertyFilter
+const FLAG_EVALUATIONS_ONLY_TEAM = { ...MOCK_DEFAULT_TEAM, flag_evaluations_mode: FlagEvaluationsModeEnumApi.Number2 }
+
+describe('flagCallsMatching', () => {
+ it.each<[string, MatchingFiltersInput, MatchingFiltersInput | null]>([
+ [
+ 'keeps only the flag call matcher and the global filters',
+ { events: [PAGEVIEW, FLAG_CALLED], actions: [ACTION], properties: [GLOBAL_PROPERTY] },
+ { events: [FLAG_CALLED], properties: [GLOBAL_PROPERTY] },
+ ],
+ ['keeps a matcher on all events', { events: [PAGEVIEW, ALL_EVENTS] }, { events: [ALL_EVENTS] }],
+ [
+ 'counts every flag call when no matcher narrows the events',
+ { properties: [GLOBAL_PROPERTY] },
+ { properties: [GLOBAL_PROPERTY] },
+ ],
+ ['is null when no matcher can match a flag call', { events: [PAGEVIEW], actions: [ACTION] }, null],
+ ['is null when only actions match', { actions: [ACTION] }, null],
+ ])('%s', (_name, input, expected) => {
+ expect(flagCallsOutsideEventsFilters(FLAG_EVALUATIONS_ONLY_TEAM, input)).toEqual(
+ expected ? matchingFiltersToPropertyGroup(expected) : null
+ )
+ })
+
+ it.each<[string, MatchingFiltersInput, boolean]>([
+ ['only flag call matchers', { events: [FLAG_CALLED] }, true],
+ ['a flag call and an action matcher', { events: [FLAG_CALLED], actions: [ACTION] }, false],
+ ['no event matcher', { events: [], actions: [] }, false],
+ ])('matches only flag calls: %s', (_name, input, expected) => {
+ expect(matchesOnlyFlagCallsOutsideEvents(FLAG_EVALUATIONS_ONLY_TEAM, input)).toBe(expected)
+ })
+
+ it('adds flag call counts to the trends days they fall on', () => {
+ const series = { data: [1, 2, 3], days: ['2026-10-15', '2026-10-16', '2026-10-17'], count: 6 }
+
+ // The flag call query starts a day early, so a row before the first trends day is expected and dropped.
+ const rows: [string, number][] = [
+ ['2026-10-14', 100],
+ ['2026-10-16', 10],
+ ['2026-10-17', 5],
+ ]
+
+ expect(withFlagCallCounts(series, rows)).toEqual({ data: [1, 12, 8], count: 21 })
+ })
+})
diff --git a/frontend/src/scenes/hog-functions/filters/flagCallsMatching.ts b/frontend/src/scenes/hog-functions/filters/flagCallsMatching.ts
new file mode 100644
index 000000000000..b1f6c7a46f07
--- /dev/null
+++ b/frontend/src/scenes/hog-functions/filters/flagCallsMatching.ts
@@ -0,0 +1,177 @@
+import { convertPropertiesToPropertyGroup, isEventPropertyFilter } from 'lib/components/PropertyFilters/utils'
+import { FEATURE_FLAG_CALLED_EVENT, storesFlagCallsOutsideEvents } from 'scenes/feature-flags/flagEvaluationsTable'
+
+import { performQuery } from '~/queries/query'
+import { EventsQuery, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'
+import { hogql, setLatestVersionsOnQuery } from '~/queries/utils'
+import {
+ CyclotronJobFilterPropertyFilter,
+ CyclotronJobInvocationGlobals,
+ EventPropertyFilter,
+ FilterLogicalOperator,
+ HogQLPropertyFilter,
+ PropertyFilterType,
+ PropertyGroupFilter,
+ PropertyOperator,
+ TeamPublicType,
+ TeamType,
+ TrendResult,
+} from '~/types'
+
+import { MatchingFiltersInput, matchingFiltersToPropertyGroup } from './matchingFilters'
+
+export const FLAG_CALLS_NOT_LOADABLE =
+ "Feature flag calls are stored separately from other events, so they can't be loaded as a test event."
+
+const NOT_A_FLAG_CALL: HogQLPropertyFilter = {
+ type: PropertyFilterType.HogQL,
+ key: hogql`event != ${FEATURE_FLAG_CALLED_EVENT}`,
+}
+
+/**
+ * The matchers that can match a flag call that `events` does not hold, as a property group to count on
+ * flag_evaluations. Null when the team's flag calls are in `events`, or when no matcher can match one.
+ * Destinations and workflows still receive those calls, so a count on `events` alone misses them.
+ * A matcher on the flag call event or on all events can match one. So can a configuration with no event or
+ * action matcher, because it matches every event. Action matchers are left out, so a flag call that only an
+ * action matches is not counted.
+ */
+export function flagCallsOutsideEventsFilters(
+ team: TeamPublicType | TeamType | null,
+ { events, actions, properties }: MatchingFiltersInput
+): PropertyGroupFilter | null {
+ if (!storesFlagCallsOutsideEvents(team)) {
+ return null
+ }
+ if (!events?.length && !actions?.length) {
+ return matchingFiltersToPropertyGroup({ properties })
+ }
+ const flagCallMatchers = (events ?? []).filter(({ id }) => !id || id === FEATURE_FLAG_CALLED_EVENT)
+ return flagCallMatchers.length ? matchingFiltersToPropertyGroup({ events: flagCallMatchers, properties }) : null
+}
+
+/**
+ * Whether the team's flag calls are outside `events` and every matcher names the flag call event. A search of
+ * `events` then finds no recent event that the matchers match.
+ */
+export function matchesOnlyFlagCallsOutsideEvents(
+ team: TeamPublicType | TeamType | null,
+ { events, actions }: MatchingFiltersInput
+): boolean {
+ return (
+ storesFlagCallsOutsideEvents(team) &&
+ !actions?.length &&
+ !!events?.length &&
+ events.every(({ id }) => id === FEATURE_FLAG_CALLED_EVENT)
+ )
+}
+
+/**
+ * Daily counts of the flag calls that `filters` match over the last `days` days. The events query runner reads
+ * flag_evaluations for a query that names only the flag call event. The window starts a day early, so the first
+ * day of a trends window over the same days is whole in every timezone.
+ */
+function flagCallsDailyCountQuery(
+ filters: PropertyGroupFilter,
+ filterTestAccounts: boolean | undefined,
+ days: number
+): EventsQuery {
+ return setLatestVersionsOnQuery({
+ kind: NodeKind.EventsQuery,
+ event: FEATURE_FLAG_CALLED_EVENT,
+ select: ['toDate(timestamp)', 'count()'],
+ fixedProperties: [filters],
+ filterTestAccounts,
+ after: `-${days + 1}d`,
+ orderBy: ['toDate(timestamp) ASC'],
+ })
+}
+
+/** Adds daily flag call counts to a trends series by date. A day outside the series is left out. */
+export function withFlagCallCounts(
+ series: Pick<TrendResult, 'data' | 'days' | 'count'> | undefined,
+ rows: [string, number][] | null
+): Pick<TrendResult, 'data' | 'count'> {
+ if (!series) {
+ return { data: [], count: 0 }
+ }
+ // With no flag call rows, the series can be a Storybook mock that has no `days`.
+ if (!rows) {
+ return { data: series.data, count: series.count }
+ }
+ const flagCallsByDay = new Map(rows)
+ const added = series.days.map((day) => flagCallsByDay.get(day) ?? 0)
+ return {
+ data: series.data.map((value, index) => value + added[index]),
+ count: series.count + added.reduce((sum, value) => sum + value, 0),
+ }
+}
+
+function exampleFlagKey({ events, properties }: MatchingFiltersInput): string {
+ const filters: CyclotronJobFilterPropertyFilter[] = [
+ ...(properties ?? []),
+ ...(events ?? []).flatMap((event) => event.properties ?? []),
+ ]
+ const flagKeyFilter = filters.find(
+ (filter): filter is EventPropertyFilter =>
+ isEventPropertyFilter(filter) &&
+ filter.key === '$feature_flag' &&
+ filter.operator === PropertyOperator.Exact
+ )
+ const value = Array.isArray(flagKeyFilter?.value) ? flagKeyFilter.value[0] : flagKeyFilter?.value
+ return value == null ? 'example-flag' : String(value)
+}
+
+/**
+ * A copy of `globals` as a flag call that passes the matchers in a test run. It names the flag that an exact
+ * `$feature_flag` filter in the matchers names. A global filter wins over a matcher's own filter.
+ */
+export function exampleFlagCall(
+ globals: CyclotronJobInvocationGlobals,
+ matchers: MatchingFiltersInput
+): CyclotronJobInvocationGlobals {
+ return {
+ ...globals,
+ event: {
+ ...globals.event,
+ event: FEATURE_FLAG_CALLED_EVENT,
+ properties: { ...globals.event.properties, $feature_flag: exampleFlagKey(matchers) },
+ },
+ }
+}
+
+function withoutFlagCalls(properties: TrendsQuery['properties']): TrendsQuery['properties'] {
+ return {
+ type: FilterLogicalOperator.And,
+ values: [
+ convertPropertiesToPropertyGroup(properties),
+ { type: FilterLogicalOperator.And, values: [NOT_A_FLAG_CALL] },
+ ],
+ }
+}
+
+/**
+ * Runs `trendsQuery`. When `flagCallFilters` is set, the trends query leaves out flag calls. This function then
+ * counts the flag calls that those filters match over the last `days` days on flag_evaluations, and adds them to the
+ * first series. On mode 2, ingestion writes each flag call to flag_evaluations. It sends the same call to destinations
+ * and workflows, so flag_evaluations holds exactly the flag calls they receive. A flag call from before the switch to
+ * mode 2 is in both tables, because mode 1 wrote both, so the count includes it once. A flag call with no flag key
+ * stays in `events` only, and the count leaves it out. `days` must cover the range of `trendsQuery`.
+ */
+export async function performTrendsQueryWithFlagCalls(
+ trendsQuery: TrendsQuery,
+ flagCallFilters: PropertyGroupFilter | null,
+ days: number
+): Promise<Pick<TrendResult, 'data' | 'count' | 'labels'>> {
+ const [trends, flagCalls] = await Promise.all([
+ performQuery(
+ flagCallFilters ? { ...trendsQuery, properties: withoutFlagCalls(trendsQuery.properties) } : trendsQuery
+ ),
+ flagCallFilters
+ ? performQuery(flagCallsDailyCountQuery(flagCallFilters, trendsQuery.filterTestAccounts, days))
+ : null,
+ ])
+ const series = trends.results?.[0] as TrendResult | undefined
+ const rows = (flagCalls?.results as [string, number][] | undefined) ?? null
+ return { ...withFlagCallCounts(series, rows), labels: series?.labels ?? [] }
+}
diff --git a/posthog/hogql_queries/events_query_runner.py b/posthog/hogql_queries/events_query_runner.py
index 31a9a22bb984..d93073f4b27c 100644
--- a/posthog/hogql_queries/events_query_runner.py
+++ b/posthog/hogql_queries/events_query_runner.py
@@ -18,6 +18,7 @@ from posthog.schema import (
EventPropertyFilter,
EventsQuery,
EventsQueryResponse,
+ FilterLogicalOperator,
HogQLQueryModifiers,
PropertyGroupFilter,
PropertyGroupFilterValue,
@@ -444,7 +445,17 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
return super().get_cache_key_variant() + self._list_table.cache_key_variant
def _property_where_expr(self, prop: QueryPropertyFilter, table: EventsListTable) -> ast.Expr:
- flag_keys = _exact_flag_keys(prop) if table is FLAG_EVALUATIONS_LIST_TABLE else None
+ if table is not FLAG_EVALUATIONS_LIST_TABLE:
+ return property_to_expr(prop, self.team)
+ if isinstance(prop, PropertyGroupFilter | PropertyGroupFilterValue):
+ # Builds the group the way property_to_expr does, so an exact flag filter inside a group also reads flag_key.
+ exprs = [self._property_where_expr(value, table) for value in prop.values]
+ if not exprs:
+ return ast.Constant(value=1)
+ if len(exprs) == 1:
+ return exprs[0]
+ return ast.And(exprs=exprs) if prop.type == FilterLogicalOperator.AND_ else ast.Or(exprs=exprs)
+ flag_keys = _exact_flag_keys(prop)
if flag_keys is None:
return property_to_expr(prop, self.team)
# HogQL reads properties.$feature_flag from the properties JSON, which reads the properties of every call of
diff --git a/posthog/hogql_queries/test/test_events_query_runner.py b/posthog/hogql_queries/test/test_events_query_runner.py
index f2b9daf0f097..82834faee314 100644
--- a/posthog/hogql_queries/test/test_events_query_runner.py
+++ b/posthog/hogql_queries/test/test_events_query_runner.py
@@ -25,9 +25,13 @@ from posthog.schema import (
EventPropertyFilter,
EventsQuery,
EventsQueryActionStep,
+ FilterLogicalOperator,
GroupPropertyFilter,
+ HogQLPropertyFilter,
HogQLQueryModifiers,
PersonPropertyFilter,
+ PropertyGroupFilter,
+ PropertyGroupFilterValue,
PropertyOperator,
)
@@ -56,6 +60,13 @@ FLAG_EVALUATIONS_DISTINCT_ID = "flag-evaluations-user"
FLAG_EVALUATIONS_EMAIL = "[email protected]"
FLAG_EVALUATIONS_GROUP_KEY = "flag-org"
FLAG_CALL_TIMESTAMP = datetime(2020, 1, 11, 12, 0, 1, tzinfo=UTC)
+FLAG_KEY_MATCHER = PropertyGroupFilterValue(
+ type=FilterLogicalOperator.AND_,
+ values=[
+ EventPropertyFilter(key="$feature_flag", value=FLAG_EVALUATIONS_FLAG_KEY, operator=PropertyOperator.EXACT),
+ HogQLPropertyFilter(key="event = '$feature_flag_called'"),
+ ],
+)
class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
@@ -1498,6 +1509,66 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert [row[0] for row in from_flag_evaluations.results] == [FLAG_EVALUATIONS_FLAG_KEY]
assert [row[0] for row in from_events.results] == [EVENTS_FLAG_KEY]
+ @parameterized.expand(
+ [
+ ("a_flag_key_matcher", [FLAG_KEY_MATCHER], [("2020-01-10", 2), ("2020-01-11", 1)], True),
+ # The flag_key filter stays inside its OR branch, so the all-events branch still counts the other flag.
+ (
+ "a_flag_key_matcher_or_all_events",
+ [
+ FLAG_KEY_MATCHER,
+ PropertyGroupFilterValue(type=FilterLogicalOperator.AND_, values=[HogQLPropertyFilter(key="true")]),
+ ],
+ [("2020-01-10", 2), ("2020-01-11", 2)],
+ True,
+ ),
+ # A destination with no event or action matcher sends an empty OR, which matches every flag call.
+ ("no_matcher", [], [("2020-01-10", 2), ("2020-01-11", 2)], False),
+ ]
+ )
+ def test_flag_evaluations_only_organization_counts_matched_flag_calls_per_day(
+ self,
+ _name: str,
+ matchers: list[PropertyGroupFilterValue],
+ expected: list[tuple[str, int]],
+ reads_flag_key: bool,
+ ):
+ self._set_flag_evaluations_mode(FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY)
+ self._create_events(
+ data=[("events-user", FLAG_CALL_TIMESTAMP.isoformat(), {"$feature_flag": FLAG_EVALUATIONS_FLAG_KEY})],
+ event="$feature_flag_called",
+ )
+ flush_persons_and_events()
+ for timestamp, flag_key in [
+ (FLAG_CALL_TIMESTAMP - timedelta(days=1), FLAG_EVALUATIONS_FLAG_KEY),
+ (FLAG_CALL_TIMESTAMP - timedelta(days=1), FLAG_EVALUATIONS_FLAG_KEY),
+ (FLAG_CALL_TIMESTAMP, FLAG_EVALUATIONS_FLAG_KEY),
+ (FLAG_CALL_TIMESTAMP, "another-flag"),
+ ]:
+ self._insert_flag_evaluation(
+ FLAG_EVALUATIONS_DISTINCT_ID, uuid.uuid4(), timestamp=timestamp, properties={"$feature_flag": flag_key}
+ )
+ # The shape a destination's volume estimate sends: one OR branch per matcher, ANDed with the global filters.
+ matcher = PropertyGroupFilter(
+ type=FilterLogicalOperator.AND_,
+ values=[PropertyGroupFilterValue(type=FilterLogicalOperator.OR_, values=matchers)],
+ )
+
+ with time_machine.travel("2020-01-11T12:01:00Z", tick=False):
+ query = EventsQuery(
+ kind="EventsQuery",
+ event="$feature_flag_called",
+ select=["toDate(timestamp)", "count()"],
+ fixedProperties=[matcher],
+ after="-8d",
+ orderBy=["toDate(timestamp) ASC"],
+ )
+ response = EventsQueryRunner(query=query, team=self.team).run()
+
+ assert isinstance(response, CachedEventsQueryResponse)
+ assert [(str(day), count) for day, count in response.results] == expected
+ assert (f"in(flag_key, tuple('{FLAG_EVALUATIONS_FLAG_KEY}'))" in (response.hogql or "")) is reads_flag_key
+
@parameterized.expand([("range_older_than_retention", "-180d"), ("all_time", "all")])
def test_flag_evaluations_list_stops_at_the_retention_window(self, _name: str, after: str):
self._set_flag_evaluations_mode(FlagEvaluationsMode.READ_FLAG_EVALUATIONS)
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/testing/HogFlowEditorTestEvent.tsx b/products/workflows/frontend/Workflows/hogflows/panel/testing/HogFlowEditorTestEvent.tsx
index fe96aba925ee..c172ee74e545 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/testing/HogFlowEditorTestEvent.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/panel/testing/HogFlowEditorTestEvent.tsx
@@ -8,6 +8,7 @@ import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { TZLabel } from 'lib/components/TZLabel'
import { Popover } from 'lib/lemon-ui/Popover/Popover'
import { HogFunctionTestEditor } from 'scenes/hog-functions/configuration/HogFunctionTest'
+import { FLAG_CALLS_NOT_LOADABLE } from 'scenes/hog-functions/filters/flagCallsMatching'
import { urls } from 'scenes/urls'
import { asDisplay } from 'products/persons/frontend/person-utils'
@@ -24,6 +25,7 @@ export function HogFlowEditorTestEvent(): JSX.Element {
noMatchingEvents,
canTryExtendedSearch,
shouldLoadSampleGlobals,
+ triggerMatchesOnlyFlagCallsOutsideEvents,
eventPanelOpen,
eventSelectorOpen,
lastSearchedEventName,
@@ -108,13 +110,15 @@ export function HogFlowEditorTestEvent(): JSX.Element {
type="secondary"
onClick={() => loadSampleGlobals()}
tooltip={
- noMatchingEvents
+ noMatchingEvents && !triggerMatchesOnlyFlagCallsOutsideEvents
? 'No events match the current filters. Try adjusting your trigger filters.'
: 'Find the last event matching the trigger event filters, and use it to populate the globals for a test run.'
}
disabledReason={
noMatchingEvents
- ? 'No matching events found - adjust your trigger filters'
+ ? triggerMatchesOnlyFlagCallsOutsideEvents
+ ? FLAG_CALLS_NOT_LOADABLE
+ : 'No matching events found - adjust your trigger filters'
: undefined
}
icon={<IconRedo />}
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.test.ts
index 76c1a6f2d0e0..e6aced26f657 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.test.ts
@@ -1,9 +1,12 @@
-import { MOCK_DEFAULT_ORGANIZATION, MOCK_GROUP_TYPES } from 'lib/api.mock'
+import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_TEAM, MOCK_GROUP_TYPES } from 'lib/api.mock'
import { expectLogic } from 'kea-test-utils'
+import { FLAG_CALLS_NOT_LOADABLE } from 'scenes/hog-functions/filters/flagCallsMatching'
import { performWideEventsQueryInTwoPhases } from 'scenes/hog-functions/sampleEventsQuery'
+import { teamLogic } from 'scenes/teamLogic'
+import { FlagEvaluationsModeEnumApi } from '~/generated/core/api.schemas'
import { useAvailableFeatures } from '~/mocks/features'
import { useMocks } from '~/mocks/jest'
import { groupsModel } from '~/models/groupsModel'
@@ -532,6 +535,73 @@ describe('hogFlowEditorTestLogic', () => {
})
})
+ describe('a trigger on feature flag calls', () => {
+ const FLAG_CALLED = {
+ id: '$feature_flag_called',
+ type: 'events',
+ properties: [{ key: '$feature_flag', type: 'event', operator: 'exact', value: 'my-flag' }],
+ }
+ const PAGEVIEW = { id: '$pageview', type: 'events', properties: [] }
+ const NO_MATCH_IN_7_DAYS =
+ 'No events match these filters in the last 7 days. Using an example $pageview event instead.'
+
+ function workflowTriggeredBy(events: (typeof FLAG_CALLED)[]): typeof WORKFLOW_FIXTURE {
+ const filters = { events }
+ return {
+ ...WORKFLOW_FIXTURE,
+ actions: WORKFLOW_FIXTURE.actions.map((action) =>
+ action.id === 'trigger_node' ? { ...action, config: { type: 'event', filters } } : action
+ ),
+ trigger: { type: 'event', filters },
+ }
+ }
+
+ it.each([
+ [
+ 'events mode',
+ FlagEvaluationsModeEnumApi.Number0,
+ [FLAG_CALLED],
+ NO_MATCH_IN_7_DAYS,
+ true,
+ '$pageview',
+ undefined,
+ ],
+ // The example flag call names the flag that the trigger filters on, so a test run passes the trigger.
+ [
+ 'flag evaluations only mode',
+ FlagEvaluationsModeEnumApi.Number2,
+ [FLAG_CALLED],
+ `${FLAG_CALLS_NOT_LOADABLE} Using an example $feature_flag_called event instead.`,
+ false,
+ '$feature_flag_called',
+ 'my-flag',
+ ],
+ // An older pageview can still match, so the 30-day search stays available.
+ [
+ 'flag evaluations only mode with a pageview matcher',
+ FlagEvaluationsModeEnumApi.Number2,
+ [FLAG_CALLED, PAGEVIEW],
+ NO_MATCH_IN_7_DAYS,
+ true,
+ '$pageview',
+ undefined,
+ ],
+ ])(
+ 'explains a missing test event on the %s',
+ async (_name, mode, events, message, canTryExtendedSearch, exampleEvent, exampleFlagKey) => {
+ useMocks({ get: { '/api/environments/:team_id/hog_flows/:id/': workflowTriggeredBy(events) } })
+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, flag_evaluations_mode: mode })
+ logic = hogFlowEditorTestLogic({ id: 'test-workflow' })
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['loadSampleGlobalsSuccess'])
+ await expectLogic(logic).toMatchValues({ sampleGlobalsError: message, canTryExtendedSearch })
+ expect(logic.values.sampleGlobals?.event?.event).toEqual(exampleEvent)
+ expect(logic.values.sampleGlobals?.event?.properties.$feature_flag).toEqual(exampleFlagKey)
+ }
+ )
+ })
+
describe('showTestEvent', () => {
it.each([
[{ type: 'event', filters: {} }, true],
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts
index c3147f1f4fbc..311911cc69dc 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts
+++ b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts
@@ -23,7 +23,14 @@ import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { groupsAccessLogic } from 'lib/introductions/groupsAccessLogic'
+import { FEATURE_FLAG_CALLED_EVENT } from 'scenes/feature-flags/flagEvaluationsTable'
+import {
+ FLAG_CALLS_NOT_LOADABLE,
+ exampleFlagCall,
+ matchesOnlyFlagCallsOutsideEvents,
+} from 'scenes/hog-functions/filters/flagCallsMatching'
import { performWideEventsQueryInTwoPhases } from 'scenes/hog-functions/sampleEventsQuery'
+import { teamLogic } from 'scenes/teamLogic'
import { groupsModel } from '~/models/groupsModel'
import { EventsQuery, NodeKind } from '~/queries/schema/schema-general'
@@ -37,6 +44,8 @@ import {
PropertyFilterType,
PropertyGroupFilter,
PropertyGroupFilterValue,
+ TeamPublicType,
+ TeamType,
} from '~/types'
import { WorkflowLogicProps, workflowLogic } from '../../../workflowLogic'
@@ -151,6 +160,7 @@ export interface hogFlowEditorTestLogicValues {
groupTypes: Map<GroupTypeIndex, GroupType> // groupsModel
mode: HogFlowEditorMode // hogFlowEditorLogic
selectedNodeId: string | null // hogFlowEditorLogic
+ currentTeam: TeamPublicType | TeamType | null // teamLogic
triggerAction: TriggerAction | null // workflowLogic
workflow: HogFlow // workflowLogic
workflowSanitized: HogFlow // workflowLogic
@@ -185,6 +195,7 @@ export interface hogFlowEditorTestLogicValues {
testInvocationValidationErrors: DeepPartialMap<HogflowTestInvocation, ValidationErrorType>
testResult: HogflowTestResult | null
testResultMode: 'diff' | 'raw'
+ triggerMatchesOnlyFlagCallsOutsideEvents: boolean
workflowVariableDefaults: Record<string, any>
}
@@ -334,6 +345,144 @@ export interface hogFlowEditorTestLogicActions {
export interface hogFlowEditorTestLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ triggerMatchesOnlyFlagCallsOutsideEvents: (
+ triggerAction:
+ | ({
+ config:
+ | {
+ type: 'api'
+ }
+ | {
+ 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'
+ }
+ | {
+ cohort_id: number | null
+ transition: 'entered' | 'left'
+ type: 'cohort'
+ }
+ | {
+ 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,
+ currentTeam: TeamPublicType | TeamType | null
+ ) => boolean
shouldLoadSampleGlobals: (
triggerAction:
| ({
@@ -911,6 +1060,8 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([
['groupTypes'],
groupsAccessLogic,
['groupsEnabled'],
+ teamLogic,
+ ['currentTeam'],
],
actions: [hogFlowEditorLogic, ['setSelectedNodeId', 'setAnimatingEdgePair']],
})),
@@ -1078,10 +1229,23 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([
if (!response?.results?.[0]) {
// No matching events found
- const exampleGlobals = createExampleEvent(values.workflow.team_id, values.workflow.name)
+ const flagCallsNotLoadable = values.triggerMatchesOnlyFlagCallsOutsideEvents
+ const triggerFilters =
+ values.triggerAction?.config.type === 'event' ? values.triggerAction.config.filters : {}
+ const pageviewGlobals = createExampleEvent(values.workflow.team_id, values.workflow.name)
+ // A test run applies the trigger filters, so a flag call trigger needs a flag call example.
+ const exampleGlobals = flagCallsNotLoadable
+ ? exampleFlagCall(pageviewGlobals, triggerFilters ?? {})
+ : pageviewGlobals
actions.setNoMatchingEvents(true)
- if (extendedSearch) {
+ if (flagCallsNotLoadable) {
+ // A longer search cannot find a flag call that the events table does not hold.
+ actions.setSampleGlobalsError(
+ `${FLAG_CALLS_NOT_LOADABLE} Using an example ${FEATURE_FLAG_CALLED_EVENT} event instead.`
+ )
+ actions.setCanTryExtendedSearch(false)
+ } else if (extendedSearch) {
// Extended search also failed
actions.setSampleGlobalsError(
`No events match these filters in the last ${EXTENDED_SEARCH_DAYS} days. Using an example $pageview event instead.`
@@ -1218,6 +1382,12 @@ export const hogFlowEditorTestLogic = kea<hogFlowEditorTestLogicType>([
],
})),
selectors(() => ({
+ triggerMatchesOnlyFlagCallsOutsideEvents: [
+ (s) => [s.triggerAction, s.currentTeam],
+ (triggerAction: TriggerAction | null, currentTeam: TeamPublicType | TeamType | null): boolean =>
+ triggerAction?.config.type === 'event' &&
+ matchesOnlyFlagCallsOutsideEvents(currentTeam, triggerAction.config.filters ?? {}),
+ ],
shouldLoadSampleGlobals: [
(s) => [s.triggerAction],
(triggerAction: TriggerAction | null): boolean => {
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/triggerVolumeLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/triggerVolumeLogic.test.ts
new file mode 100644
index 000000000000..ca07f64a4be2
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/steps/triggerVolumeLogic.test.ts
@@ -0,0 +1,72 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import { expectLogic } from 'kea-test-utils'
+
+import { matchingFiltersToPropertyGroup } from 'scenes/hog-functions/filters/matchingFilters'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { FlagEvaluationsModeEnumApi } from '~/generated/core/api.schemas'
+import { performQuery } from '~/queries/query'
+import { NodeKind } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+
+import { triggerVolumeLogic } from './triggerVolumeLogic'
+
+jest.mock('~/queries/query', () => ({
+ ...jest.requireActual('~/queries/query'),
+ performQuery: jest.fn(),
+}))
+
+describe('triggerVolumeLogic', () => {
+ beforeEach(() => {
+ initKeaTests()
+ ;(performQuery as jest.Mock).mockReset()
+ ;(performQuery as jest.Mock).mockImplementation(async (query) =>
+ query.kind === NodeKind.EventsQuery
+ ? {
+ results: [
+ ['2026-10-16', 700],
+ ['2026-10-17', 3],
+ ],
+ }
+ : {
+ results: [
+ {
+ data: [0, 500, 0],
+ count: 500,
+ labels: ['15-Oct-2026', '16-Oct-2026', '17-Oct-2026'],
+ days: ['2026-10-15', '2026-10-16', '2026-10-17'],
+ },
+ ],
+ }
+ )
+ })
+
+ // Mode 1 still writes flag calls to events, so only mode 2 adds the flag_evaluations count.
+ // On mode 2 the trends query leaves out flag calls, so a call that both tables hold counts once.
+ it.each([
+ ['events', FlagEvaluationsModeEnumApi.Number0, 500, 500, false],
+ ['read flag evaluations', FlagEvaluationsModeEnumApi.Number1, 500, 500, false],
+ ['flag evaluations only', FlagEvaluationsModeEnumApi.Number2, 1203, 1200, true],
+ ])(
+ 'estimates a trigger on feature flag calls on the %s mode',
+ async (_name, mode, total, peakPerDay, excludesFlagCalls) => {
+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, flag_evaluations_mode: mode })
+ const filters = {
+ events: [{ id: '$feature_flag_called', type: 'events' as const, name: '$feature_flag_called' }],
+ }
+ const logic = triggerVolumeLogic({ id: 'trigger_node', filters })
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['loadVolumeSuccess'])
+
+ expect(logic.values.volume).toMatchObject({ total, peakPerDay })
+ const trendsQuery = (performQuery as jest.Mock).mock.calls
+ .map(([query]) => query)
+ .find((query) => query.kind === NodeKind.TrendsQuery)
+ const trendsProperties = JSON.stringify(trendsQuery.properties)
+ expect(trendsProperties).toContain(JSON.stringify(matchingFiltersToPropertyGroup(filters)))
+ expect(trendsProperties.includes("event != '$feature_flag_called'")).toBe(excludesFlagCalls)
+ }
+ )
+})
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/triggerVolumeLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/triggerVolumeLogic.ts
index 531d73e4483a..663b1ded53fb 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/triggerVolumeLogic.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/triggerVolumeLogic.ts
@@ -1,9 +1,14 @@
-import { MakeLogicType, afterMount, kea, key, path, props, propsChanged, reducers } from 'kea'
+import { MakeLogicType, afterMount, connect, kea, key, path, props, propsChanged, reducers } from 'kea'
import { loaders } from 'kea-loaders'
import { objectsEqual } from 'lib/utils/objects'
+import {
+ flagCallsOutsideEventsFilters,
+ performTrendsQueryWithFlagCalls,
+} from 'scenes/hog-functions/filters/flagCallsMatching'
+import { teamLogic } from 'scenes/teamLogic'
-import { performQuery } from '~/queries/query'
+import { TeamPublicType, TeamType } from '~/types'
import { EventTriggerFilters, TRIGGER_VOLUME_DAYS, eventTriggerVolumeQuery } from './triggerVolume'
@@ -28,6 +33,7 @@ export interface TriggerVolumeLogicProps {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface triggerVolumeLogicValues {
+ currentTeam: TeamPublicType | TeamType | null // teamLogic
volume: TriggerVolume | null
volumeFailed: boolean
volumeLoading: boolean
@@ -68,6 +74,9 @@ export const triggerVolumeLogic = kea<triggerVolumeLogicType>([
path(['products', 'workflows', 'frontend', 'Workflows', 'hogflows', 'steps', 'triggerVolumeLogic']),
props({} as TriggerVolumeLogicProps),
key(({ id }) => `trigger-volume-logic-${id}`),
+ connect(() => ({
+ values: [teamLogic, ['currentTeam']],
+ })),
reducers(() => ({
volumeFailed: [
false,
@@ -89,19 +98,24 @@ export const triggerVolumeLogic = kea<triggerVolumeLogicType>([
// Every filter edit asks for a new count, so wait out a burst of typing. The
// first estimate of a trigger waits far less, since there is nothing to show yet.
await breakpoint(values.volume === null ? 100 : 1000)
- const response = await performQuery(eventTriggerVolumeQuery(props.filters))
+ const {
+ data: daily,
+ count: total,
+ labels,
+ } = await performTrendsQueryWithFlagCalls(
+ eventTriggerVolumeQuery(props.filters),
+ flagCallsOutsideEventsFilters(values.currentTeam, props.filters),
+ TRIGGER_VOLUME_DAYS
+ )
breakpoint()
- const series = response.results?.[0]
- const daily: number[] = series?.data ?? []
- const total: number = series?.count ?? 0
// Divide by the days the response actually carries, so a range that resolves to
// a different number of buckets than asked for cannot skew the average.
const days = daily.length || TRIGGER_VOLUME_DAYS
return {
total,
daily,
- labels: series?.labels ?? [],
+ labels,
perDay: Math.round(total / days),
peakPerDay: daily.length ? Math.max(...daily) : 0,
}