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): keep test account and global filters on flag calls (#118242)

Phil Haack56b0f1b57acc
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightDetails.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightDetails.tsx
index 33e7df263383..559c0b6fb88d 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightDetails.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightDetails.tsx
@@ -30,6 +30,7 @@ import { Link } from 'lib/lemon-ui/Link'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { dateFilterToText } from 'lib/utils/dateFilters'
import { capitalizeFirstLetter } from 'lib/utils/strings'
+import { everyWarehouseSeriesReadsFlagCalls } from 'scenes/insights/filters/ActionFilter/flagCallsSeries'
import { BreakdownTag } from 'scenes/insights/filters/BreakdownFilter/BreakdownTag'
import { humanizePathsEventTypes, hasUnsupportedBreakdownForDataWarehouseTrends } from 'scenes/insights/utils'
import { QUERY_TYPES_METADATA } from 'scenes/saved-insights/insightTypesMetadata'
@@ -787,6 +788,8 @@ export const InsightDetails = React.memo(
)
const overrideBreakdownFilter = overrideBreakdown?.breakdownFilter
const hasPropertyOverrides = propertyGroups.length > 0
+ const ignoresPropertyOverrides =
+ hasDataWarehouseSeries && isInsightVizNode(query) && !everyWarehouseSeriesReadsFlagCalls(query.source)
const hasIgnoredBreakdownOverrides =
isInsightVizNode(query) &&
isTrendsQuery(query.source) &&
@@ -817,7 +820,7 @@ export const InsightDetails = React.memo(
override={dateOverride}
/>
)}
- {hasDataWarehouseSeries && hasPropertyOverrides ? (
+ {ignoresPropertyOverrides && hasPropertyOverrides ? (
<PropertiesIgnoredWarning />
) : (
<PropertiesSummary
diff --git a/frontend/src/queries/nodes/InsightViz/GlobalAndOrFilters.tsx b/frontend/src/queries/nodes/InsightViz/GlobalAndOrFilters.tsx
index b333190e2fe6..fd5623fbc4c3 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, hasDataWarehouseEntity } = useValues(insightVizDataLogic(insightProps))
+ const { querySource, globalFiltersUnsupported } = 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={hasDataWarehouseEntity}
+ globalFiltersUnsupported={globalFiltersUnsupported}
/>
)
}
diff --git a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
index e80cedbbe7c1..c62a772b25e7 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
@@ -273,13 +273,8 @@ export function InsightVizDisplay({
<LemonButton
type="primary"
loading={insightDataLoading}
- onClick={() =>
- updateQuerySource({
- filterTestAccounts: false,
- properties: undefined,
- samplingFactor: undefined,
- })
- }
+ // updateQuerySource also clears the filter groups and test account filtering that the series cannot take.
+ onClick={() => updateQuerySource({ samplingFactor: undefined })}
>
Reset unsupported settings
</LemonButton>
diff --git a/frontend/src/queries/nodes/InsightViz/PropertyGroupFilters/PropertyGroupFilters.tsx b/frontend/src/queries/nodes/InsightViz/PropertyGroupFilters/PropertyGroupFilters.tsx
index 0b5dfb9f7914..124974945b66 100644
--- a/frontend/src/queries/nodes/InsightViz/PropertyGroupFilters/PropertyGroupFilters.tsx
+++ b/frontend/src/queries/nodes/InsightViz/PropertyGroupFilters/PropertyGroupFilters.tsx
@@ -13,7 +13,6 @@ 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'
@@ -30,7 +29,7 @@ type PropertyGroupFiltersProps = {
pageKey: string
eventNames?: string[]
taxonomicGroupTypes?: TaxonomicFilterGroupType[]
- hasDataWarehouseSeries?: boolean
+ globalFiltersUnsupported?: boolean
}
export function PropertyGroupFilters({
@@ -40,7 +39,7 @@ export function PropertyGroupFilters({
pageKey,
eventNames = [],
taxonomicGroupTypes,
- hasDataWarehouseSeries,
+ globalFiltersUnsupported,
}: PropertyGroupFiltersProps): JSX.Element {
const logicProps = { query, setQuery, pageKey }
const { featureFlags } = useValues(featureFlagLogic)
@@ -63,11 +62,9 @@ export function PropertyGroupFilters({
[propertyGroupFilter.values]
)
const showHeader = propertyGroupFilter.type && propertyGroupFilter.values.length > 1
- 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.'
+ const disabledReason = globalFiltersUnsupported
+ ? 'Filter groups cannot be added to insights with a data warehouse series. Please use individual series filters instead.'
+ : undefined
return (
<div className="deprecated-space-y-2 PropertyGroupFilters @container">
{propertyGroupFilter.values && (
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/flagCallsSeries.ts b/frontend/src/scenes/insights/filters/ActionFilter/flagCallsSeries.ts
index da38b87790f8..dacf52677d9d 100644
--- a/frontend/src/scenes/insights/filters/ActionFilter/flagCallsSeries.ts
+++ b/frontend/src/scenes/insights/filters/ActionFilter/flagCallsSeries.ts
@@ -13,6 +13,7 @@ import {
LifecycleDataWarehouseNode,
NodeKind,
} from '~/queries/schema/schema-general'
+import { isAnyDataWarehouseNode } from '~/queries/utils'
import { CORE_FILTER_DEFINITIONS_BY_GROUP } from '~/taxonomy/taxonomy'
import {
AnyPropertyFilter,
@@ -56,14 +57,34 @@ export const FLAG_CALLS_UNSUPPORTED_MATH_TYPES: ReadonlySet<string> = new Set<st
GroupMathType.FirstMatchingEventForGroup,
])
+type SeriesOrRetentionEntity = { kind?: string; type?: string; table_name?: string } | null | undefined
+
+function seriesNodes(query: InsightQueryNode): SeriesOrRetentionEntity[] {
+ return query.kind === NodeKind.RetentionQuery
+ ? [query.retentionFilter?.targetEntity, query.retentionFilter?.returningEntity]
+ : 'series' in query
+ ? (query.series ?? [])
+ : []
+}
+
+function readsFlagCallsTable(node: SeriesOrRetentionEntity): boolean {
+ return node?.table_name === FLAG_EVALUATIONS_TABLE
+}
+
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)
+ return seriesNodes(query).some(readsFlagCallsTable)
+}
+
+export function dataWarehouseSeriesNodes(query: InsightQueryNode): SeriesOrRetentionEntity[] {
+ return seriesNodes(query).filter((node) => isAnyDataWarehouseNode(node) || node?.type === 'data_warehouse')
+}
+
+/**
+ * Whether each data warehouse series in the query reads flag calls. True when there is none.
+ * Mirrors every_warehouse_series_reads_flag_calls in posthog/hogql_queries/utils/entities.py.
+ */
+export function everyWarehouseSeriesReadsFlagCalls(query: InsightQueryNode): boolean {
+ return dataWarehouseSeriesNodes(query).every(readsFlagCallsTable)
}
/** Sets the actor columns of each flag calls series to the query's aggregation.
diff --git a/frontend/src/scenes/insights/insightVizDataLogic.test.ts b/frontend/src/scenes/insights/insightVizDataLogic.test.ts
index 30c04e4fb3e7..4009e2bf0123 100644
--- a/frontend/src/scenes/insights/insightVizDataLogic.test.ts
+++ b/frontend/src/scenes/insights/insightVizDataLogic.test.ts
@@ -366,11 +366,28 @@ describe('insightVizDataLogic', () => {
initial: { series: [{ kind: NodeKind.EventsNode, name: '$pageview', event: '$pageview' }] },
update: { series: [{ ...warehouseSeries, kind: warehouseKind }] },
})
+ 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 }
+ const flagCallsTrendsSeries = { ...flagCallsNode, kind: NodeKind.DataWarehouseNode }
it.each([
addsWarehouseSeries(NodeKind.TrendsQuery, NodeKind.DataWarehouseNode),
addsWarehouseSeries(NodeKind.FunnelsQuery, NodeKind.FunnelsDataWarehouseNode),
addsWarehouseSeries(NodeKind.StickinessQuery, NodeKind.DataWarehouseNode),
+ {
+ kind: NodeKind.TrendsQuery,
+ added: 'series beside a flag calls series',
+ initial: { series: [pageviewSeries] },
+ update: { series: [flagCallsTrendsSeries, warehouseTrendsSeries] },
+ },
{
kind: NodeKind.RetentionQuery,
added: 'target entity',
@@ -413,19 +430,53 @@ describe('insightVizDataLogic', () => {
filterTestAccounts: false,
properties: undefined,
})
+ expect(builtInsightVizDataLogic.values.globalFiltersUnsupported).toBe(true)
}
)
- 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.each([
+ {
+ kind: NodeKind.TrendsQuery,
+ added: 'series',
+ initial: { series: [pageviewSeries] },
+ update: { series: [flagCallsTrendsSeries] },
+ },
+ {
+ kind: NodeKind.TrendsQuery,
+ added: 'series beside an event series',
+ initial: { series: [pageviewSeries] },
+ update: { series: [pageviewSeries, flagCallsTrendsSeries] },
+ },
+ {
+ kind: NodeKind.RetentionQuery,
+ added: 'target entity',
+ initial: { retentionFilter: { targetEntity: { id: '$pageview', type: 'events' } } },
+ update: { retentionFilter: { targetEntity: flagCallsEntity } },
+ },
+ ])(
+ 'keeps filterTestAccounts and properties but clears sampling when adding a flag calls $added to $kind',
+ ({ kind, initial, update }) => {
+ const initialSource: Record<string, unknown> = {
+ kind,
+ filterTestAccounts: true,
+ properties: [{ type: 'event', key: 'browser', value: 'Chrome', operator: 'exact' }],
+ samplingFactor: 0.1,
+ ...initial,
+ }
+ builtInsightVizDataLogic.actions.updateQuerySource(initialSource as QuerySourceUpdate)
+
+ const updateSource: Record<string, unknown> = { kind, ...update }
+ builtInsightVizDataLogic.actions.updateQuerySource(updateSource as QuerySourceUpdate)
+
+ expect(builtInsightVizDataLogic.values.querySource).toMatchObject({
+ kind,
+ filterTestAccounts: true,
+ properties: [expect.objectContaining({ key: 'browser' })],
+ samplingFactor: undefined,
+ })
+ expect(builtInsightVizDataLogic.values.globalFiltersUnsupported).toBe(false)
+ }
+ )
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)
@@ -466,28 +517,28 @@ describe('insightVizDataLogic', () => {
{
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 }],
+ series: [pageviewSeries, flagCallsTrendsSeries],
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 }],
+ series: [flagCallsTrendsSeries],
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 }],
+ series: [flagCallsTrendsSeries],
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 }],
+ series: [pageviewSeries, flagCallsTrendsSeries],
expected: undefined,
toasts: [
expect.stringMatching(/^Feature flag called can't share a breakdown with event or action series/),
@@ -590,6 +641,34 @@ describe('insightVizDataLogic', () => {
infoToast.mockRestore()
})
+ it.each([
+ {
+ saved: 'another warehouse table',
+ series: warehouseTrendsSeries,
+ kept: { filterTestAccounts: false, properties: undefined },
+ },
+ {
+ saved: 'flag calls',
+ series: flagCallsTrendsSeries,
+ kept: { filterTestAccounts: true, properties: [expect.objectContaining({ key: 'browser' })] },
+ },
+ ])('resets sampling and the filters a saved $saved series cannot take', ({ series, kept }) => {
+ builtInsightDataLogic.actions.setQuery({
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [series],
+ filterTestAccounts: true,
+ properties: [{ type: 'event', key: 'browser', value: 'Chrome', operator: 'exact' }],
+ samplingFactor: 0.1,
+ },
+ } as Node)
+
+ builtInsightVizDataLogic.actions.updateQuerySource({ samplingFactor: undefined } as TrendsQuery)
+
+ expect(builtInsightVizDataLogic.values.querySource).toMatchObject({ ...kept, samplingFactor: undefined })
+ })
+
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,
@@ -605,7 +684,7 @@ describe('insightVizDataLogic', () => {
kind: NodeKind.RetentionQuery,
filterTestAccounts: false,
})
- expect(builtInsightVizDataLogic.values.hasDataWarehouseEntity).toBe(true)
+ expect(builtInsightVizDataLogic.values.globalFiltersUnsupported).toBe(true)
})
})
diff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.ts
index 72178df5aff6..65af5ad5c41a 100644
--- a/frontend/src/scenes/insights/insightVizDataLogic.ts
+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts
@@ -30,6 +30,8 @@ import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFil
import { cleanSeriesNodes } from 'scenes/insights/filters/ActionFilter/cleanSeriesNodes'
import {
FLAG_CALLS_SERIES_NAME,
+ dataWarehouseSeriesNodes,
+ everyWarehouseSeriesReadsFlagCalls,
flagCallsBreakdownFromEventBreakdown,
readsFlagCalls,
withFlagCallsAggregationTarget,
@@ -240,8 +242,8 @@ export interface insightVizDataLogicValues {
formulas: string[] | null | undefined
funnelPathsFilter: FunnelPathsFilter | null | undefined
funnelsFilter: FunnelsFilter | null | undefined
+ globalFiltersUnsupported: boolean
goalLines: GoalLine[] | null | undefined
- hasDataWarehouseEntity: boolean
hasDataWarehouseSeries: boolean
hasDetailedResultsTable: boolean
hasFormula: boolean
@@ -1240,7 +1242,7 @@ export interface insightVizDataLogicMeta {
hasDataWarehouseSeries: (
series: (AnyEntityNode<AnyDataWarehouseNode> | GroupNode<DataWarehouseNode>)[] | null | undefined
) => boolean
- hasDataWarehouseEntity: (
+ globalFiltersUnsupported: (
querySource:
| FunnelsQuery
| LifecycleQuery
@@ -2415,9 +2417,10 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([
| undefined
): boolean => (series || []).length > 0 && !!series?.some((node) => isAnyDataWarehouseNode(node)),
],
- hasDataWarehouseEntity: [
+ globalFiltersUnsupported: [
(s) => [s.querySource],
- (querySource: InsightQueryNode | null): boolean => !!querySource && readsDataWarehouseTable(querySource),
+ (querySource: InsightQueryNode | null): boolean =>
+ !!querySource && !everyWarehouseSeriesReadsFlagCalls(querySource),
],
hasOnlyDataWarehouseSeries: [
(s) => [s.series],
@@ -3017,17 +3020,6 @@ 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'])
@@ -3144,22 +3136,20 @@ const handleQuerySourceUpdateSideEffects = (
}
}
- // We do not support properties, filtering test accounts, and sampling for DWH nodes
- // Disable them if there are any. Check the query after the update, so a later edit cannot turn them on again.
+ // DWH series do not support sampling. They support properties and test account filtering only when every DWH
+ // series reads flag calls. 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.'
- )
- }
-
+ if (
+ !everyWarehouseSeriesReadsFlagCalls(nextQuery) &&
+ (!!nextQuery.filterTestAccounts || parseProperties(nextQuery.properties).length > 0)
+ ) {
+ lemonToast.info(
+ '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
+ }
+ if (dataWarehouseSeriesNodes(nextQuery).length > 0 && (nextQuery as TrendsQuery).samplingFactor != null) {
;(mergedUpdate as TrendsQuery).samplingFactor = undefined
}
diff --git a/posthog/hogql_queries/apply_dashboard_filters.py b/posthog/hogql_queries/apply_dashboard_filters.py
index 60c3482a0c83..796ee82dca45 100644
--- a/posthog/hogql_queries/apply_dashboard_filters.py
+++ b/posthog/hogql_queries/apply_dashboard_filters.py
@@ -2,6 +2,8 @@ from typing import Any, TypedDict
from posthog.schema import DashboardFilter, HogQLVariable, NodeKind
+from posthog.hogql.database.schema.flag_evaluations import FLAG_EVALUATIONS_HOGQL_TABLE
+
from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.query_runner import get_query_runner
@@ -261,12 +263,16 @@ def remove_query_properties_overridden_by(query: dict, overriding_filters: dict
return _strip_query_properties(query, overriding_props)
-def _has_data_warehouse_series(query: dict) -> bool:
+def _ignores_dashboard_properties(query: dict) -> bool:
+ """The rule that QueryRunner.apply_dashboard_filters applies, read from the query dict before a runner exists."""
if query.get("kind") in WRAPPER_NODE_KINDS:
- return _has_data_warehouse_series(query["source"])
+ return _ignores_dashboard_properties(query["source"])
series = query.get("series")
return isinstance(series, list) and any(
- isinstance(node, dict) and node.get("kind") in _DATA_WAREHOUSE_NODE_KINDS for node in series
+ isinstance(node, dict)
+ and node.get("kind") in _DATA_WAREHOUSE_NODE_KINDS
+ and node.get("table_name") != FLAG_EVALUATIONS_HOGQL_TABLE
+ for node in series
)
@@ -295,7 +301,7 @@ def resolve_effective_dashboard_filters(
# `merge_filters_by_priority` can early-return a raw layer (and a single layer is unmerged), so
# `properties` may still be a group dict here — normalize before it reaches `DashboardFilter`.
effective_filters = normalize_dashboard_filters_properties(effective_filters)
- if effective_filters and not _has_data_warehouse_series(query):
+ if effective_filters and not _ignores_dashboard_properties(query):
query = remove_query_properties_overridden_by(query, effective_filters)
return EffectiveDashboardFilters(query=query, filters=effective_filters)
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index 162f6373bd7b..14453e9f8a3a 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -177,7 +177,7 @@ from posthog.hogql_queries.query_failure_handling import (
)
from posthog.hogql_queries.query_metadata import extract_query_metadata
from posthog.hogql_queries.utils.breakdowns import has_multi_breakdown, has_single_breakdown
-from posthog.hogql_queries.utils.entities import has_data_warehouse_node
+from posthog.hogql_queries.utils.entities import every_warehouse_series_reads_flag_calls, has_data_warehouse_node
from posthog.hogql_queries.utils.event_usage import log_event_usage_from_query_metadata
from posthog.hogql_queries.utils.properties import has_any_property_filters
from posthog.hogql_queries.validation.validation import (
@@ -3414,11 +3414,9 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
)
return
- has_data_warehouse_series = (
- hasattr(self.query, "series")
- and isinstance(self.query.series, list)
- and has_data_warehouse_node(self.query.series)
- )
+ series = getattr(self.query, "series", None)
+ series_nodes = series if isinstance(series, list) else []
+ has_data_warehouse_series = has_data_warehouse_node(series_nodes)
dashboard_breakdown_filter = dashboard_filter.breakdown_filter
@@ -3435,7 +3433,9 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
)
)
- if dashboard_filter.properties and not has_data_warehouse_series:
+ applies_dashboard_properties = every_warehouse_series_reads_flag_calls(series_nodes)
+
+ if dashboard_filter.properties and applies_dashboard_properties:
if self.query.properties and has_any_property_filters(self.query.properties):
# Check if query expects only a list (e.g. WebOverviewQuery) vs union with PropertyGroupFilter
properties_field = self.query.__class__.model_fields.get("properties")
diff --git a/posthog/hogql_queries/test/test_dashboard_filters_overrides.py b/posthog/hogql_queries/test/test_dashboard_filters_overrides.py
index 31de3a6f08fc..857ff26ec882 100644
--- a/posthog/hogql_queries/test/test_dashboard_filters_overrides.py
+++ b/posthog/hogql_queries/test/test_dashboard_filters_overrides.py
@@ -153,16 +153,28 @@ class TestDashboardFiltersCompareFilterOverride(BaseTest):
class TestDashboardPropertyOverrides(BaseTest):
- def test_warehouse_insight_property_is_kept_when_dashboard_properties_are_ignored(self) -> None:
+ @parameterized.expand(
+ [
+ ("other_warehouse_table_ignores_dashboard_property", "warehouse_table", ["US"], []),
+ ("flag_calls_apply_dashboard_property", "posthog.flag_evaluations", [], ["EU"]),
+ ]
+ )
+ def test_dashboard_property_conflicting_with_a_warehouse_series_property(
+ self,
+ _name: str,
+ table_name: str,
+ expected_series_values: list[str],
+ expected_query_values: list[str],
+ ) -> None:
insight_property = {"key": "region", "value": "US", "operator": "exact", "type": "data_warehouse"}
dashboard_property = {"key": "region", "value": "EU", "operator": "exact", "type": "data_warehouse"}
query = TrendsQuery(
series=[
DataWarehouseNode(
- id="warehouse_table",
+ id=table_name,
id_field="id",
distinct_id_field="distinct_id",
- table_name="warehouse_table",
+ table_name=table_name,
timestamp_field="timestamp",
properties=[insight_property],
)
@@ -172,4 +184,5 @@ class TestDashboardPropertyOverrides(BaseTest):
effective = resolve_effective_dashboard_filters(query, {"properties": [dashboard_property]}, None)
result = apply_dashboard_filters_to_dict(effective.query, effective.filters, self.team)
- assert [prop["value"] for prop in result["series"][0]["properties"]] == ["US"]
+ assert [prop["value"] for prop in result["series"][0]["properties"]] == expected_series_values
+ assert [prop["value"] for prop in result["properties"] or []] == expected_query_values
diff --git a/posthog/hogql_queries/utils/entities.py b/posthog/hogql_queries/utils/entities.py
index d2082ded64de..279ea713f2bd 100644
--- a/posthog/hogql_queries/utils/entities.py
+++ b/posthog/hogql_queries/utils/entities.py
@@ -6,6 +6,7 @@ from posthog.schema import (
CohortPropertyFilter,
DataWarehouseNode,
EmptyPropertyFilter,
+ EntityType,
EventsNode,
FunnelExclusionActionsNode,
FunnelExclusionEventsNode,
@@ -13,8 +14,11 @@ from posthog.schema import (
GroupNode,
HogQLPropertyFilter,
LifecycleDataWarehouseNode,
+ RetentionEntity,
)
+from posthog.hogql.database.schema.flag_evaluations import FLAG_EVALUATIONS_HOGQL_TABLE
+
from posthog.types import AnyPropertyFilter, EntityNode, FunnelExclusionEntityNode
@@ -26,6 +30,25 @@ def has_data_warehouse_node(nodes: Sequence[EntityNode]) -> bool:
return any(is_data_warehouse_node(node) for node in nodes)
+def is_data_warehouse_entity(node: EntityNode | RetentionEntity | None) -> bool:
+ if isinstance(node, RetentionEntity):
+ return node.type == EntityType.DATA_WAREHOUSE
+ return node is not None and is_data_warehouse_node(node)
+
+
+def every_warehouse_series_reads_flag_calls(nodes: Sequence[EntityNode | RetentionEntity | None]) -> bool:
+ """Whether each data warehouse series in `nodes` reads `posthog.flag_evaluations`. True when there is none.
+
+ A flag calls series takes test account filters and global property filters, as an events series does.
+ A series on any other warehouse table takes neither.
+ """
+ return all(
+ getattr(node, "table_name", None) == FLAG_EVALUATIONS_HOGQL_TABLE
+ for node in nodes
+ if is_data_warehouse_entity(node)
+ )
+
+
def is_equal_type(a: EntityNode, b: EntityNode | FunnelExclusionEntityNode) -> bool:
if isinstance(a, EventsNode):
return isinstance(b, EventsNode) or isinstance(b, FunnelExclusionEventsNode)
diff --git a/posthog/hogql_queries/validation/rules.py b/posthog/hogql_queries/validation/rules.py
index 6d280fd1c41a..77fa18ee0f0e 100644
--- a/posthog/hogql_queries/validation/rules.py
+++ b/posthog/hogql_queries/validation/rules.py
@@ -1,13 +1,16 @@
+from collections.abc import Sequence
+
from rest_framework.exceptions import ValidationError
-from posthog.schema import EntityType, FunnelsQuery, LifecycleQuery, RetentionQuery, StickinessQuery, TrendsQuery
+from posthog.schema import FunnelsQuery, LifecycleQuery, RetentionEntity, RetentionQuery, StickinessQuery, TrendsQuery
from posthog.hogql.constants import MAX_EXPANDED_INSIGHT_QUERIES
-from posthog.hogql_queries.utils.entities import has_data_warehouse_node
+from posthog.hogql_queries.utils.entities import every_warehouse_series_reads_flag_calls, is_data_warehouse_entity
from posthog.hogql_queries.utils.properties import has_any_property_filters
from posthog.hogql_queries.validation.utils import get_query_insight_name
from posthog.hogql_queries.validation.validation import QueryValidationContext
+from posthog.types import EntityNode
class RequireAtLeastOneSeries:
@@ -24,7 +27,10 @@ class RequireAtLeastOneSeries:
class DisallowUnsupportedDataWarehouseSettings:
- """Global property filters, test account filters and sampling can't be used together with data warehouse series."""
+ """Global property filters, test account filters and sampling can't be used together with data warehouse series.
+
+ A query whose warehouse series all read flag calls takes global property filters and test account filters.
+ """
code = "data_warehouse_series_unsupported_settings"
@@ -32,14 +38,16 @@ class DisallowUnsupportedDataWarehouseSettings:
self,
context: QueryValidationContext[TrendsQuery | FunnelsQuery | StickinessQuery | LifecycleQuery | RetentionQuery],
) -> None:
- if not _query_has_data_warehouse_series(context.query):
+ series = _series_entities(context.query)
+ if not any(is_data_warehouse_entity(node) for node in series):
return
unsupported_settings: list[str] = []
- if has_any_property_filters(context.query.properties):
- unsupported_settings.append("filters")
- if context.query.filterTestAccounts:
- unsupported_settings.append("test account filters")
+ if not every_warehouse_series_reads_flag_calls(series):
+ if has_any_property_filters(context.query.properties):
+ unsupported_settings.append("filters")
+ if context.query.filterTestAccounts:
+ unsupported_settings.append("test account filters")
if context.query.samplingFactor is not None:
unsupported_settings.append("sampling")
@@ -52,16 +60,12 @@ class DisallowUnsupportedDataWarehouseSettings:
)
-def _query_has_data_warehouse_series(
+def _series_entities(
query: TrendsQuery | FunnelsQuery | StickinessQuery | LifecycleQuery | RetentionQuery,
-) -> bool:
+) -> Sequence[EntityNode | RetentionEntity | None]:
if isinstance(query, RetentionQuery):
- return any(
- entity is not None and entity.type == EntityType.DATA_WAREHOUSE
- for entity in (query.retentionFilter.targetEntity, query.retentionFilter.returningEntity)
- )
-
- return has_data_warehouse_node(query.series)
+ return [query.retentionFilter.targetEntity, query.retentionFilter.returningEntity]
+ return query.series
SERIES_FAN_OUT_TOO_LARGE = "insight_series_fan_out_too_large"
diff --git a/posthog/hogql_queries/validation/test_rules.py b/posthog/hogql_queries/validation/test_rules.py
index 388011ed4d31..f527018f448c 100644
--- a/posthog/hogql_queries/validation/test_rules.py
+++ b/posthog/hogql_queries/validation/test_rules.py
@@ -11,12 +11,20 @@ from posthog.schema import (
BreakdownFilter,
BreakdownType,
CompareFilter,
+ DataWarehouseNode,
+ DataWarehousePropertyFilter,
+ EntityType,
+ EventPropertyFilter,
EventsNode,
FilterLogicalOperator,
LifecycleDataWarehouseNode,
LifecycleQuery,
PropertyGroupFilter,
PropertyGroupFilterValue,
+ PropertyOperator,
+ RetentionEntity,
+ RetentionFilter,
+ RetentionQuery,
StickinessQuery,
TrendsQuery,
)
@@ -52,67 +60,146 @@ class TestRequireAtLeastOneSeries(BaseTest):
RequireAtLeastOneSeries().validate(self._context(query))
+FLAG_CALLS_TABLE = "posthog.flag_evaluations"
+MESSAGES_SERIES = LifecycleDataWarehouseNode(
+ id="messages",
+ table_name="messages",
+ timestamp_field="sent_at",
+ aggregation_target_field="person_id",
+ created_at_field="signed_up_at",
+)
+FLAG_CALLS_SERIES = LifecycleDataWarehouseNode(
+ id=FLAG_CALLS_TABLE,
+ table_name=FLAG_CALLS_TABLE,
+ timestamp_field="timestamp",
+ aggregation_target_field="person_id",
+ created_at_field="timestamp",
+)
+EVENT_FILTER = EventPropertyFilter(key="$browser", value="Chrome", operator=PropertyOperator.EXACT)
+
+
+def _trends_warehouse_series(table_name: str) -> DataWarehouseNode:
+ return DataWarehouseNode(
+ id=table_name,
+ table_name=table_name,
+ timestamp_field="timestamp",
+ distinct_id_field="distinct_id",
+ id_field="uuid",
+ )
+
+
+def _retention_warehouse_entity(table_name: str) -> RetentionEntity:
+ return RetentionEntity(
+ id=table_name,
+ type=EntityType.DATA_WAREHOUSE,
+ table_name=table_name,
+ timestamp_field="timestamp",
+ aggregation_target_field="person_id",
+ )
+
+
class TestDisallowUnsupportedDataWarehouseSettings(BaseTest):
- def _context(self, query: LifecycleQuery) -> QueryValidationContext:
+ def _context(self, query: TrendsQuery | LifecycleQuery | RetentionQuery) -> QueryValidationContext:
runner = MagicMock(query=query, team=self.team, user=None)
return QueryValidationContext(query=query, team=self.team, user=None, runner=runner)
- def _data_warehouse_series(self) -> list[LifecycleDataWarehouseNode]:
- return [
- LifecycleDataWarehouseNode(
- id="messages",
- table_name="messages",
- timestamp_field="sent_at",
- aggregation_target_field="person_id",
- created_at_field="signed_up_at",
- )
- ]
-
@parameterized.expand(
[
(
"filters",
- {"properties": [{"key": "text", "value": "new", "operator": "exact", "type": "data_warehouse"}]},
+ LifecycleQuery(
+ series=[MESSAGES_SERIES],
+ properties=[DataWarehousePropertyFilter(key="text", value="new", operator=PropertyOperator.EXACT)],
+ ),
"Filters are not supported for lifecycle insights with a data warehouse series.",
),
(
"test_account_filters",
- {"filterTestAccounts": True},
+ LifecycleQuery(series=[MESSAGES_SERIES], filterTestAccounts=True),
"Test account filters are not supported for lifecycle insights with a data warehouse series.",
),
(
"sampling",
- {"samplingFactor": 0.1},
+ LifecycleQuery(series=[MESSAGES_SERIES], samplingFactor=0.1),
"Sampling is not supported for lifecycle insights with a data warehouse series.",
),
(
"multiple_settings",
- {"filterTestAccounts": True, "samplingFactor": 0.1},
+ LifecycleQuery(series=[MESSAGES_SERIES], filterTestAccounts=True, samplingFactor=0.1),
"Test account filters and sampling are not supported for lifecycle insights with a data warehouse series.",
),
+ (
+ "flag_calls_beside_another_warehouse_table",
+ TrendsQuery(
+ series=[_trends_warehouse_series(FLAG_CALLS_TABLE), _trends_warehouse_series("messages")],
+ filterTestAccounts=True,
+ ),
+ "Test account filters are not supported for trends insights with a data warehouse series.",
+ ),
+ (
+ "flag_calls_target_returning_on_another_warehouse_table",
+ RetentionQuery(
+ filterTestAccounts=True,
+ retentionFilter=RetentionFilter(
+ targetEntity=_retention_warehouse_entity(FLAG_CALLS_TABLE),
+ returningEntity=_retention_warehouse_entity("messages"),
+ ),
+ ),
+ "Test account filters are not supported for retention insights with a data warehouse series.",
+ ),
+ (
+ "flag_calls_sampling",
+ LifecycleQuery(series=[FLAG_CALLS_SERIES], samplingFactor=0.1),
+ "Sampling is not supported for lifecycle insights with a data warehouse series.",
+ ),
]
)
- def test_disallows_unsupported_data_warehouse_settings(self, _name, query_kwargs, expected_error):
- query = LifecycleQuery(series=self._data_warehouse_series(), **query_kwargs)
-
+ def test_disallows_unsupported_data_warehouse_settings(
+ self, _name: str, query: TrendsQuery | LifecycleQuery | RetentionQuery, expected_error: str
+ ):
with self.assertRaises(ValidationError) as context:
DisallowUnsupportedDataWarehouseSettings().validate(self._context(query))
self.assertIn(expected_error, str(context.exception))
self.assertEqual(context.exception.get_codes(), ["data_warehouse_series_unsupported_settings"])
- def test_allows_supported_settings_without_data_warehouse_series(self):
- query = LifecycleQuery(
- filterTestAccounts=True,
- samplingFactor=0.1,
- series=[EventsNode(event="$pageview")],
- )
-
+ @parameterized.expand(
+ [
+ (
+ "events_only",
+ LifecycleQuery(filterTestAccounts=True, samplingFactor=0.1, series=[EventsNode(event="$pageview")]),
+ ),
+ (
+ "flag_calls_only",
+ LifecycleQuery(filterTestAccounts=True, properties=[EVENT_FILTER], series=[FLAG_CALLS_SERIES]),
+ ),
+ (
+ "flag_calls_beside_events",
+ TrendsQuery(
+ filterTestAccounts=True,
+ properties=[EVENT_FILTER],
+ series=[EventsNode(event="$pageview"), _trends_warehouse_series(FLAG_CALLS_TABLE)],
+ ),
+ ),
+ (
+ "retention_flag_calls_target_returning_on_events",
+ RetentionQuery(
+ filterTestAccounts=True,
+ properties=[EVENT_FILTER],
+ retentionFilter=RetentionFilter(
+ targetEntity=_retention_warehouse_entity(FLAG_CALLS_TABLE),
+ returningEntity=RetentionEntity(id="$pageview", type=EntityType.EVENTS),
+ ),
+ ),
+ ),
+ ]
+ )
+ def test_allows_supported_settings(self, _name: str, query: TrendsQuery | LifecycleQuery | RetentionQuery):
DisallowUnsupportedDataWarehouseSettings().validate(self._context(query))
def test_allows_empty_property_groups_for_data_warehouse_series(self):
query = LifecycleQuery(
- series=self._data_warehouse_series(),
+ series=[MESSAGES_SERIES],
properties=PropertyGroupFilter(
type=FilterLogicalOperator.AND_,
values=[PropertyGroupFilterValue(type=FilterLogicalOperator.AND_, values=[])],
@@ -123,7 +210,7 @@ class TestDisallowUnsupportedDataWarehouseSettings(BaseTest):
def test_allows_empty_property_list_for_data_warehouse_series(self):
query = LifecycleQuery(
- series=self._data_warehouse_series(),
+ series=[MESSAGES_SERIES],
properties=[],
)
diff --git a/posthog/test/base.py b/posthog/test/base.py
index 3107db13a76a..49c2b329e8e7 100644
--- a/posthog/test/base.py
+++ b/posthog/test/base.py
@@ -1815,6 +1815,7 @@ def _create_flag_evaluations(
person_created_at: dt.datetime | None = None,
response: str | bool = True,
properties: dict[str, Any] | None = None,
+ person_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. Each row gets a new random person_id unless the caller passes one. Without a
@@ -1825,7 +1826,7 @@ def _create_flag_evaluations(
sync_execute(
"""
INSERT INTO writable_flag_evaluations
- (uuid, event, properties, timestamp, team_id, distinct_id, created_at, person_id, person_created_at)
+ (uuid, event, properties, timestamp, team_id, distinct_id, created_at, person_id, person_created_at, person_properties)
VALUES
""",
[
@@ -1839,6 +1840,7 @@ def _create_flag_evaluations(
timestamp,
str(person_id or uuid.uuid4()),
person_created_at or ZERO_DATE,
+ json.dumps(person_properties or {}),
)
for _ in range(count)
],
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 9d8e278460e8..ee9777b09362 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
@@ -278,6 +278,7 @@ class FunnelEventQuery(DataWarehouseSchemaMixin):
),
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,
+ *self._properties_expr(),
]
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 84eb04db87ac..63ecec748fe2 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
@@ -878,8 +878,9 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
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] = []
+ conditions on its entity and the query window. Apart from the global property filters, these filters therefore
+ drop only rows that no aggregate reads."""
+ filters = list(self.runner.global_property_filters)
# 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):
diff --git a/products/product_analytics/backend/hogql_queries/retention/retention_base_query_rolling.py b/products/product_analytics/backend/hogql_queries/retention/retention_base_query_rolling.py
index f9c0248bd145..8976785bb568 100644
--- a/products/product_analytics/backend/hogql_queries/retention/retention_base_query_rolling.py
+++ b/products/product_analytics/backend/hogql_queries/retention/retention_base_query_rolling.py
@@ -169,8 +169,9 @@ class RetentionRollingIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
# Breakdowns are rejected upstream by DisallowBreakdownsWithDataWarehouse24HourWindows: apply_breakdown
# references events / person columns, which aren't in scope in this query shape. Group aggregation is
# rejected by DisallowGroupAggregationWithDataWarehouse24HourWindows: these scans identify actors by each
- # entity's aggregation_target_field, which has no group counterpart to join against. Global property
- # filters, test-account filters, and sampling are rejected by DisallowUnsupportedDataWarehouseSettings.
+ # entity's aggregation_target_field, which has no group counterpart to join against. DisallowUnsupportedDataWarehouseSettings
+ # rejects sampling. It rejects global property filters and test-account filters unless every warehouse entity
+ # reads flag calls. Each scan applies those filters itself.
first_event_cte = self._build_data_warehouse_first_event_cte()
return_scan = self._build_return_scan()
@@ -269,6 +270,7 @@ class RetentionRollingIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
select_from=ast.JoinExpr(table=ast.Field(chain=[return_table_name])),
where=ast.And(
exprs=[
+ *self.runner.global_property_filters,
self.entity_expr_with_props(self.return_event),
self.events_timestamp_filter(field=return_ts_field),
]
@@ -282,7 +284,7 @@ class RetentionRollingIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
assert start_table_name
actor_id_expr = self.coerce_actor_id_expr(self.entity_actor_id_expr(self.start_event))
- where: ast.Expr | None
+ where_exprs = list(self.runner.global_property_filters)
having: ast.Expr | None
if self.is_first_occurrence_matching_filters or self.is_first_ever_occurrence:
# The anchor must see the actor's true-earliest row, so the start table is scanned unwindowed; an
@@ -296,7 +298,8 @@ class RetentionRollingIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
# An events-typed start still gets the entity matcher as WHERE: both anchor variants condition on the
# entity, so rows outside it never feed the aggregates, and without the pre-filter this scan reads the
# team's entire events table.
- where = None if start_is_dwh else self.entity_expr_no_props(self.start_event)
+ if not start_is_dwh:
+ where_exprs.append(self.entity_expr_no_props(self.start_event))
having = ast.CompareOperation(
op=ast.CompareOperationOp.NotEq, left=ast.Field(chain=["t_0"]), right=ast.Constant(value=None)
)
@@ -304,8 +307,8 @@ class RetentionRollingIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
# Recurring: t_0 is the earliest qualifying start row inside the analysis window. The WHERE restricts the
# group to qualifying rows so min() over a non-empty set is the cohorting timestamp (no HAVING needed).
t0_expr = ast.Call(name="min", args=[start_ts_field])
- where = ast.And(
- exprs=[
+ where_exprs.extend(
+ [
self.entity_expr_with_props(self.start_event),
self.events_timestamp_filter(field=start_ts_field),
]
@@ -318,7 +321,7 @@ class RetentionRollingIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
ast.Alias(alias="t_0", expr=t0_expr),
],
select_from=ast.JoinExpr(table=ast.Field(chain=[start_table_name])),
- where=where,
+ where=ast.And(exprs=where_exprs) if where_exprs else None,
group_by=[ast.Field(chain=["actor_id"])],
having=having,
)
diff --git a/products/product_analytics/backend/hogql_queries/retention/retention_query_runner.py b/products/product_analytics/backend/hogql_queries/retention/retention_query_runner.py
index ebebbca12920..acbed7705500 100644
--- a/products/product_analytics/backend/hogql_queries/retention/retention_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/retention/retention_query_runner.py
@@ -408,17 +408,13 @@ class RetentionQueryRunner(AnalyticsQueryRunner[RetentionQueryResponse]):
return action.get_step_events()
return [entity.id] if isinstance(entity.id, str) else [None]
- def events_where_clause(
- self,
- is_first_occurrence_matching_filters: bool,
- is_first_ever_occurrence: bool = False,
- entities: list[RetentionEntity] | None = None,
- ):
- """Event filters for both start and return events, or just `entities` for a per-arm scan."""
- events_where = []
+ @cached_property
+ def global_property_filters(self) -> tuple[ast.Expr, ...]:
+ """The query's global property filters, then the team's test account filters when the query turns them on."""
+ filters: list[ast.Expr] = []
if self.query.properties is not None and self.query.properties != []:
- events_where.append(property_to_expr(self.query.properties, self.team))
+ filters.append(property_to_expr(self.query.properties, self.team))
if (
self.query.filterTestAccounts
@@ -426,7 +422,18 @@ class RetentionQueryRunner(AnalyticsQueryRunner[RetentionQueryResponse]):
and len(self.team.test_account_filters) > 0
):
for prop in self.team.test_account_filters:
- events_where.append(property_to_expr(prop, self.team))
+ filters.append(property_to_expr(prop, self.team))
+
+ return tuple(filters)
+
+ def events_where_clause(
+ self,
+ is_first_occurrence_matching_filters: bool,
+ is_first_ever_occurrence: bool = False,
+ entities: list[RetentionEntity] | None = None,
+ ):
+ """Event filters for both start and return events, or just `entities` for a per-arm scan."""
+ events_where = list(self.global_property_filters)
if not is_first_occurrence_matching_filters and not is_first_ever_occurrence:
# when it's recurring, we only have to grab events for the period, rather than events for all time
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
index f0e63b649b64..275e6789a6d1 100644
--- a/products/product_analytics/backend/tests/test_flag_evaluations_insight_series.py
+++ b/products/product_analytics/backend/tests/test_flag_evaluations_insight_series.py
@@ -1,3 +1,4 @@
+from collections.abc import Callable
from datetime import UTC, datetime
from typing import Any
@@ -14,15 +15,18 @@ from posthog.test.base import (
from unittest.mock import patch
from parameterized import parameterized
+from pydantic import BaseModel
from posthog.schema import (
BaseMathType,
BreakdownFilter,
BreakdownType,
+ CohortPropertyFilter,
DataWarehouseNode,
DataWarehousePropertyFilter,
DateRange,
EventsNode,
+ FilterLogicalOperator,
FunnelsDataWarehouseNode,
FunnelsFilter,
FunnelsQuery,
@@ -31,17 +35,24 @@ from posthog.schema import (
LifecycleDataWarehouseNode,
LifecycleQuery,
PersonsOnEventsMode,
+ PropertyGroupFilter,
+ PropertyGroupFilterValue,
PropertyOperator,
RetentionQuery,
+ RetentionType,
StickinessQuery,
+ TimeWindowMode,
TrendsQuery,
)
from posthog.hogql.database.schema.flag_evaluations import FLAG_EVALUATIONS_HOGQL_TABLE
+from posthog.hogql_queries.query_runner import QueryRunner
from posthog.models.group.util import create_group
from posthog.models.person import Person
+from products.cohorts.backend.models.cohort import Cohort
+from products.cohorts.backend.models.util import insert_static_cohort
from products.product_analytics.backend.facade.queries import (
FunnelsQueryRunner,
LifecycleQueryRunner,
@@ -56,6 +67,7 @@ DATE_RANGE = DateRange(date_from="2025-01-08", date_to="2025-01-10")
IN_DATE_RANGE = datetime(2025, 1, 8, 8, 0, tzinfo=UTC)
BEFORE_DATE_RANGE = datetime(2024, 12, 1, tzinfo=UTC)
PROBE_FLAG = DataWarehousePropertyFilter(key="flag_key", operator=PropertyOperator.EXACT, value="probe-flag")
+EXCLUDED_PEOPLE = ("dave", "erin", "frank", "gina")
def _flag_calls_series(**kwargs: Any) -> DataWarehouseNode:
@@ -92,6 +104,46 @@ def _retention_entity(aggregation_target_field: str) -> dict[str, Any]:
}
+def _flag_calls_funnel_step(aggregation_target_field: str = "person_id") -> FunnelsDataWarehouseNode:
+ return FunnelsDataWarehouseNode(
+ id=TABLE,
+ table_name=TABLE,
+ timestamp_field="timestamp",
+ id_field="uuid",
+ aggregation_target_field=aggregation_target_field,
+ properties=[PROBE_FLAG],
+ )
+
+
+def _flag_calls_lifecycle_series(aggregation_group_type_index: int | None = None) -> LifecycleDataWarehouseNode:
+ return LifecycleDataWarehouseNode(
+ id=TABLE,
+ table_name=TABLE,
+ timestamp_field="timestamp",
+ aggregation_target_field=_aggregation_target(aggregation_group_type_index),
+ created_at_field=_created_at_field(aggregation_group_type_index),
+ )
+
+
+def _flag_calls_retention(
+ aggregation_group_type_index: int | None = None,
+ returning_entity: dict[str, Any] | None = None,
+ **retention_filter: Any,
+) -> RetentionQuery:
+ flag_calls = _retention_entity(_aggregation_target(aggregation_group_type_index))
+ return RetentionQuery(
+ dateRange=DATE_RANGE,
+ aggregation_group_type_index=aggregation_group_type_index,
+ retentionFilter={
+ "period": "Day",
+ "totalIntervals": 3,
+ "targetEntity": flag_calls,
+ "returningEntity": returning_entity or flag_calls,
+ **retention_filter,
+ },
+ )
+
+
@time_machine.travel(NOW, tick=False)
class TestFlagEvaluationsInsightSeries(ClickhouseTestMixin, BaseTest):
def setUp(self):
@@ -101,7 +153,7 @@ class TestFlagEvaluationsInsightSeries(ClickhouseTestMixin, BaseTest):
)
table_gate.start()
self.addCleanup(table_gate.stop)
- alice = _create_person(team_id=self.team.pk, distinct_ids=["alice"], created_at=IN_DATE_RANGE)
+ alice = self.alice = _create_person(team_id=self.team.pk, distinct_ids=["alice"], created_at=IN_DATE_RANGE)
bob = _create_person(team_id=self.team.pk, distinct_ids=["bob"], created_at=IN_DATE_RANGE)
alice_2 = _create_person(team_id=self.team.pk, distinct_ids=["alice-2"], created_at=IN_DATE_RANGE)
for distinct_id, person, flag_key, response, occurred_at, properties in [
@@ -216,14 +268,7 @@ class TestFlagEvaluationsInsightSeries(ClickhouseTestMixin, BaseTest):
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],
- ),
+ _flag_calls_funnel_step(aggregate_by_hogql or _aggregation_target(aggregation_group_type_index)),
EventsNode(event="$pageview"),
],
)
@@ -251,17 +296,7 @@ class TestFlagEvaluationsInsightSeries(ClickhouseTestMixin, BaseTest):
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,
- },
- )
+ query = _flag_calls_retention(aggregation_group_type_index, returning_entity=returning_event)
results = RetentionQueryRunner(query=query, team=self.team).calculate().model_dump()["results"]
@@ -328,15 +363,7 @@ class TestFlagEvaluationsInsightSeries(ClickhouseTestMixin, BaseTest):
modifiers=HogQLQueryModifiers(
personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS
),
- series=[
- LifecycleDataWarehouseNode(
- id=TABLE,
- table_name=TABLE,
- timestamp_field="timestamp",
- aggregation_target_field=_aggregation_target(aggregation_group_type_index),
- created_at_field=_created_at_field(aggregation_group_type_index),
- )
- ],
+ series=[_flag_calls_lifecycle_series(aggregation_group_type_index)],
)
events_query = query.model_copy(update={"series": [EventsNode(event="$feature_flag_called")]})
@@ -346,3 +373,141 @@ class TestFlagEvaluationsInsightSeries(ClickhouseTestMixin, BaseTest):
lifecycle = {r["status"]: r["data"] for r in results}
assert lifecycle == expected
assert lifecycle == {r["status"]: r["data"] for r in events_results}
+
+ @parameterized.expand(
+ [
+ (
+ "trends",
+ TrendsQueryRunner,
+ TrendsQuery(
+ dateRange=DATE_RANGE,
+ interval=IntervalType.DAY,
+ series=[_flag_calls_series(math=BaseMathType.TOTAL, properties=[PROBE_FLAG])],
+ breakdownFilter=BreakdownFilter(breakdown_type=BreakdownType.DATA_WAREHOUSE, breakdown="response"),
+ ),
+ lambda results: {r["breakdown_value"]: r["count"] for r in results},
+ {"test": 3, "control": 1},
+ ),
+ (
+ "funnels",
+ FunnelsQueryRunner,
+ FunnelsQuery(
+ dateRange=DATE_RANGE,
+ series=[_flag_calls_funnel_step(), EventsNode(event="$pageview")],
+ ),
+ lambda results: [step["count"] for step in results],
+ [2, 1],
+ ),
+ (
+ "retention_fixed_intervals",
+ RetentionQueryRunner,
+ _flag_calls_retention(),
+ lambda results: [value["count"] for value in results[0]["values"]],
+ [2, 1, 0],
+ ),
+ (
+ "retention_24_hour_windows",
+ RetentionQueryRunner,
+ _flag_calls_retention(timeWindowMode=TimeWindowMode.FIELD_24_HOUR_WINDOWS),
+ lambda results: [value["count"] for value in results[0]["values"]],
+ [2, 0, 0],
+ ),
+ (
+ "retention_first_time_fixed_intervals",
+ RetentionQueryRunner,
+ _flag_calls_retention(retentionType=RetentionType.RETENTION_FIRST_TIME),
+ lambda results: [value["count"] for value in results[0]["values"]],
+ [2, 1, 0],
+ ),
+ (
+ "retention_first_time_24_hour_windows",
+ RetentionQueryRunner,
+ _flag_calls_retention(
+ retentionType=RetentionType.RETENTION_FIRST_TIME,
+ timeWindowMode=TimeWindowMode.FIELD_24_HOUR_WINDOWS,
+ ),
+ lambda results: [value["count"] for value in results[0]["values"]],
+ [2, 0, 0],
+ ),
+ (
+ "stickiness",
+ StickinessQueryRunner,
+ StickinessQuery(dateRange=DATE_RANGE, interval=IntervalType.DAY, series=[_flag_calls_series()]),
+ lambda results: results[0]["data"],
+ [1, 1, 0],
+ ),
+ (
+ "lifecycle",
+ LifecycleQueryRunner,
+ LifecycleQuery(
+ dateRange=DATE_RANGE,
+ interval=IntervalType.DAY,
+ series=[_flag_calls_lifecycle_series()],
+ ),
+ lambda results: {r["status"]: r["data"] for r in results},
+ {"new": [2, 0, 0], "returning": [0, 1, 0], "resurrecting": [0, 0, 0], "dormant": [0, -1, -1]},
+ ),
+ ]
+ )
+ def test_filters_drop_excluded_people(
+ self,
+ _name: str,
+ runner_class: type[QueryRunner],
+ query: BaseModel,
+ read_results: Callable[[list[Any]], Any],
+ expected: Any,
+ ):
+ people = {name: _create_person(team_id=self.team.pk, distinct_ids=[name]) for name in EXCLUDED_PEOPLE}
+ flush_persons_and_events()
+ for name, properties, person_properties in [
+ ("dave", {"$host": "localhost:8000"}, None),
+ ("erin", None, {"email": "[email protected]"}),
+ ("frank", None, None),
+ ("gina", None, None),
+ ]:
+ _create_flag_evaluations(
+ self.team.pk,
+ "probe-flag",
+ timestamp=datetime(2025, 1, 8, 14, tzinfo=UTC),
+ distinct_id=name,
+ person_id=people[name].uuid,
+ response="test",
+ properties=properties,
+ person_properties=person_properties,
+ )
+ # Alice's first calls pass every filter. Her return call does not, so only a scan that drops it keeps her
+ # out of the later retention intervals.
+ self._create_flag_call(
+ "alice", self.alice, "other-flag", "true", datetime(2025, 1, 9, 10, tzinfo=UTC), {"$host": "localhost:8000"}
+ )
+ test_account_cohort = Cohort.objects.create(team=self.team, is_static=True)
+ insert_static_cohort([people["frank"].uuid], test_account_cohort.pk, team_id=self.team.pk)
+ global_filter_cohort = Cohort.objects.create(team=self.team, is_static=True)
+ insert_static_cohort([people["gina"].uuid], global_filter_cohort.pk, team_id=self.team.pk)
+ self.team.test_account_filters = [
+ {"key": "$host", "operator": "is_not", "value": ["localhost:8000"], "type": "event"},
+ {"key": "email", "operator": "not_icontains", "value": "posthog.com", "type": "person"},
+ {"key": "id", "operator": "not_in", "value": test_account_cohort.pk, "type": "cohort"},
+ ]
+ self.team.save()
+ filtered_query = query.model_copy(
+ deep=True,
+ update={
+ "filterTestAccounts": True,
+ "properties": PropertyGroupFilter(
+ type=FilterLogicalOperator.AND_,
+ values=[
+ PropertyGroupFilterValue(
+ type=FilterLogicalOperator.AND_,
+ values=[
+ CohortPropertyFilter(value=global_filter_cohort.pk, operator=PropertyOperator.NOT_IN)
+ ],
+ )
+ ],
+ ),
+ },
+ )
+
+ response = runner_class(query=filtered_query, team=self.team).calculate()
+
+ assert read_results(response.model_dump()["results"]) == expected