: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
feat(workflows): show how often an event trigger fired (#97307)
Harley Alexanderf085cea880cd
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 2153086630e8..ebc65501481a 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5897,9 +5897,13 @@ snapshots:products-workflows-editor-configuration-panel--metrics--light:hash: v1.k794b7964.609fbe2b979a5be98bcbc013a33fea41aa0c114e1aa1ac2d9a11e01f27b7fda5.SPwPLnrmhsRpBj9Bl_s4OyLAm7bV1rlJPgaB6ZwnXAoproducts-workflows-editor-configuration-panel--test--dark:- hash: v1.k794b7964.a005c215d18dd3b4a91651f9bc62a17ca6cc6d4ab07ca9708ebe62d76e8ccd5c.Ediq2wIVv_iK0b1q9d4R4iEvzQWpsPK1YaE5_KRciZQ+ hash: v1.k794b7964.9dc8563bad3c610afe3a9a11e3dd565c61baf592e508c40ee7ed2cb518aa7bc5.8CXuUKcSDMO1JOR_T1aMnzbL9-iJFiT6A8JY3p06_d4products-workflows-editor-configuration-panel--test--light:- hash: v1.k794b7964.324443ca3dfa6d45f269a44f666d446169faf32d27d79ce8185412da262bc7ab.bisWMQlMS56hK2z2NzlvALn30r5FtH9mIi38xWAkW4A+ hash: v1.k794b7964.77e439c596febbef403bb59ac7479c423a034cca8657970821ac4ec0918584cb.VyTiPbd6I_VSVPXWvG_w1csrciseUEIxMYL7WX2EdP8+ products-workflows-editor-configuration-panel--trigger--dark:+ hash: v1.k794b7964.f87dda2f9c27f65bcc6745d1732801fc46f364ffdbd880b912d786822f9bbf0a.8qefE9GrPI_A7rK73q8D4TyBYQB1mLlkASC8YTOB_P4+ products-workflows-editor-configuration-panel--trigger--light:+ hash: v1.k794b7964.42af8e81ab682f18d4918aa28718b5c611925a9325b50b7ade47ebb247ccd08f.Im6_Ee5xssBUgp9NJbkJ25j98_Tar3bl6v4Uf5LAiFgproducts-workflows-editor-configuration-panel--variables--dark:hash: v1.k794b7964.c936a553b0ecd3a1a7cd478e4848cb6ad5d3c7c566e7c47aca7c164b663ce106.PFeB3oTy3Wr4fmTcYgVv56Ur35h7UpA9BOFeO-8Y63sproducts-workflows-editor-configuration-panel--variables--light:@@ -5964,6 +5968,14 @@ snapshots:hash: v1.k794b7964.9e7a12c3094416ddf703121095bc7eba5189420cab88d6967618bf43139069fe.UZSvEld_DwpzTPi6QpbRfxOtDYP7S_gR0F03DJcFMpMproducts-workflows-steps-delay--fixed-duration--light:hash: v1.k794b7964.f394f1e00c55c84136a291d5acb646dc12e0b27951a99e493137f7bad05a2082.zj4h9BHlkIR9RBHiB6nkO0QjDgPC1UKa08uSHemhjSQ+ products-workflows-steps-trigger-volume--event-trigger--dark:+ hash: v1.k794b7964.2650854dfdf42c9ce43499445bbe06f8bd55b8d5a032cbdd8e5dcf037ee21080.zVFSrKI3MkfgGSToHH78WhYcRVqXQUUTYcVJQFSgJ0Y+ products-workflows-steps-trigger-volume--event-trigger--light:+ hash: v1.k794b7964.1b48d9803efd5970884d2648542ad21fd9f73c87672969321cc4bed7063596fa.cVc__eKLeEueP9PZEciqT-WKeC-nVwNr9X4fFFpj3tM+ products-workflows-steps-trigger-volume--over-the-ai-task-limit--dark:+ hash: v1.k794b7964.da6c2d35d62b6b43e01e4b6f7ecc32a981bdc56f110b933a19205ac2d0b5d567.epPMTVeLRSLHG64PRCenl8X9DieogcisrFmsTpmqSN0+ products-workflows-steps-trigger-volume--over-the-ai-task-limit--light:+ hash: v1.k794b7964.8c8a035a4c109d2ba4954e9622ffa4f34d5192a300ce82e7f2ffecc02d33dc5e.kSIxebraTtjma2-YSM6dC5HpBl4guWxa84_80ajPpcUproducts-workflows-template-card--ai--dark:hash: v1.k794b7964.5ca1cd71851625754d87c675688f56c0feb039ade940912f8df2ddd171d89d83.5SQmAn1fsl5RQ572BttZHT0wNAtJeZRNP0OqajxrUMcproducts-workflows-template-card--ai--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex c42804b970d5..6fca31b82a9a 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -575,6 +575,7 @@ export const FEATURE_FLAGS = {WORKFLOWS_INTERNAL_EVENT_FILTERS: 'workflows-internal-event-filters', // owner: @haven #team-workflowsWORKFLOWS_ISP_SENDING_HEALTH: 'workflows-isp-sending-health', // owner: #team-workflowsWORKFLOWS_PUSH_NOTIFICATIONS: 'workflows-push-notifications', // owner: #team-workflows+ WORKFLOWS_TRIGGER_VOLUME_ESTIMATE: 'workflows-trigger-volume-estimate', // owner: @mayteio #team-workflowsXAA_AUTHENTICATION: 'xaa-authentication', // owner: @reecejones #team-platform-features} as constexport type FeatureFlagLookupKey = keyof typeof FEATURE_FLAGSdiff --git a/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsxindex 33839630639b..ebb081492255 100644--- a/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx+++ b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigurationLogic.tsx@@ -53,7 +53,7 @@ import {ProductKey,TrendsQuery,} from '~/queries/schema/schema-general'-import { escapePropertyAsHogQLIdentifier, hogql, setLatestVersionsOnQuery } from '~/queries/utils'+import { escapePropertyAsHogQLIdentifier, setLatestVersionsOnQuery } from '~/queries/utils'import {AnyPropertyFilter,AvailableFeature,@@ -76,7 +76,6 @@ import {PersonType,PropertyFilterType,PropertyGroupFilter,- PropertyGroupFilterValue,Survey,SurveyEventName,SurveyEventProperties,@@ -84,6 +83,7 @@ import {import type { GroupType, GroupTypeIndex, HogFunctionMappingTemplateType, ProjectType } from '../../../types'import type { TeamPublicType, TeamType } from '../../../types'+import { matchingFiltersToPropertyGroup } from '../filters/matchingFilters'import { performWideEventsQueryInTwoPhases } from '../sampleEventsQuery'import { eventToHogFunctionContextId } from '../sub-templates/sub-templates'import { SAMPLE_GLOBALS_CONTEXTS } from './sampleGlobalsContexts'@@ -1610,16 +1610,9 @@ export const hogFunctionConfigurationLogic = kea<hogFunctionConfigurationLogicTy}}- const seriesProperties: PropertyGroupFilterValue = {- type: FilterLogicalOperator.Or,- values: [],- }- const properties: PropertyGroupFilter = {- type: FilterLogicalOperator.And,- values: [seriesProperties],- }- const allPossibleEventFilters = configuration.filters?.events ?? []- const allPossibleActionFilters = configuration.filters?.actions ?? []+ // Copied before the mappings are merged in: these arrays are the form's own state.+ const allPossibleEventFilters = [...(configuration.filters?.events ?? [])]+ const allPossibleActionFilters = [...(configuration.filters?.actions ?? [])]if (Array.isArray(configuration.mappings)) {for (const mapping of configuration.mappings) {@@ -1632,49 +1625,11 @@ export const hogFunctionConfigurationLogic = kea<hogFunctionConfigurationLogicTy}}- for (const event of allPossibleEventFilters) {- const eventProperties: AnyPropertyFilter[] = [...(event.properties ?? [])]- if (event.id) {- eventProperties.push({- type: PropertyFilterType.HogQL,- key: hogql`event = ${event.id}`,- })- }- if (eventProperties.length === 0) {- eventProperties.push({- type: PropertyFilterType.HogQL,- key: 'true',- })- }- seriesProperties.values.push({- type: FilterLogicalOperator.And,- values: eventProperties,- })- }- for (const action of allPossibleActionFilters) {- const actionProperties: AnyPropertyFilter[] = [...(action.properties ?? [])]- if (action.id) {- actionProperties.push({- type: PropertyFilterType.HogQL,- key: hogql`matchesAction(${parseInt(action.id)})`,- })- }- seriesProperties.values.push({- type: FilterLogicalOperator.And,- values: actionProperties,- })- }- if ((configuration.filters?.properties?.length ?? 0) > 0) {- const globalProperties: PropertyGroupFilterValue = {- type: FilterLogicalOperator.And,- values: [],- }- for (const property of configuration.filters?.properties ?? []) {- globalProperties.values.push(property as AnyPropertyFilter)- }- properties.values.push(globalProperties)- }- return properties+ return matchingFiltersToPropertyGroup({+ events: allPossibleEventFilters,+ actions: allPossibleActionFilters,+ properties: configuration.filters?.properties,+ })},{ resultEqualityCheck: equal },],diff --git a/frontend/src/scenes/hog-functions/filters/matchingFilters.test.ts b/frontend/src/scenes/hog-functions/filters/matchingFilters.test.tsnew file mode 100644index 000000000000..39c269823d6c--- /dev/null+++ b/frontend/src/scenes/hog-functions/filters/matchingFilters.test.ts@@ -0,0 +1,76 @@+import { FilterLogicalOperator, PropertyFilterType, PropertyOperator } from '~/types'++import { matchingFiltersToPropertyGroup } from './matchingFilters'++describe('matchingFiltersToPropertyGroup', () => {+ it('pins each event to its own OR branch', () => {+ const group = matchingFiltersToPropertyGroup({+ events: [+ { id: '$pageview', type: 'events' },+ { id: 'purchase', type: 'events' },+ ],+ })++ expect(group).toEqual({+ type: FilterLogicalOperator.And,+ values: [+ {+ type: FilterLogicalOperator.Or,+ values: [+ {+ type: FilterLogicalOperator.And,+ values: [{ type: PropertyFilterType.HogQL, key: "event = '$pageview'" }],+ },+ {+ type: FilterLogicalOperator.And,+ values: [{ type: PropertyFilterType.HogQL, key: "event = 'purchase'" }],+ },+ ],+ },+ ],+ })+ })++ it('keeps an event with no id from narrowing the count', () => {+ const group = matchingFiltersToPropertyGroup({ events: [{ id: '', type: 'events' }] })++ expect(group.values[0].values).toEqual([+ { type: FilterLogicalOperator.And, values: [{ type: PropertyFilterType.HogQL, key: 'true' }] },+ ])+ })++ it('ANDs the global properties over every branch', () => {+ const group = matchingFiltersToPropertyGroup({+ events: [{ id: '$pageview', type: 'events' }],+ actions: [{ id: '42', type: 'actions' }],+ properties: [+ {+ key: 'email',+ value: '[email protected]',+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Person,+ },+ ],+ })++ expect(group.values).toHaveLength(2)+ expect(group.values[0].values).toEqual([+ {+ type: FilterLogicalOperator.And,+ values: [{ type: PropertyFilterType.HogQL, key: "event = '$pageview'" }],+ },+ { type: FilterLogicalOperator.And, values: [{ type: PropertyFilterType.HogQL, key: 'matchesAction(42)' }] },+ ])+ expect(group.values[1]).toEqual({+ type: FilterLogicalOperator.And,+ values: [+ {+ key: 'email',+ value: '[email protected]',+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Person,+ },+ ],+ })+ })+})diff --git a/frontend/src/scenes/hog-functions/filters/matchingFilters.ts b/frontend/src/scenes/hog-functions/filters/matchingFilters.tsnew file mode 100644index 000000000000..c8a460ebb122--- /dev/null+++ b/frontend/src/scenes/hog-functions/filters/matchingFilters.ts@@ -0,0 +1,81 @@+import { hogql } from '~/queries/utils'+import {+ AnyPropertyFilter,+ CyclotronJobFilterActions,+ CyclotronJobFilterEvents,+ CyclotronJobFilterPropertyFilter,+ FilterLogicalOperator,+ PropertyFilterType,+ PropertyGroupFilter,+ PropertyGroupFilterValue,+} from '~/types'++export type MatchingFiltersInput = {+ events?: CyclotronJobFilterEvents[]+ actions?: CyclotronJobFilterActions[]+ properties?: CyclotronJobFilterPropertyFilter[]+}++/**+ * Translate cyclotron event filters into a property group that selects the same events in ClickHouse,+ * so a query can count what the matcher would have matched. Each event or action is one OR branch,+ * and the global properties are ANDed over all of them.+ */+export function matchingFiltersToPropertyGroup({+ events,+ actions,+ properties,+}: MatchingFiltersInput): PropertyGroupFilter {+ const seriesProperties: PropertyGroupFilterValue = {+ type: FilterLogicalOperator.Or,+ values: [],+ }+ const propertyGroup: PropertyGroupFilter = {+ type: FilterLogicalOperator.And,+ values: [seriesProperties],+ }++ for (const event of events ?? []) {+ const eventProperties: AnyPropertyFilter[] = [...(event.properties ?? [])]+ if (event.id) {+ eventProperties.push({+ type: PropertyFilterType.HogQL,+ key: hogql`event = ${event.id}`,+ })+ }+ // A branch with no constraints at all would serialize to an empty AND, which matches nothing.+ if (eventProperties.length === 0) {+ eventProperties.push({+ type: PropertyFilterType.HogQL,+ key: 'true',+ })+ }+ seriesProperties.values.push({+ type: FilterLogicalOperator.And,+ values: eventProperties,+ })+ }++ for (const action of actions ?? []) {+ const actionProperties: AnyPropertyFilter[] = [...(action.properties ?? [])]+ if (action.id) {+ actionProperties.push({+ type: PropertyFilterType.HogQL,+ key: hogql`matchesAction(${parseInt(action.id)})`,+ })+ }+ seriesProperties.values.push({+ type: FilterLogicalOperator.And,+ values: actionProperties,+ })+ }++ if ((properties?.length ?? 0) > 0) {+ propertyGroup.values.push({+ type: FilterLogicalOperator.And,+ values: [...(properties ?? [])] as AnyPropertyFilter[],+ })+ }++ return propertyGroup+}diff --git a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanel.stories.tsx b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanel.stories.tsxindex 0ae45e8f57a7..58ee4a581299 100644--- a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanel.stories.tsx+++ b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanel.stories.tsx@@ -3,6 +3,8 @@ import { ReactFlowProvider } from '@xyflow/react'import { BindLogic, useActions, useValues } from 'kea'import { useEffect } from 'react'+import { FEATURE_FLAGS } from 'lib/constants'+import { mswDecorator } from '~/mocks/browser'import { NEW_WORKFLOW, WorkflowLogicProps, workflowLogic } from '../../workflowLogic'@@ -32,7 +34,10 @@ const PANEL_WORKFLOW: HogFlow = {type: 'trigger',name: 'New account created',description: 'Start when a new account is created.',- config: { type: 'event', filters: {} },+ config: {+ type: 'event',+ filters: { events: [{ id: 'account_created', name: 'Account created', type: 'events' }] },+ },},{id: 'delay',@@ -115,6 +120,7 @@ const meta: Meta<typeof HogFlowEditorPanel> = {component: HogFlowEditorPanel,parameters: {layout: 'fullscreen',+ featureFlags: [FEATURE_FLAGS.WORKFLOWS_TRIGGER_VOLUME_ESTIMATE],},decorators: [mswDecorator({@@ -136,6 +142,15 @@ const meta: Meta<typeof HogFlowEditorPanel> = {dedupe_key: null,confirm_token: 'storybook-confirm-token',},+ '/api/environments/:team_id/query/:query_kind/': {+ results: [+ {+ data: [120, 140, 180, 150, 130, 190, 170],+ count: 1080,+ labels: ['1-Sep', '2-Sep', '3-Sep', '4-Sep', '5-Sep', '6-Sep', '7-Sep'],+ },+ ],+ },},}),],@@ -182,6 +197,9 @@ Build.args = { mode: 'build', selectedNodeId: 'delay' }export const BuildPalette: StoryFn<PanelStoryProps> = Template.bind({})BuildPalette.args = { mode: 'build', selectedNodeId: null }+export const Trigger: StoryFn<PanelStoryProps> = Template.bind({})+Trigger.args = { mode: 'build', selectedNodeId: 'trigger' }+export const Webhook: StoryFn<PanelStoryProps> = Template.bind({})Webhook.args = { mode: 'build', selectedNodeId: 'webhook' }diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsxindex 3267b74291ec..d29730022ce8 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx@@ -61,6 +61,7 @@ import { batchTriggerLogic, getAudienceDedupeKey, hogFlowSendsEmail } from './baimport { HogFlowFunctionConfiguration } from './components/HogFlowFunctionConfiguration'import { RecurringSchedulePicker } from './components/RecurringSchedulePicker'import { ScheduleStatusBadge } from './components/ScheduleStatusBadge'+import { TriggerVolumeEstimate } from './components/TriggerVolumeEstimate'type TriggerAction = Extract<HogFlowAction, { type: 'trigger' }>type EventTriggerConfig = {@@ -349,6 +350,9 @@ export function StepTriggerConfiguration({ node }: { node: Node<TriggerAction> }{registeredMatch?.ConfigComponent ? (<><registeredMatch.ConfigComponent node={node} />+ {featureFlags[FEATURE_FLAGS.WORKFLOWS_TRIGGER_VOLUME_ESTIMATE] ? (+ <TriggerVolumeEstimate action={node.data} />+ ) : null}{registeredMatch.frequencyOptions ? (<><LemonDivider />@@ -394,6 +398,7 @@ function StepTriggerConfigurationEvents({}): JSX.Element {const { setWorkflowActionConfig } = useActions(workflowLogic)const { actionValidationErrorsById } = useValues(workflowLogic)+ const { featureFlags } = useValues(featureFlagLogic)const validationResult = actionValidationErrorsById[action.id]const filterTestAccounts = config.filters?.filter_test_accounts ?? false@@ -428,6 +433,10 @@ function StepTriggerConfigurationEvents({}/>+ {featureFlags[FEATURE_FLAGS.WORKFLOWS_TRIGGER_VOLUME_ESTIMATE] ? (+ <TriggerVolumeEstimate action={action} />+ ) : null}+<LemonDivider /><FrequencySection /><LemonDivider />diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/TriggerVolumeEstimate.stories.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/TriggerVolumeEstimate.stories.tsxnew file mode 100644index 000000000000..c8b76a15896b--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/TriggerVolumeEstimate.stories.tsx@@ -0,0 +1,92 @@+import { Meta, StoryFn } from '@storybook/react'+import { BindLogic } from 'kea'++import { mswDecorator } from '~/mocks/browser'++import { NEW_WORKFLOW, WorkflowLogicProps, workflowLogic } from '../../../workflowLogic'+import { HOG_FLOW_EDITOR_DEFAULT_PANEL_WIDTH } from '../../hogFlowEditorLogic'+import { HogFlow, HogFlowAction } from '../../types'+import { TriggerVolumeEstimate } from './TriggerVolumeEstimate'++const DAILY_COUNTS = [820, 910, 1150, 1040, 980, 1310, 1220]++const TRIGGER_ACTION = {+ id: 'trigger',+ type: 'trigger',+ name: 'Pageview',+ description: '',+ config: { type: 'event', filters: { events: [{ id: '$pageview', name: '$pageview', type: 'events' }] } },+} as HogFlowAction++const AI_TASK_ACTION = {+ id: 'ai_task',+ type: 'function',+ name: 'Create AI task',+ description: '',+ config: { template_id: 'template-posthog-create-task', inputs: {} },+} as HogFlowAction++const EVENT_TRIGGER_WORKFLOW_ID = 'storybook-trigger-volume'+const AI_TASK_WORKFLOW_ID = 'storybook-trigger-volume-ai-task'++const WORKFLOWS: Record<string, HogFlow> = {+ [EVENT_TRIGGER_WORKFLOW_ID]: {+ ...NEW_WORKFLOW,+ id: EVENT_TRIGGER_WORKFLOW_ID,+ name: 'Welcome email',+ actions: [TRIGGER_ACTION],+ } as HogFlow,+ [AI_TASK_WORKFLOW_ID]: {+ ...NEW_WORKFLOW,+ id: AI_TASK_WORKFLOW_ID,+ name: 'Triage every pageview',+ actions: [TRIGGER_ACTION, AI_TASK_ACTION],+ } as HogFlow,+}++const meta: Meta<typeof TriggerVolumeEstimate> = {+ title: 'Products/Workflows/Steps/Trigger volume',+ component: TriggerVolumeEstimate,+ decorators: [+ mswDecorator({+ get: {+ // nosemgrep: no-environments-api-urls-frontend -- api.hogFlows has not migrated to generated project routes.+ '/api/environments/:team_id/hog_flows/:id/': ({ params }) => [+ 200,+ WORKFLOWS[String(params.id)] ?? WORKFLOWS[EVENT_TRIGGER_WORKFLOW_ID],+ ],+ },+ post: {+ '/api/environments/:team_id/query/:query_kind/': {+ results: [+ {+ data: DAILY_COUNTS,+ count: DAILY_COUNTS.reduce((sum, value) => sum + value, 0),+ labels: ['1-Sep', '2-Sep', '3-Sep', '4-Sep', '5-Sep', '6-Sep', '7-Sep'],+ },+ ],+ },+ },+ }),+ ],+}+export default meta++const Template: StoryFn<{ id: string; width: number }> = ({ id, width }) => {+ const logicProps: WorkflowLogicProps = { id }++ return (+ <BindLogic logic={workflowLogic} props={logicProps}>+ {/* Pinned to the panel's width, minus its own px-2, so the chart is as wide as it is in the app */}+ <div className="px-2" style={{ width }}>+ <TriggerVolumeEstimate action={TRIGGER_ACTION} />+ </div>+ </BindLogic>+ )+}++export const EventTrigger: StoryFn<{ id: string; width: number }> = Template.bind({})+EventTrigger.args = { id: EVENT_TRIGGER_WORKFLOW_ID, width: HOG_FLOW_EDITOR_DEFAULT_PANEL_WIDTH }++export const OverTheAiTaskLimit: StoryFn<{ id: string; width: number }> = Template.bind({})+OverTheAiTaskLimit.args = { id: AI_TASK_WORKFLOW_ID, width: HOG_FLOW_EDITOR_DEFAULT_PANEL_WIDTH }diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/TriggerVolumeEstimate.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/TriggerVolumeEstimate.tsxnew file mode 100644index 000000000000..bb186d20b2d2--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/TriggerVolumeEstimate.tsx@@ -0,0 +1,90 @@+import { useValues } from 'kea'++import { LemonLabel } from '@posthog/lemon-ui'++import { Sparkline } from 'lib/components/Sparkline'+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { humanFriendlyNumber } from 'lib/utils/numbers'+import { pluralize } from 'lib/utils/strings'++import { workflowLogic } from '../../../workflowLogic'+import { HogFlowAction } from '../../types'+import {+ DEFAULT_AI_TASKS_PER_WORKFLOW_PER_DAY,+ TRIGGER_VOLUME_DAYS,+ countAiTaskSteps,+ countScoutSteps,+ eventTriggerVolumeFilters,+ exceedsAiTaskLimit,+} from '../triggerVolume'+import { triggerVolumeLogic } from '../triggerVolumeLogic'++/**+ * How often an event trigger fired recently, so an author sees the workload a workflow takes on+ * before they save it. Renders nothing for a trigger whose volume cannot be counted; the logic is+ * still bound in that case, because hooks cannot be skipped.+ */+export function TriggerVolumeEstimate({ action }: { action: HogFlowAction }): JSX.Element | null {+ const { workflow } = useValues(workflowLogic)+ const filters = eventTriggerVolumeFilters(action)+ const { volume, volumeLoading, volumeFailed } = useValues(triggerVolumeLogic({ id: action.id, filters }))++ if (!filters) {+ return null+ }++ const taskSteps = countAiTaskSteps(workflow)+ const scoutSteps = countScoutSteps(workflow)+ const overAiLimit = volume != null && exceedsAiTaskLimit(volume.peakPerDay, taskSteps)+ const perRunCopy =+ taskSteps > 1 ? `Each run can start up to ${taskSteps} AI tasks` : 'Each run can start an AI task'++ return (+ <div className="flex flex-col gap-2 w-full">+ <LemonLabel>Volume estimate</LemonLabel>+ {volumeLoading ? (+ <>+ <p className="mb-0 text-secondary">Counting how often this trigger fired.</p>+ <Sparkline type="line" loading className="w-full h-10" data={[]} />+ </>+ ) : volumeFailed || !volume ? (+ <p className="mb-0 text-secondary">+ Couldn't count how often this trigger fired. Check the filters above, then try again.+ </p>+ ) : (+ <>+ <p className="mb-0">+ This trigger matched <strong translate="no">{pluralize(volume.total, 'event')}</strong> in the+ last {TRIGGER_VOLUME_DAYS} days, about{' '}+ <span translate="no">{humanFriendlyNumber(volume.perDay)}</span> a day.+ </p>+ <Sparkline+ type="line"+ className="w-full h-10"+ data={volume.daily}+ labels={volume.labels}+ color={overAiLimit ? 'warning' : 'muted'}+ />+ {workflow.trigger_masking ? (+ <p className="mb-0 text-secondary">+ Your frequency limit is not in this count, so the workflow may start fewer runs than this.+ </p>+ ) : null}+ {overAiLimit ? (+ <LemonBanner type="warning">+ {perRunCopy}, and a workflow stops at {DEFAULT_AI_TASKS_PER_WORKFLOW_PER_DAY} AI tasks a+ day. This trigger passes that on its busiest day. Narrow the filters or set a frequency+ limit.+ </LemonBanner>+ ) : taskSteps > 0 ? (+ <p className="mb-0 text-secondary">{perRunCopy}. AI tasks count toward your AI usage.</p>+ ) : scoutSteps > 0 ? (+ <p className="mb-0 text-secondary">+ Each run can start a scout run, which counts toward your AI usage.+ </p>+ ) : null}+ </>+ )}+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/hogflows/steps/triggerVolume.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/triggerVolume.test.tsnew file mode 100644index 000000000000..f9b85520940f--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/triggerVolume.test.ts@@ -0,0 +1,122 @@+import { HogFlowAction } from '../types'+import {+ DEFAULT_AI_TASKS_PER_WORKFLOW_PER_DAY,+ TRIGGER_VOLUME_DAYS,+ countAiTaskSteps,+ countScoutSteps,+ eventTriggerVolumeFilters,+ eventTriggerVolumeQuery,+ exceedsAiTaskLimit,+} from './triggerVolume'++function functionAction(templateId: string, id: string = 'function_1'): HogFlowAction {+ return {+ id,+ type: 'function',+ name: 'Step',+ description: '',+ config: { template_id: templateId, inputs: {} },+ } as HogFlowAction+}++describe('triggerVolume', () => {+ describe('eventTriggerVolumeFilters', () => {+ const cases: [string, Record<string, any>, boolean][] = [+ [+ 'an event trigger with an event',+ { type: 'event', filters: { events: [{ id: '$pageview', type: 'events' }] } },+ true,+ ],+ ['an event trigger with only properties', { type: 'event', filters: { properties: [{}] } }, true],+ ['an event trigger with nothing configured', { type: 'event', filters: {} }, false],+ [+ // Internal events are never written to the events table, so no query can count them.+ 'an internal event trigger',+ {+ type: 'internal-event',+ filters: { source: 'internal-events', events: [{ id: '$slack_message_received' }] },+ },+ false,+ ],+ ['a batch trigger', { type: 'batch', filters: { properties: [] } }, false],+ ['a schedule trigger', { type: 'schedule' }, false],+ ]++ it.each(cases)('%s', (_name, config, expected) => {+ const action = { id: 'trigger_1', type: 'trigger', name: 'Trigger', description: '', config }+ expect(eventTriggerVolumeFilters(action as HogFlowAction) !== null).toBe(expected)+ })++ it('is null for a step that is not the trigger', () => {+ expect(eventTriggerVolumeFilters(functionAction('template-webhook'))).toBeNull()+ })+ })++ describe('step counts', () => {+ // A scout run goes to its own endpoint with its own throttle, so counting it against the+ // task cap would warn a scout-only workflow about a limit it never reaches.+ it.each([+ ['an AI task step', 'template-posthog-create-task', 1, 0],+ ['a scout step', 'template-posthog-run-scout', 0, 1],+ ['a webhook step', 'template-webhook', 0, 0],+ ])('%s', (_name, templateId, tasks, scouts) => {+ const workflow = { actions: [functionAction(templateId as string)] }++ expect(countAiTaskSteps(workflow)).toBe(tasks)+ expect(countScoutSteps(workflow)).toBe(scouts)+ })++ // Each step a run reaches creates its own task, so two steps reach the daily cap at half+ // the runs. A flag here would leave the warning silent at that volume.+ it('counts every task step, not just the first', () => {+ expect(+ countAiTaskSteps({+ actions: [+ functionAction('template-posthog-create-task', 'task_1'),+ functionAction('template-webhook', 'webhook_1'),+ functionAction('template-posthog-create-task', 'task_2'),+ ],+ })+ ).toBe(2)+ })++ it('is zero for a workflow with no steps', () => {+ expect(countAiTaskSteps({ actions: [] })).toBe(0)+ expect(countAiTaskSteps(null)).toBe(0)+ expect(countScoutSteps(null)).toBe(0)+ })+ })++ describe('exceedsAiTaskLimit', () => {+ const cap = DEFAULT_AI_TASKS_PER_WORKFLOW_PER_DAY++ it.each([+ // The backend counts tasks over a trailing 24 hours, so one busy day breaches the cap+ // even when the weekly average sits far below it.+ ['a burst day above the cap', cap * 5, 1, true],+ // Two steps double the tasks per run, so half the runs reach the same cap.+ ['half the runs with two task steps', cap * 0.6, 2, true],+ ['a quiet trigger', cap - 10, 1, false],+ ['a workflow with no task step', cap * 50, 0, false],+ ])('%s', (_name, peakPerDay, taskSteps, expected) => {+ expect(exceedsAiTaskLimit(peakPerDay as number, taskSteps as number)).toBe(expected)+ })+ })++ describe('eventTriggerVolumeQuery', () => {+ it('counts the trigger events over the window the copy promises', () => {+ const query = eventTriggerVolumeQuery({+ events: [{ id: 'purchase', type: 'events' }],+ filter_test_accounts: true,+ })++ expect(query.dateRange?.date_from).toBe(`-${TRIGGER_VOLUME_DAYS}d`)+ // Ends yesterday, so the window is whole days only. An open end would add today's+ // partial day, which the daily average divides as though it were complete.+ expect(query.dateRange?.date_to).toBe('-1d')+ expect(query.interval).toBe('day')+ expect(query.filterTestAccounts).toBe(true)+ expect(JSON.stringify(query.properties)).toContain("event = 'purchase'")+ })+ })+})diff --git a/products/workflows/frontend/Workflows/hogflows/steps/triggerVolume.ts b/products/workflows/frontend/Workflows/hogflows/steps/triggerVolume.tsnew file mode 100644index 000000000000..d31951101125--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/triggerVolume.ts@@ -0,0 +1,113 @@+import { matchingFiltersToPropertyGroup } from 'scenes/hog-functions/filters/matchingFilters'++import { EventsNode, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'+import { setLatestVersionsOnQuery } from '~/queries/utils'+import { BaseMathType, ChartDisplayType } from '~/types'++import { HogFlowAction } from '../types'++type TriggerAction = Extract<HogFlowAction, { type: 'trigger' }>++export type EventTriggerFilters = Extract<TriggerAction['config'], { type: 'event' }>['filters']++/** Days of history the estimate looks back over. */+export const TRIGGER_VOLUME_DAYS = 7++/**+ * Tasks one workflow can create per day by default, mirroring WORKFLOW_TASK_RATE_CAP_PER_DAY in+ * products/tasks/backend/logic/services/workflow_tasks.py.+ *+ * The default, not the effective cap: staff can set another value per project on+ * `TeamWorkflowsConfig.workflow_task_rate_limit_per_day`, and no read API carries it, so the panel+ * cannot know a project's real number. Copy that names it says so.+ */+export const DEFAULT_AI_TASKS_PER_WORKFLOW_PER_DAY = 100++const AI_TASK_TEMPLATE_ID = 'template-posthog-create-task'+const SCOUT_TEMPLATE_ID = 'template-posthog-run-scout'++function countStepsOfTemplate(workflow: { actions?: HogFlowAction[] } | null | undefined, templateId: string): number {+ return (workflow?.actions ?? []).filter(+ (action) => action.type === 'function' && action.config.template_id === templateId+ ).length+}++/**+ * Steps of this workflow that create an AI task, which is what the daily task cap counts.+ *+ * A count rather than a flag, because every step a run reaches creates its own task: two steps+ * reach the cap at half the runs. Branches mean a run does not always reach all of them, so the+ * count is a ceiling, which is the safe side for a cost warning.+ */+export function countAiTaskSteps(workflow?: { actions?: HogFlowAction[] } | null): number {+ return countStepsOfTemplate(workflow, AI_TASK_TEMPLATE_ID)+}++/**+ * Steps of this workflow that start a Signals scout run.+ *+ * Counted apart from AI tasks: a scout run goes to its own endpoint, with its own pause, cooldown+ * and throttle, so it costs AI usage but never counts against the task cap.+ */+export function countScoutSteps(workflow?: { actions?: HogFlowAction[] } | null): number {+ return countStepsOfTemplate(workflow, SCOUT_TEMPLATE_ID)+}++/**+ * Whether the busiest day in the window would pass the default daily task cap.+ *+ * The busiest day, not the weekly average: the backend counts tasks over a trailing 24 hours, so+ * one busy day can break the cap while the average stays under it.+ */+export function exceedsAiTaskLimit(peakPerDay: number, taskSteps: number): boolean {+ return taskSteps > 0 && peakPerDay * taskSteps > DEFAULT_AI_TASKS_PER_WORKFLOW_PER_DAY+}++/**+ * The filters to estimate a trigger's volume from, or null when no estimate is possible.+ *+ * Only triggers that match real PostHog events can be counted. Internal events are not stored, and+ * a trigger with nothing configured yet would count every event in the project.+ */+export function eventTriggerVolumeFilters(action: HogFlowAction): EventTriggerFilters | null {+ if (action.type !== 'trigger' || action.config.type !== 'event') {+ return null+ }+ const filters = action.config.filters ?? {}+ const configured =+ (filters.events?.length ?? 0) > 0 || (filters.actions?.length ?? 0) > 0 || (filters.properties?.length ?? 0) > 0+ return configured ? filters : null+}++/** Daily counts of the events this trigger would have matched over the estimate window. */+export function eventTriggerVolumeQuery(filters: EventTriggerFilters): TrendsQuery {+ return setLatestVersionsOnQuery({+ kind: NodeKind.TrendsQuery,+ filterTestAccounts: filters.filter_test_accounts,+ series: [+ {+ kind: NodeKind.EventsNode,+ event: null,+ name: 'All events',+ math: BaseMathType.TotalCount,+ } satisfies EventsNode,+ ],+ properties: matchingFiltersToPropertyGroup(filters),+ interval: 'day',+ dateRange: {+ date_from: `-${TRIGGER_VOLUME_DAYS}d`,+ // End at yesterday, so the window holds exactly TRIGGER_VOLUME_DAYS whole days. An open+ // end adds today's partial day as an eighth bucket, which the daily average would then+ // divide as though it were complete.+ date_to: '-1d',+ },+ trendsFilter: {+ display: ChartDisplayType.ActionsBar,+ },+ modifiers: {+ // The matcher sees the person properties as they were when the event came in, so count+ // the same way rather than against today's person.+ personsOnEventsMode: 'person_id_no_override_properties_on_events',+ },+ })+}diff --git a/products/workflows/frontend/Workflows/hogflows/steps/triggerVolumeLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/triggerVolumeLogic.tsnew file mode 100644index 000000000000..531d73e4483a--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/triggerVolumeLogic.ts@@ -0,0 +1,120 @@+import { MakeLogicType, afterMount, kea, key, path, props, propsChanged, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import { objectsEqual } from 'lib/utils/objects'++import { performQuery } from '~/queries/query'++import { EventTriggerFilters, TRIGGER_VOLUME_DAYS, eventTriggerVolumeQuery } from './triggerVolume'++export type TriggerVolume = {+ /** Events matched over the whole window. */+ total: number+ /** One count per day, oldest first. */+ daily: number[]+ /** One label per daily count, for the chart tooltip. */+ labels: string[]+ /** Average matches per day over the window. */+ perDay: number+ /** Matches on the busiest day of the window. */+ peakPerDay: number+}++export interface TriggerVolumeLogicProps {+ /** Trigger action id, so each trigger keeps its own estimate. */+ id: string+ filters: EventTriggerFilters | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface triggerVolumeLogicValues {+ volume: TriggerVolume | null+ volumeFailed: boolean+ volumeLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface triggerVolumeLogicActions {+ loadVolume: (_: void) => void+ loadVolumeFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadVolumeSuccess: (+ volume: TriggerVolume | null,+ payload?: void+ ) => {+ volume: TriggerVolume | null+ payload?: void+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface triggerVolumeLogicMeta {+ key: string+}++export type triggerVolumeLogicType = MakeLogicType<+ triggerVolumeLogicValues,+ triggerVolumeLogicActions,+ TriggerVolumeLogicProps,+ triggerVolumeLogicMeta+>++export const triggerVolumeLogic = kea<triggerVolumeLogicType>([+ path(['products', 'workflows', 'frontend', 'Workflows', 'hogflows', 'steps', 'triggerVolumeLogic']),+ props({} as TriggerVolumeLogicProps),+ key(({ id }) => `trigger-volume-logic-${id}`),+ reducers(() => ({+ volumeFailed: [+ false,+ {+ loadVolume: () => false,+ loadVolumeSuccess: () => false,+ loadVolumeFailure: () => true,+ },+ ],+ })),+ loaders(({ props, values }) => ({+ volume: [+ null as TriggerVolume | null,+ {+ loadVolume: async (_: void, breakpoint): Promise<TriggerVolume | null> => {+ if (!props.filters) {+ return null+ }+ // 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))+ 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 ?? [],+ perDay: Math.round(total / days),+ peakPerDay: daily.length ? Math.max(...daily) : 0,+ }+ },+ },+ ],+ })),+ propsChanged(({ actions, props }, oldProps) => {+ if (!oldProps || !objectsEqual(props.filters, oldProps.filters)) {+ actions.loadVolume()+ }+ }),+ afterMount(({ actions }) => {+ actions.loadVolume()+ }),+])