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): read the usage tab from flag_evaluations behind a flag (#98888)

Phil Haackc6f7f99535d4
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 11f975293577..45c043cc93a5 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -335,6 +335,8 @@ export const FEATURE_FLAGS = {
FEATURE_FLAG_REQUEST_USAGE: 'feature-flag-request-usage', // owner: #team-feature-flags
FIELD_NOTES: 'field-notes', // owner: @adamleithp
FLAG_EVALUATION_TAGS: 'flag-evaluation-tags', // owner: @dmarticus #team-feature-flags
+ FLAG_EVALUATIONS_HOGQL_TABLE: 'flag-evaluations-hogql-table', // owner: #team-feature-flags, also read by the backend to expose posthog.flag_evaluations
+ FLAG_EVALUATIONS_USAGE_TAB: 'flag-evaluations-usage-tab', // owner: #team-feature-flags, reads the Usage tab from flag_evaluations instead of events
FLAGGED_FEATURE_INDICATOR: 'flagged-feature-indicator', // owner: @benjackwhite
FLAT_NAV: 'flat-nav', // owner: @rafaeelaudibert #team-growth multivariate=control,test, swaps the tree-based Browse tab for the flat sidebar, see FlatNavBrowse.tsx
GITHUB_FIRST_SELF_DRIVING_ONBOARDING: 'github-first-self-driving-onboarding', // owner: #team-self-driving
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagUsageMetrics.tsx b/frontend/src/scenes/feature-flags/FeatureFlagUsageMetrics.tsx
index 8273994bc2ae..8ffe9f8c5cb9 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagUsageMetrics.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagUsageMetrics.tsx
@@ -4,20 +4,27 @@ 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'
export function FeatureFlagUsageMetrics({ id }: { id: number }): JSX.Element {
const logic = featureFlagUsageLogic({ id })
- const { dateRange, usageCharts } = useValues(logic)
+ const { dateRange, dateOptions, readsFlagEvaluationsTable, usageCharts } = useValues(logic)
const { setDates } = useActions(logic)
return (
<div className="flex flex-col gap-4" data-attr="feature-flag-usage-inline">
- <div>
+ <div className="flex flex-wrap items-center gap-2">
<DateFilter
dateFrom={dateRange.date_from ?? null}
dateTo={dateRange.date_to ?? null}
+ dateOptions={dateOptions}
onChange={(fromDate, toDate) => setDates(fromDate, toDate)}
/>
+ {readsFlagEvaluationsTable && (
+ <span className="text-secondary text-xs">
+ Flag evaluations are kept for {FLAG_EVALUATIONS_RETENTION_DAYS} days.
+ </span>
+ )}
</div>
<div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
{usageCharts.map((chart) => (
diff --git a/frontend/src/scenes/feature-flags/featureFlagUsageLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagUsageLogic.test.ts
index 8161e66ea830..36cc7240f210 100644
--- a/frontend/src/scenes/feature-flags/featureFlagUsageLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagUsageLogic.test.ts
@@ -1,18 +1,34 @@
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic as enabledFeaturesLogic } from 'lib/logic/featureFlagLogic'
import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
+import { NodeKind, TrendsQuery } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { FeatureFlagType } from '~/types'
import { NEW_FLAG, featureFlagLogic } from './featureFlagLogic'
import { featureFlagUsageLogic } from './featureFlagUsageLogic'
-import { DEFAULT_USAGE_DATE_RANGE } from './featureFlagUsageQueries'
+import { DEFAULT_USAGE_DATE_RANGE, FlagUsageQuery } from './featureFlagUsageQueries'
const FLAG_ID = 1
+const BOTH_EVALUATION_FLAGS = {
+ [FEATURE_FLAGS.FLAG_EVALUATIONS_USAGE_TAB]: true,
+ [FEATURE_FLAGS.FLAG_EVALUATIONS_HOGQL_TABLE]: true,
+}
+
+// Every chart reads the events table unless a test enables both evaluation flags.
+function trendsSource(query: FlagUsageQuery): TrendsQuery {
+ if (query.kind !== NodeKind.InsightVizNode) {
+ throw new Error(`Expected an events-table trend, got ${query.kind}`)
+ }
+ return query.source
+}
+
function flag(overrides: Partial<FeatureFlagType> = {}): FeatureFlagType {
return {
...NEW_FLAG,
@@ -38,6 +54,42 @@ describe('featureFlagUsageLogic', () => {
logic.mount()
})
+ afterEach(() => {
+ // The flag set persists across tests, so a test that enables one must not leak it.
+ enabledFeaturesLogic.actions.setFeatureFlags([], {})
+ })
+
+ it.each([
+ ['neither flag', {}, false],
+ ['the usage-tab flag alone', { [FEATURE_FLAGS.FLAG_EVALUATIONS_USAGE_TAB]: true }, false],
+ ['the HogQL-table flag alone', { [FEATURE_FLAGS.FLAG_EVALUATIONS_HOGQL_TABLE]: true }, false],
+ ['both flags', BOTH_EVALUATION_FLAGS, true],
+ ])('reads flag_evaluations with %s', (_name, variants, readsEvaluations) => {
+ enabledFeaturesLogic.actions.setFeatureFlags([], variants)
+
+ expect(logic.values.readsFlagEvaluationsTable).toEqual(readsEvaluations)
+ expect(logic.values.usageCharts.map((chart) => chart.query.kind)).toEqual(
+ readsEvaluations
+ ? [NodeKind.DataVisualizationNode, NodeKind.DataVisualizationNode]
+ : [NodeKind.InsightVizNode, NodeKind.InsightVizNode]
+ )
+ })
+
+ it('holds the date range inside the retention window when reading flag_evaluations', async () => {
+ enabledFeaturesLogic.actions.setFeatureFlags([], BOTH_EVALUATION_FLAGS)
+
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-180d', null)
+ }).toMatchValues({
+ selectedDateRange: { date_from: '-180d', date_to: null },
+ dateRange: { date_from: '-90d', date_to: null },
+ })
+
+ const optionKeys = logic.values.dateOptions?.map((option) => option.key)
+ expect(optionKeys).toContain('Last 90 days')
+ expect(optionKeys).not.toContain('All time')
+ })
+
it.each([
[false, ['total-volume', 'unique-callers']],
[true, ['total-volume', 'unique-callers', 'feature-view', 'feature-interaction']],
@@ -56,8 +108,8 @@ describe('featureFlagUsageLogic', () => {
expect(logic.values.usageCharts).toHaveLength(4)
for (const chart of logic.values.usageCharts) {
- expect(chart.query.source.dateRange).toEqual({ date_from: '-24h', date_to: null })
- expect(chart.query.source.interval).toEqual('hour')
+ expect(trendsSource(chart.query).dateRange).toEqual({ date_from: '-24h', date_to: null })
+ expect(trendsSource(chart.query).interval).toEqual('hour')
}
})
@@ -65,7 +117,9 @@ describe('featureFlagUsageLogic', () => {
featureFlagLogic({ id: FLAG_ID }).actions.loadFeatureFlagSuccess(flag({ key: 'renamed-feature' }))
for (const chart of logic.values.usageCharts) {
- expect(chart.query.source.properties).toEqual([expect.objectContaining({ value: 'renamed-feature' })])
+ expect(trendsSource(chart.query).properties).toEqual([
+ expect.objectContaining({ value: 'renamed-feature' }),
+ ])
}
})
diff --git a/frontend/src/scenes/feature-flags/featureFlagUsageLogic.ts b/frontend/src/scenes/feature-flags/featureFlagUsageLogic.ts
index 5ff66f3bdf34..a447dfa2f187 100644
--- a/frontend/src/scenes/feature-flags/featureFlagUsageLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagUsageLogic.ts
@@ -1,11 +1,13 @@
import { LogicWrapper, MakeLogicType, actions, connect, kea, key, path, props, reducers, selectors } from 'kea'
import { actionToUrl, router, urlToAction } from 'kea-router'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { FeatureFlagsSet, featureFlagLogic as enabledFeaturesLogic } from 'lib/logic/featureFlagLogic'
import { urls } from 'scenes/urls'
import { Noun, groupsModel } from '~/models/groupsModel'
import { DateRange } from '~/queries/schema/schema-general'
-import { FeatureFlagType } from '~/types'
+import { DateMappingOption, FeatureFlagType } from '~/types'
import { featureFlagLogic } from './featureFlagLogic'
import {
@@ -15,6 +17,10 @@ import {
buildEnrichedUsageCharts,
buildFlagCalledTotalVolumeChart,
buildFlagCalledUniqueCallersChart,
+ buildFlagEvaluationsTotalVolumeChart,
+ buildFlagEvaluationsUniqueCallersChart,
+ clampToFlagEvaluationsRetention,
+ flagEvaluationsDateOptions,
} from './featureFlagUsageQueries'
// The Usage tab only renders for persisted flags, so unlike featureFlagLogic this
@@ -25,12 +31,16 @@ export interface FeatureFlagUsageLogicProps {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featureFlagUsageLogicValues {
+ featureFlags: FeatureFlagsSet // enabledFeaturesLogic
featureFlag: FeatureFlagType // featureFlagLogic
aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel
aggregationGroupTypeIndex: number | null | undefined
+ dateOptions: DateMappingOption[] | undefined
dateRange: DateRange
flagKey: string
hasEnrichedAnalytics: boolean | undefined
+ readsFlagEvaluationsTable: boolean
+ selectedDateRange: DateRange
usageCharts: FlagUsageChart[]
}
@@ -52,11 +62,15 @@ export interface featureFlagUsageLogicMeta {
flagKey: (featureFlag: FeatureFlagType) => string
aggregationGroupTypeIndex: (featureFlag: FeatureFlagType) => number | null | undefined
hasEnrichedAnalytics: (featureFlag: FeatureFlagType) => boolean | undefined
+ readsFlagEvaluationsTable: (featureFlags: FeatureFlagsSet) => boolean
+ dateRange: (selectedDateRange: DateRange, readsFlagEvaluationsTable: boolean) => DateRange
+ dateOptions: (readsFlagEvaluationsTable: boolean) => DateMappingOption[] | undefined
usageCharts: (
flagKey: string,
aggregationGroupTypeIndex: number | null | undefined,
hasEnrichedAnalytics: boolean | undefined,
dateRange: DateRange,
+ readsFlagEvaluationsTable: boolean,
aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel
) => FlagUsageChart[]
}
@@ -74,13 +88,20 @@ export const featureFlagUsageLogic: LogicWrapper<featureFlagUsageLogicType> = ke
key(({ id }) => id),
path((key) => ['scenes', 'feature-flags', 'featureFlagUsageLogic', key]),
connect((props: FeatureFlagUsageLogicProps) => ({
- values: [featureFlagLogic(props), ['featureFlag'], groupsModel, ['aggregationLabel']],
+ values: [
+ featureFlagLogic(props),
+ ['featureFlag'],
+ groupsModel,
+ ['aggregationLabel'],
+ enabledFeaturesLogic,
+ ['featureFlags'],
+ ],
})),
actions({
setDates: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
}),
reducers({
- dateRange: [
+ selectedDateRange: [
DEFAULT_USAGE_DATE_RANGE,
{
setDates: (_, { dateFrom, dateTo }) => ({ date_from: dateFrom, date_to: dateTo }),
@@ -100,13 +121,41 @@ export const featureFlagUsageLogic: LogicWrapper<featureFlagUsageLogicType> = ke
(s) => [s.featureFlag],
(featureFlag: FeatureFlagType): boolean | undefined => featureFlag.has_enriched_analytics,
],
+ // The usage-tab flag alone is not enough: flag_evaluations is missing from the HogQL catalog
+ // of an organization without flag-evaluations-hogql-table, so a query against it fails there.
+ readsFlagEvaluationsTable: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean =>
+ !!featureFlags[FEATURE_FLAGS.FLAG_EVALUATIONS_USAGE_TAB] &&
+ !!featureFlags[FEATURE_FLAGS.FLAG_EVALUATIONS_HOGQL_TABLE],
+ ],
+ // flag_evaluations holds 90 days, so a longer range would show fewer rows than the events
+ // table. The clamp covers the date picker, a shared link, and a range typed into the URL.
+ dateRange: [
+ (s) => [s.selectedDateRange, s.readsFlagEvaluationsTable],
+ (selectedDateRange: DateRange, readsFlagEvaluationsTable: boolean): DateRange =>
+ readsFlagEvaluationsTable ? clampToFlagEvaluationsRetention(selectedDateRange) : selectedDateRange,
+ ],
+ dateOptions: [
+ (s) => [s.readsFlagEvaluationsTable],
+ (readsFlagEvaluationsTable: boolean): DateMappingOption[] | undefined =>
+ readsFlagEvaluationsTable ? flagEvaluationsDateOptions() : undefined,
+ ],
usageCharts: [
- (s) => [s.flagKey, s.aggregationGroupTypeIndex, s.hasEnrichedAnalytics, s.dateRange, s.aggregationLabel],
+ (s) => [
+ s.flagKey,
+ s.aggregationGroupTypeIndex,
+ s.hasEnrichedAnalytics,
+ s.dateRange,
+ s.readsFlagEvaluationsTable,
+ s.aggregationLabel,
+ ],
(
flagKey: string,
aggregationGroupTypeIndex: number | null | undefined,
hasEnrichedAnalytics: boolean | undefined,
dateRange: DateRange,
+ readsFlagEvaluationsTable: boolean,
aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun
): FlagUsageChart[] => {
const options: FlagUsageQueryOptions = {
@@ -115,7 +164,11 @@ export const featureFlagUsageLogic: LogicWrapper<featureFlagUsageLogicType> = ke
callerNoun: aggregationLabel(aggregationGroupTypeIndex, true),
dateRange,
}
- const charts = [buildFlagCalledTotalVolumeChart(options), buildFlagCalledUniqueCallersChart(options)]
+ // The enriched-analytics charts stay on the events table either way: $feature_view
+ // and $feature_interaction are not flag evaluations, so that table does not hold them.
+ const charts: FlagUsageChart[] = readsFlagEvaluationsTable
+ ? [buildFlagEvaluationsTotalVolumeChart(options), buildFlagEvaluationsUniqueCallersChart(options)]
+ : [buildFlagCalledTotalVolumeChart(options), buildFlagCalledUniqueCallersChart(options)]
if (hasEnrichedAnalytics) {
charts.push(...buildEnrichedUsageCharts(options))
}
diff --git a/frontend/src/scenes/feature-flags/featureFlagUsageQueries.test.ts b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.test.ts
index 034b0ad9a0d0..a898bcf00104 100644
--- a/frontend/src/scenes/feature-flags/featureFlagUsageQueries.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.test.ts
@@ -1,14 +1,29 @@
+import { dateMapping } from 'lib/utils/dateFilters'
+
import { Noun } from '~/models/groupsModel'
-import { DateRange } from '~/queries/schema/schema-general'
+import { DataVisualizationNode, DateRange, InsightVizNode, TrendsQuery } from '~/queries/schema/schema-general'
import {
buildEnrichedUsageCharts,
buildFlagCalledTotalVolumeChart,
buildFlagCalledUniqueCallersChart,
+ buildFlagEvaluationsTotalVolumeChart,
+ buildFlagEvaluationsUniqueCallersChart,
+ clampToFlagEvaluationsRetention,
+ FLAG_EVALUATIONS_RETENTION_DAYS,
+ FLAG_EVALUATIONS_VOLUME_ROW_LIMIT,
+ flagEvaluationsDateOptions,
FlagUsageChart,
FlagUsageQueryOptions,
} from './featureFlagUsageQueries'
+type TrendsUsageChart = FlagUsageChart<InsightVizNode<TrendsQuery>>
+
+const flagEvaluationsBuilders: [string, (options: FlagUsageQueryOptions) => FlagUsageChart<DataVisualizationNode>][] = [
+ ['buildFlagEvaluationsTotalVolumeChart', buildFlagEvaluationsTotalVolumeChart],
+ ['buildFlagEvaluationsUniqueCallersChart', buildFlagEvaluationsUniqueCallersChart],
+]
+
const dateRange: DateRange = { date_from: '-30d', date_to: null }
const userNoun: Noun = { singular: 'user', plural: 'users' }
@@ -28,12 +43,12 @@ const groupFlagOptions: FlagUsageQueryOptions = {
describe('featureFlagUsageQueries', () => {
it.each([
- ['buildFlagCalledTotalVolumeChart', (): FlagUsageChart => buildFlagCalledTotalVolumeChart(personFlagOptions)],
+ ['buildFlagCalledTotalVolumeChart', (): TrendsUsageChart => buildFlagCalledTotalVolumeChart(personFlagOptions)],
[
'buildFlagCalledUniqueCallersChart',
- (): FlagUsageChart => buildFlagCalledUniqueCallersChart(personFlagOptions),
+ (): TrendsUsageChart => buildFlagCalledUniqueCallersChart(personFlagOptions),
],
- ['buildEnrichedUsageCharts', (): FlagUsageChart => buildEnrichedUsageCharts(personFlagOptions)[0]],
+ ['buildEnrichedUsageCharts', (): TrendsUsageChart => buildEnrichedUsageCharts(personFlagOptions)[0]],
])('%s builds an unsaved TrendsQuery with the shared envelope', (_name, build) => {
const { query } = build()
@@ -77,11 +92,11 @@ describe('featureFlagUsageQueries', () => {
it.each([
[
'buildFlagCalledTotalVolumeChart',
- (options: FlagUsageQueryOptions): FlagUsageChart => buildFlagCalledTotalVolumeChart(options),
+ (options: FlagUsageQueryOptions): TrendsUsageChart => buildFlagCalledTotalVolumeChart(options),
],
[
'buildFlagCalledUniqueCallersChart',
- (options: FlagUsageQueryOptions): FlagUsageChart => buildFlagCalledUniqueCallersChart(options),
+ (options: FlagUsageQueryOptions): TrendsUsageChart => buildFlagCalledUniqueCallersChart(options),
],
])('%s filters on $feature_flag, adding a $group_N is_set filter only for group flags', (_name, build) => {
expect(build(personFlagOptions).query.source.properties).toEqual([
@@ -136,6 +151,128 @@ describe('featureFlagUsageQueries', () => {
])
})
+ it.each(flagEvaluationsBuilders)('%s reads flag_evaluations over the tab date range', (_name, build) => {
+ const { query } = build(personFlagOptions)
+
+ expect(query.kind).toEqual('DataVisualizationNode')
+ expect(query.source.kind).toEqual('HogQLQuery')
+ expect(query.source.query).toContain('FROM posthog.flag_evaluations')
+ expect(query.source.query).toContain("flag_key = 'alpha-feature'")
+ // Without the date filter the query scans the whole retention window whatever range the
+ // tab shows.
+ expect(query.source.query).toContain('{filters(timestamp AS timestamp)}')
+ expect(query.source.filters).toEqual({ dateRange })
+ // HogQLQueryRunner compiles every placeholder in `values` while it parses, and
+ // `{filters(...)}` is not compilable, so carrying both fails the query at run time. The
+ // unit tests read the query string alone, so only this assertion catches a re-added value.
+ expect(query.source.values).toBeUndefined()
+ // The backend cannot infer a product for this table, and an untagged ClickHouse query
+ // raises under DEBUG.
+ expect(query.source.tags).toEqual({ productKey: 'feature_flags' })
+ })
+
+ it.each(flagEvaluationsBuilders)('%s escapes a quote in the flag key', (_name, build) => {
+ // The flag key reaches the SQL as a literal, so an unescaped quote closes the string and
+ // the rest of the key parses as HogQL.
+ const { query } = build({ ...personFlagOptions, flagKey: "o'brien-flag" })
+
+ expect(query.source.query).toContain("flag_key = 'o\\'brien-flag'")
+ })
+
+ it('buildFlagEvaluationsTotalVolumeChart breaks the line graph down by response over the date range interval', () => {
+ const { query } = buildFlagEvaluationsTotalVolumeChart({
+ ...personFlagOptions,
+ dateRange: { date_from: '-24h', date_to: null },
+ })
+
+ expect(query.display).toEqual('ActionsLineGraph')
+ expect(query.source.query).toContain("dateTrunc('hour', timestamp) AS period")
+ expect(query.chartSettings).toEqual({
+ xAxis: { column: 'period' },
+ yAxis: [{ column: 'total' }],
+ seriesBreakdownColumn: 'variant',
+ showNullsAsZero: true,
+ })
+ })
+
+ it('buildFlagEvaluationsTotalVolumeChart limits past the rows the widest supported window returns', () => {
+ // HogQL falls back to 100 rows without a LIMIT, and 90 days across two variants already
+ // passes that, so the newest periods would drop off the end of a period-ascending chart.
+ const { query } = buildFlagEvaluationsTotalVolumeChart({
+ ...personFlagOptions,
+ dateRange: { date_from: `-${FLAG_EVALUATIONS_RETENTION_DAYS}d`, date_to: null },
+ })
+
+ expect(query.source.query).toContain(`LIMIT ${FLAG_EVALUATIONS_VOLUME_ROW_LIMIT}`)
+ expect(FLAG_EVALUATIONS_VOLUME_ROW_LIMIT).toBeGreaterThan(FLAG_EVALUATIONS_RETENTION_DAYS * 2)
+ })
+
+ it.each([
+ ['-24h', 'hour'],
+ ['-30d', 'day'],
+ ])('buildFlagEvaluationsTotalVolumeChart fills the quiet %s periods of every variant', (date_from, interval) => {
+ // GROUP BY skips a period with no evaluations, which would read as a gap in the line
+ // rather than the drop to zero it is. The fill step has to match the dateTrunc unit.
+ const { query } = buildFlagEvaluationsTotalVolumeChart({
+ ...personFlagOptions,
+ dateRange: { date_from, date_to: null },
+ })
+
+ expect(query.source.query).toContain(`ORDER BY variant, period WITH FILL STEP INTERVAL 1 ${interval}`)
+ // The fill reorders rows by variant, so the outer query has to put them back in time order.
+ expect(
+ query.source.query.trimEnd().endsWith(`ORDER BY period\nLIMIT ${FLAG_EVALUATIONS_VOLUME_ROW_LIMIT}`)
+ ).toBe(true)
+ })
+
+ it.each([
+ ['person flag', personFlagOptions, 'uniq(person_id)', false],
+ ['group flag', groupFlagOptions, 'uniq(`$group_0`)', true],
+ ])(
+ 'buildFlagEvaluationsUniqueCallersChart counts the callers of a %s',
+ (_name, options, expectedAggregation, expectsGroupFilter) => {
+ const { query } = buildFlagEvaluationsUniqueCallersChart(options)
+
+ expect(query.source.query).toContain(expectedAggregation)
+ expect(query.source.query.includes("`$group_0` != ''")).toEqual(expectsGroupFilter)
+ }
+ )
+
+ it.each([
+ [
+ 'a range inside the window is left alone',
+ { date_from: '-30d', date_to: null },
+ { date_from: '-30d', date_to: null },
+ ],
+ ['the window itself is left alone', { date_from: '-90d', date_to: null }, { date_from: '-90d', date_to: null }],
+ ['a longer range is pulled back', { date_from: '-180d', date_to: null }, { date_from: '-90d', date_to: null }],
+ ['all time is pulled back', { date_from: 'all', date_to: null }, { date_from: '-90d', date_to: null }],
+ ['a missing start is pulled back', { date_from: null, date_to: null }, { date_from: '-90d', date_to: null }],
+ [
+ 'a range that ends before the window runs to now instead of backwards',
+ { date_from: '-200d', date_to: '-150d' },
+ { date_from: '-90d', date_to: null },
+ ],
+ [
+ 'an end inside the window is kept',
+ { date_from: '-200d', date_to: '-10d' },
+ { date_from: '-90d', date_to: '-10d' },
+ ],
+ ])('clampToFlagEvaluationsRetention: %s', (_name, dateRange, expected) => {
+ expect(clampToFlagEvaluationsRetention(dateRange)).toEqual(expected)
+ })
+
+ it('flagEvaluationsDateOptions offers no preset older than the retention window', () => {
+ const keys = flagEvaluationsDateOptions().map((option) => option.key)
+
+ expect(keys).toContain('Last 90 days')
+ expect(keys).toContain('Last 30 days')
+ expect(keys).not.toContain('Last 180 days')
+ expect(keys).not.toContain('All time')
+ // The custom entry carries no range of its own, so it must survive the filter.
+ expect(keys).toContain(dateMapping[0].key)
+ })
+
it('buildEnrichedUsageCharts filters on the bare feature_flag property key with no breakdown', () => {
// A wrong property key here silently produces an empty chart, so pin the exact key.
for (const chart of buildEnrichedUsageCharts(personFlagOptions)) {
diff --git a/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts
index dca7b0f97d69..eb5858732c89 100644
--- a/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts
@@ -5,10 +5,13 @@
// 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 { getDefaultInterval } from 'lib/utils/dateFilters'
+import { dayjs } from 'lib/dayjs'
+import { dateMapping, dateStringToDayJs, getDefaultInterval } from 'lib/utils/dateFilters'
import { Noun } from '~/models/groupsModel'
import {
+ ChartSettings,
+ DataVisualizationNode,
DateRange,
EventsNode,
InsightVizNode,
@@ -16,11 +19,12 @@ import {
ProductKey,
TrendsQuery,
} from '~/queries/schema/schema-general'
-import { setLatestVersionsOnQuery } from '~/queries/utils'
+import { escapeHogQLString, setLatestVersionsOnQuery } from '~/queries/utils'
import {
AnyPropertyFilter,
BaseMathType,
ChartDisplayType,
+ DateMappingOption,
GroupMathType,
GroupTypeIndex,
PropertyFilterType,
@@ -37,11 +41,13 @@ export interface FlagUsageQueryOptions {
export const DEFAULT_USAGE_DATE_RANGE: DateRange = { date_from: '-30d', date_to: null }
-export interface FlagUsageChart {
+export type FlagUsageQuery = InsightVizNode<TrendsQuery> | DataVisualizationNode
+
+export interface FlagUsageChart<Q extends FlagUsageQuery = FlagUsageQuery> {
key: string
title: string
description: string
- query: InsightVizNode<TrendsQuery>
+ query: Q
}
function flagCalledProperties({ flagKey, aggregationGroupTypeIndex }: FlagUsageQueryOptions): AnyPropertyFilter[] {
@@ -83,7 +89,9 @@ function buildUsageQuery(
})
}
-export function buildFlagCalledTotalVolumeChart(options: FlagUsageQueryOptions): FlagUsageChart {
+export function buildFlagCalledTotalVolumeChart(
+ options: FlagUsageQueryOptions
+): FlagUsageChart<InsightVizNode<TrendsQuery>> {
return {
key: 'total-volume',
title: 'Feature flag called total volume',
@@ -100,7 +108,9 @@ export function buildFlagCalledTotalVolumeChart(options: FlagUsageQueryOptions):
}
}
-export function buildFlagCalledUniqueCallersChart(options: FlagUsageQueryOptions): FlagUsageChart {
+export function buildFlagCalledUniqueCallersChart(
+ options: FlagUsageQueryOptions
+): FlagUsageChart<InsightVizNode<TrendsQuery>> {
const mathProperties: Pick<EventsNode, 'math' | 'math_group_type_index'> =
options.aggregationGroupTypeIndex != null
? {
@@ -133,7 +143,7 @@ export function buildFlagCalledUniqueCallersChart(options: FlagUsageQueryOptions
export function buildEnrichedUsageCharts(
options: Pick<FlagUsageQueryOptions, 'flagKey' | 'dateRange'>
-): FlagUsageChart[] {
+): FlagUsageChart<InsightVizNode<TrendsQuery>>[] {
return [
{
key: 'feature-view',
@@ -171,6 +181,167 @@ function enrichedSeries(event: '$feature_view' | '$feature_interaction', seriesL
]
}
+// Not a root table, so the `posthog.` prefix is part of the name. An organization 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'
+
+/** How long a row stays in flag_evaluations. The events table keeps $feature_flag_called forever. */
+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.
+function earliestRetainedDay(): dayjs.Dayjs {
+ return dayjs.utc().startOf('day').subtract(FLAG_EVALUATIONS_RETENTION_DAYS, 'day')
+}
+
+/** 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 {
+ const earliest = earliestRetainedDay()
+ const dateFrom = dateStringToDayJs(dateRange.date_from ?? null)
+ // A null start is "all time", which reaches further than any retained day.
+ if (dateFrom && !dateFrom.isBefore(earliest)) {
+ return dateRange
+ }
+ const dateTo = dateStringToDayJs(dateRange.date_to ?? null)
+ return {
+ date_from: `-${FLAG_EVALUATIONS_RETENTION_DAYS}d`,
+ // A range that ended before the window holds nothing, and the clamped start would sit
+ // after its end. Run to now instead of showing a backwards range.
+ date_to: dateTo?.isBefore(earliest) ? null : (dateRange.date_to ?? null),
+ }
+}
+
+/** The presets that stay inside the retention window, plus the custom-range entry. */
+export function flagEvaluationsDateOptions(): DateMappingOption[] {
+ const earliest = earliestRetainedDay()
+ return dateMapping.filter(({ values }) => {
+ const dateFrom = values[0]
+ if (dateFrom === undefined) {
+ return true
+ }
+ const parsed = dateStringToDayJs(dateFrom)
+ return !!parsed && !parsed.isBefore(earliest)
+ })
+}
+
+function flagEvaluationsConditions(
+ { aggregationGroupTypeIndex, flagKey }: FlagUsageQueryOptions,
+ indent: string = ' '
+): string {
+ // The flag key is an escaped literal rather than a placeholder because HogQLQueryRunner compiles
+ // every placeholder while it parses, and `{filters(...)}` is not compilable, so a query that
+ // carries both fails before it reaches replace_filters.
+ // `{filters(... AS timestamp)}` binds the tab's date range to this table's own timestamp column.
+ // The bare `{filters}` placeholder only knows a fixed set of tables, and this is not one of them.
+ const conditions = [`flag_key = ${escapeHogQLString(flagKey)}`, '{filters(timestamp AS timestamp)}']
+ if (aggregationGroupTypeIndex != null) {
+ // The group columns are non-nullable and hold an empty string when the evaluation
+ // carried no group, so this is the equivalent of the events path's is_set filter.
+ conditions.push(`\`$group_${aggregationGroupTypeIndex}\` != ''`)
+ }
+ return conditions.join(`\n${indent}AND `)
+}
+
+function buildFlagEvaluationsQuery(
+ options: FlagUsageQueryOptions,
+ query: string,
+ display: ChartDisplayType,
+ chartSettings?: ChartSettings
+): DataVisualizationNode {
+ const { dateRange } = options
+ return setLatestVersionsOnQuery({
+ kind: NodeKind.DataVisualizationNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query,
+ filters: { dateRange },
+ // The backend infers a product from the event or table a query reads, and knows neither
+ // posthog.flag_evaluations nor this scene, so the tag has to be explicit. An untagged
+ // ClickHouse query raises under DEBUG and records with no product in production.
+ tags: { productKey: ProductKey.FEATURE_FLAGS },
+ },
+ display,
+ chartSettings,
+ })
+}
+
+/**
+ * A HogQL query without a LIMIT falls back to 100 rows, which would cut the newest periods off a
+ * period-ascending chart. The volume query returns one row per period per variant: at most 90 days
+ * of the retention window at the shortest interval the presets reach, times the 50 series the
+ * breakdown renders.
+ */
+export const FLAG_EVALUATIONS_VOLUME_ROW_LIMIT = 10000
+
+export function buildFlagEvaluationsTotalVolumeChart(
+ options: FlagUsageQueryOptions
+): FlagUsageChart<DataVisualizationNode> {
+ // dateTrunc needs a literal unit, so the interval is written into the query rather than
+ // passed as a value. getDefaultInterval only returns members of IntervalType.
+ const interval = getDefaultInterval(options.dateRange.date_from ?? null, options.dateRange.date_to ?? null)
+ return {
+ key: 'total-volume',
+ title: 'Feature flag called total volume',
+ description: `Shows the number of total calls made on feature flag with key: ${options.flagKey}`,
+ query: buildFlagEvaluationsQuery(
+ options,
+ // GROUP BY only emits the periods that hold evaluations, and the chart builds its time
+ // axis from the rows it gets back, so a quiet period would vanish instead of reading
+ // zero. WITH FILL puts the missing periods back for each variant, and the outer query
+ // restores the ascending period order the axis needs.
+ `SELECT period, variant, total
+FROM (
+ SELECT
+ dateTrunc('${interval}', timestamp) AS period,
+ response AS variant,
+ count() AS total
+ FROM ${FLAG_EVALUATIONS_TABLE}
+ WHERE ${flagEvaluationsConditions(options, ' ')}
+ GROUP BY period, variant
+ ORDER BY variant, period WITH FILL STEP INTERVAL 1 ${interval}
+)
+ORDER BY period
+LIMIT ${FLAG_EVALUATIONS_VOLUME_ROW_LIMIT}`,
+ ChartDisplayType.ActionsLineGraph,
+ {
+ xAxis: { column: 'period' },
+ yAxis: [{ column: 'total' }],
+ seriesBreakdownColumn: 'variant',
+ // A variant that starts or stops mid-range sits outside its own filled span.
+ showNullsAsZero: true,
+ }
+ ),
+ }
+}
+
+export function buildFlagEvaluationsUniqueCallersChart(
+ options: FlagUsageQueryOptions
+): FlagUsageChart<DataVisualizationNode> {
+ const { aggregationGroupTypeIndex, callerNoun, flagKey } = options
+ // `person_id` is not the column the row stores. HogQL resolves it through
+ // person_distinct_id_overrides, so a person who evaluated the flag before and after logging in
+ // counts once. That join is bounded by neither the date range nor the flag key, which means the
+ // retention clamp does not make this query cheaper.
+ const caller = aggregationGroupTypeIndex != null ? `\`$group_${aggregationGroupTypeIndex}\`` : 'person_id'
+ return {
+ key: 'unique-callers',
+ title: `Feature flag calls made by unique ${callerNoun.plural} per variant`,
+ description: `Shows the number of unique ${callerNoun.singular} calls made on feature flag per variant with key: ${flagKey}`,
+ query: buildFlagEvaluationsQuery(
+ options,
+ `SELECT
+ response AS \`Variant\`,
+ uniq(${caller}) AS \`Unique callers\`
+FROM ${FLAG_EVALUATIONS_TABLE}
+WHERE ${flagEvaluationsConditions(options)}
+GROUP BY \`Variant\`
+ORDER BY \`Unique callers\` DESC`,
+ ChartDisplayType.ActionsTable
+ ),
+ }
+}
+
// Enriched analytics events carry the flag key in the bare `feature_flag` property,
// unlike $feature_flag_called which uses `$feature_flag`.
function enrichedProperties(flagKey: string): AnyPropertyFilter[] {