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): let insights chart flag calls from flag_evaluations (#112991)

Phil Haack06ad50a69c3b
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index dfe827925378..45f1115d3e97 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -11932,6 +11932,10 @@ snapshots:
hash: v1.k794b7964.78c398feb22adb44344fad6c155ad42ecdbd9d77d80e4e0a60227b4a32abf14f.wmWI9S-nFvoZ5tNpxol33U3eINboLyZM9cggyHqv8hU
scenes-app-insights-error-empty-states--validation-error--light:
hash: v1.k794b7964.2b012576da17dc343cba68c671217dcfb23f907543fd897d65e42e8793f31958.gL9lf9tk2rIHPSZBxNHmPitiTqUvCG08VR3K9hK7xMo
+ scenes-app-insights-flag-calls-retention-notice--default--dark:
+ hash: v1.k794b7964.d9aefe5f9ce9d7a864d6bf0338965adf5c01284b0fa767b3db193cbf9102838b.F_x981isYjYR1oKf0BPU3Agkr_bpR7TqheKovVn432o
+ scenes-app-insights-flag-calls-retention-notice--default--light:
+ hash: v1.k794b7964.7923e9cd78a4bd2e62c7f95ce8eb80df0bb9fab29de527b307048b8e5b5011ff.Mrf6YkRMfO82M2uM5Fc4LKBf3vjTEjIDdw4MZ1cPIrA
scenes-app-insights-flag-called-rebuild-banner--insight-on-flag-calls--dark:
hash: v1.k794b7964.3d946f71319ec412299b8888e9a3fed48a7098bcf0e92cda25f6f34a43071a3f.PbH5UAwbwGY8tveYtVSlUz6TeywtNh7otO1PSPZi9vw
scenes-app-insights-flag-called-rebuild-banner--insight-on-flag-calls--light:
diff --git a/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverContents.tsx b/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverContents.tsx
index 380a48d4fcf7..b42b76c3908d 100644
--- a/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverContents.tsx
+++ b/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverContents.tsx
@@ -116,7 +116,14 @@ export function PropertyStatusControl({
)
}
-function DefinitionView({ group }: { group: TaxonomicFilterGroup }): JSX.Element {
+export function DefinitionView({
+ group,
+ description: descriptionOverride,
+}: {
+ group: TaxonomicFilterGroup
+ /** Wins over both the definition's own description and the core one. */
+ description?: string
+}): JSX.Element {
const {
definition,
localDefinition,
@@ -167,6 +174,7 @@ function DefinitionView({ group }: { group: TaxonomicFilterGroup }): JSX.Element
}
const description =
+ descriptionOverride ||
(definition && 'description' in definition && definition?.description) ||
(definition?.name ? getCoreFilterDefinition(definition.name, group.type)?.description : undefined)
@@ -741,11 +749,10 @@ export function ControlledDefinitionPopover({
return null
}
- const isDataWarehouseFunnelWidePopover =
- group.type === TaxonomicFilterGroupType.DataWarehouse && !!definitionPopoverRenderer
-
const defaultView = <DefinitionView group={group} />
const customView = definitionPopoverRenderer?.({ item, group, defaultView }) ?? defaultView
+ const isDataWarehouseFunnelWidePopover =
+ group.type === TaxonomicFilterGroupType.DataWarehouse && customView !== defaultView
return (
<Popover
diff --git a/frontend/src/lib/components/EntityFilterInfo.test.tsx b/frontend/src/lib/components/EntityFilterInfo.test.tsx
index 7411c973ae66..5e11d2b71e1f 100644
--- a/frontend/src/lib/components/EntityFilterInfo.test.tsx
+++ b/frontend/src/lib/components/EntityFilterInfo.test.tsx
@@ -3,10 +3,11 @@ import '@testing-library/jest-dom'
import { cleanup, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { ActionFilter, EntityFilter, EntityTypes } from '~/types'
-import { EntityFilterInfo } from './EntityFilterInfo'
+import { DisplayableEntity, EntityFilterInfo } from './EntityFilterInfo'
describe('EntityFilterInfo', () => {
beforeEach(() => {
@@ -43,7 +44,21 @@ describe('EntityFilterInfo', () => {
'Total traffic',
'All events',
],
- ] as [string, EntityFilter | ActionFilter, string, string][])(
+ [
+ 'name on a flag calls series',
+ {
+ kind: NodeKind.DataWarehouseNode,
+ id: 'posthog.flag_evaluations',
+ table_name: 'posthog.flag_evaluations',
+ name: 'Checkout flag calls',
+ timestamp_field: 'timestamp',
+ id_field: 'uuid',
+ distinct_id_field: 'distinct_id',
+ },
+ 'Checkout flag calls',
+ 'Feature flag called',
+ ],
+ ] as [string, DisplayableEntity, string, string][])(
'shows the underlying entity next to a series renamed via %s',
(_, filter, label, underlying) => {
render(<EntityFilterInfo filter={filter} />)
@@ -62,11 +77,47 @@ describe('EntityFilterInfo', () => {
// API-created series often carry no name at all — the raw id label is not a rename
['a name-less core event', { type: EntityTypes.EVENTS, id: '$pageview' }, '$pageview'],
['an all-events series', { type: EntityTypes.EVENTS, id: null, name: 'All events' }, 'All events'],
- ] as [string, EntityFilter, string][])('shows a single label for an unrenamed series on %s', (_, filter, label) => {
- const { container } = render(<EntityFilterInfo filter={filter} />)
- expect(screen.getAllByText(label)).toHaveLength(1)
- expect(container.querySelectorAll('.EntityFilterInfo')).toHaveLength(1)
- })
+ [
+ 'a flag calls series',
+ {
+ kind: NodeKind.DataWarehouseNode,
+ id: 'posthog.flag_evaluations',
+ table_name: 'posthog.flag_evaluations',
+ name: 'Feature flag called',
+ timestamp_field: 'timestamp',
+ id_field: 'uuid',
+ distinct_id_field: 'distinct_id',
+ },
+ 'Feature flag called',
+ ],
+ [
+ 'a flag calls series in query results',
+ {
+ type: EntityTypes.EVENTS,
+ id: 'posthog.flag_evaluations',
+ name: 'posthog.flag_evaluations',
+ custom_name: 'Feature flag called',
+ },
+ 'Feature flag called',
+ ],
+ [
+ 'a flag calls step in funnel results',
+ {
+ type: EntityTypes.DATA_WAREHOUSE,
+ id: null,
+ name: 'posthog.flag_evaluations',
+ custom_name: 'Feature flag called',
+ },
+ 'Feature flag called',
+ ],
+ ] as [string, DisplayableEntity, string][])(
+ 'shows a single label for an unrenamed series on %s',
+ (_, filter, label) => {
+ const { container } = render(<EntityFilterInfo filter={filter} />)
+ expect(screen.getAllByText(label)).toHaveLength(1)
+ expect(container.querySelectorAll('.EntityFilterInfo')).toHaveLength(1)
+ }
+ )
it('keeps the underlying entity out of the inline label when showSingleName is set', () => {
const { container } = render(
diff --git a/frontend/src/lib/components/EntityFilterInfo.tsx b/frontend/src/lib/components/EntityFilterInfo.tsx
index 5fedf8cb3632..456a4664980e 100644
--- a/frontend/src/lib/components/EntityFilterInfo.tsx
+++ b/frontend/src/lib/components/EntityFilterInfo.tsx
@@ -3,6 +3,8 @@ import clsx from 'clsx'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { ensureStringIsNotBlank } from 'lib/utils/strings'
import { getEventDefinitionIcon } from 'scenes/data-management/events/DefinitionHeader'
+import { FEATURE_FLAG_CALLED_EVENT, FLAG_EVALUATIONS_TABLE } from 'scenes/feature-flags/flagEvaluationsTable'
+import { FLAG_CALLS_SERIES_NAME } from 'scenes/insights/filters/ActionFilter/flagCallsSeries'
import {
SeriesNode,
isActionsSeriesNode,
@@ -25,6 +27,28 @@ export type DisplayableEntity = EntityFilter | ActionFilter | SeriesNode
export type DisplayEntityFilter = (EntityFilter | ActionFilter) & { table_name?: string }
export function toDisplayEntityFilter(filter: DisplayableEntity): DisplayEntityFilter {
+ const displayFilter = nodeToDisplayEntityFilter(filter)
+ // Trends and lifecycle results describe a warehouse series as an events entity whose id is the table name.
+ // Funnel results describe a warehouse step with no id and the table name in `name`.
+ if (
+ displayFilter.id === FLAG_EVALUATIONS_TABLE ||
+ (displayFilter.type === EntityTypes.DATA_WAREHOUSE &&
+ (displayFilter.table_name ?? displayFilter.name) === FLAG_EVALUATIONS_TABLE)
+ ) {
+ const name = ensureStringIsNotBlank(displayFilter.name)
+ return {
+ ...displayFilter,
+ type: EntityTypes.EVENTS,
+ id: FEATURE_FLAG_CALLED_EVENT,
+ // Any name other than the table's is a rename, for example one set through the API.
+ name: name && name !== FLAG_EVALUATIONS_TABLE ? name : FLAG_CALLS_SERIES_NAME,
+ table_name: undefined,
+ }
+ }
+ return displayFilter
+}
+
+function nodeToDisplayEntityFilter(filter: DisplayableEntity): DisplayEntityFilter {
if (!('kind' in filter)) {
return filter
}
diff --git a/frontend/src/lib/components/FlagCalledRebuildBanner/flagCalledDependencies.ts b/frontend/src/lib/components/FlagCalledRebuildBanner/flagCalledDependencies.ts
index ad4cf02a7644..39740dfd6041 100644
--- a/frontend/src/lib/components/FlagCalledRebuildBanner/flagCalledDependencies.ts
+++ b/frontend/src/lib/components/FlagCalledRebuildBanner/flagCalledDependencies.ts
@@ -1,7 +1,7 @@
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { BehavioralFilterKey } from 'scenes/cohorts/CohortFilters/types'
import { isCohortCriteriaGroup } from 'scenes/cohorts/cohortUtils'
-import { FEATURE_FLAG_CALLED_EVENT } from 'scenes/feature-flags/featureFlagUsageQueries'
+import { FEATURE_FLAG_CALLED_EVENT } from 'scenes/feature-flags/flagEvaluationsTable'
import { Node } from '~/queries/schema/schema-general'
import {
diff --git a/frontend/src/lib/components/FlagCalledRebuildBanner/flagCalledRebuildBannerLogic.ts b/frontend/src/lib/components/FlagCalledRebuildBanner/flagCalledRebuildBannerLogic.ts
index b245fb1fe8d4..434fe1dd6966 100644
--- a/frontend/src/lib/components/FlagCalledRebuildBanner/flagCalledRebuildBannerLogic.ts
+++ b/frontend/src/lib/components/FlagCalledRebuildBanner/flagCalledRebuildBannerLogic.ts
@@ -3,7 +3,7 @@ import posthog from 'posthog-js'
import { FEATURE_FLAGS } from 'lib/constants'
import { FeatureFlagsSet, featureFlagLogic, getFeatureFlagPayload } from 'lib/logic/featureFlagLogic'
-import { readsFlagEvaluationsTable } from 'scenes/feature-flags/featureFlagUsageQueries'
+import { readsFlagEvaluationsTable } from 'scenes/feature-flags/flagEvaluationsTable'
import { teamLogic } from 'scenes/teamLogic'
import { TeamPublicType, TeamType } from '~/types'
diff --git a/frontend/src/lib/components/TaxonomicFilter/types.ts b/frontend/src/lib/components/TaxonomicFilter/types.ts
index 6eb16da7ed61..03b5ee92041f 100644
--- a/frontend/src/lib/components/TaxonomicFilter/types.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/types.ts
@@ -237,6 +237,7 @@ export type DefinitionPopoverRendererProps = {
group: TaxonomicFilterGroup
defaultView: JSX.Element
}
+/** Return `defaultView` itself for an item the renderer does not handle. The popover compares it by reference. */
export type DefinitionPopoverRenderer = (props: DefinitionPopoverRendererProps) => JSX.Element | null
export interface TaxonomicFilterGroup {
diff --git a/frontend/src/queries/nodes/InsightViz/FlagCallsRetentionNotice.stories.tsx b/frontend/src/queries/nodes/InsightViz/FlagCallsRetentionNotice.stories.tsx
new file mode 100644
index 000000000000..424c6dacb2a9
--- /dev/null
+++ b/frontend/src/queries/nodes/InsightViz/FlagCallsRetentionNotice.stories.tsx
@@ -0,0 +1,16 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { FlagCallsRetentionNotice } from './FlagCallsRetentionNotice'
+
+const meta: Meta<typeof FlagCallsRetentionNotice> = {
+ title: 'Scenes-App/Insights/Flag calls retention notice',
+ component: FlagCallsRetentionNotice,
+ parameters: {
+ mockDate: '2026-10-07',
+ },
+}
+export default meta
+
+type Story = StoryObj<typeof FlagCallsRetentionNotice>
+
+export const Default: Story = {}
diff --git a/frontend/src/queries/nodes/InsightViz/FlagCallsRetentionNotice.tsx b/frontend/src/queries/nodes/InsightViz/FlagCallsRetentionNotice.tsx
new file mode 100644
index 000000000000..761ece994031
--- /dev/null
+++ b/frontend/src/queries/nodes/InsightViz/FlagCallsRetentionNotice.tsx
@@ -0,0 +1,15 @@
+import { LemonBanner } from '@posthog/lemon-ui'
+
+import {
+ FLAG_EVALUATIONS_RETENTION_DAYS,
+ flagEvaluationsRetentionStart,
+} from 'scenes/feature-flags/flagEvaluationsTable'
+
+export function FlagCallsRetentionNotice(): JSX.Element {
+ return (
+ <LemonBanner type="info" className="m-2">
+ This insight includes feature flag calls from the last {FLAG_EVALUATIONS_RETENTION_DAYS} days only. Periods
+ before {flagEvaluationsRetentionStart().format('MMMM D, YYYY')} show no calls.
+ </LemonBanner>
+ )
+}
diff --git a/frontend/src/queries/nodes/InsightViz/GlobalAndOrFilters.tsx b/frontend/src/queries/nodes/InsightViz/GlobalAndOrFilters.tsx
index 831c1a0ff891..b333190e2fe6 100644
--- a/frontend/src/queries/nodes/InsightViz/GlobalAndOrFilters.tsx
+++ b/frontend/src/queries/nodes/InsightViz/GlobalAndOrFilters.tsx
@@ -16,7 +16,7 @@ import { getAllEventNames } from './utils'
export function GlobalAndOrFilters({ insightProps }: EditorFilterProps): JSX.Element {
const { groupsTaxonomicTypes } = useValues(groupsModel)
- const { querySource, hasDataWarehouseSeries } = useValues(insightVizDataLogic(insightProps))
+ const { querySource, hasDataWarehouseEntity } = useValues(insightVizDataLogic(insightProps))
const { actions: allActions } = useValues(
actionsModel({
shouldLoad:
@@ -41,7 +41,7 @@ export function GlobalAndOrFilters({ insightProps }: EditorFilterProps): JSX.Ele
setQuery={updateQuerySource}
eventNames={getAllEventNames(querySource as ProductAnalyticsInsightQueryNode, allActions)}
taxonomicGroupTypes={taxonomicGroupTypes}
- hasDataWarehouseSeries={hasDataWarehouseSeries}
+ hasDataWarehouseSeries={hasDataWarehouseEntity}
/>
)
}
diff --git a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
index 4f4d665f1382..e80cedbbe7c1 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
@@ -64,6 +64,7 @@ import { BoxPlotLegend } from 'products/product_analytics/frontend/insights/tren
import { BoxPlotResultsTable } from 'products/product_analytics/frontend/insights/trends/BoxPlot/BoxPlotResultsTable'
import { TrendInsight } from 'products/product_analytics/frontend/insights/trends/Trends'
+import { FlagCallsRetentionNotice } from './FlagCallsRetentionNotice'
import { InsightDisplayConfig } from './InsightDisplayConfig'
import { InsightResultMetadata } from './InsightResultMetadata'
import { ResultCustomizationsModal } from './ResultCustomizationsModal'
@@ -218,6 +219,7 @@ export function InsightVizDisplay({
validationError,
validationErrorCode,
theme,
+ showsFlagCallsRetentionNotice,
} = useValues(insightVizDataLogic(insightProps))
const { loadData, updateQuerySource } = useActions(insightVizDataLogic(insightProps))
const { exportContext, queryId, insightDataError } = useValues(insightDataLogic(insightProps))
@@ -600,6 +602,7 @@ export function InsightVizDisplay({
</div>
)}
+ {!embedded && showsFlagCallsRetentionNotice && <FlagCallsRetentionNotice />}
<div
className={clsx(
'InsightVizDisplay__content',
diff --git a/frontend/src/queries/nodes/InsightViz/PropertyGroupFilters/PropertyGroupFilters.tsx b/frontend/src/queries/nodes/InsightViz/PropertyGroupFilters/PropertyGroupFilters.tsx
index e3ec8e70e6d6..0b5dfb9f7914 100644
--- a/frontend/src/queries/nodes/InsightViz/PropertyGroupFilters/PropertyGroupFilters.tsx
+++ b/frontend/src/queries/nodes/InsightViz/PropertyGroupFilters/PropertyGroupFilters.tsx
@@ -13,6 +13,7 @@ import { inlineEquivalentPropertyGroups, isPropertyGroupFilterLike } from 'lib/c
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { FLAG_CALLS_SERIES_NAME, readsFlagCalls } from 'scenes/insights/filters/ActionFilter/flagCallsSeries'
import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'
import { InsightQueryNode, ProductAnalyticsInsightQueryNode } from '~/queries/schema/schema-general'
@@ -62,9 +63,11 @@ export function PropertyGroupFilters({
[propertyGroupFilter.values]
)
const showHeader = propertyGroupFilter.type && propertyGroupFilter.values.length > 1
- const disabledReason = hasDataWarehouseSeries
- ? 'Filter groups cannot be added to insights with a data warehouse series. Please use individual series filters instead.'
- : undefined
+ const disabledReason = !hasDataWarehouseSeries
+ ? undefined
+ : readsFlagCalls(query)
+ ? `${FLAG_CALLS_SERIES_NAME} doesn't support filter groups. Use the filters on the series instead.`
+ : 'Filter groups cannot be added to insights with a data warehouse series. Please use individual series filters instead.'
return (
<div className="deprecated-space-y-2 PropertyGroupFilters @container">
{propertyGroupFilter.values && (
diff --git a/frontend/src/queries/nodes/InsightViz/TrendsSeries.tsx b/frontend/src/queries/nodes/InsightViz/TrendsSeries.tsx
index 917bba0887a2..99c975352b78 100644
--- a/frontend/src/queries/nodes/InsightViz/TrendsSeries.tsx
+++ b/frontend/src/queries/nodes/InsightViz/TrendsSeries.tsx
@@ -130,6 +130,7 @@ export function TrendsSeries(): JSX.Element | null {
TaxonomicFilterGroupType.AutocaptureEvents,
...(supportsDataWarehouse ? [TaxonomicFilterGroupType.DataWarehouse] : []),
]}
+ flagCallsFromFlagEvaluations={supportsDataWarehouse}
hideDeleteBtn={series?.length === 1}
addFilterDocLink="https://posthog.com/docs/product-analytics/trends/filters"
dataWarehousePopoverFields={isLifecycle ? lifecycleDataWarehousePopoverFields : undefined}
diff --git a/frontend/src/scenes/activity/explore/EventsScene.tsx b/frontend/src/scenes/activity/explore/EventsScene.tsx
index 5eca7de8ca8e..0be180f84313 100644
--- a/frontend/src/scenes/activity/explore/EventsScene.tsx
+++ b/frontend/src/scenes/activity/explore/EventsScene.tsx
@@ -5,7 +5,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { ActivitySceneTabs } from 'scenes/activity/ActivitySceneTabs'
-import { FLAG_EVALUATIONS_RETENTION_DAYS } from 'scenes/feature-flags/featureFlagUsageQueries'
+import { FLAG_EVALUATIONS_RETENTION_DAYS } from 'scenes/feature-flags/flagEvaluationsTable'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene, SceneExport } from 'scenes/sceneTypes'
import { LiveRecordingsCount } from 'scenes/session-recordings/components/LiveRecordingsCount'
diff --git a/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx b/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx
index 4e9ffec46a3a..a644b8f95e69 100644
--- a/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx
+++ b/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx
@@ -17,7 +17,7 @@ import {
FEATURE_FLAG_CALLED_EVENT,
reachesPastFlagEvaluationsRetention,
readsFlagEvaluationsTable,
-} from 'scenes/feature-flags/featureFlagUsageQueries'
+} from 'scenes/feature-flags/flagEvaluationsTable'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene } from 'scenes/sceneTypes'
import { filterTestAccountsDefaultsLogic } from 'scenes/settings/environment/filterTestAccountDefaultsLogic'
diff --git a/frontend/src/scenes/feature-flags/FeatureFlag.tsx b/frontend/src/scenes/feature-flags/FeatureFlag.tsx
index 8ccce5408679..135715b6c203 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlag.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlag.tsx
@@ -102,7 +102,7 @@ import FeatureFlagSchedule from './FeatureFlagSchedule'
import { FeatureFlagsTab, featureFlagsLogic } from './featureFlagsLogic'
import { FeatureFlagTestingTab } from './FeatureFlagTestingTab'
import { FeatureFlagUsageMetrics } from './FeatureFlagUsageMetrics'
-import { FLAG_EVALUATIONS_RETENTION_DAYS, readsFlagEvaluationsTable } from './featureFlagUsageQueries'
+import { FLAG_EVALUATIONS_RETENTION_DAYS, readsFlagEvaluationsTable } from './flagEvaluationsTable'
import { useFeatureFlagAgentRefresh } from './useFeatureFlagAgentRefresh'
const RESOURCE_TYPE = 'feature_flag'
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagUsageMetrics.tsx b/frontend/src/scenes/feature-flags/FeatureFlagUsageMetrics.tsx
index 8ffe9f8c5cb9..6f95a9a6a388 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagUsageMetrics.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagUsageMetrics.tsx
@@ -4,7 +4,7 @@ import { QueryCard } from 'lib/components/Cards/InsightCard/QueryCard'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { featureFlagUsageLogic } from './featureFlagUsageLogic'
-import { FLAG_EVALUATIONS_RETENTION_DAYS } from './featureFlagUsageQueries'
+import { FLAG_EVALUATIONS_RETENTION_DAYS } from './flagEvaluationsTable'
export function FeatureFlagUsageMetrics({ id }: { id: number }): JSX.Element {
const logic = featureFlagUsageLogic({ id })
diff --git a/frontend/src/scenes/feature-flags/featureFlagUsageLogic.ts b/frontend/src/scenes/feature-flags/featureFlagUsageLogic.ts
index e16909516a04..e2a0daf1c657 100644
--- a/frontend/src/scenes/feature-flags/featureFlagUsageLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagUsageLogic.ts
@@ -20,8 +20,8 @@ import {
buildFlagEvaluationsUniqueCallersChart,
clampToFlagEvaluationsRetention,
flagEvaluationsDateOptions,
- readsFlagEvaluationsTable,
} from './featureFlagUsageQueries'
+import { readsFlagEvaluationsTable } from './flagEvaluationsTable'
// The Usage tab only renders for persisted flags, so unlike featureFlagLogic this
// logic never mounts for 'new'/'link' ids.
diff --git a/frontend/src/scenes/feature-flags/featureFlagUsageQueries.test.ts b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.test.ts
index fe03087d19c1..17d90ddd088b 100644
--- a/frontend/src/scenes/feature-flags/featureFlagUsageQueries.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.test.ts
@@ -11,12 +11,12 @@ import {
buildFlagEvaluationsTotalVolumeChart,
buildFlagEvaluationsUniqueCallersChart,
clampToFlagEvaluationsRetention,
- FLAG_EVALUATIONS_RETENTION_DAYS,
FLAG_EVALUATIONS_VOLUME_ROW_LIMIT,
flagEvaluationsDateOptions,
FlagUsageChart,
FlagUsageQueryOptions,
} from './featureFlagUsageQueries'
+import { FLAG_EVALUATIONS_RETENTION_DAYS } from './flagEvaluationsTable'
type TrendsUsageChart = FlagUsageChart<InsightVizNode<TrendsQuery>>
diff --git a/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts
index 46e8265e09d2..9f135d332e50 100644
--- a/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts
@@ -5,11 +5,9 @@
// Titles differ on purpose: update_feature_flag_dashboard looks tiles up by name, so the Python
// names are pinned, while these use sentence case. The interval here follows the user's date range
// rather than the template's fixed "day".
-import { dayjs } from 'lib/dayjs'
import { dateMapping, dateStringToDayJs, getDefaultInterval } from 'lib/utils/dateFilters'
import { BREAKDOWN_NULL_DISPLAY } from 'scenes/insights/utils'
-import { FlagEvaluationsModeEnumApi } from '~/generated/core/api.schemas'
import { Noun } from '~/models/groupsModel'
import {
ChartSettings,
@@ -31,10 +29,15 @@ import {
GroupTypeIndex,
PropertyFilterType,
PropertyOperator,
- TeamPublicType,
- TeamType,
} from '~/types'
+import {
+ FLAG_EVALUATIONS_RETENTION_DAYS,
+ FLAG_EVALUATIONS_TABLE,
+ flagEvaluationsRetentionStart,
+ reachesPastFlagEvaluationsRetention,
+} from './flagEvaluationsTable'
+
export interface FlagUsageQueryOptions {
flagKey: string
aggregationGroupTypeIndex: number | null | undefined
@@ -185,10 +188,6 @@ function enrichedSeries(event: '$feature_view' | '$feature_interaction', seriesL
]
}
-// Not a root table, so the `posthog.` prefix is part of the name. A team on the Events mode without
-// the flag-evaluations-hogql-table flag has no such table, and these queries fail to resolve for it.
-const FLAG_EVALUATIONS_TABLE = 'posthog.flag_evaluations'
-
// The table stores a JSON-null $feature_flag_response as 'null' and a missing one as ''. The events-mode
// breakdown puts both cases in one bucket labelled BREAKDOWN_NULL_DISPLAY, so these charts do the same.
// The label is in the query because the SQL line chart names a NULL series "[No value]" and the SQL
@@ -196,39 +195,12 @@ const FLAG_EVALUATIONS_TABLE = 'posthog.flag_evaluations'
// editor rejects that key, but the API accepts it.
const FLAG_EVALUATIONS_VARIANT = `if(response IN ('', 'null'), ${escapeHogQLString(BREAKDOWN_NULL_DISPLAY)}, response)`
-/**
- * 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.
- */
-export const FLAG_EVALUATIONS_RETENTION_DAYS = 90
-
-const EVENTS_MODE = FlagEvaluationsModeEnumApi.Number0
-
-export const FEATURE_FLAG_CALLED_EVENT = '$feature_flag_called'
-
-export function readsFlagEvaluationsTable(team: TeamPublicType | TeamType | null): boolean {
- return (team?.flag_evaluations_mode ?? EVENTS_MODE) !== EVENTS_MODE
-}
-
-// Start of the oldest day the table still holds. dateStringToDayJs resolves the ranges this is
-// compared to against UTC, so the boundary is UTC too: a browser-local midnight sits hours off it,
-// which drops the 90-day preset in a timezone ahead of UTC.
-function earliestRetainedDay(): dayjs.Dayjs {
- return dayjs.utc().startOf('day').subtract(FLAG_EVALUATIONS_RETENTION_DAYS, 'day')
-}
-
-export function reachesPastFlagEvaluationsRetention(dateFrom: string | null): boolean {
- const parsed = dateStringToDayJs(dateFrom)
- // A null start and "all" are all time, which reaches further than any retained day.
- return !parsed || parsed.isBefore(earliestRetainedDay())
-}
-
/** Pulls a range back inside the retention window, where it cannot quietly show fewer rows than the events table. */
export function clampToFlagEvaluationsRetention(dateRange: DateRange): DateRange {
if (!reachesPastFlagEvaluationsRetention(dateRange.date_from ?? null)) {
return dateRange
}
- const earliest = earliestRetainedDay()
+ const earliest = flagEvaluationsRetentionStart()
const dateTo = dateStringToDayJs(dateRange.date_to ?? null)
return {
date_from: `-${FLAG_EVALUATIONS_RETENTION_DAYS}d`,
diff --git a/frontend/src/scenes/feature-flags/flagEvaluationsTable.test.ts b/frontend/src/scenes/feature-flags/flagEvaluationsTable.test.ts
new file mode 100644
index 000000000000..5b9a10809227
--- /dev/null
+++ b/frontend/src/scenes/feature-flags/flagEvaluationsTable.test.ts
@@ -0,0 +1,56 @@
+import { dayjs } from 'lib/dayjs'
+
+import { insightReachesPastFlagEvaluationsRetention } from './flagEvaluationsTable'
+
+const daysAgo = (days: number): string => dayjs.utc().subtract(days, 'day').toISOString()
+const now = (): string => dayjs.utc().toISOString()
+
+describe('flagEvaluationsTable', () => {
+ it.each([
+ ['a range inside the window', '-30d', { date_from: daysAgo(30), date_to: now() }, undefined, false],
+ ['a range past the window', '-180d', { date_from: daysAgo(180), date_to: now() }, undefined, true],
+ [
+ 'all time, which resolves inside the window',
+ 'all',
+ { date_from: daysAgo(10), date_to: now() },
+ undefined,
+ true,
+ ],
+ ['a query that has not run yet', '-180d', undefined, undefined, false],
+ [
+ 'a previous period inside the window',
+ '-30d',
+ { date_from: daysAgo(30), date_to: now() },
+ { compare: true },
+ false,
+ ],
+ [
+ 'a previous period that doubles the range back past the window',
+ '-60d',
+ { date_from: daysAgo(60), date_to: now() },
+ { compare: true },
+ true,
+ ],
+ [
+ 'a comparison shifted inside the window',
+ '-30d',
+ { date_from: daysAgo(30), date_to: now() },
+ { compare: true, compare_to: '-30d' },
+ false,
+ ],
+ [
+ 'a comparison shifted past the window',
+ '-30d',
+ { date_from: daysAgo(30), date_to: now() },
+ { compare: true, compare_to: '-1y' },
+ true,
+ ],
+ ])(
+ 'insightReachesPastFlagEvaluationsRetention: %s',
+ (_name, dateFrom, resolvedDateRange, compareFilter, expected) => {
+ expect(insightReachesPastFlagEvaluationsRetention({ dateFrom, resolvedDateRange, compareFilter })).toBe(
+ expected
+ )
+ }
+ )
+})
diff --git a/frontend/src/scenes/feature-flags/flagEvaluationsTable.ts b/frontend/src/scenes/feature-flags/flagEvaluationsTable.ts
new file mode 100644
index 000000000000..9983ea7be0dd
--- /dev/null
+++ b/frontend/src/scenes/feature-flags/flagEvaluationsTable.ts
@@ -0,0 +1,65 @@
+import { dayjs } from 'lib/dayjs'
+import { componentsToDayJs, dateStringToComponents, dateStringToDayJs } from 'lib/utils/dateFilters'
+
+import { FlagEvaluationsModeEnumApi } from '~/generated/core/api.schemas'
+import { CompareFilter } from '~/queries/schema/schema-general'
+import type { TeamPublicType, TeamType } from '~/types'
+
+// Not a root table, so the `posthog.` prefix is part of the name. A team on the Events mode without
+// the flag-evaluations-hogql-table flag has no such table. Queries on it fail to resolve for that team.
+export const FLAG_EVALUATIONS_TABLE = 'posthog.flag_evaluations'
+
+export const FEATURE_FLAG_CALLED_EVENT = '$feature_flag_called'
+
+const EVENTS_MODE = FlagEvaluationsModeEnumApi.Number0
+
+export function readsFlagEvaluationsTable(team: TeamPublicType | TeamType | null): boolean {
+ return (team?.flag_evaluations_mode ?? EVENTS_MODE) !== EVENTS_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.
+ */
+export const FLAG_EVALUATIONS_RETENTION_DAYS = 90
+
+// Start of the oldest day the table still holds. dateStringToDayJs resolves the ranges this is
+// compared to against UTC, so the boundary is UTC too: a browser-local midnight sits hours off it,
+// which drops the 90-day preset in a timezone ahead of UTC.
+export function flagEvaluationsRetentionStart(): dayjs.Dayjs {
+ return dayjs.utc().startOf('day').subtract(FLAG_EVALUATIONS_RETENTION_DAYS, 'day')
+}
+
+export function reachesPastFlagEvaluationsRetention(dateFrom: string | null): boolean {
+ const parsed = dateStringToDayJs(dateFrom)
+ // A null start and "all" are all time, which reaches further than any retained day.
+ return !parsed || parsed.isBefore(flagEvaluationsRetentionStart())
+}
+
+/** Whether the range an insight ran over, or the period it compares against, starts before the table's oldest day. */
+export function insightReachesPastFlagEvaluationsRetention({
+ dateFrom,
+ resolvedDateRange,
+ compareFilter,
+}: {
+ /** The live editor range, which wins over the saved query's. */
+ dateFrom: string | null | undefined
+ resolvedDateRange: { date_from?: string | null; date_to?: string | null } | null | undefined
+ compareFilter: CompareFilter | null | undefined
+}): boolean {
+ // All time resolves to the oldest row the table still holds, so the resolved range never shows the cutoff.
+ if (dateFrom === 'all') {
+ return true
+ }
+ if (!resolvedDateRange?.date_from) {
+ return false
+ }
+ const start = dayjs(resolvedDateRange.date_from)
+ const compareToComponents = compareFilter?.compare ? dateStringToComponents(compareFilter.compare_to ?? null) : null
+ const comparedStart = !compareFilter?.compare
+ ? start
+ : compareToComponents
+ ? componentsToDayJs(compareToComponents, start)
+ : start.subtract(dayjs(resolvedDateRange.date_to ?? undefined).diff(start), 'millisecond')
+ return comparedStart.isBefore(flagEvaluationsRetentionStart())
+}
diff --git a/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts b/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts
index 89e36075f65b..e30b0d926635 100644
--- a/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts
+++ b/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts
@@ -14,6 +14,7 @@ import { nodeKindToDefaultQuery } from '~/queries/nodes/InsightQuery/defaults'
import {
Breakdown,
BreakdownFilter,
+ DataWarehouseNode,
EventsQuery,
FunnelsQuery,
InsightVizNode,
@@ -1516,6 +1517,15 @@ describe('insightNavLogic', () => {
expect(stickinessSource.stickinessFilter?.display).toEqual(ChartDisplayType.ActionsBar)
})
+ const flagCallsTrendsNode: DataWarehouseNode = {
+ kind: NodeKind.DataWarehouseNode,
+ id: 'posthog.flag_evaluations',
+ name: 'posthog.flag_evaluations',
+ table_name: 'posthog.flag_evaluations',
+ id_field: 'uuid',
+ timestamp_field: 'timestamp',
+ distinct_id_field: 'distinct_id',
+ }
const dataWarehouseTestCases: {
label: string
source: InsightVizNode['source']
@@ -1716,6 +1726,159 @@ describe('insightNavLogic', () => {
funnelsFilter: { funnelVizType: 'steps' },
},
},
+ {
+ label: 'trends flag calls to funnels',
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [flagCallsTrendsNode],
+ },
+ targetView: InsightType.FUNNELS,
+ expectedSource: {
+ kind: NodeKind.FunnelsQuery,
+ series: [
+ {
+ kind: NodeKind.FunnelsDataWarehouseNode,
+ table_name: 'posthog.flag_evaluations',
+ id_field: 'uuid',
+ timestamp_field: 'timestamp',
+ aggregation_target_field: 'person_id',
+ },
+ ],
+ },
+ },
+ {
+ label: 'trends flag calls by group to funnels',
+ source: {
+ kind: NodeKind.TrendsQuery,
+ aggregation_group_type_index: 0,
+ series: [flagCallsTrendsNode],
+ },
+ targetView: InsightType.FUNNELS,
+ expectedSource: {
+ kind: NodeKind.FunnelsQuery,
+ aggregation_group_type_index: 0,
+ series: [
+ {
+ kind: NodeKind.FunnelsDataWarehouseNode,
+ table_name: 'posthog.flag_evaluations',
+ aggregation_target_field: '$group_0',
+ },
+ ],
+ },
+ },
+ {
+ label: 'trends flag calls to retention',
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [
+ {
+ kind: NodeKind.DataWarehouseNode,
+ id: 'posthog.flag_evaluations',
+ name: 'Feature flag called',
+ table_name: 'posthog.flag_evaluations',
+ id_field: 'uuid',
+ timestamp_field: 'timestamp',
+ distinct_id_field: 'distinct_id',
+ },
+ ],
+ },
+ targetView: InsightType.RETENTION,
+ expectedSource: {
+ kind: NodeKind.RetentionQuery,
+ retentionFilter: {
+ targetEntity: {
+ type: 'data_warehouse',
+ table_name: 'posthog.flag_evaluations',
+ timestamp_field: 'timestamp',
+ aggregation_target_field: 'person_id',
+ },
+ returningEntity: {
+ type: 'data_warehouse',
+ table_name: 'posthog.flag_evaluations',
+ aggregation_target_field: 'person_id',
+ },
+ },
+ },
+ },
+ {
+ label: 'retention flag calls to funnels',
+ source: {
+ kind: NodeKind.RetentionQuery,
+ retentionFilter: {
+ targetEntity: {
+ type: 'data_warehouse',
+ id: 'posthog.flag_evaluations',
+ name: 'Feature flag called',
+ table_name: 'posthog.flag_evaluations',
+ timestamp_field: 'timestamp',
+ aggregation_target_field: 'person_id',
+ },
+ },
+ },
+ targetView: InsightType.FUNNELS,
+ expectedSource: {
+ kind: NodeKind.FunnelsQuery,
+ series: [
+ {
+ kind: NodeKind.FunnelsDataWarehouseNode,
+ table_name: 'posthog.flag_evaluations',
+ id_field: 'uuid',
+ timestamp_field: 'timestamp',
+ aggregation_target_field: 'person_id',
+ },
+ ],
+ },
+ },
+ {
+ label: 'trends flag calls to lifecycle',
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [flagCallsTrendsNode],
+ },
+ targetView: InsightType.LIFECYCLE,
+ expectedSource: {
+ kind: NodeKind.LifecycleQuery,
+ series: [
+ {
+ kind: NodeKind.LifecycleDataWarehouseNode,
+ table_name: 'posthog.flag_evaluations',
+ timestamp_field: 'timestamp',
+ aggregation_target_field: 'person_id',
+ created_at_field: 'timestamp',
+ },
+ ],
+ },
+ },
+ {
+ label: 'lifecycle flag calls to trends',
+ source: {
+ kind: NodeKind.LifecycleQuery,
+ series: [
+ {
+ kind: NodeKind.LifecycleDataWarehouseNode,
+ id: 'posthog.flag_evaluations',
+ name: 'posthog.flag_evaluations',
+ table_name: 'posthog.flag_evaluations',
+ timestamp_field: 'timestamp',
+ aggregation_target_field: 'person_id',
+ created_at_field: 'timestamp',
+ },
+ ],
+ },
+ targetView: InsightType.TRENDS,
+ expectedSource: {
+ kind: NodeKind.TrendsQuery,
+ series: [
+ {
+ kind: NodeKind.DataWarehouseNode,
+ table_name: 'posthog.flag_evaluations',
+ id_field: 'uuid',
+ timestamp_field: 'timestamp',
+ distinct_id_field: 'distinct_id',
+ },
+ ],
+ },
+ },
]
it.each(dataWarehouseTestCases)('converts $label', async ({ source, targetView, expectedSource }) => {
diff --git a/frontend/src/scenes/insights/InsightNav/insightNavLogic.tsx b/frontend/src/scenes/insights/InsightNav/insightNavLogic.tsx
index c43583ad1a64..b90ef17fe38c 100644
--- a/frontend/src/scenes/insights/InsightNav/insightNavLogic.tsx
+++ b/frontend/src/scenes/insights/InsightNav/insightNavLogic.tsx
@@ -5,6 +5,11 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { LemonTag } from 'lib/lemon-ui/LemonTag'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { identifierToHuman } from 'lib/utils/strings'
+import { FLAG_EVALUATIONS_TABLE } from 'scenes/feature-flags/flagEvaluationsTable'
+import {
+ FLAG_EVALUATIONS_SERIES_FIELDS,
+ withFlagCallsAggregationTarget,
+} from 'scenes/insights/filters/ActionFilter/flagCallsSeries'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'
import { filterTestAccountsDefaultsLogic } from 'scenes/settings/environment/filterTestAccountDefaultsLogic'
@@ -192,14 +197,19 @@ const cleanDataWarehouseNode = (
created_at_field,
...baseEntity
} = entity as EntityNode & DataWarehouseNodeSharedFields
+ // A flag calls series has a known column for each field. It does not copy one field into another.
+ const knownFields: DataWarehouseNodeSharedFields =
+ entity.table_name === FLAG_EVALUATIONS_TABLE ? FLAG_EVALUATIONS_SERIES_FIELDS : {}
+ const idField = id_field ?? knownFields.id_field
if (dataWarehouseNodeKind === NodeKind.DataWarehouseNode) {
return {
...baseEntity,
kind: NodeKind.DataWarehouseNode,
- ...(id_field ? { id_field } : {}),
+ ...(idField ? { id_field: idField } : {}),
distinct_id_field:
distinct_id_field ??
+ knownFields.distinct_id_field ??
(isFunnelsDataWarehouseNode(entity) || isLifecycleDataWarehouseNode(entity)
? entity.aggregation_target_field
: undefined),
@@ -210,9 +220,11 @@ const cleanDataWarehouseNode = (
return {
...baseEntity,
kind: NodeKind.FunnelsDataWarehouseNode,
- ...(id_field ? { id_field } : {}),
+ ...(idField ? { id_field: idField } : {}),
aggregation_target_field:
- aggregation_target_field ?? (isDataWarehouseNode(entity) ? entity.distinct_id_field : undefined),
+ aggregation_target_field ??
+ knownFields.aggregation_target_field ??
+ (isDataWarehouseNode(entity) ? entity.distinct_id_field : undefined),
} as FunnelsDataWarehouseNode | GroupNode
}
@@ -220,8 +232,10 @@ const cleanDataWarehouseNode = (
...baseEntity,
kind: NodeKind.LifecycleDataWarehouseNode,
aggregation_target_field:
- aggregation_target_field ?? (isDataWarehouseNode(entity) ? entity.distinct_id_field : undefined),
- created_at_field: created_at_field ?? entity.timestamp_field,
+ aggregation_target_field ??
+ knownFields.aggregation_target_field ??
+ (isDataWarehouseNode(entity) ? entity.distinct_id_field : undefined),
+ created_at_field: created_at_field ?? knownFields.created_at_field ?? entity.timestamp_field,
} as LifecycleDataWarehouseNode | GroupNode
}
@@ -327,10 +341,25 @@ const seriesEntityToRetentionEntity = (
...(entity.properties?.length ? { properties: entity.properties } : {}),
}
}
+ // A flag calls series has a known column for each field, so it maps to a warehouse retention entity.
+ if (isAnyDataWarehouseNode(entity) && entity.table_name === FLAG_EVALUATIONS_TABLE) {
+ return {
+ type: EntityTypes.DATA_WAREHOUSE,
+ id: FLAG_EVALUATIONS_TABLE,
+ table_name: FLAG_EVALUATIONS_TABLE,
+ timestamp_field: FLAG_EVALUATIONS_SERIES_FIELDS.timestamp_field,
+ aggregation_target_field: FLAG_EVALUATIONS_SERIES_FIELDS.aggregation_target_field,
+ ...(entity.name ? { name: entity.name } : {}),
+ ...(entity.custom_name ? { custom_name: entity.custom_name } : {}),
+ ...(entity.properties?.length ? { properties: entity.properties } : {}),
+ }
+ }
return undefined
}
-const retentionEntityToSeriesEntity = (entity: RetentionEntity | undefined): EventsNode | ActionsNode | undefined => {
+const retentionEntityToSeriesEntity = (
+ entity: RetentionEntity | undefined
+): EventsNode | ActionsNode | DataWarehouseNode | undefined => {
if (!entity) {
return undefined
}
@@ -343,6 +372,19 @@ const retentionEntityToSeriesEntity = (entity: RetentionEntity | undefined): Eve
...(entity.properties?.length ? { properties: entity.properties } : {}),
}
}
+ if (entity.type === EntityTypes.DATA_WAREHOUSE && entity.table_name === FLAG_EVALUATIONS_TABLE) {
+ return {
+ kind: NodeKind.DataWarehouseNode,
+ id: FLAG_EVALUATIONS_TABLE,
+ table_name: FLAG_EVALUATIONS_TABLE,
+ id_field: FLAG_EVALUATIONS_SERIES_FIELDS.id_field,
+ timestamp_field: FLAG_EVALUATIONS_SERIES_FIELDS.timestamp_field,
+ distinct_id_field: FLAG_EVALUATIONS_SERIES_FIELDS.distinct_id_field,
+ ...(entity.name ? { name: entity.name } : {}),
+ ...(entity.custom_name ? { custom_name: entity.custom_name } : {}),
+ ...(entity.properties?.length ? { properties: entity.properties } : {}),
+ }
+ }
// A data warehouse target carries table_name/timestamp_field that no EventsNode can hold, and a
// RetentionEntity lacks the id_field/distinct_id_field a DataWarehouseNode needs, so it can't map to
// a series. Drop it rather than fabricate an event named after the table; the retentionFilter cache
@@ -850,10 +892,14 @@ const cachePropertiesFromQuery = (query: InsightQueryNode, cache: QueryPropertyC
// A target that still points at the cached entity keeps it whole, math included; a target
// edited on retention replaces it.
const targetIsCachedEntity =
- firstCached?.kind === seriesEntity.kind &&
- (seriesEntity.kind === NodeKind.ActionsNode
- ? (firstCached as ActionsNode).id === seriesEntity.id
- : (firstCached as EventsNode).event === seriesEntity.event)
+ seriesEntity.kind === NodeKind.DataWarehouseNode
+ ? !!firstCached &&
+ isAnyDataWarehouseNode(firstCached) &&
+ firstCached.table_name === seriesEntity.table_name
+ : firstCached?.kind === seriesEntity.kind &&
+ (seriesEntity.kind === NodeKind.ActionsNode
+ ? (firstCached as ActionsNode).id === seriesEntity.id
+ : (firstCached as EventsNode).event === seriesEntity.event)
newCache.series = [targetIsCachedEntity ? firstCached : seriesEntity, ...restCached]
}
}
@@ -902,11 +948,11 @@ const mergeCachedProperties = (query: InsightQueryNode, cache: QueryPropertyCach
}
// Insight-specific filter merge (web analytics already returned above)
- return {
+ return withFlagCallsAggregationTarget({
...mergedQuery,
...buildCachedFields(query, cache),
...buildInsightFilter(query, cache),
- } as InsightQueryNode
+ } as InsightQueryNode)
}
const buildCachedFields = (query: InsightQueryNode, cache: QueryPropertyCache): Partial<QueryPropertyCache> => {
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilter.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilter.tsx
index 47662d067dab..6fcae9ef26f5 100644
--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilter.tsx
+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilter.tsx
@@ -110,6 +110,11 @@ export interface SeriesActionFilterProps {
includeHiddenEvents?: TaxonomicPopoverProps['includeHiddenEvents']
/** Allow adding non-captured events */
allowNonCapturedEvents?: boolean
+ /**
+ * Picking `$feature_flag_called` builds a `posthog.flag_evaluations` series when the team reads that table.
+ * Set it only where the insight accepts data warehouse series.
+ */
+ flagCallsFromFlagEvaluations?: boolean
hogQLGlobals?: Record<string, any>
definitionPopoverRenderer?: DefinitionPopoverRenderer
operatorAllowlist?: PropertyOperator[]
@@ -157,6 +162,7 @@ export const SeriesActionFilter = React.forwardRef<HTMLDivElement, SeriesActionF
excludedProperties,
includeHiddenEvents,
allowNonCapturedEvents,
+ flagCallsFromFlagEvaluations,
hogQLGlobals,
definitionPopoverRenderer,
operatorAllowlist,
@@ -232,6 +238,7 @@ export const SeriesActionFilter = React.forwardRef<HTMLDivElement, SeriesActionF
excludedProperties,
includeHiddenEvents,
allowNonCapturedEvents,
+ flagCallsFromFlagEvaluations,
hogQLGlobals,
operatorAllowlist,
inlineEventsDocLink: isTrendsInsight
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.test.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.test.tsx
index 28ed8d78ea16..1e8c07ffe8e0 100644
--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.test.tsx
+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.test.tsx
@@ -1,4 +1,4 @@
-import { MOCK_GROUP_TYPES } from '~/lib/api.mock'
+import { MOCK_DEFAULT_TEAM, MOCK_GROUP_TYPES } from '~/lib/api.mock'
import '@testing-library/jest-dom'
@@ -6,12 +6,16 @@ import { cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Provider } from 'kea'
+import { lemonToast } from '@posthog/lemon-ui'
+
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
-import { entityFilterLogic } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'
+import { EntityFilterProps, entityFilterLogic } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'
+import { teamLogic } from 'scenes/teamLogic'
+import { FlagEvaluationsModeEnumApi } from '~/generated/core/api.schemas'
import { useAvailableFeatures } from '~/mocks/features'
import { useMocks } from '~/mocks/jest'
import { actionsModel } from '~/models/actionsModel'
@@ -19,9 +23,10 @@ import { groupsModel } from '~/models/groupsModel'
import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
import { NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
-import { searchAndSelect, setupInsightMocks } from '~/test/insight-testing'
+import { eventDefinitions, searchAndSelect, setupInsightMocks } from '~/test/insight-testing'
import {
AvailableFeature,
+ BaseMathType,
EntityTypes,
FilterType,
HogQLMathType,
@@ -73,13 +78,16 @@ const INLINE_CONTEXT = {
mathAvailability: MathAvailability.None,
}
-function setup(seriesOverride?: SeriesNode[]): {
+function setup(
+ seriesOverride?: SeriesNode[],
+ logicProps: Partial<EntityFilterProps> = {}
+): {
logic: ReturnType<typeof entityFilterLogic.build>
onChange: jest.Mock
} {
const series = seriesOverride ?? legacyFiltersToSeries(filtersJson as FilterType)
const onChange = jest.fn()
- const logic = entityFilterLogic({ onChange, series, typeKey: 'test-key' })
+ const logic = entityFilterLogic({ onChange, series, typeKey: 'test-key', ...logicProps })
logic.mount()
return { logic, onChange }
}
@@ -299,62 +307,69 @@ describe('ActionFilterRow', () => {
expect(screen.getByTestId('box-plot-property-select')).toBeInTheDocument()
})
- it('offers only numeric warehouse columns in the box plot property selector for data warehouse series', async () => {
- databaseTableListLogic.mount()
- databaseTableListLogic.actions.loadDatabaseSuccess({
- tables: {
- events_table: {
- type: 'data_warehouse',
- id: 'wh-table-1',
- name: 'events_table',
- fields: {
- duration: {
- name: 'duration',
- hogql_value: 'duration',
- type: 'float',
- schema_valid: true,
- },
- customer_name: {
- name: 'customer_name',
- hogql_value: 'customer_name',
- type: 'string',
- schema_valid: true,
+ it.each([
+ { tableType: 'data_warehouse', tableName: 'events_table', seriesName: 'events_table' },
+ // A flag calls series reads a PostHog table, which the warehouse table map leaves out.
+ { tableType: 'posthog', tableName: 'posthog.flag_evaluations', seriesName: 'Feature flag called' },
+ ])(
+ 'offers only numeric columns of a $tableType table in the box plot property selector',
+ async ({ tableType, tableName, seriesName }) => {
+ databaseTableListLogic.mount()
+ databaseTableListLogic.actions.loadDatabaseSuccess({
+ tables: {
+ [tableName]: {
+ type: tableType,
+ id: 'wh-table-1',
+ name: tableName,
+ fields: {
+ duration: {
+ name: 'duration',
+ hogql_value: 'duration',
+ type: 'float',
+ schema_valid: true,
+ },
+ customer_name: {
+ name: 'customer_name',
+ hogql_value: 'customer_name',
+ type: 'string',
+ schema_valid: true,
+ },
},
},
},
- },
- joins: [],
- } as any)
-
- const dataWarehouseNode = {
- kind: NodeKind.DataWarehouseNode,
- id: 'events_table',
- name: 'events_table',
- table_name: 'events_table',
- } as SeriesNode
- const { logic, onChange } = setup([dataWarehouseNode])
- renderRow(logic, {
- mathAvailability: MathAvailability.BoxPlotOnly,
- node: dataWarehouseNode,
- })
+ joins: [],
+ } as any)
+
+ const dataWarehouseNode = {
+ kind: NodeKind.DataWarehouseNode,
+ id: tableName,
+ name: seriesName,
+ table_name: tableName,
+ } as SeriesNode
+ const { logic, onChange } = setup([dataWarehouseNode])
+ renderRow(logic, {
+ mathAvailability: MathAvailability.BoxPlotOnly,
+ node: dataWarehouseNode,
+ })
- await userEvent.click(screen.getByTestId('box-plot-property-select'))
- await screen.findByText('duration')
- // The box plot runner applies toFloat() to the selected column, so non-numeric
- // columns must not be offered
- expect(screen.queryByText('customer_name')).not.toBeInTheDocument()
- await userEvent.click(screen.getByText('duration'))
+ await userEvent.click(screen.getByTestId('box-plot-property-select'))
+ await screen.findByText('duration')
+ // The box plot runner applies toFloat() to the selected column, so non-numeric
+ // columns must not be offered
+ expect(screen.queryByText('customer_name')).not.toBeInTheDocument()
+ await userEvent.click(screen.getByText('duration'))
- await waitFor(() => {
- expect(onChange).toHaveBeenCalledWith([
- expect.objectContaining({
- kind: NodeKind.DataWarehouseNode,
- math_property: 'duration',
- math_property_type: TaxonomicFilterGroupType.DataWarehouseProperties,
- }),
- ])
- })
- })
+ await waitFor(() => {
+ expect(onChange).toHaveBeenCalledWith([
+ expect.objectContaining({
+ kind: NodeKind.DataWarehouseNode,
+ math_property: 'duration',
+ math_property_type: TaxonomicFilterGroupType.DataWarehouseProperties,
+ }),
+ ])
+ })
+ }
+ )
})
describe('property filters', () => {
@@ -854,6 +869,267 @@ describe('ActionFilterRow', () => {
)
})
+ describe('feature flag calls series', () => {
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/projects/:team/event_definitions': ({ request }: { request: Request }) => {
+ const search = new URL(request.url).searchParams.get('search') ?? ''
+ const flagCalled = {
+ ...eventDefinitions[0],
+ id: 'flag-called',
+ name: '$feature_flag_called',
+ description: '',
+ }
+ const results = [...eventDefinitions, flagCalled].filter((d) => d.name.includes(search))
+ return [200, { results, count: results.length }]
+ },
+ },
+ })
+ })
+
+ // entityFilterLogic copies only the warehouse fields named in its own popover fields. Each case
+ // passes the editor's fields to the logic as well as to the row.
+ it.each([
+ {
+ insight: 'trends on mode 1',
+ mode: FlagEvaluationsModeEnumApi.Number1,
+ mathAvailability: MathAvailability.None,
+ dataWarehousePopoverFields: undefined,
+ expected: {
+ kind: NodeKind.DataWarehouseNode,
+ name: 'Feature flag called',
+ table_name: 'posthog.flag_evaluations',
+ timestamp_field: 'timestamp',
+ id_field: 'uuid',
+ distinct_id_field: 'distinct_id',
+ },
+ description: /Insights include calls from the last 90 days/,
+ },
+ {
+ insight: 'funnels on mode 2',
+ mode: FlagEvaluationsModeEnumApi.Number2,
+ mathAvailability: MathAvailability.FunnelsOnly,
+ dataWarehousePopoverFields: [
+ { key: 'id_field', label: 'Unique ID' },
+ { key: 'timestamp_field', label: 'Timestamp' },
+ { key: 'aggregation_target_field', label: 'Aggregation target', allowHogQL: true },
+ ],
+ expected: {
+ table_name: 'posthog.flag_evaluations',
+ timestamp_field: 'timestamp',
+ id_field: 'uuid',
+ aggregation_target_field: 'person_id',
+ },
+ description: /Insights include calls from the last 90 days/,
+ },
+ {
+ insight: 'trends on mode 0',
+ mode: FlagEvaluationsModeEnumApi.Number0,
+ mathAvailability: MathAvailability.None,
+ dataWarehousePopoverFields: undefined,
+ expected: { kind: NodeKind.EventsNode, event: '$feature_flag_called' },
+ description: /queries on this event will stop returning results/,
+ },
+ ])(
+ 'describes and picks Feature flag called for $insight',
+ async ({ mode, mathAvailability, dataWarehousePopoverFields, expected, description }) => {
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.FLAG_CALLED_MOVE_NOTICES]: true })
+ try {
+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, flag_evaluations_mode: mode })
+ const { logic, onChange } = setup(undefined, { dataWarehousePopoverFields })
+ renderRow(logic, {
+ ...INLINE_CONTEXT,
+ mathAvailability,
+ dataWarehousePopoverFields,
+ flagCallsFromFlagEvaluations: true,
+ actionsTaxonomicGroupTypes: [
+ TaxonomicFilterGroupType.Events,
+ TaxonomicFilterGroupType.Actions,
+ TaxonomicFilterGroupType.DataWarehouse,
+ ],
+ })
+
+ await userEvent.click(screen.getByTestId('trend-element-subject-0'))
+ await userEvent.type(
+ await screen.findByTestId('taxonomic-filter-searchfield'),
+ '$feature_flag_called'
+ )
+ const [entry] = await screen.findAllByText('Feature flag called')
+ await userEvent.hover(entry.closest('[data-attr^="prop-filter-"]') as HTMLElement)
+ expect(await screen.findByText(description)).toBeInTheDocument()
+ await userEvent.click(entry)
+
+ await waitFor(() => {
+ const lastCall = onChange.mock.calls[onChange.mock.calls.length - 1]?.[0]
+ expect(lastCall?.[0]).toEqual(expect.objectContaining(expected))
+ })
+ } finally {
+ featureFlagLogic.actions.setFeatureFlags([], {})
+ }
+ }
+ )
+
+ it('carries the flag filters of an event series over when Feature flag called is picked again', async () => {
+ teamLogic.actions.loadCurrentTeamSuccess({
+ ...MOCK_DEFAULT_TEAM,
+ flag_evaluations_mode: FlagEvaluationsModeEnumApi.Number1,
+ })
+ const infoToast = jest.spyOn(lemonToast, 'info')
+ const eventsNode: SeriesNode = {
+ kind: NodeKind.EventsNode,
+ event: '$feature_flag_called',
+ name: '$feature_flag_called',
+ math: BaseMathType.WeeklyActiveUsers,
+ properties: [
+ {
+ key: '$feature_flag',
+ value: 'probe-flag',
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Event,
+ },
+ {
+ key: '$feature_flag_response',
+ value: 'test',
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Event,
+ },
+ { key: '$feature_flag_response', operator: PropertyOperator.IsSet, type: PropertyFilterType.Event },
+ {
+ key: '$browser',
+ value: 'Chrome',
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Event,
+ },
+ { key: "properties.$lib = 'web'", type: PropertyFilterType.HogQL },
+ ],
+ }
+ const { logic, onChange } = setup([eventsNode])
+ renderRow(logic, {
+ ...INLINE_CONTEXT,
+ node: eventsNode,
+ flagCallsFromFlagEvaluations: true,
+ actionsTaxonomicGroupTypes: [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.DataWarehouse],
+ })
+
+ await userEvent.click(screen.getByTestId('trend-element-subject-0'))
+ await userEvent.type(await screen.findByTestId('taxonomic-filter-searchfield'), '$feature_flag_called')
+ await userEvent.click(await screen.findByTestId('prop-filter-events-0'))
+
+ await waitFor(() => {
+ const lastCall = onChange.mock.calls[onChange.mock.calls.length - 1]?.[0]
+ expect(lastCall?.[0]).toEqual(
+ expect.objectContaining({
+ table_name: 'posthog.flag_evaluations',
+ math: undefined,
+ properties: [
+ {
+ key: 'flag_key',
+ value: 'probe-flag',
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.DataWarehouse,
+ },
+ {
+ key: 'response',
+ value: 'test',
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.DataWarehouse,
+ },
+ {
+ key: 'response',
+ value: ['', 'null'],
+ operator: PropertyOperator.NotIn,
+ type: PropertyFilterType.DataWarehouse,
+ },
+ { key: "properties.$lib = 'web'", type: PropertyFilterType.HogQL },
+ ],
+ })
+ )
+ })
+ expect(infoToast.mock.calls.map(([message]) => message)).toEqual([
+ 'Feature flag called supports only flag key, response and SQL filters, so 1 other filter was removed.',
+ ])
+ infoToast.mockRestore()
+ })
+
+ it('leaves out math that trends computes from events', async () => {
+ const flagCallsNode: SeriesNode = {
+ kind: NodeKind.DataWarehouseNode,
+ id: 'posthog.flag_evaluations',
+ table_name: 'posthog.flag_evaluations',
+ name: 'Feature flag called',
+ timestamp_field: 'timestamp',
+ id_field: 'uuid',
+ distinct_id_field: 'distinct_id',
+ }
+ const { logic } = setup([flagCallsNode])
+ renderRow(logic, { node: flagCallsNode, mathAvailability: MathAvailability.All })
+
+ await userEvent.click(screen.getByTestId('math-selector-0'))
+
+ expect(await screen.findByText('Unique users')).toBeInTheDocument()
+ for (const label of [
+ 'Weekly active users',
+ 'Monthly active users',
+ 'First-ever occurrence',
+ 'First occurrence matching filters',
+ ]) {
+ expect(screen.queryByText(label)).not.toBeInTheDocument()
+ }
+ })
+
+ it('reopens a flag calls series on the event and picks it again in the rebuilt menu', async () => {
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TAXONOMIC_FILTER_MENU_REBUILD]: true })
+ try {
+ teamLogic.actions.loadCurrentTeamSuccess({
+ ...MOCK_DEFAULT_TEAM,
+ flag_evaluations_mode: FlagEvaluationsModeEnumApi.Number1,
+ })
+ const flagCallsNode: SeriesNode = {
+ kind: NodeKind.DataWarehouseNode,
+ id: 'posthog.flag_evaluations',
+ table_name: 'posthog.flag_evaluations',
+ name: 'Feature flag called',
+ timestamp_field: 'timestamp',
+ id_field: 'uuid',
+ distinct_id_field: 'distinct_id',
+ }
+ const { logic, onChange } = setup([flagCallsNode])
+ renderRow(logic, {
+ ...INLINE_CONTEXT,
+ node: flagCallsNode,
+ flagCallsFromFlagEvaluations: true,
+ actionsTaxonomicGroupTypes: [
+ TaxonomicFilterGroupType.Events,
+ TaxonomicFilterGroupType.Actions,
+ TaxonomicFilterGroupType.DataWarehouse,
+ ],
+ })
+
+ await userEvent.click(screen.getByTestId('taxonomic-popover-menu-trigger'))
+ await userEvent.type(await screen.findByTestId('menu-filter-search'), '$feature_flag_called')
+ const options = await screen.findAllByRole('option')
+ const flagCalledOption = options.find((option) => option.textContent?.includes('Feature flag called'))
+ await userEvent.click(flagCalledOption!)
+
+ await waitFor(() => {
+ const lastCall = onChange.mock.calls[onChange.mock.calls.length - 1]?.[0]
+ expect(lastCall?.[0]).toEqual(
+ expect.objectContaining({
+ kind: NodeKind.DataWarehouseNode,
+ table_name: 'posthog.flag_evaluations',
+ })
+ )
+ })
+ } finally {
+ // The flag persists across tests, so the classic-picker tests after this one need it off.
+ featureFlagLogic.actions.setFeatureFlags([], {})
+ }
+ })
+ })
+
describe('all events entity filter', () => {
it('renders "All events" placeholder for null event id', () => {
const { logic } = setup()
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx
index 47152e6b48dc..b989920b11f6 100644
--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx
+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx
@@ -9,7 +9,9 @@ import posthog from 'posthog-js'
import { useCallback, useEffect } from 'react'
import { IconCopy, IconFilter, IconGroupIntersect, IconPencil, IconTrash } from '@posthog/icons'
+import { lemonToast } from '@posthog/lemon-ui'
+import { DefinitionView } from 'lib/components/DefinitionPopover/DefinitionPopoverContents'
import { EntityFilterInfo } from 'lib/components/EntityFilterInfo'
import { AddBehavioralFilterButton } from 'lib/components/PropertyFilters/components/AddBehavioralFilterButton'
import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'
@@ -17,6 +19,7 @@ import { SeriesGlyph, SeriesLetter } from 'lib/components/SeriesGlyph'
import { defaultDataWarehousePopoverFields } from 'lib/components/TaxonomicFilter/taxonomicFilterLogic'
import {
DataWarehousePopoverField,
+ DefinitionPopoverRenderer,
TaxonomicFilterGroupType,
isQuickFilterItem,
quickFilterToPropertyFilters,
@@ -28,11 +31,17 @@ import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { getEventNamesForAction } from 'lib/utils/events'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
+import {
+ FEATURE_FLAG_CALLED_EVENT,
+ FLAG_EVALUATIONS_TABLE,
+ readsFlagEvaluationsTable,
+} from 'scenes/feature-flags/flagEvaluationsTable'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import { teamLogic } from 'scenes/teamLogic'
import { actionsModel } from '~/models/actionsModel'
+import { PropValue } from '~/models/propertyDefinitionsModel'
import { DatabaseSerializedFieldType, NodeKind } from '~/queries/schema/schema-general'
import {
AnyPropertyFilter,
@@ -50,6 +59,13 @@ import {
mathsLogic,
} from 'products/product_analytics/frontend/insights/trends/mathsLogic'
+import {
+ FLAG_CALLS_SERIES_DESCRIPTION,
+ FLAG_CALLS_SERIES_NAME,
+ FLAG_CALLS_UNSUPPORTED_MATH_TYPES,
+ FLAG_EVALUATIONS_SERIES_FIELDS,
+ flagCallsFiltersFromEventFilters,
+} from '../flagCallsSeries'
import {
isActionsSeriesNode,
isAllEventsSeriesNode,
@@ -86,6 +102,23 @@ const DragHandle = ({ listeners }: DragHandleProps): JSX.Element => (
// so numeric-only pickers must not be fed non-numeric columns in the first place.
const NUMERIC_SCHEMA_FIELD_TYPES: DatabaseSerializedFieldType[] = ['integer', 'float', 'decimal']
+// A warehouse series filter without a warehouse values endpoint falls back to the event values endpoint.
+// That endpoint scans recent events for a column that events do not carry, so these filters fetch no values.
+const NO_VALUE_SUGGESTIONS = (): PropValue[] => []
+
+function picksFlagCalledEvent(groupType: TaxonomicFilterGroupType | undefined, value: unknown): boolean {
+ return groupType === TaxonomicFilterGroupType.Events && value === FEATURE_FLAG_CALLED_EVENT
+}
+
+function withFlagCallsDescription(renderer: DefinitionPopoverRenderer | undefined): DefinitionPopoverRenderer {
+ return (props) =>
+ picksFlagCalledEvent(props.group.type, props.group.getValue?.(props.item)) ? (
+ <DefinitionView group={props.group} description={FLAG_CALLS_SERIES_DESCRIPTION} />
+ ) : (
+ (renderer?.(props) ?? props.defaultView)
+ )
+}
+
// Which warehouse tables a row's picker may offer, by the caller's typeKey. Anything not listed
// gets the unrestricted data warehouse group.
const DATA_WAREHOUSE_GROUP_TYPE_BY_TYPE_KEY: Record<string, TaxonomicFilterGroupType> = {
@@ -132,6 +165,7 @@ export function ActionFilterRow({
excludedProperties,
includeHiddenEvents,
allowNonCapturedEvents,
+ flagCallsFromFlagEvaluations,
hogQLGlobals,
inlineEventsDocLink,
definitionPopoverRenderer,
@@ -143,7 +177,11 @@ export function ActionFilterRow({
...actionsTaxonomicGroupTypes,
]
- const { currentTeamId } = useValues(teamLogic)
+ const { currentTeam, currentTeamId } = useValues(teamLogic)
+ const buildsFlagCallsSeries = !!flagCallsFromFlagEvaluations && readsFlagEvaluationsTable(currentTeam)
+ const rowDefinitionPopoverRenderer = buildsFlagCallsSeries
+ ? withFlagCallsDescription(definitionPopoverRenderer)
+ : definitionPopoverRenderer
const { entityFilterVisible } = useValues(logic)
const {
updateSeriesEntity,
@@ -158,9 +196,16 @@ export function ActionFilterRow({
} = useActions(logic)
const { actions } = useValues(actionsModel({ shouldLoad: isActionsSeriesNode(node) }))
const { mathDefinitions } = useValues(mathsLogic)
- const { dataWarehouseTablesMap } = useValues(databaseTableListLogic)
+ const { allTablesMap } = useValues(databaseTableListLogic)
const { ensureAllTableFields } = useActions(databaseTableListLogic)
const isDataWarehouseFilter = isWarehouseSeriesNode(node)
+ // A flag calls series stands in for the event, so the picker reopens on the event row, not on the table.
+ const isFlagCallsSeries = isDataWarehouseFilter && node.table_name === FLAG_EVALUATIONS_TABLE
+ // The data warehouse map leaves out PostHog tables, which a flag calls series reads.
+ const seriesTable = isDataWarehouseFilter ? allTablesMap[node.table_name] : undefined
+ // The property values endpoint only serves warehouse tables and views.
+ const seriesValuesTableName =
+ seriesTable?.type === 'data_warehouse' || seriesTable?.type === 'view' ? seriesTable.name : undefined
useEffect(() => {
if (isDataWarehouseFilter) {
ensureAllTableFields()
@@ -263,6 +308,34 @@ export function ActionFilterRow({
])
return
}
+ if (buildsFlagCallsSeries && picksFlagCalledEvent(taxonomicGroupType, changedValue)) {
+ updateSeriesEntity(index, {
+ kind: dataWarehouseNodeKind ?? NodeKind.DataWarehouseNode,
+ key: FLAG_EVALUATIONS_TABLE,
+ name: FLAG_CALLS_SERIES_NAME,
+ ...FLAG_EVALUATIONS_SERIES_FIELDS,
+ })
+ if (isEventsSeriesNode(node) && node.event === FEATURE_FLAG_CALLED_EVENT) {
+ const flagCallsFilters = flagCallsFiltersFromEventFilters(node.properties)
+ updateSeriesProperties(index, flagCallsFilters)
+ const removedCount = (node.properties?.length ?? 0) - flagCallsFilters.length
+ if (removedCount > 0) {
+ lemonToast.info(
+ `${FLAG_CALLS_SERIES_NAME} supports only flag key, response and SQL filters, so ${removedCount} other ${removedCount === 1 ? 'filter was' : 'filters were'} removed.`
+ )
+ }
+ }
+ if (node.math && FLAG_CALLS_UNSUPPORTED_MATH_TYPES.has(node.math)) {
+ updateSeriesMath(index, {
+ math: undefined,
+ math_group_type_index: undefined,
+ math_property: undefined,
+ math_property_type: undefined,
+ math_hogql: undefined,
+ })
+ }
+ return
+ }
if (taxonomicGroupType === TaxonomicFilterGroupType.AutocaptureEvents) {
updateSeriesEntity(index, { kind: NodeKind.EventsNode, key: '$autocapture', name: '$autocapture' })
updateSeriesProperties(index, [
@@ -292,7 +365,16 @@ export function ActionFilterRow({
})
}
},
- [updateSeriesEntity, updateSeriesProperties, index, dataWarehousePopoverFields, dataWarehouseNodeKind]
+ [
+ updateSeriesEntity,
+ updateSeriesProperties,
+ updateSeriesMath,
+ index,
+ dataWarehousePopoverFields,
+ dataWarehouseNodeKind,
+ buildsFlagCallsSeries,
+ node,
+ ]
)
const onMathSelect = (_: unknown, selectedMath?: string): void => {
@@ -354,7 +436,11 @@ export function ActionFilterRow({
name = node.name || String(nodeKey)
// The node's own key is the event actually queried — `name` can be a rename (e.g. set via
// the API), and committing it as the taxonomic value would select a non-existent event.
- value = nodeKey != null && nodeKey !== '' ? nodeKey : (node.name ?? null)
+ value = isFlagCallsSeries
+ ? FEATURE_FLAG_CALLED_EVENT
+ : nodeKey != null && nodeKey !== ''
+ ? nodeKey
+ : (node.name ?? null)
}
const seriesIndicator =
@@ -377,13 +463,15 @@ export function ActionFilterRow({
// affordance (selected row floats to the top, with the series' rename applied).
// The picker still opens on the suggested-filters surface either way. All-events
// and inline-group series have no single committed row to promote.
- const initialGroupType = isDataWarehouseFilter
- ? dataWarehouseGroupType
- : isActionsSeriesNode(node)
- ? TaxonomicFilterGroupType.Actions
- : isEventsSeriesNode(node) && !isAllEventsSeriesNode(node) && nodeKey != null && nodeKey !== ''
- ? TaxonomicFilterGroupType.Events
- : TaxonomicFilterGroupType.SuggestedFilters
+ const initialGroupType = isFlagCallsSeries
+ ? TaxonomicFilterGroupType.Events
+ : isDataWarehouseFilter
+ ? dataWarehouseGroupType
+ : isActionsSeriesNode(node)
+ ? TaxonomicFilterGroupType.Actions
+ : isEventsSeriesNode(node) && !isAllEventsSeriesNode(node) && nodeKey != null && nodeKey !== ''
+ ? TaxonomicFilterGroupType.Events
+ : TaxonomicFilterGroupType.SuggestedFilters
// DWH events are not supported in inline events yet
const canCombine = showCombine && !singleFilter && !isDataWarehouseFilter
@@ -413,9 +501,10 @@ export function ActionFilterRow({
typeKey === 'plugin-filters' ? ([] as DataWarehousePopoverField[]) : dataWarehousePopoverFields
}
excludedProperties={excludedProperties}
- includeHiddenEvents={includeHiddenEvents}
+ // The hidden flag-call event shows again, because picking it builds the flag_evaluations series.
+ includeHiddenEvents={includeHiddenEvents || flagCallsFromFlagEvaluations}
allowNonCapturedEvents={allowNonCapturedEvents}
- definitionPopoverRenderer={definitionPopoverRenderer}
+ definitionPopoverRenderer={rowDefinitionPopoverRenderer}
/>
)
@@ -594,6 +683,11 @@ export function ActionFilterRow({
mathAvailability={mathAvailability}
trendsDisplayCategory={trendsDisplayCategory}
allowedMathTypes={allowedMathTypes}
+ excludedMathTypes={
+ isFlagCallsSeries
+ ? FLAG_CALLS_UNSUPPORTED_MATH_TYPES
+ : undefined
+ }
query={query || {}}
fullWidth
truncateText={{ maxWidthClass: 'max-w-full' }}
@@ -628,10 +722,8 @@ export function ActionFilterRow({
onMathPropertySelect={onMathPropertySelect}
showNumericalPropsOnly={isBoxPlotContext || showNumericalPropsOnly}
schemaColumns={
- isDataWarehouseFilter && node.name
- ? Object.values(
- dataWarehouseTablesMap[node.name]?.fields ?? []
- ).filter(
+ seriesTable
+ ? Object.values(seriesTable.fields).filter(
(field) =>
!(isBoxPlotContext || showNumericalPropsOnly) ||
NUMERIC_SCHEMA_FIELD_TYPES.includes(field.type)
@@ -732,12 +824,11 @@ export function ActionFilterRow({
? getEventNamesForAction(node.id, actions)
: []
}
- schemaColumns={
- isDataWarehouseFilter && node.name
- ? Object.values(dataWarehouseTablesMap[node.name]?.fields ?? [])
- : []
+ schemaColumns={seriesTable ? Object.values(seriesTable.fields) : []}
+ dataWarehouseTableName={seriesValuesTableName}
+ staticValueOptions={
+ isDataWarehouseFilter && !seriesValuesTableName ? NO_VALUE_SUGGESTIONS : undefined
}
- dataWarehouseTableName={isDataWarehouseFilter ? (node.name ?? undefined) : undefined}
addFilterDocLink={addFilterDocLink}
excludedProperties={excludedProperties}
hogQLGlobals={hogQLGlobals}
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/types.ts b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/types.ts
index cff9d5b4f5f9..f1dff919c111 100644
--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/types.ts
+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/types.ts
@@ -80,6 +80,7 @@ export interface ActionFilterRowProps {
inlineEventsDocLink?: string
/** Allow adding non-captured events */
allowNonCapturedEvents?: boolean
+ flagCallsFromFlagEvaluations?: boolean
hogQLGlobals?: Record<string, any>
definitionPopoverRenderer?: DefinitionPopoverRenderer
operatorAllowlist?: PropertyOperator[]
@@ -98,6 +99,7 @@ export interface MathSelectorProps {
size?: LemonButtonProps['size']
/** Only allow these math types in the selector */
allowedMathTypes?: readonly string[]
+ excludedMathTypes?: ReadonlySet<string>
query?: Record<string, any>
fullWidth?: boolean
truncateText?: { maxWidthClass: string }
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/useMathSelectorOptions.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/useMathSelectorOptions.tsx
index b5680548b0cd..112f89cc7425 100644
--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/useMathSelectorOptions.tsx
+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/useMathSelectorOptions.tsx
@@ -55,6 +55,7 @@ export function useMathSelectorOptions({
onMathSelect,
trendsDisplayCategory,
allowedMathTypes,
+ excludedMathTypes,
query,
mathGroupTypeIndex,
}: MathSelectorProps): LemonSelectOptions<string> {
@@ -140,6 +141,9 @@ export function useMathSelectorOptions({
.filter((entry): entry is [string, MathDefinition] => !!entry[1])
.filter(([key]) => {
const mathTypeKey = key as MathType
+ if (excludedMathTypes?.has(key.split('::')[0])) {
+ return false
+ }
if (isStickiness) {
// Remove WAU and MAU from stickiness insights
return !TRAILING_MATH_TYPES.has(mathTypeKey)
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/flagCallsSeries.ts b/frontend/src/scenes/insights/filters/ActionFilter/flagCallsSeries.ts
new file mode 100644
index 000000000000..780d541cbb2c
--- /dev/null
+++ b/frontend/src/scenes/insights/filters/ActionFilter/flagCallsSeries.ts
@@ -0,0 +1,166 @@
+import {
+ FEATURE_FLAG_CALLED_EVENT,
+ FLAG_EVALUATIONS_RETENTION_DAYS,
+ FLAG_EVALUATIONS_TABLE,
+} from 'scenes/feature-flags/flagEvaluationsTable'
+import { getHogQLValue } from 'scenes/insights/filters/aggregationTarget'
+
+import {
+ BreakdownFilter,
+ DataWarehouseNode,
+ FunnelsDataWarehouseNode,
+ InsightQueryNode,
+ LifecycleDataWarehouseNode,
+ NodeKind,
+} from '~/queries/schema/schema-general'
+import { CORE_FILTER_DEFINITIONS_BY_GROUP } from '~/taxonomy/taxonomy'
+import {
+ AnyPropertyFilter,
+ BaseMathType,
+ DataWarehousePropertyFilter,
+ GroupMathType,
+ PropertyFilterType,
+ PropertyOperator,
+} from '~/types'
+
+export const FLAG_CALLS_SERIES_NAME: string = CORE_FILTER_DEFINITIONS_BY_GROUP.events[FEATURE_FLAG_CALLED_EVENT].label
+
+/** Replaces the event's core description on insight pickers where picking the event builds a flag calls series. */
+export const FLAG_CALLS_SERIES_DESCRIPTION = `Sent by PostHog SDKs each time a feature flag is evaluated.
+
+Insights include calls from the last ${FLAG_EVALUATIONS_RETENTION_DAYS} days. Filter or break down by \`flag_key\` and \`response\`.`
+
+/** A picker keeps only the fields its own warehouse series kind takes. */
+export const FLAG_EVALUATIONS_SERIES_FIELDS: Required<
+ Pick<DataWarehouseNode, 'id_field' | 'timestamp_field' | 'distinct_id_field'> &
+ Pick<FunnelsDataWarehouseNode, 'aggregation_target_field'> &
+ Pick<LifecycleDataWarehouseNode, 'created_at_field'>
+> = {
+ id_field: 'uuid',
+ timestamp_field: 'timestamp',
+ distinct_id_field: 'distinct_id',
+ // person_id is the merge-corrected person. A flag calls step counts the same person as an events step.
+ aggregation_target_field: 'person_id',
+ // The table stores no person creation time. Lifecycle takes the earliest flag call it reads instead.
+ created_at_field: 'timestamp',
+}
+
+/** Trends computes these maths from events for every series. On a flag calls series they would count events, not flag calls. */
+export const FLAG_CALLS_UNSUPPORTED_MATH_TYPES: ReadonlySet<string> = new Set<string>([
+ BaseMathType.WeeklyActiveUsers,
+ BaseMathType.MonthlyActiveUsers,
+ BaseMathType.FirstTimeForUser,
+ BaseMathType.FirstMatchingEventForUser,
+ GroupMathType.FirstTimeForGroup,
+ GroupMathType.FirstMatchingEventForGroup,
+])
+
+export function readsFlagCalls(query: InsightQueryNode): boolean {
+ const nodes: unknown[] =
+ query.kind === NodeKind.RetentionQuery
+ ? [query.retentionFilter?.targetEntity, query.retentionFilter?.returningEntity]
+ : 'series' in query
+ ? (query.series ?? [])
+ : []
+ return nodes.some((node) => (node as { table_name?: string } | undefined)?.table_name === FLAG_EVALUATIONS_TABLE)
+}
+
+/** Sets the actor column of each flag calls series to the query's aggregation: a group key, the funnel's SQL expression, or the person. */
+export function withFlagCallsAggregationTarget<Q extends InsightQueryNode>(query: Q): Q {
+ const groupTypeIndex = 'aggregation_group_type_index' in query ? query.aggregation_group_type_index : null
+ // The flag_evaluations row carries the event's properties.
+ // An expression such as properties.$session_id reads the same value there as on events.
+ const aggregateByHogQL = query.kind === NodeKind.FunnelsQuery ? query.funnelsFilter?.funnelAggregateByHogQL : null
+ const target = getHogQLValue(groupTypeIndex, aggregateByHogQL)
+ const retarget = <T>(node: T): T => {
+ const fields = node as { table_name?: string; aggregation_target_field?: string } | null | undefined
+ return fields?.table_name === FLAG_EVALUATIONS_TABLE &&
+ fields.aggregation_target_field != null &&
+ fields.aggregation_target_field !== target
+ ? { ...node, aggregation_target_field: target }
+ : node
+ }
+
+ if (query.kind === NodeKind.RetentionQuery) {
+ const { targetEntity, returningEntity } = query.retentionFilter ?? {}
+ const nextTarget = retarget(targetEntity)
+ const nextReturning = retarget(returningEntity)
+ return nextTarget === targetEntity && nextReturning === returningEntity
+ ? query
+ : {
+ ...query,
+ retentionFilter: {
+ ...query.retentionFilter,
+ targetEntity: nextTarget,
+ returningEntity: nextReturning,
+ },
+ }
+ }
+ if ('series' in query && query.series) {
+ const series = query.series.map(retarget)
+ return series.some((node, index) => node !== query.series[index]) ? { ...query, series } : query
+ }
+ return query
+}
+
+const FLAG_CALLS_COLUMN_BY_EVENT_PROPERTY: Record<string, string> = {
+ $feature_flag: 'flag_key',
+ $feature_flag_response: 'response',
+}
+
+// An event read turns a missing property into NULL. The table stores a missing flag key as '' and a missing response as '' or 'null'.
+const FLAG_CALLS_UNSET_VALUES_BY_COLUMN: Record<string, string[]> = {
+ flag_key: [''],
+ response: ['', 'null'],
+}
+
+/** Rewrites an event series' flag filters onto the flag_evaluations columns and keeps its SQL filters. */
+export function flagCallsFiltersFromEventFilters(properties: AnyPropertyFilter[] | undefined): AnyPropertyFilter[] {
+ return (properties ?? []).flatMap((property): AnyPropertyFilter[] => {
+ if (property.type === PropertyFilterType.HogQL) {
+ return [property]
+ }
+ if (property.type !== PropertyFilterType.Event) {
+ return []
+ }
+ const column = FLAG_CALLS_COLUMN_BY_EVENT_PROPERTY[property.key]
+ if (!column) {
+ return []
+ }
+ const checksSet = property.operator === PropertyOperator.IsSet
+ const checksNotSet = property.operator === PropertyOperator.IsNotSet
+ const filter: DataWarehousePropertyFilter = {
+ key: column,
+ value: checksSet || checksNotSet ? FLAG_CALLS_UNSET_VALUES_BY_COLUMN[column] : property.value,
+ operator: checksSet ? PropertyOperator.NotIn : checksNotSet ? PropertyOperator.In : property.operator,
+ type: PropertyFilterType.DataWarehouse,
+ }
+ return [filter]
+ })
+}
+
+/** Rewrites event breakdowns on the flag properties onto the flag_evaluations columns. Other breakdowns stay as they are. */
+export function flagCallsBreakdownFromEventBreakdown(
+ breakdownFilter: BreakdownFilter | undefined
+): BreakdownFilter | undefined {
+ if (!breakdownFilter) {
+ return breakdownFilter
+ }
+ if (breakdownFilter.breakdowns?.length) {
+ const breakdowns = breakdownFilter.breakdowns.map((breakdown) => {
+ const column =
+ (breakdown.type ?? 'event') === 'event'
+ ? FLAG_CALLS_COLUMN_BY_EVENT_PROPERTY[String(breakdown.property)]
+ : undefined
+ return column ? { ...breakdown, type: 'data_warehouse' as const, property: column } : breakdown
+ })
+ return breakdowns.some((breakdown, index) => breakdown !== breakdownFilter.breakdowns?.[index])
+ ? { ...breakdownFilter, breakdowns }
+ : breakdownFilter
+ }
+ const column =
+ (breakdownFilter.breakdown_type ?? 'event') === 'event' && typeof breakdownFilter.breakdown === 'string'
+ ? FLAG_CALLS_COLUMN_BY_EVENT_PROPERTY[breakdownFilter.breakdown]
+ : undefined
+ return column ? { ...breakdownFilter, breakdown_type: 'data_warehouse', breakdown: column } : breakdownFilter
+}
diff --git a/frontend/src/scenes/insights/filters/AggregationSelect.tsx b/frontend/src/scenes/insights/filters/AggregationSelect.tsx
index ce30694e89e3..a1a137d269c6 100644
--- a/frontend/src/scenes/insights/filters/AggregationSelect.tsx
+++ b/frontend/src/scenes/insights/filters/AggregationSelect.tsx
@@ -19,25 +19,8 @@ import { InsightLogicProps } from '~/types'
import { GroupIntroductionFooter } from 'products/groups/frontend/components/GroupsIntroduction'
-export function getHogQLValue(groupIndex?: number | null, aggregationQuery?: string | null): string {
- if (groupIndex != undefined) {
- return `$group_${groupIndex}`
- } else if (aggregationQuery) {
- return aggregationQuery
- }
- return UNIQUE_USERS
-}
-
-export function hogQLToFilterValue(value?: string): { groupIndex?: number; aggregationQuery?: string } {
- if (value?.match(/^\$group_[0-9]+$/)) {
- return { groupIndex: parseInt(value.replace('$group_', '')) }
- } else if (value === 'person_id') {
- return {}
- }
- return { aggregationQuery: value }
-}
+import { UNIQUE_USERS, getHogQLValue, hogQLToFilterValue } from './aggregationTarget'
-const UNIQUE_USERS = 'person_id'
export const CUSTOM_DATA_WAREHOUSE_ITEMS = '__custom_data_warehouse_items__'
export function getCustomAggregationEditorValue(value: string, baseValues: string[]): string {
diff --git a/frontend/src/scenes/insights/filters/aggregationTarget.ts b/frontend/src/scenes/insights/filters/aggregationTarget.ts
new file mode 100644
index 000000000000..3a2d78f3e2dc
--- /dev/null
+++ b/frontend/src/scenes/insights/filters/aggregationTarget.ts
@@ -0,0 +1,19 @@
+export const UNIQUE_USERS = 'person_id'
+
+export function getHogQLValue(groupIndex?: number | null, aggregationQuery?: string | null): string {
+ if (groupIndex != undefined) {
+ return `$group_${groupIndex}`
+ } else if (aggregationQuery) {
+ return aggregationQuery
+ }
+ return UNIQUE_USERS
+}
+
+export function hogQLToFilterValue(value?: string): { groupIndex?: number; aggregationQuery?: string } {
+ if (value?.match(/^\$group_[0-9]+$/)) {
+ return { groupIndex: parseInt(value.replace('$group_', '')) }
+ } else if (value === 'person_id') {
+ return {}
+ }
+ return { aggregationQuery: value }
+}
diff --git a/frontend/src/scenes/insights/insightVizDataLogic.test.ts b/frontend/src/scenes/insights/insightVizDataLogic.test.ts
index b8e0ef51b1f6..ed1f85024af1 100644
--- a/frontend/src/scenes/insights/insightVizDataLogic.test.ts
+++ b/frontend/src/scenes/insights/insightVizDataLogic.test.ts
@@ -1,8 +1,9 @@
import { expectLogic } from 'kea-test-utils'
import { FEATURE_FLAGS, FunnelLayout } from 'lib/constants'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
+import { QuerySourceUpdate, insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { useMocks } from '~/mocks/jest'
import { actionsModel } from '~/models/actionsModel'
@@ -341,61 +342,244 @@ describe('insightVizDataLogic', () => {
})
})
- it('disables filterTestAccounts and properties when adding a data warehouse series to trends', () => {
- builtInsightVizDataLogic.actions.updateQuerySource({
- filterTestAccounts: true,
- properties: [
- {
- type: 'event',
- key: 'browser',
- value: 'Chrome',
- operator: 'exact',
+ const warehouseSeries = {
+ id: 'warehouse_orders',
+ table_name: 'warehouse_orders',
+ name: 'Orders',
+ timestamp_field: 'created_at',
+ id_field: 'order_id',
+ }
+ const warehouseEntity = {
+ id: 'warehouse_orders',
+ type: 'data_warehouse' as const,
+ table_name: 'warehouse_orders',
+ timestamp_field: 'created_at',
+ aggregation_target_field: 'customer_id',
+ }
+ const addsWarehouseSeries = (kind: NodeKind, warehouseKind: NodeKind): Record<string, any> => ({
+ kind,
+ added: 'series',
+ initial: { series: [{ kind: NodeKind.EventsNode, name: '$pageview', event: '$pageview' }] },
+ update: { series: [{ ...warehouseSeries, kind: warehouseKind }] },
+ })
+
+ it.each([
+ addsWarehouseSeries(NodeKind.TrendsQuery, NodeKind.DataWarehouseNode),
+ addsWarehouseSeries(NodeKind.FunnelsQuery, NodeKind.FunnelsDataWarehouseNode),
+ addsWarehouseSeries(NodeKind.StickinessQuery, NodeKind.DataWarehouseNode),
+ {
+ kind: NodeKind.RetentionQuery,
+ added: 'target entity',
+ initial: { retentionFilter: { targetEntity: { id: '$pageview', type: 'events' } } },
+ update: { retentionFilter: { targetEntity: warehouseEntity } },
+ },
+ {
+ kind: NodeKind.RetentionQuery,
+ added: 'returning entity',
+ initial: { retentionFilter: { targetEntity: { id: '$pageview', type: 'events' } } },
+ update: {
+ retentionFilter: {
+ targetEntity: { id: '$pageview', type: 'events' },
+ returningEntity: warehouseEntity,
},
+ },
+ },
+ ])(
+ 'disables filterTestAccounts and properties when adding a data warehouse $added to $kind',
+ ({ kind, initial, update }) => {
+ const initialSource: Record<string, unknown> = {
+ kind,
+ filterTestAccounts: true,
+ properties: [{ type: 'event', key: 'browser', value: 'Chrome', operator: 'exact' }],
+ ...initial,
+ }
+ builtInsightVizDataLogic.actions.updateQuerySource(initialSource as QuerySourceUpdate)
+
+ expect(builtInsightVizDataLogic.values.querySource).toMatchObject({
+ kind,
+ filterTestAccounts: true,
+ properties: [expect.objectContaining({ key: 'browser' })],
+ })
+
+ const updateSource: Record<string, unknown> = { kind, ...update }
+ builtInsightVizDataLogic.actions.updateQuerySource(updateSource as QuerySourceUpdate)
+
+ expect(builtInsightVizDataLogic.values.querySource).toMatchObject({
+ kind,
+ filterTestAccounts: false,
+ properties: undefined,
+ })
+ }
+ )
+
+ const warehouseTrendsSeries = { ...warehouseSeries, kind: NodeKind.DataWarehouseNode }
+ const pageviewSeries = { kind: NodeKind.EventsNode, name: '$pageview', event: '$pageview' }
+ const flagCallsNode = {
+ id: 'posthog.flag_evaluations',
+ table_name: 'posthog.flag_evaluations',
+ name: 'Feature flag called',
+ timestamp_field: 'timestamp',
+ aggregation_target_field: 'person_id',
+ }
+ const flagCallsEntity = { ...flagCallsNode, type: 'data_warehouse' as const }
+
+ it('clears sampling when adding a data warehouse series to an insight with no other unsupported settings', () => {
+ builtInsightVizDataLogic.actions.updateQuerySource({ samplingFactor: 0.1 } as TrendsQuery)
+ expect(builtInsightVizDataLogic.values.querySource).toMatchObject({ samplingFactor: 0.1 })
+
+ builtInsightVizDataLogic.actions.updateQuerySource({ series: [warehouseTrendsSeries] } as TrendsQuery)
+
+ expect(builtInsightVizDataLogic.values.querySource).toMatchObject({ samplingFactor: undefined })
+ })
+
+ it.each([
+ {
+ name: 'an event breakdown',
+ breakdownFilter: { breakdown_type: 'event', breakdown: '$browser' },
+ series: [warehouseTrendsSeries],
+ expected: undefined,
+ toasts: [expect.stringMatching(/^A data warehouse series doesn't support this breakdown/)],
+ },
+ {
+ name: 'multiple breakdowns with an event one',
+ breakdownFilter: {
+ breakdowns: [
+ { type: 'data_warehouse', property: 'status' },
+ { type: 'event', property: '$browser' },
+ ],
+ },
+ series: [warehouseTrendsSeries],
+ expected: undefined,
+ toasts: [expect.stringMatching(/^A data warehouse series doesn't support this breakdown/)],
+ },
+ {
+ name: 'a data warehouse breakdown',
+ breakdownFilter: { breakdown_type: 'data_warehouse', breakdown: 'status' },
+ series: [warehouseTrendsSeries],
+ expected: { breakdown_type: 'data_warehouse', breakdown: 'status' },
+ toasts: [],
+ },
+ {
+ name: 'an event breakdown when a flag calls series joins an event series',
+ breakdownFilter: { breakdown_type: 'event', breakdown: '$browser' },
+ series: [pageviewSeries, { ...flagCallsNode, kind: NodeKind.DataWarehouseNode }],
+ expected: undefined,
+ toasts: [expect.stringMatching(/^Feature flag called doesn't support this breakdown/)],
+ },
+ {
+ name: 'a flag response breakdown when a trends series changes to flag calls',
+ breakdownFilter: { breakdown_type: 'event', breakdown: '$feature_flag_response' },
+ series: [{ ...flagCallsNode, kind: NodeKind.DataWarehouseNode }],
+ expected: { breakdown_type: 'data_warehouse', breakdown: 'response' },
+ toasts: [],
+ },
+ {
+ name: 'multiple breakdowns with a flag key one when a trends series changes to flag calls',
+ breakdownFilter: { breakdowns: [{ type: 'event', property: '$feature_flag' }] },
+ series: [{ ...flagCallsNode, kind: NodeKind.DataWarehouseNode }],
+ expected: { breakdowns: [{ type: 'data_warehouse', property: 'flag_key' }] },
+ toasts: [],
+ },
+ {
+ name: 'a flag calls breakdown when an event series joins a flag calls series',
+ breakdownFilter: { breakdown_type: 'data_warehouse', breakdown: 'flag_key' },
+ series: [pageviewSeries, { ...flagCallsNode, kind: NodeKind.DataWarehouseNode }],
+ expected: undefined,
+ toasts: [
+ expect.stringMatching(/^Feature flag called can't share a breakdown with event or action series/),
],
- series: [
- {
- kind: NodeKind.EventsNode,
- name: '$pageview',
- event: '$pageview',
- },
+ },
+ ])(
+ 'handles $name when a trends series changes to a data warehouse series',
+ ({ breakdownFilter, series, expected, toasts }) => {
+ builtInsightVizDataLogic.actions.updateQuerySource({ breakdownFilter } as TrendsQuery)
+ const infoToast = jest.spyOn(lemonToast, 'info')
+
+ builtInsightVizDataLogic.actions.updateQuerySource({ series } as TrendsQuery)
+
+ expect((builtInsightVizDataLogic.values.querySource as TrendsQuery).breakdownFilter).toEqual(expected)
+ expect(infoToast.mock.calls.map(([message]) => message)).toEqual(toasts)
+ infoToast.mockRestore()
+ }
+ )
+
+ it.each([
+ {
+ kind: NodeKind.FunnelsQuery,
+ flagCalls: { series: [{ ...flagCallsNode, kind: NodeKind.FunnelsDataWarehouseNode }] },
+ targets: (source: any) => [source.series[0].aggregation_target_field],
+ },
+ {
+ kind: NodeKind.LifecycleQuery,
+ flagCalls: { series: [{ ...flagCallsNode, kind: NodeKind.LifecycleDataWarehouseNode }] },
+ targets: (source: any) => [source.series[0].aggregation_target_field],
+ },
+ {
+ kind: NodeKind.RetentionQuery,
+ flagCalls: { retentionFilter: { targetEntity: flagCallsEntity, returningEntity: flagCallsEntity } },
+ targets: (source: any) => [
+ source.retentionFilter.targetEntity.aggregation_target_field,
+ source.retentionFilter.returningEntity.aggregation_target_field,
],
- } as TrendsQuery)
+ },
+ ])('counts $kind flag calls by the aggregation group', ({ kind, flagCalls, targets }) => {
+ const update = (source: Record<string, unknown>): void =>
+ builtInsightVizDataLogic.actions.updateQuerySource({ kind, ...source } as QuerySourceUpdate)
- expect(builtInsightVizDataLogic.values.querySource).toMatchObject({
- filterTestAccounts: true,
- properties: [expect.objectContaining({ key: 'browser' })],
- })
+ update({ aggregation_group_type_index: 1 })
+ update(flagCalls)
+ expect(new Set(targets(builtInsightVizDataLogic.values.querySource))).toEqual(new Set(['$group_1']))
- expectLogic(builtInsightDataLogic, () => {
+ update({ aggregation_group_type_index: undefined })
+ expect(new Set(targets(builtInsightVizDataLogic.values.querySource))).toEqual(new Set(['person_id']))
+ })
+
+ it('counts funnel flag calls by the funnel aggregation expression', () => {
+ const update = (source: Record<string, unknown>): void =>
builtInsightVizDataLogic.actions.updateQuerySource({
- series: [
- {
- kind: NodeKind.DataWarehouseNode,
- id: 'warehouse_orders',
- table_name: 'warehouse_orders',
- name: 'Orders',
- timestamp_field: 'created_at',
- id_field: 'order_id',
- distinct_id_field: 'customer_id',
- },
- ],
- } as TrendsQuery)
- }).toMatchValues({
- query: {
- kind: NodeKind.InsightVizNode,
- source: expect.objectContaining({
- kind: NodeKind.TrendsQuery,
- filterTestAccounts: false,
- properties: undefined,
- series: [
- expect.objectContaining({
- kind: NodeKind.DataWarehouseNode,
- table_name: 'warehouse_orders',
- }),
- ],
- }),
- },
+ kind: NodeKind.FunnelsQuery,
+ ...source,
+ } as QuerySourceUpdate)
+ const target = (): string | undefined =>
+ (builtInsightVizDataLogic.values.querySource as any).series[0].aggregation_target_field
+
+ update({ series: [{ ...flagCallsNode, kind: NodeKind.FunnelsDataWarehouseNode }] })
+ update({ funnelsFilter: { funnelAggregateByHogQL: 'properties.$session_id' } })
+ expect(target()).toEqual('properties.$session_id')
+
+ update({ funnelsFilter: { funnelAggregateByHogQL: undefined } })
+ expect(target()).toEqual('person_id')
+ })
+
+ it('does not toast on an edit of a saved trends insight whose mixed series left empty properties', () => {
+ builtInsightDataLogic.actions.setQuery({
+ kind: NodeKind.InsightVizNode,
+ source: { kind: NodeKind.TrendsQuery, series: [pageviewSeries, warehouseTrendsSeries], properties: [] },
+ } as Node)
+ const infoToast = jest.spyOn(lemonToast, 'info')
+
+ builtInsightVizDataLogic.actions.updateQuerySource({ dateRange: { date_from: '-30d' } } as TrendsQuery)
+
+ expect(infoToast).not.toHaveBeenCalled()
+ infoToast.mockRestore()
+ })
+
+ it('keeps test accounts off when a later edit turns them on for a retention insight with a data warehouse entity', () => {
+ builtInsightVizDataLogic.actions.updateQuerySource({
+ kind: NodeKind.RetentionQuery,
+ retentionFilter: { targetEntity: warehouseEntity, returningEntity: warehouseEntity },
+ } as QuerySourceUpdate)
+
+ builtInsightVizDataLogic.actions.updateQuerySource({
+ ...builtInsightVizDataLogic.values.querySource,
+ filterTestAccounts: true,
+ } as QuerySourceUpdate)
+
+ expect(builtInsightVizDataLogic.values.querySource).toMatchObject({
+ kind: NodeKind.RetentionQuery,
+ filterTestAccounts: false,
})
+ expect(builtInsightVizDataLogic.values.hasDataWarehouseEntity).toBe(true)
})
})
diff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.ts
index 79b947ec2529..1f28b8fc1f55 100644
--- a/frontend/src/scenes/insights/insightVizDataLogic.ts
+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts
@@ -22,6 +22,16 @@ import { dateMapping, is12HoursOrLess, isLessThan2Days } from 'lib/utils/dateFil
import { objectsEqual } from 'lib/utils/objects'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { dataThemeLogic } from 'scenes/dataThemeLogic'
+import {
+ FLAG_EVALUATIONS_TABLE,
+ insightReachesPastFlagEvaluationsRetention,
+} from 'scenes/feature-flags/flagEvaluationsTable'
+import {
+ FLAG_CALLS_SERIES_NAME,
+ flagCallsBreakdownFromEventBreakdown,
+ readsFlagCalls,
+ withFlagCallsAggregationTarget,
+} from 'scenes/insights/filters/ActionFilter/flagCallsSeries'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'
@@ -228,6 +238,7 @@ export interface insightVizDataLogicValues {
funnelPathsFilter: FunnelPathsFilter | null | undefined
funnelsFilter: FunnelsFilter | null | undefined
goalLines: GoalLine[] | null | undefined
+ hasDataWarehouseEntity: boolean
hasDataWarehouseSeries: boolean
hasDetailedResultsTable: boolean
hasFormula: boolean
@@ -288,6 +299,7 @@ export interface insightVizDataLogicValues {
showPercentStackView: boolean | null | undefined
showPercentagesOnSeries: boolean | null | undefined
showValuesOnSeries: boolean | null | undefined
+ showsFlagCallsRetentionNotice: boolean
slowQueryPossibilities: SlowQueryPossibilities[]
stickinessFilter: StickinessFilter | null | undefined
supportsBarValueStacking: boolean
@@ -1181,6 +1193,22 @@ export interface insightVizDataLogicMeta {
isUsingSessionAnalysis: boolean | Breakdown,
query: Node<Record<string, any>> | null
) => boolean
+ showsFlagCallsRetentionNotice: (
+ querySource:
+ | FunnelsQuery
+ | LifecycleQuery
+ | PathsQuery
+ | PathsV2Query
+ | RetentionQuery
+ | StickinessQuery
+ | TrendsQuery
+ | WebOverviewQuery
+ | WebStatsTableQuery
+ | null,
+ dateRange: DateRange | null | undefined,
+ compareFilter: CompareFilter | null | undefined,
+ insightData: Record<string, any>
+ ) => boolean
isNonTimeSeriesDisplay: (display: ChartDisplayType | null | undefined) => boolean
isSingleSeriesOutput: (
isTrends: boolean,
@@ -1201,6 +1229,19 @@ export interface insightVizDataLogicMeta {
hasDataWarehouseSeries: (
series: (AnyEntityNode<AnyDataWarehouseNode> | GroupNode<DataWarehouseNode>)[] | null | undefined
) => boolean
+ hasDataWarehouseEntity: (
+ querySource:
+ | FunnelsQuery
+ | LifecycleQuery
+ | PathsQuery
+ | PathsV2Query
+ | RetentionQuery
+ | StickinessQuery
+ | TrendsQuery
+ | WebOverviewQuery
+ | WebStatsTableQuery
+ | null
+ ) => boolean
hasOnlyDataWarehouseSeries: (
series: (AnyEntityNode<AnyDataWarehouseNode> | GroupNode<DataWarehouseNode>)[] | null | undefined
) => boolean
@@ -2258,6 +2299,22 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([
query: Node | null
) => isUsingSessionAnalysis && !(isInsightVizNode(query) && query.suppressSessionAnalysisWarning),
],
+ showsFlagCallsRetentionNotice: [
+ (s) => [s.querySource, s.dateRange, s.compareFilter, s.insightData],
+ (
+ querySource: InsightQueryNode | null,
+ dateRange: DateRange | null | undefined,
+ compareFilter: CompareFilter | null | undefined,
+ insightData: Record<string, any>
+ ): boolean =>
+ !!querySource &&
+ readsFlagCalls(querySource) &&
+ insightReachesPastFlagEvaluationsRetention({
+ dateFrom: dateRange?.date_from,
+ resolvedDateRange: insightData?.resolved_date_range,
+ compareFilter,
+ }),
+ ],
isNonTimeSeriesDisplay: [
(s) => [s.display],
(display: ChartDisplayType | null | undefined) =>
@@ -2326,6 +2383,10 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([
| undefined
): boolean => (series || []).length > 0 && !!series?.some((node) => isAnyDataWarehouseNode(node)),
],
+ hasDataWarehouseEntity: [
+ (s) => [s.querySource],
+ (querySource: InsightQueryNode | null): boolean => !!querySource && readsDataWarehouseTable(querySource),
+ ],
hasOnlyDataWarehouseSeries: [
(s) => [s.series],
(
@@ -2711,14 +2772,14 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([
updateQuerySource: ({ querySource }) => {
actions.setQuery({
...values.query,
- source: {
+ source: withFlagCallsAggregationTarget({
...values.querySource,
...handleQuerySourceUpdateSideEffects(
querySource,
values.querySource as InsightQueryNode,
values.isIntervalManuallySet
),
- },
+ } as InsightQueryNode),
} as Node)
},
@@ -2919,6 +2980,32 @@ export function dateRangeZoomEnd(bucketStart: string, interval: IntervalType | n
return start.add(1, interval).subtract(1, 'day').format('YYYY-MM-DD')
}
+function readsDataWarehouseTable(query: InsightQueryNode): boolean {
+ const retentionEntities = isRetentionQuery(query)
+ ? [query.retentionFilter?.targetEntity, query.retentionFilter?.returningEntity]
+ : []
+ return (
+ !!(query as TrendsQuery | FunnelsQuery | StickinessQuery | LifecycleQuery).series?.some(
+ isAnyDataWarehouseNode
+ ) || retentionEntities.some((entity) => entity?.type === 'data_warehouse')
+ )
+}
+
+// The only breakdown types the trends backend resolves against a data warehouse series.
+const DATA_WAREHOUSE_SERIES_BREAKDOWN_TYPES = new Set<string>(['data_warehouse', 'hogql'])
+
+function hasEventBasedBreakdown(breakdownFilter: BreakdownFilter | null | undefined): boolean {
+ if (breakdownFilter?.breakdowns?.length) {
+ return breakdownFilter.breakdowns.some(
+ (breakdown) => !DATA_WAREHOUSE_SERIES_BREAKDOWN_TYPES.has(breakdown.type ?? '')
+ )
+ }
+ return (
+ breakdownFilter?.breakdown != null &&
+ !DATA_WAREHOUSE_SERIES_BREAKDOWN_TYPES.has(breakdownFilter.breakdown_type ?? '')
+ )
+}
+
const handleQuerySourceUpdateSideEffects = (
update: QuerySourceUpdate,
currentState: InsightQueryNode,
@@ -3003,42 +3090,36 @@ const handleQuerySourceUpdateSideEffects = (
;(mergedUpdate as LifecycleQuery).customAggregationTarget = undefined
}
- if (
- maybeChangedSeries &&
- isLifecycleQuery(currentState) &&
- maybeChangedSeries.some((series) => isLifecycleDataWarehouseNode(series))
- ) {
- ;(mergedUpdate as LifecycleQuery).properties = undefined
- ;(mergedUpdate as LifecycleQuery).filterTestAccounts = false
- ;(mergedUpdate as LifecycleQuery).samplingFactor = undefined
- }
+ const nextRetentionFilter = isRetentionQuery(currentState)
+ ? (maybeChangedInsightFilter as RetentionFilter | undefined)
+ : undefined
// Switching a retention entity away from the data warehouse invalidates the "Custom entities"
// aggregation target, which the backend rejects for non-warehouse entities.
- if (isRetentionQuery(currentState) && maybeChangedInsightFilter) {
- const nextRetentionFilter = maybeChangedInsightFilter as RetentionFilter
- if (
- nextRetentionFilter.customAggregationTarget &&
- (nextRetentionFilter.targetEntity?.type !== 'data_warehouse' ||
- nextRetentionFilter.returningEntity?.type !== 'data_warehouse')
- ) {
- ;(mergedUpdate as RetentionQuery).retentionFilter = {
- ...nextRetentionFilter,
- customAggregationTarget: undefined,
- }
+ if (
+ nextRetentionFilter?.customAggregationTarget &&
+ (nextRetentionFilter.targetEntity?.type !== 'data_warehouse' ||
+ nextRetentionFilter.returningEntity?.type !== 'data_warehouse')
+ ) {
+ ;(mergedUpdate as RetentionQuery).retentionFilter = {
+ ...nextRetentionFilter,
+ customAggregationTarget: undefined,
}
}
// We do not support properties, filtering test accounts, and sampling for DWH nodes
- // Disable them if there are any
- if (
- isTrendsQuery(currentState) &&
- (currentState.filterTestAccounts || currentState.properties) &&
- maybeChangedSeries?.some(isAnyDataWarehouseNode)
- ) {
- lemonToast.info(
- 'Filter groups and test accounts are not supported for Data Warehouse series and have been disabled.'
- )
+ // Disable them if there are any. Check the query after the update, so a later edit cannot turn them on again.
+ const nextQuery = { ...currentState, ...mergedUpdate } as InsightQueryNode
+ const hasDataWarehouseSeries = readsDataWarehouseTable(nextQuery)
+ const hasFiltersOrTestAccounts = !!nextQuery.filterTestAccounts || parseProperties(nextQuery.properties).length > 0
+ if (hasDataWarehouseSeries && (hasFiltersOrTestAccounts || (nextQuery as TrendsQuery).samplingFactor != null)) {
+ if (hasFiltersOrTestAccounts) {
+ lemonToast.info(
+ readsFlagCalls(nextQuery)
+ ? `${FLAG_CALLS_SERIES_NAME} doesn't support filter groups or test account filtering, so they're turned off.`
+ : 'Filter groups and test accounts are not supported for Data Warehouse series and have been disabled.'
+ )
+ }
;(mergedUpdate as TrendsQuery).properties = undefined
;(mergedUpdate as TrendsQuery).filterTestAccounts = false
@@ -3126,15 +3207,42 @@ const handleQuerySourceUpdateSideEffects = (
}
}
- // if mixed, clear breakdown and trends filter
+ let breakdownFilter = (('breakdownFilter' in mergedUpdate ? mergedUpdate : currentState) as TrendsQuery)
+ .breakdownFilter
if (
+ kind === NodeKind.TrendsQuery &&
+ maybeChangedSeries?.length &&
+ maybeChangedSeries.every(
+ (series) => isDataWarehouseNode(series) && series.table_name === FLAG_EVALUATIONS_TABLE
+ )
+ ) {
+ const flagCallsBreakdownFilter = flagCallsBreakdownFromEventBreakdown(breakdownFilter)
+ if (flagCallsBreakdownFilter !== breakdownFilter) {
+ breakdownFilter = flagCallsBreakdownFilter
+ ;(mergedUpdate as TrendsQuery).breakdownFilter = flagCallsBreakdownFilter
+ }
+ }
+ // A trends insight that mixes event and data warehouse series cannot have a breakdown.
+ const mixesEventAndDataWarehouseSeries =
kind === NodeKind.TrendsQuery &&
(mergedUpdate as TrendsQuery).series?.length >= 0 &&
(mergedUpdate as TrendsQuery).series.some((series) => isDataWarehouseNode(series)) &&
(mergedUpdate as TrendsQuery).series.some((series) => isActionsNode(series) || isEventsNode(series))
- ) {
+ // The trends backend rejects an event-based breakdown on a data warehouse series.
+ const hasEventBreakdownOnDataWarehouseSeries =
+ kind === NodeKind.TrendsQuery &&
+ !!maybeChangedSeries?.some((series) => isDataWarehouseNode(series)) &&
+ hasEventBasedBreakdown(breakdownFilter)
+ if (mixesEventAndDataWarehouseSeries || hasEventBreakdownOnDataWarehouseSeries) {
+ if (hasBreakdownFilter(breakdownFilter)) {
+ const subject = readsFlagCalls(nextQuery) ? FLAG_CALLS_SERIES_NAME : 'A data warehouse series'
+ lemonToast.info(
+ hasEventBreakdownOnDataWarehouseSeries
+ ? `${subject} doesn't support this breakdown, so it's removed.`
+ : `${subject} can't share a breakdown with event or action series, so it's removed.`
+ )
+ }
;(mergedUpdate as TrendsQuery).breakdownFilter = undefined
- mergedUpdate['properties'] = []
}
// Remove breakdown filter if display type is BoldNumber because it is not supported
diff --git a/posthog/clickhouse/test/test_schema.py b/posthog/clickhouse/test/test_schema.py
index 76f9f31b3ded..41513c42a875 100644
--- a/posthog/clickhouse/test/test_schema.py
+++ b/posthog/clickhouse/test/test_schema.py
@@ -9,7 +9,7 @@ import pytest
from django.conf import settings as django_settings
from django.test import override_settings
-from posthog.hogql.database.models import DatabaseField, Table
+from posthog.hogql.database.models import DatabaseField, ExpressionField, Table
from posthog.hogql.database.schema.flag_evaluations import FLAG_EVALUATIONS_CLICKHOUSE_TABLE, FlagEvaluationsTable
from posthog.clickhouse.client import sync_execute
@@ -246,7 +246,7 @@ def _hogql_column_names(table: Table) -> set[str]:
for field in table.fields.values():
if isinstance(field, Table):
names |= _hogql_column_names(field)
- elif isinstance(field, DatabaseField):
+ elif isinstance(field, DatabaseField) and not isinstance(field, ExpressionField):
names.add(field.name)
return names
diff --git a/posthog/hogql/database/schema/flag_evaluations.py b/posthog/hogql/database/schema/flag_evaluations.py
index 327ebd3631f5..473420398033 100644
--- a/posthog/hogql/database/schema/flag_evaluations.py
+++ b/posthog/hogql/database/schema/flag_evaluations.py
@@ -141,6 +141,10 @@ class FlagEvaluationsTable(Table):
"session_id": StringDatabaseField(
name="session_id", nullable=False, description="Session the evaluation happened in, if the SDK sent one."
),
+ # Insight session math reads the events column name.
+ "$session_id": ExpressionField(
+ name="$session_id", expr=ast.Field(chain=["session_id"]), isolate_scope=True, hidden=True
+ ),
"request_id": StringDatabaseField(
name="request_id",
nullable=False,
@@ -207,9 +211,6 @@ def add_events_list_fields_to_flag_evaluations(database: "Database") -> None:
# The events session resolvers ignore from_field and read $session_id and $session_id_uuid from the source table.
# Copying the events join keeps the sessions table version that the team's modifiers chose.
- flag_evaluations.fields["$session_id"] = ExpressionField(
- name="$session_id", expr=ast.Field(chain=["session_id"]), isolate_scope=True
- )
flag_evaluations.fields["$session_id_uuid"] = ExpressionField(
name="$session_id_uuid",
expr=uuid_string_expr_to_uint128_expr(ast.Field(chain=["session_id"])),
diff --git a/posthog/test/base.py b/posthog/test/base.py
index f1fafc60e498..1678c86e9079 100644
--- a/posthog/test/base.py
+++ b/posthog/test/base.py
@@ -1794,11 +1794,21 @@ def _create_event(**kwargs):
return kwargs["event_uuid"]
-def _create_flag_evaluations(team_id: int, flag_key: str, count: int = 1, timestamp: dt.datetime | None = None) -> None:
+def _create_flag_evaluations(
+ team_id: int,
+ flag_key: str,
+ count: int = 1,
+ timestamp: dt.datetime | None = None,
+ *,
+ distinct_id: str = "evaluator",
+ person_id: uuid.UUID | str | None = None,
+ response: str | bool = True,
+ properties: dict[str, str] | None = None,
+) -> None:
"""Insert `count` $feature_flag_called rows for flag_key into flag_evaluations. Unlike _create_event, it writes
- the rows immediately."""
+ the rows immediately. Each row gets a new random person_id unless the caller passes one."""
timestamp = timestamp or dt.datetime.now(dt.UTC)
- properties = json.dumps({"$feature_flag": flag_key, "$feature_flag_response": True})
+ properties_json = json.dumps({**(properties or {}), "$feature_flag": flag_key, "$feature_flag_response": response})
# writable_flag_evaluations does not declare flag_key. The shard computes it from properties.$feature_flag.
sync_execute(
"""
@@ -1810,12 +1820,12 @@ def _create_flag_evaluations(team_id: int, flag_key: str, count: int = 1, timest
(
str(uuid.uuid4()),
"$feature_flag_called",
- properties,
+ properties_json,
timestamp,
team_id,
- "evaluator",
+ distinct_id,
timestamp,
- str(uuid.uuid4()),
+ str(person_id or uuid.uuid4()),
)
for _ in range(count)
],
diff --git a/products/experiments/frontend/legacy/metrics/FunnelsMetricForm.tsx b/products/experiments/frontend/legacy/metrics/FunnelsMetricForm.tsx
index f6375a240e90..91076a371f0a 100644
--- a/products/experiments/frontend/legacy/metrics/FunnelsMetricForm.tsx
+++ b/products/experiments/frontend/legacy/metrics/FunnelsMetricForm.tsx
@@ -9,7 +9,7 @@ import { EXPERIMENT_DEFAULT_DURATION } from 'lib/constants'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { ActionFilter } from 'scenes/insights/filters/ActionFilter/ActionFilter'
import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/types'
-import { getHogQLValue } from 'scenes/insights/filters/AggregationSelect'
+import { getHogQLValue } from 'scenes/insights/filters/aggregationTarget'
import { teamLogic } from 'scenes/teamLogic'
import { actionsAndEventsToSeries } from '~/queries/nodes/InsightQuery/utils/actionsAndEventsToSeries'
diff --git a/products/experiments/frontend/legacy/sharedMetrics/LegacySharedFunnelsMetricForm.tsx b/products/experiments/frontend/legacy/sharedMetrics/LegacySharedFunnelsMetricForm.tsx
index 4b55988efb4a..0a050b7656f1 100644
--- a/products/experiments/frontend/legacy/sharedMetrics/LegacySharedFunnelsMetricForm.tsx
+++ b/products/experiments/frontend/legacy/sharedMetrics/LegacySharedFunnelsMetricForm.tsx
@@ -7,7 +7,7 @@ import { TestAccountFilterSwitch } from 'lib/components/TestAccountFiltersSwitch
import { EXPERIMENT_DEFAULT_DURATION } from 'lib/constants'
import { ActionFilter } from 'scenes/insights/filters/ActionFilter/ActionFilter'
import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/types'
-import { getHogQLValue } from 'scenes/insights/filters/AggregationSelect'
+import { getHogQLValue } from 'scenes/insights/filters/aggregationTarget'
import { teamLogic } from 'scenes/teamLogic'
import { actionsAndEventsToSeries } from '~/queries/nodes/InsightQuery/utils/actionsAndEventsToSeries'
diff --git a/products/product_analytics/backend/hogql_queries/funnels/funnel_event_query.py b/products/product_analytics/backend/hogql_queries/funnels/funnel_event_query.py
index 46f314df0caf..9d8e278460e8 100644
--- a/products/product_analytics/backend/hogql_queries/funnels/funnel_event_query.py
+++ b/products/product_analytics/backend/hogql_queries/funnels/funnel_event_query.py
@@ -277,6 +277,7 @@ class FunnelEventQuery(DataWarehouseSchemaMixin):
right=ast.Constant(value=date_range.date_to()),
),
self._day_of_week_filter_expr(ast.Field(chain=["timestamp"])),
+ self._aggregation_target_filter() if self.context.query.aggregation_group_type_index is not None else None,
]
where = ast.And(exprs=[expr for expr in where_exprs if expr is not None])
diff --git a/products/product_analytics/backend/hogql_queries/retention/retention_base_query_fixed.py b/products/product_analytics/backend/hogql_queries/retention/retention_base_query_fixed.py
index b51ca78bfe11..bcaa6f3e3200 100644
--- a/products/product_analytics/backend/hogql_queries/retention/retention_base_query_fixed.py
+++ b/products/product_analytics/backend/hogql_queries/retention/retention_base_query_fixed.py
@@ -557,7 +557,11 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
table_name = entity.table_name if entity_is_dwh else "events"
assert table_name
- where_expr = None if entity_is_dwh else ast.And(exprs=self._arm_where_filters(entity, query_kind))
+ where_expr: ast.Expr | None = None
+ if not entity_is_dwh:
+ where_expr = ast.And(exprs=self._arm_where_filters(entity, query_kind))
+ elif dwh_filters := self._dwh_arm_where_filters(entity, query_kind, timestamp_field):
+ where_expr = ast.And(exprs=dwh_filters)
select_fields: list[ast.Expr] = [
ast.Alias(alias="actor_id", expr=actor_field),
@@ -890,6 +894,23 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
filters.append(predicate)
return filters
+ def _dwh_arm_where_filters(
+ self, entity: RetentionEntity, query_kind: Literal["start", "return"], timestamp_field: ast.Expr
+ ) -> list[ast.Expr]:
+ """The warehouse counterpart of _arm_where_filters. Every aggregate that a warehouse arm computes already
+ conditions on its entity and the query window. These filters therefore drop only rows that no aggregate reads."""
+ filters: list[ast.Expr] = []
+ # A first-time start arm finds the first start row of each actor across all time.
+ # It reads rows outside the window.
+ if query_kind == "return" or not (self.is_first_occurrence_matching_filters or self.is_first_ever_occurrence):
+ filters.append(self.events_timestamp_filter(field=timestamp_field))
+ predicate = self._arm_scan_predicate(entity, query_kind)
+ if not (isinstance(predicate, ast.Constant) and predicate.value is True):
+ filters.append(predicate)
+ if self.runner.group_type_index is not None:
+ filters.append(parse_expr("toString({actor}) != ''", {"actor": self.entity_actor_id_expr(entity)}))
+ return filters
+
def _is_valid_start_interval_expr(self, start_event_timestamps_field: str = "start_event_timestamps") -> ast.Expr:
start_event_timestamps = ast.Field(chain=[start_event_timestamps_field])
if self.is_first_occurrence_matching_filters or self.is_first_ever_occurrence:
diff --git a/products/product_analytics/backend/hogql_queries/retention/test/__snapshots__/test_retention_data_warehouse.ambr b/products/product_analytics/backend/hogql_queries/retention/test/__snapshots__/test_retention_data_warehouse.ambr
index 8bd5b30d87e1..cb9f243edf93 100644
--- a/products/product_analytics/backend/hogql_queries/retention/test/__snapshots__/test_retention_data_warehouse.ambr
+++ b/products/product_analytics/backend/hogql_queries/retention/test/__snapshots__/test_retention_data_warehouse.ambr
@@ -16,6 +16,7 @@
arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(posthog_test_warehouse_event_mix_signups_uuid.signed_up_at, 'UTC')), and(greaterOrEquals(toTimeZone(posthog_test_warehouse_event_mix_signups_uuid.signed_up_at, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(posthog_test_warehouse_event_mix_signups_uuid.signed_up_at, 'UTC'), toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))))) AS start_event_timestamps,
[] AS return_event_timestamps
FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.retention.data_warehouse/posthog_test_warehouse_event_mix_signups_uuid/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` UUID, `signed_up_at` DateTime64(3, \'UTC\')') AS posthog_test_warehouse_event_mix_signups_uuid
+ WHERE and(greaterOrEquals(posthog_test_warehouse_event_mix_signups_uuid.signed_up_at, toDateTime64(toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1)), 6, 'UTC')), less(posthog_test_warehouse_event_mix_signups_uuid.signed_up_at, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))
GROUP BY actor_id
UNION ALL SELECT toString(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS actor_id,
[] AS start_event_timestamps,
@@ -68,6 +69,7 @@
arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(posthog_test_warehouse_event_mix_signups_string.signed_up_at, 'UTC')), and(greaterOrEquals(toTimeZone(posthog_test_warehouse_event_mix_signups_string.signed_up_at, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(posthog_test_warehouse_event_mix_signups_string.signed_up_at, 'UTC'), toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))))) AS start_event_timestamps,
[] AS return_event_timestamps
FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.retention.data_warehouse/posthog_test_warehouse_event_mix_signups_string/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` String, `signed_up_at` DateTime64(3, \'UTC\')') AS posthog_test_warehouse_event_mix_signups_string
+ WHERE and(greaterOrEquals(posthog_test_warehouse_event_mix_signups_string.signed_up_at, toDateTime64(toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1)), 6, 'UTC')), less(posthog_test_warehouse_event_mix_signups_string.signed_up_at, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))
GROUP BY actor_id
UNION ALL SELECT toString(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS actor_id,
[] AS start_event_timestamps,
@@ -123,6 +125,7 @@
[] AS return_event_timestamps,
ifNull(toString(posthog_test_warehouse_activity_breakdown.plan), '') AS breakdown_value
FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.retention.data_warehouse/posthog_test_warehouse_activity_breakdown/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `plan` String, `person_id` UUID, `occurred_at` DateTime64(3, \'UTC\'), `activity_type` String') AS posthog_test_warehouse_activity_breakdown
+ WHERE and(and(greaterOrEquals(posthog_test_warehouse_activity_breakdown.occurred_at, toDateTime64(toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1)), 6, 'UTC')), less(posthog_test_warehouse_activity_breakdown.occurred_at, toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC'))), equals(posthog_test_warehouse_activity_breakdown.activity_type, 'signed_up'))
GROUP BY actor_id,
breakdown_value
UNION ALL SELECT toString(posthog_test_warehouse_activity_breakdown.person_id) AS actor_id,
@@ -130,6 +133,7 @@
arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(posthog_test_warehouse_activity_breakdown.occurred_at, 'UTC')), and(equals(posthog_test_warehouse_activity_breakdown.activity_type, 'renewed'), and(greaterOrEquals(toTimeZone(posthog_test_warehouse_activity_breakdown.occurred_at, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(posthog_test_warehouse_activity_breakdown.occurred_at, 'UTC'), toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC')))))) AS return_event_timestamps,
ifNull(toString(posthog_test_warehouse_activity_breakdown.plan), '') AS breakdown_value
FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.retention.data_warehouse/posthog_test_warehouse_activity_breakdown/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `plan` String, `person_id` UUID, `occurred_at` DateTime64(3, \'UTC\'), `activity_type` String') AS posthog_test_warehouse_activity_breakdown
+ WHERE and(and(greaterOrEquals(posthog_test_warehouse_activity_breakdown.occurred_at, toDateTime64(toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1)), 6, 'UTC')), less(posthog_test_warehouse_activity_breakdown.occurred_at, toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC'))), equals(posthog_test_warehouse_activity_breakdown.activity_type, 'renewed'))
GROUP BY actor_id,
breakdown_value) AS retention_events
GROUP BY actor_id,
@@ -173,11 +177,13 @@
arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(posthog_test_warehouse_signups.signed_up_at, 'UTC')), and(greaterOrEquals(toTimeZone(posthog_test_warehouse_signups.signed_up_at, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(posthog_test_warehouse_signups.signed_up_at, 'UTC'), toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC'))))) AS start_event_timestamps,
[] AS return_event_timestamps
FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.retention.data_warehouse/posthog_test_warehouse_signups/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` UUID, `signed_up_at` DateTime64(3, \'UTC\')') AS posthog_test_warehouse_signups
+ WHERE and(greaterOrEquals(posthog_test_warehouse_signups.signed_up_at, toDateTime64(toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1)), 6, 'UTC')), less(posthog_test_warehouse_signups.signed_up_at, toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC')))
GROUP BY actor_id
UNION ALL SELECT toString(posthog_test_warehouse_renewals.person_id) AS actor_id,
[] AS start_event_timestamps,
arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(posthog_test_warehouse_renewals.renewed_at, 'UTC')), and(greaterOrEquals(toTimeZone(posthog_test_warehouse_renewals.renewed_at, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(posthog_test_warehouse_renewals.renewed_at, 'UTC'), toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC'))))) AS return_event_timestamps
FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.retention.data_warehouse/posthog_test_warehouse_renewals/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` UUID, `renewed_at` DateTime64(3, \'UTC\')') AS posthog_test_warehouse_renewals
+ WHERE and(greaterOrEquals(posthog_test_warehouse_renewals.renewed_at, toDateTime64(toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1)), 6, 'UTC')), less(posthog_test_warehouse_renewals.renewed_at, toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC')))
GROUP BY actor_id) AS retention_events
GROUP BY actor_id
HAVING 1) AS actor_activity
@@ -217,11 +223,13 @@
arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(posthog_test_warehouse_activity.occurred_at, 'UTC')), and(equals(posthog_test_warehouse_activity.activity_type, 'signed_up'), and(greaterOrEquals(toTimeZone(posthog_test_warehouse_activity.occurred_at, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(posthog_test_warehouse_activity.occurred_at, 'UTC'), toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC')))))) AS start_event_timestamps,
[] AS return_event_timestamps
FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.retention.data_warehouse/posthog_test_warehouse_activity/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` UUID, `occurred_at` DateTime64(3, \'UTC\'), `activity_type` String') AS posthog_test_warehouse_activity
+ WHERE and(and(greaterOrEquals(posthog_test_warehouse_activity.occurred_at, toDateTime64(toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1)), 6, 'UTC')), less(posthog_test_warehouse_activity.occurred_at, toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC'))), equals(posthog_test_warehouse_activity.activity_type, 'signed_up'))
GROUP BY actor_id
UNION ALL SELECT toString(posthog_test_warehouse_activity.person_id) AS actor_id,
[] AS start_event_timestamps,
arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(posthog_test_warehouse_activity.occurred_at, 'UTC')), and(equals(posthog_test_warehouse_activity.activity_type, 'renewed'), and(greaterOrEquals(toTimeZone(posthog_test_warehouse_activity.occurred_at, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(posthog_test_warehouse_activity.occurred_at, 'UTC'), toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC')))))) AS return_event_timestamps
FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.retention.data_warehouse/posthog_test_warehouse_activity/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` UUID, `occurred_at` DateTime64(3, \'UTC\'), `activity_type` String') AS posthog_test_warehouse_activity
+ WHERE and(and(greaterOrEquals(posthog_test_warehouse_activity.occurred_at, toDateTime64(toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1)), 6, 'UTC')), less(posthog_test_warehouse_activity.occurred_at, toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC'))), equals(posthog_test_warehouse_activity.activity_type, 'renewed'))
GROUP BY actor_id) AS retention_events
GROUP BY actor_id
HAVING 1) AS actor_activity
diff --git a/products/product_analytics/backend/hogql_queries/retention/test/__snapshots__/test_retention_data_warehouse.new_events_schema.ambr b/products/product_analytics/backend/hogql_queries/retention/test/__snapshots__/test_retention_data_warehouse.new_events_schema.ambr
index 36a68cf006be..51843b1503b3 100644
--- a/products/product_analytics/backend/hogql_queries/retention/test/__snapshots__/test_retention_data_warehouse.new_events_schema.ambr
+++ b/products/product_analytics/backend/hogql_queries/retention/test/__snapshots__/test_retention_data_warehouse.new_events_schema.ambr
@@ -16,6 +16,7 @@
arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(posthog_test_warehouse_event_mix_signups_uuid.signed_up_at, 'UTC')), and(greaterOrEquals(toTimeZone(posthog_test_warehouse_event_mix_signups_uuid.signed_up_at, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(posthog_test_warehouse_event_mix_signups_uuid.signed_up_at, 'UTC'), toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))))) AS start_event_timestamps,
[] AS return_event_timestamps
FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.retention.data_warehouse/posthog_test_warehouse_event_mix_signups_uuid/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` UUID, `signed_up_at` DateTime64(3, \'UTC\')') AS posthog_test_warehouse_event_mix_signups_uuid
+ WHERE and(greaterOrEquals(posthog_test_warehouse_event_mix_signups_uuid.signed_up_at, toDateTime64(toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1)), 6, 'UTC')), less(posthog_test_warehouse_event_mix_signups_uuid.signed_up_at, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))
GROUP BY actor_id
UNION ALL SELECT toString(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS actor_id,
[] AS start_event_timestamps,
@@ -70,6 +71,7 @@
arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(posthog_test_warehouse_event_mix_signups_string.signed_up_at, 'UTC')), and(greaterOrEquals(toTimeZone(posthog_test_warehouse_event_mix_signups_string.signed_up_at, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(posthog_test_warehouse_event_mix_signups_string.signed_up_at, 'UTC'), toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))))) AS start_event_timestamps,
[] AS return_event_timestamps
FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-products.product_analytics.backend.hogql_queries.retention.data_warehouse/posthog_test_warehouse_event_mix_signups_string/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` String, `signed_up_at` DateTime64(3, \'UTC\')') AS posthog_test_warehouse_event_mix_signups_string
+ WHERE and(greaterOrEquals(posthog_test_warehouse_event_mix_signups_string.signed_up_at, toDateTime64(toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1)), 6, 'UTC')), less(posthog_test_warehouse_event_mix_signups_string.signed_up_at, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))
GROUP BY actor_id
UNION ALL SELECT toString(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS actor_id,
[] AS start_event_timestamps,
diff --git a/products/product_analytics/backend/tests/test_flag_evaluations_insight_series.py b/products/product_analytics/backend/tests/test_flag_evaluations_insight_series.py
new file mode 100644
index 000000000000..b455021e4928
--- /dev/null
+++ b/products/product_analytics/backend/tests/test_flag_evaluations_insight_series.py
@@ -0,0 +1,279 @@
+import uuid
+from datetime import UTC, datetime
+from typing import Any
+
+import time_machine
+from posthog.test.base import (
+ BaseTest,
+ ClickhouseTestMixin,
+ _create_event,
+ _create_flag_evaluations,
+ _create_person,
+ create_person_id_override_by_distinct_id,
+ flush_persons_and_events,
+)
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ BaseMathType,
+ BreakdownFilter,
+ BreakdownType,
+ DataWarehouseNode,
+ DataWarehousePropertyFilter,
+ DateRange,
+ EventsNode,
+ FunnelsDataWarehouseNode,
+ FunnelsFilter,
+ FunnelsQuery,
+ IntervalType,
+ LifecycleDataWarehouseNode,
+ LifecycleQuery,
+ PropertyOperator,
+ RetentionQuery,
+ StickinessQuery,
+ TrendsQuery,
+)
+
+from products.product_analytics.backend.facade.queries import (
+ FunnelsQueryRunner,
+ LifecycleQueryRunner,
+ RetentionQueryRunner,
+ StickinessQueryRunner,
+ TrendsQueryRunner,
+)
+
+TABLE = "posthog.flag_evaluations"
+NOW = datetime(2025, 1, 10, 12, 0, tzinfo=UTC)
+DATE_RANGE = DateRange(date_from="2025-01-08", date_to="2025-01-10")
+PROBE_FLAG = DataWarehousePropertyFilter(key="flag_key", operator=PropertyOperator.EXACT, value="probe-flag")
+
+
+def _flag_calls_series(**kwargs: Any) -> DataWarehouseNode:
+ return DataWarehouseNode(
+ id=TABLE,
+ table_name=TABLE,
+ timestamp_field="timestamp",
+ distinct_id_field="distinct_id",
+ id_field="uuid",
+ **kwargs,
+ )
+
+
+def _aggregation_target(aggregation_group_type_index: int | None) -> str:
+ return "person_id" if aggregation_group_type_index is None else f"$group_{aggregation_group_type_index}"
+
+
+def _retention_entity(aggregation_target_field: str) -> dict[str, Any]:
+ return {
+ "id": TABLE,
+ "name": TABLE,
+ "type": "data_warehouse",
+ "table_name": TABLE,
+ "timestamp_field": "timestamp",
+ "aggregation_target_field": aggregation_target_field,
+ }
+
+
+@time_machine.travel(NOW, tick=False)
+class TestFlagEvaluationsInsightSeries(ClickhouseTestMixin, BaseTest):
+ def setUp(self):
+ super().setUp()
+ table_gate = patch(
+ "products.feature_flags.backend.facade.flags.is_flag_evaluations_table_enabled", return_value=True
+ )
+ table_gate.start()
+ self.addCleanup(table_gate.stop)
+ person_created_at = datetime(2025, 1, 8, 8, 0, tzinfo=UTC)
+ alice = _create_person(team_id=self.team.pk, distinct_ids=["alice"], created_at=person_created_at)
+ bob = _create_person(team_id=self.team.pk, distinct_ids=["bob"], created_at=person_created_at)
+ for distinct_id, person_id, flag_key, response, occurred_at, properties in [
+ (
+ "alice",
+ alice.uuid,
+ "probe-flag",
+ "test",
+ datetime(2025, 1, 8, 10, tzinfo=UTC),
+ {"$session_id": "s-alice", "$group_0": "org-a"},
+ ),
+ (
+ "alice",
+ alice.uuid,
+ "probe-flag",
+ "test",
+ datetime(2025, 1, 8, 11, tzinfo=UTC),
+ {"$session_id": "s-alice", "$group_0": "org-a"},
+ ),
+ (
+ "bob",
+ bob.uuid,
+ "probe-flag",
+ "control",
+ datetime(2025, 1, 8, 12, tzinfo=UTC),
+ {"$session_id": "s-bob", "$group_0": "org-b"},
+ ),
+ ("bob", bob.uuid, "other-flag", "true", datetime(2025, 1, 9, 9, tzinfo=UTC), {}),
+ # The row stores the person alice-2 had before the merge. Only the override makes it alice's call.
+ (
+ "alice-2",
+ uuid.uuid4(),
+ "probe-flag",
+ "test",
+ datetime(2025, 1, 8, 13, tzinfo=UTC),
+ {"$session_id": "s-alice-2"},
+ ),
+ ]:
+ _create_flag_evaluations(
+ self.team.pk,
+ flag_key,
+ timestamp=occurred_at,
+ distinct_id=distinct_id,
+ person_id=person_id,
+ response=response,
+ properties=properties,
+ )
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="alice",
+ timestamp=datetime(2025, 1, 9, 10, tzinfo=UTC),
+ properties={"$group_0": "org-a", "$session_id": "s-alice"},
+ )
+ flush_persons_and_events()
+ create_person_id_override_by_distinct_id("alice-2", "alice", self.team.pk, version=1)
+
+ @parameterized.expand(
+ [
+ ("total_calls", BaseMathType.TOTAL, {"test": 3, "control": 1}),
+ ("unique_users", BaseMathType.DAU, {"test": 1, "control": 1}),
+ ("unique_sessions", BaseMathType.UNIQUE_SESSION, {"test": 2, "control": 1}),
+ ]
+ )
+ def test_trend_by_variant(self, _name: str, math: BaseMathType, expected: dict[str, int]):
+ query = TrendsQuery(
+ dateRange=DATE_RANGE,
+ interval=IntervalType.DAY,
+ series=[_flag_calls_series(math=math, properties=[PROBE_FLAG])],
+ breakdownFilter=BreakdownFilter(breakdown_type=BreakdownType.DATA_WAREHOUSE, breakdown="response"),
+ )
+
+ results = TrendsQueryRunner(query=query, team=self.team).calculate().results
+
+ assert {r["breakdown_value"]: r["count"] for r in results} == expected
+
+ @parameterized.expand(
+ [
+ ("by_person", None, None, [2, 1]),
+ ("by_group", 0, None, [2, 1]),
+ ("by_session", None, "properties.$session_id", [3, 1]),
+ ]
+ )
+ def test_funnel_from_flag_call_to_pageview(
+ self,
+ _name: str,
+ aggregation_group_type_index: int | None,
+ aggregate_by_hogql: str | None,
+ expected: list[int],
+ ):
+ query = FunnelsQuery(
+ dateRange=DATE_RANGE,
+ aggregation_group_type_index=aggregation_group_type_index,
+ funnelsFilter=FunnelsFilter(funnelAggregateByHogQL=aggregate_by_hogql),
+ series=[
+ FunnelsDataWarehouseNode(
+ id=TABLE,
+ table_name=TABLE,
+ timestamp_field="timestamp",
+ id_field="uuid",
+ aggregation_target_field=aggregate_by_hogql or _aggregation_target(aggregation_group_type_index),
+ properties=[PROBE_FLAG],
+ ),
+ EventsNode(event="$pageview"),
+ ],
+ )
+
+ results = FunnelsQueryRunner(query=query, team=self.team, just_summarize=True).calculate().results
+
+ assert [step["count"] for step in results] == expected
+
+ @parameterized.expand(
+ [
+ ("flag_calls_return_as_flag_calls", None, None, [2, 1, 0]),
+ (
+ "flag_calls_return_as_pageviews",
+ None,
+ {"id": "$pageview", "name": "$pageview", "type": "events"},
+ [2, 1, 0],
+ ),
+ ("by_group", 0, None, [2, 0, 0]),
+ ]
+ )
+ def test_retention(
+ self,
+ _name: str,
+ aggregation_group_type_index: int | None,
+ returning_event: dict[str, Any] | None,
+ expected: list[int],
+ ):
+ flag_calls = _retention_entity(_aggregation_target(aggregation_group_type_index))
+ query = RetentionQuery(
+ dateRange=DATE_RANGE,
+ aggregation_group_type_index=aggregation_group_type_index,
+ retentionFilter={
+ "period": "Day",
+ "totalIntervals": 3,
+ "targetEntity": flag_calls,
+ "returningEntity": returning_event or flag_calls,
+ },
+ )
+
+ results = RetentionQueryRunner(query=query, team=self.team).calculate().model_dump()["results"]
+
+ assert [value["count"] for value in results[0]["values"]] == expected
+
+ def test_stickiness(self):
+ query = StickinessQuery(dateRange=DATE_RANGE, interval=IntervalType.DAY, series=[_flag_calls_series()])
+
+ results = StickinessQueryRunner(query=query, team=self.team).calculate().results
+
+ assert results[0]["data"] == [1, 1, 0]
+
+ @parameterized.expand(
+ [
+ (
+ "by_person",
+ None,
+ {"new": [2, 0, 0], "returning": [0, 1, 0], "resurrecting": [0, 0, 0], "dormant": [0, -1, -1]},
+ ),
+ (
+ "by_group",
+ 0,
+ {"new": [2, 0, 0], "returning": [0, 0, 0], "resurrecting": [0, 0, 0], "dormant": [0, -2, 0]},
+ ),
+ ]
+ )
+ def test_lifecycle(
+ self,
+ _name: str,
+ aggregation_group_type_index: int | None,
+ expected: dict[str, list[int]],
+ ):
+ query = LifecycleQuery(
+ dateRange=DATE_RANGE,
+ interval=IntervalType.DAY,
+ aggregation_group_type_index=aggregation_group_type_index,
+ series=[
+ LifecycleDataWarehouseNode(
+ id=TABLE,
+ table_name=TABLE,
+ timestamp_field="timestamp",
+ aggregation_target_field=_aggregation_target(aggregation_group_type_index),
+ created_at_field="timestamp",
+ )
+ ],
+ )
+
+ results = LifecycleQueryRunner(query=query, team=self.team).calculate().results
+
+ assert {r["status"]: r["data"] for r in results} == expected
diff --git a/products/product_analytics/frontend/insights/funnels/editor/FunnelsQuerySteps.tsx b/products/product_analytics/frontend/insights/funnels/editor/FunnelsQuerySteps.tsx
index e93deee258fd..edad0be246f9 100644
--- a/products/product_analytics/frontend/insights/funnels/editor/FunnelsQuerySteps.tsx
+++ b/products/product_analytics/frontend/insights/funnels/editor/FunnelsQuerySteps.tsx
@@ -79,6 +79,7 @@ export function FunnelsQuerySteps({ insightProps }: EditorFilterProps): JSX.Elem
TaxonomicFilterGroupType.AutocaptureEvents,
TaxonomicFilterGroupType.DataWarehouse,
]}
+ flagCallsFromFlagEvaluations
definitionPopoverRenderer={FunnelDataWarehouseStepDefinitionPopover}
dataWarehousePopoverFields={[
{
diff --git a/products/product_analytics/frontend/insights/retention/editor/RetentionCondition.tsx b/products/product_analytics/frontend/insights/retention/editor/RetentionCondition.tsx
index ae5a776959b7..408186e51e3e 100644
--- a/products/product_analytics/frontend/insights/retention/editor/RetentionCondition.tsx
+++ b/products/product_analytics/frontend/insights/retention/editor/RetentionCondition.tsx
@@ -188,6 +188,7 @@ export function RetentionCondition({ insightProps }: EditorFilterProps): JSX.Ele
typeKey={`${keyForInsightLogicProps('new')(insightProps)}-targetEntity`}
propertiesTaxonomicGroupTypes={getRetentionPropertyFilterGroupTypes()}
actionsTaxonomicGroupTypes={actionsTaxonomicGroupTypes}
+ flagCallsFromFlagEvaluations
dataWarehousePopoverFields={retentionDataWarehousePopoverFields}
/>
<LemonSelect
@@ -226,6 +227,7 @@ export function RetentionCondition({ insightProps }: EditorFilterProps): JSX.Ele
typeKey={`${keyForInsightLogicProps('new')(insightProps)}-returningEntity`}
propertiesTaxonomicGroupTypes={getRetentionPropertyFilterGroupTypes()}
actionsTaxonomicGroupTypes={actionsTaxonomicGroupTypes}
+ flagCallsFromFlagEvaluations
dataWarehousePopoverFields={retentionDataWarehousePopoverFields}
/>
<div className="flex items-center gap-2">
diff --git a/products/product_analytics/frontend/insights/retention/filters/RetentionAggregationSelector.tsx b/products/product_analytics/frontend/insights/retention/filters/RetentionAggregationSelector.tsx
index 2c646d38690e..d04004e2e1b7 100644
--- a/products/product_analytics/frontend/insights/retention/filters/RetentionAggregationSelector.tsx
+++ b/products/product_analytics/frontend/insights/retention/filters/RetentionAggregationSelector.tsx
@@ -33,7 +33,7 @@ export function RetentionAggregationSelector(): JSX.Element {
const { insightProps } = useValues(insightLogic)
const { retentionFilter } = useValues(insightVizDataLogic(insightProps))
const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))
- const { dataWarehouseTablesMap } = useValues(databaseTableListLogic)
+ const { allTablesMap } = useValues(databaseTableListLogic)
const aggregationType = retentionFilter?.aggregationType || 'count'
const aggregationProperty = retentionFilter?.aggregationProperty
@@ -46,7 +46,7 @@ export function RetentionAggregationSelector(): JSX.Element {
? (returningEntity.table_name ?? (returningEntity.id as string | undefined))
: null
const schemaColumns: DatabaseSchemaField[] = dwhTableName
- ? Object.values(dataWarehouseTablesMap[dwhTableName]?.fields ?? {})
+ ? Object.values(allTablesMap[dwhTableName]?.fields ?? {})
: []
const propertyGroupType = aggregationTypeToTaxonomicType[aggregationPropertyType]
diff --git a/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.test.ts b/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.test.ts
index 6653b9255a8f..21cf143e08be 100644
--- a/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.test.ts
+++ b/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.test.ts
@@ -22,6 +22,19 @@ describe('getTrendsSeriesDisplayLabel', () => {
['custom name wins over the event name', { action: { name: '$pageview', custom_name: 'Signups' } }, 'Signups'],
['humanizes the event name when no custom name', { action: { name: '$pageview' } }, 'Pageview'],
['uses the action name when not a built-in event', { action: { name: 'purchase' } }, 'purchase'],
+ [
+ 'shows a flag calls series as the event',
+ {
+ action: {
+ type: 'events',
+ id: 'posthog.flag_evaluations',
+ name: 'posthog.flag_evaluations',
+ custom_name: null,
+ },
+ label: 'posthog.flag_evaluations',
+ },
+ 'Feature flag called',
+ ],
[
'falls back to the humanized label when there is no action (formula row)',
{ action: null, label: 'A + B' },
diff --git a/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.ts b/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.ts
index 1f2a3d88757d..9d9d34cf6046 100644
--- a/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.ts
+++ b/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.ts
@@ -1,3 +1,4 @@
+import { toDisplayEntityFilter } from 'lib/components/EntityFilterInfo'
import { alphabet } from 'lib/utils/strings'
import { formatBreakdownLabel, getDisplayNameFromEntityFilter } from 'scenes/insights/utils'
@@ -19,7 +20,8 @@ export interface TrendsSeriesLabelDeps {
}
export function getTrendsSeriesDisplayLabel(r: IndexedTrendResult, deps: TrendsSeriesLabelDeps): string {
- const seriesName = getDisplayNameFromEntityFilter(r.action) ?? humanizeSeriesLabel(r.label)
+ const seriesName =
+ getDisplayNameFromEntityFilter(r.action && toDisplayEntityFilter(r.action)) ?? humanizeSeriesLabel(r.label)
if (r.breakdown_value != null) {
const breakdownLabel = formatBreakdownLabel(
r.breakdown_value,