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): show rebuild banners on artifacts that read flag calls (#113691)

Phil Haack90d137cdefef
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 925cdb636472..6ed5eabc30f2 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -11892,6 +11892,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-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:
+ hash: v1.k794b7964.c1bca29126f3f201df46989d83af5e777ad42f21aba60febca75e2ded1a00d6e.WHUf4o3J7Uo7jwnFaGNXQgqa9jMdohuIOo1eSFbW9a4
scenes-app-insights-insight-quick-start--default--dark:
hash: v1.k794b7964.f190c463ee799e93ea5d408200712776460a5a9a920977e2b7a85348350fa43b.dcN7n63RW9QEXstFsPgnAaKodbV6piSN7PMhBuHkaGc
scenes-app-insights-insight-quick-start--default--light:
diff --git a/frontend/src/lib/components/FlagCalledRebuildBanner/FlagCalledRebuildBanner.stories.tsx b/frontend/src/lib/components/FlagCalledRebuildBanner/FlagCalledRebuildBanner.stories.tsx
new file mode 100644
index 000000000000..88b1ebdbe531
--- /dev/null
+++ b/frontend/src/lib/components/FlagCalledRebuildBanner/FlagCalledRebuildBanner.stories.tsx
@@ -0,0 +1,75 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import { Meta, StoryObj } from '@storybook/react'
+import { useActions } from 'kea'
+import { useLayoutEffect, useState } from 'react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { createInsightStory } from 'scenes/insights/__mocks__/createInsightScene'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { FlagEvaluationsModeEnumApi } from '~/generated/core/api.schemas'
+import { mswDecorator } from '~/mocks/browser'
+import { InsightVizNode, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'
+import { InsightModel } from '~/types'
+
+import trendsLine from '../../../mocks/fixtures/api/projects/team_id/insights/trendsLine.json'
+
+const team = { ...MOCK_DEFAULT_TEAM, flag_evaluations_mode: FlagEvaluationsModeEnumApi.Number1 }
+
+const fixture = trendsLine as unknown as Partial<InsightModel> & { query: InsightVizNode<TrendsQuery> }
+const query: InsightVizNode<TrendsQuery> = {
+ ...fixture.query,
+ source: {
+ ...fixture.query.source,
+ series: [{ kind: NodeKind.EventsNode, event: '$feature_flag_called', name: '$feature_flag_called' }],
+ },
+}
+const flagCallsInsight: Partial<InsightModel> = { ...fixture, query }
+
+type Story = StoryObj<{}>
+const meta: Meta = {
+ title: 'Scenes-App/Insights/Flag Called Rebuild Banner',
+ parameters: {
+ layout: 'fullscreen',
+ featureFlags: [FEATURE_FLAGS.FLAG_CALLED_MOVE_NOTICES],
+ testOptions: {
+ snapshotBrowsers: ['chromium'],
+ // Narrow enough that the banner text and its action wrap, as they do with the side panel open.
+ viewport: { width: 900, height: 720 },
+ },
+ viewMode: 'story',
+ mockDate: '2026-10-07T12:00:00Z',
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/environments/@current/': team,
+ '/api/environments/:team_id/': team,
+ },
+ // The default handlers answer these with the mode 0 team, which would hide the banner after a write.
+ patch: {
+ '/api/environments/:team_id/add_product_intent/': team,
+ '/api/environments/:team_id/': team,
+ },
+ }),
+ ],
+}
+export default meta
+
+const FlagCallsInsightScene = createInsightStory(flagCallsInsight) as unknown as () => JSX.Element
+
+// The app context bootstraps the default team on mode 0, so the story loads the mode 1 team before the scene mounts.
+function InsightOnFlagCallsStory(): JSX.Element | null {
+ const { loadCurrentTeamSuccess } = useActions(teamLogic)
+ const [ready, setReady] = useState(false)
+
+ useLayoutEffect(() => {
+ loadCurrentTeamSuccess(team)
+ setReady(true)
+ }, [loadCurrentTeamSuccess])
+
+ return ready ? <FlagCallsInsightScene /> : null
+}
+
+export const InsightOnFlagCalls: Story = { render: () => <InsightOnFlagCallsStory /> }
diff --git a/frontend/src/lib/components/FlagCalledRebuildBanner/FlagCalledRebuildBanner.tsx b/frontend/src/lib/components/FlagCalledRebuildBanner/FlagCalledRebuildBanner.tsx
new file mode 100644
index 000000000000..4e8e524f84bc
--- /dev/null
+++ b/frontend/src/lib/components/FlagCalledRebuildBanner/FlagCalledRebuildBanner.tsx
@@ -0,0 +1,58 @@
+import { useActions, useValues } from 'kea'
+import { useEffect } from 'react'
+
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+import { LemonBannerAction } from 'lib/lemon-ui/LemonBanner/LemonBanner'
+import { Link } from 'lib/lemon-ui/Link'
+
+import { FlagCalledArtifactType, flagCalledRebuildBannerLogic } from './flagCalledRebuildBannerLogic'
+
+interface FlagCalledRebuildBannerProps {
+ artifactType: FlagCalledArtifactType
+ readsFlagCalls: boolean
+ action?: LemonBannerAction
+ className?: string
+ children: React.ReactNode
+}
+
+// Remove once every organization is on flag_evaluations_mode 2 and no saved artifact matches (#88126).
+// Delete this folder and every component that renders it together. Other move warnings read
+// FEATURE_FLAGS.FLAG_CALLED_MOVE_NOTICES, so delete the flag only after they are gone too.
+export function FlagCalledRebuildBanner({
+ artifactType,
+ readsFlagCalls,
+ action,
+ className,
+ children,
+}: FlagCalledRebuildBannerProps): JSX.Element | null {
+ const { bannersEnabled, announcementUrl } = useValues(flagCalledRebuildBannerLogic)
+ const { reportBannerShown } = useActions(flagCalledRebuildBannerLogic)
+ const shown = bannersEnabled && readsFlagCalls
+
+ useEffect(() => {
+ if (shown) {
+ reportBannerShown(artifactType)
+ }
+ }, [shown, artifactType, reportBannerShown])
+
+ if (!shown) {
+ return null
+ }
+ const announcementAction: LemonBannerAction | undefined = announcementUrl
+ ? { children: 'Learn more', to: announcementUrl, targetBlank: true }
+ : undefined
+ return (
+ <LemonBanner type="warning" action={action ?? announcementAction} className={className}>
+ {children}
+ {/* A banner that already has a button links the announcement at the end of its text instead. */}
+ {action && announcementUrl && (
+ <>
+ {' '}
+ <Link to={announcementUrl} target="_blank">
+ Learn more
+ </Link>
+ </>
+ )}
+ </LemonBanner>
+ )
+}
diff --git a/frontend/src/lib/components/FlagCalledRebuildBanner/flagCalledDependencies.test.ts b/frontend/src/lib/components/FlagCalledRebuildBanner/flagCalledDependencies.test.ts
new file mode 100644
index 000000000000..c36d8f68b0e7
--- /dev/null
+++ b/frontend/src/lib/components/FlagCalledRebuildBanner/flagCalledDependencies.test.ts
@@ -0,0 +1,236 @@
+import {
+ actionOnlyReadsFlagCalls,
+ actionReadsFlagCalls,
+ cohortReadsFlagCalls,
+ insightReadsFlagCalls,
+} from 'lib/components/FlagCalledRebuildBanner/flagCalledDependencies'
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { BehavioralFilterKey } from 'scenes/cohorts/CohortFilters/types'
+
+import {
+ DataTableNode,
+ DataVisualizationNode,
+ DataWarehouseNode,
+ EventsNode,
+ FunnelExclusion,
+ FunnelsQuery,
+ GroupNode,
+ InsightQueryNode,
+ InsightVizNode,
+ Node,
+ NodeKind,
+ RetentionQuery,
+ TrendsQuery,
+ TrendsQuerySeriesNode,
+} from '~/queries/schema/schema-general'
+import {
+ ActionType,
+ AnyCohortCriteriaType,
+ BehavioralEventType,
+ CohortCriteriaGroupFilter,
+ CohortType,
+ FilterLogicalOperator,
+ RetentionEntity,
+ TimeUnitType,
+} from '~/types'
+
+const FLAG_CALLED = '$feature_flag_called'
+const ACTION_ID = 5
+
+const PAGEVIEW_ACTION = { id: ACTION_ID, steps: [{ event: '$pageview' }] } as ActionType
+
+const events = (event: string | null): EventsNode => ({ kind: NodeKind.EventsNode, event })
+const trends = (series: TrendsQuerySeriesNode[]): TrendsQuery => ({ kind: NodeKind.TrendsQuery, series })
+const viz = <T extends InsightQueryNode>(source: T): InsightVizNode<T> => ({ kind: NodeKind.InsightVizNode, source })
+
+const funnelExcluding = (exclusion: FunnelExclusion): InsightVizNode<FunnelsQuery> =>
+ viz({
+ kind: NodeKind.FunnelsQuery,
+ series: [events('$pageview'), events('signed_up')],
+ funnelsFilter: { exclusions: [exclusion] },
+ })
+
+const retention = (targetEntity: RetentionEntity, returningEntity: RetentionEntity): InsightVizNode<RetentionQuery> =>
+ viz({ kind: NodeKind.RetentionQuery, retentionFilter: { targetEntity, returningEntity } })
+
+const FLAG_CALLED_ENTITY: RetentionEntity = { id: FLAG_CALLED, type: 'events' }
+const PAGEVIEW_ENTITY: RetentionEntity = { id: '$pageview', type: 'events' }
+
+const groupOf = (nodes: GroupNode['nodes']): GroupNode => ({
+ kind: NodeKind.GroupNode,
+ operator: FilterLogicalOperator.Or,
+ nodes,
+})
+
+// The insights picker from #112991 builds this series to chart flag calls from flag_evaluations.
+const FLAG_EVALUATIONS_SERIES: DataWarehouseNode = {
+ 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 SQL_INSIGHT: DataVisualizationNode = {
+ kind: NodeKind.DataVisualizationNode,
+ source: { kind: NodeKind.HogQLQuery, query: `SELECT count() FROM events WHERE event = '${FLAG_CALLED}'` },
+}
+
+const EVENTS_LIST: DataTableNode = {
+ kind: NodeKind.DataTableNode,
+ source: { kind: NodeKind.EventsQuery, select: ['*'], event: FLAG_CALLED },
+}
+
+const performed = (key: string, eventType: TaxonomicFilterGroupType): AnyCohortCriteriaType => ({
+ type: BehavioralFilterKey.Behavioral,
+ value: BehavioralEventType.PerformEvent,
+ key,
+ event_type: eventType,
+ time_value: 30,
+ time_interval: TimeUnitType.Day,
+})
+
+const followedBy = (seqEvent: string, seqEventType: TaxonomicFilterGroupType): AnyCohortCriteriaType => ({
+ type: BehavioralFilterKey.Behavioral,
+ value: BehavioralEventType.PerformSequenceEvents,
+ key: '$pageview',
+ event_type: TaxonomicFilterGroupType.Events,
+ time_value: 30,
+ time_interval: TimeUnitType.Day,
+ seq_event: seqEvent,
+ seq_event_type: seqEventType,
+ seq_time_value: 15,
+ seq_time_interval: TimeUnitType.Day,
+})
+
+const and = (values: AnyCohortCriteriaType[] | CohortCriteriaGroupFilter[]): CohortCriteriaGroupFilter => ({
+ type: FilterLogicalOperator.And,
+ values,
+})
+
+const dynamicCohort = (...groups: CohortCriteriaGroupFilter[]): CohortType => ({
+ id: 1,
+ is_static: false,
+ groups: [],
+ filters: { properties: { type: FilterLogicalOperator.Or, values: groups } },
+})
+
+describe('flag called dependencies', () => {
+ describe('insights', () => {
+ it.each<[string, boolean, Node | null]>([
+ // Event nodes match on `event`.
+ ['an events series on $feature_flag_called', true, viz(trends([events(FLAG_CALLED)]))],
+ [
+ '$feature_flag_called inside a series group',
+ true,
+ viz(trends([groupOf([events('$pageview'), events(FLAG_CALLED)])])),
+ ],
+ [
+ 'a funnel exclusion on $feature_flag_called',
+ true,
+ funnelExcluding({ ...events(FLAG_CALLED), funnelFromStep: 0, funnelToStep: 1 }),
+ ],
+ // Retention entities name their event in `id`.
+ ['a retention target on $feature_flag_called', true, retention(FLAG_CALLED_ENTITY, PAGEVIEW_ENTITY)],
+ [
+ 'a retention returning entity on $feature_flag_called',
+ true,
+ retention(PAGEVIEW_ENTITY, FLAG_CALLED_ENTITY),
+ ],
+ // The rebuilt series shows the event's label as its name, so a match on `name` flags the fixed insight.
+ ['the flag_evaluations series that replaces it', false, viz(trends([FLAG_EVALUATIONS_SERIES]))],
+ // An all-events series keeps working. Its count only drops by the flag calls.
+ ['an all-events series', false, viz(trends([events(null)]))],
+ ['a series on another event', false, viz(trends([events('$pageview')]))],
+ // A legacy insight saved with only `filters` arrives with a null query.
+ ['no query', false, null],
+ // Saved SQL insights get their own warning.
+ ['a SQL query on $feature_flag_called', false, SQL_INSIGHT],
+ // The events query runner already reads saved events lists from flag_evaluations.
+ ['an events list filtered to $feature_flag_called', false, EVENTS_LIST],
+ ])('an insight with %s reads flag calls: %s', (_label, expected, query) => {
+ expect(insightReadsFlagCalls(query)).toBe(expected)
+ })
+ })
+
+ describe('cohorts', () => {
+ it.each<[string, boolean, CohortType]>([
+ // Behavioral criteria name an event in `key`. A sequence names its second event in `seq_event`.
+ [
+ 'a performed-event criterion on $feature_flag_called',
+ true,
+ dynamicCohort(and([performed(FLAG_CALLED, TaxonomicFilterGroupType.Events)])),
+ ],
+ [
+ 'a sequence followed by $feature_flag_called',
+ true,
+ dynamicCohort(and([followedBy(FLAG_CALLED, TaxonomicFilterGroupType.Events)])),
+ ],
+ // The API accepts groups nested deeper than the editor builds them.
+ [
+ 'a $feature_flag_called criterion in a nested group after another group',
+ true,
+ dynamicCohort(
+ and([performed('$pageview', TaxonomicFilterGroupType.Events)]),
+ and([and([performed(FLAG_CALLED, TaxonomicFilterGroupType.Events)])])
+ ),
+ ],
+ [
+ 'criteria on other events only',
+ false,
+ dynamicCohort(
+ and([
+ performed('$pageview', TaxonomicFilterGroupType.Events),
+ followedBy('signed_up', TaxonomicFilterGroupType.Events),
+ ])
+ ),
+ ],
+ // A static cohort is a snapshot, so it never adds people from new flag calls.
+ [
+ 'static membership and a $feature_flag_called criterion',
+ false,
+ {
+ ...dynamicCohort(and([performed(FLAG_CALLED, TaxonomicFilterGroupType.Events)])),
+ is_static: true,
+ },
+ ],
+ // An experiment's exposure cohort counts the event on purpose. Its criterion belongs to the experiment.
+ [
+ 'experiment exposure management and a $feature_flag_called criterion',
+ false,
+ {
+ ...dynamicCohort(and([performed(FLAG_CALLED, TaxonomicFilterGroupType.Events)])),
+ experiment_set: [7],
+ },
+ ],
+ ])('a cohort with %s reads flag calls: %s', (_label, expected, cohort) => {
+ expect(cohortReadsFlagCalls(cohort)).toBe(expected)
+ })
+ })
+
+ describe('actions', () => {
+ it.each<[string, boolean, boolean, ActionType]>([
+ [
+ 'a $feature_flag_called step after another step',
+ true,
+ false,
+ { id: ACTION_ID, steps: [{ event: '$pageview' }, { event: FLAG_CALLED }] } as ActionType,
+ ],
+ [
+ 'only $feature_flag_called steps',
+ true,
+ true,
+ { id: ACTION_ID, steps: [{ event: FLAG_CALLED }, { event: FLAG_CALLED }] } as ActionType,
+ ],
+ ['steps on other events only', false, false, PAGEVIEW_ACTION],
+ ])(
+ 'an action with %s reads flag calls: %s, only flag calls: %s',
+ (_label, readsFlagCalls, onlyFlagCalls, actionWithSteps) => {
+ expect(actionReadsFlagCalls(actionWithSteps)).toBe(readsFlagCalls)
+ expect(actionOnlyReadsFlagCalls(actionWithSteps)).toBe(onlyFlagCalls)
+ }
+ )
+ })
+})
diff --git a/frontend/src/lib/components/FlagCalledRebuildBanner/flagCalledDependencies.ts b/frontend/src/lib/components/FlagCalledRebuildBanner/flagCalledDependencies.ts
new file mode 100644
index 000000000000..ad4cf02a7644
--- /dev/null
+++ b/frontend/src/lib/components/FlagCalledRebuildBanner/flagCalledDependencies.ts
@@ -0,0 +1,89 @@
+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 { Node } from '~/queries/schema/schema-general'
+import {
+ isEventsNode,
+ isFunnelsQuery,
+ isGroupNode,
+ isInsightQueryWithSeries,
+ isInsightVizNode,
+ isRetentionQuery,
+} from '~/queries/utils'
+import {
+ ActionType,
+ AnyCohortCriteriaType,
+ CohortCriteriaGroupFilter,
+ CohortType,
+ EntityTypes,
+ RetentionEntity,
+} from '~/types'
+
+// Matches on the event key, never the display name. A flag_evaluations series carries the same name.
+function entityReadsFlagCalls(node: Record<string, any> | null | undefined): boolean {
+ if (isEventsNode(node)) {
+ return node.event === FEATURE_FLAG_CALLED_EVENT
+ }
+ return isGroupNode(node) && node.nodes.some(entityReadsFlagCalls)
+}
+
+function retentionEntityReadsFlagCalls(entity: RetentionEntity | undefined): boolean {
+ return entity?.type === EntityTypes.EVENTS && entity.id === FEATURE_FLAG_CALLED_EVENT
+}
+
+/**
+ * Reads the insight's `query` only. An insight saved with only legacy `filters` has no query and renders blank.
+ * An "All events" series is left out, because its count only drops by the flag calls and keeps working.
+ * A series on an action is left out, because few saved insights reach the event through an action.
+ */
+export function insightReadsFlagCalls(query: Node | null | undefined): boolean {
+ const source = isInsightVizNode(query) ? query.source : (query ?? undefined)
+ if (isRetentionQuery(source)) {
+ return (
+ retentionEntityReadsFlagCalls(source.retentionFilter?.targetEntity) ||
+ retentionEntityReadsFlagCalls(source.retentionFilter?.returningEntity)
+ )
+ }
+ if (!isInsightQueryWithSeries(source)) {
+ return false
+ }
+ const exclusions = isFunnelsQuery(source) ? (source.funnelsFilter?.exclusions ?? []) : []
+ return [...source.series, ...exclusions].some(entityReadsFlagCalls)
+}
+
+export function actionReadsFlagCalls(action: Pick<ActionType, 'steps'>): boolean {
+ return !!action.steps?.some((step) => step.event === FEATURE_FLAG_CALLED_EVENT)
+}
+
+/** An action keeps at least one step, so the user can't remove the flag-call steps from this one. */
+export function actionOnlyReadsFlagCalls(action: Pick<ActionType, 'steps'>): boolean {
+ return !!action.steps?.length && action.steps.every((step) => step.event === FEATURE_FLAG_CALLED_EVENT)
+}
+
+function criterionReadsFlagCalls(criterion: AnyCohortCriteriaType): boolean {
+ return (
+ criterion.type === BehavioralFilterKey.Behavioral &&
+ ((criterion.event_type === TaxonomicFilterGroupType.Events && criterion.key === FEATURE_FLAG_CALLED_EVENT) ||
+ (criterion.seq_event_type === TaxonomicFilterGroupType.Events &&
+ criterion.seq_event === FEATURE_FLAG_CALLED_EVENT))
+ )
+}
+
+function criteriaGroupReadsFlagCalls(group: CohortCriteriaGroupFilter): boolean {
+ const values: (AnyCohortCriteriaType | CohortCriteriaGroupFilter)[] = group.values
+ return values.some((value) =>
+ isCohortCriteriaGroup(value) ? criteriaGroupReadsFlagCalls(value) : criterionReadsFlagCalls(value)
+ )
+}
+
+/**
+ * A static cohort keeps the people it already has, so only a dynamic cohort stops adding them.
+ * An experiment's exposure cohort is left out, because its criterion belongs to the experiment.
+ * A criterion on an action is left out, because few cohorts reach the event through an action.
+ */
+export function cohortReadsFlagCalls(cohort: Pick<CohortType, 'is_static' | 'filters' | 'experiment_set'>): boolean {
+ const criteria = cohort.filters?.properties
+ return !cohort.is_static && !cohort.experiment_set?.length && !!criteria && criteriaGroupReadsFlagCalls(criteria)
+}
diff --git a/frontend/src/lib/components/FlagCalledRebuildBanner/flagCalledRebuildBannerLogic.test.ts b/frontend/src/lib/components/FlagCalledRebuildBanner/flagCalledRebuildBannerLogic.test.ts
new file mode 100644
index 000000000000..0e1581921a1a
--- /dev/null
+++ b/frontend/src/lib/components/FlagCalledRebuildBanner/flagCalledRebuildBannerLogic.test.ts
@@ -0,0 +1,45 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { FlagEvaluationsModeEnumApi } from '~/generated/core/api.schemas'
+import { initKeaTests } from '~/test/init'
+
+import { announcementUrlFromPayload, flagCalledRebuildBannerLogic } from './flagCalledRebuildBannerLogic'
+
+describe('flagCalledRebuildBannerLogic', () => {
+ let logic: ReturnType<typeof flagCalledRebuildBannerLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ logic = flagCalledRebuildBannerLogic()
+ logic.mount()
+ })
+
+ it.each([
+ ['off', FlagEvaluationsModeEnumApi.Number1, false],
+ ['on', FlagEvaluationsModeEnumApi.Number0, false],
+ ['on', FlagEvaluationsModeEnumApi.Number1, true],
+ ['on', FlagEvaluationsModeEnumApi.Number2, true],
+ ])('with the flag %s on mode %s, banners enabled: %s', (flagState, mode, expected) => {
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.FLAG_CALLED_MOVE_NOTICES]: flagState === 'on',
+ })
+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, flag_evaluations_mode: mode })
+
+ expect(logic.values.bannersEnabled).toBe(expected)
+ })
+
+ it.each([
+ ['no payload', undefined, null],
+ ['a null url', { url: null }, null],
+ ['text that is not a URL', { url: 'the announcement' }, null],
+ ['a javascript URL', { url: 'javascript:alert(1)' }, null],
+ ['an http URL', { url: 'http://posthog.com/blog/flag-calls' }, null],
+ ['an https URL', { url: 'https://posthog.com/blog/flag-calls' }, 'https://posthog.com/blog/flag-calls'],
+ ])('a payload with %s links to %s', (_label, payload, expected) => {
+ expect(announcementUrlFromPayload(payload)).toBe(expected)
+ })
+})
diff --git a/frontend/src/lib/components/FlagCalledRebuildBanner/flagCalledRebuildBannerLogic.ts b/frontend/src/lib/components/FlagCalledRebuildBanner/flagCalledRebuildBannerLogic.ts
new file mode 100644
index 000000000000..b245fb1fe8d4
--- /dev/null
+++ b/frontend/src/lib/components/FlagCalledRebuildBanner/flagCalledRebuildBannerLogic.ts
@@ -0,0 +1,87 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, selectors } from 'kea'
+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 { teamLogic } from 'scenes/teamLogic'
+
+import { TeamPublicType, TeamType } from '~/types'
+
+export type FlagCalledArtifactType = 'insight' | 'dashboard' | 'action' | 'cohort'
+
+/** The announcement link from the flag's `{ "url": … }` payload, or null until the payload holds an https URL with a host. */
+export function announcementUrlFromPayload(payload: unknown): string | null {
+ const url = (payload as { url?: unknown } | null | undefined)?.url
+ if (typeof url !== 'string') {
+ return null
+ }
+ try {
+ const { protocol, host } = new URL(url)
+ return protocol === 'https:' && host ? url : null
+ } catch {
+ return null
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface flagCalledRebuildBannerLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ currentTeam: TeamPublicType | TeamType | null // teamLogic
+ announcementUrl: string | null
+ bannersEnabled: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface flagCalledRebuildBannerLogicActions {
+ reportBannerShown: (artifactType: FlagCalledArtifactType) => {
+ artifactType: FlagCalledArtifactType
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface flagCalledRebuildBannerLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ bannersEnabled: (currentTeam: TeamPublicType | TeamType | null, featureFlags: FeatureFlagsSet) => boolean
+ announcementUrl: (featureFlags: FeatureFlagsSet) => string | null
+ }
+}
+
+export type flagCalledRebuildBannerLogicType = MakeLogicType<
+ flagCalledRebuildBannerLogicValues,
+ flagCalledRebuildBannerLogicActions,
+ Record<string, any>,
+ flagCalledRebuildBannerLogicMeta
+>
+
+export const flagCalledRebuildBannerLogic = kea<flagCalledRebuildBannerLogicType>([
+ path(['lib', 'components', 'FlagCalledRebuildBanner', 'flagCalledRebuildBannerLogic']),
+ connect(() => ({
+ values: [teamLogic, ['currentTeam'], featureFlagLogic, ['featureFlags']],
+ })),
+ actions({
+ reportBannerShown: (artifactType: FlagCalledArtifactType) => ({ artifactType }),
+ }),
+ selectors({
+ // A team on mode 0 still builds events series in its pickers, so it has no way to rebuild yet.
+ bannersEnabled: [
+ (s) => [s.currentTeam, s.featureFlags],
+ (currentTeam: TeamPublicType | TeamType | null, featureFlags: FeatureFlagsSet): boolean =>
+ !!featureFlags[FEATURE_FLAGS.FLAG_CALLED_MOVE_NOTICES] && readsFlagEvaluationsTable(currentTeam),
+ ],
+ // Reads the payload when the flags change, because the payload arrives with them.
+ announcementUrl: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): string | null =>
+ featureFlags[FEATURE_FLAGS.FLAG_CALLED_MOVE_NOTICES]
+ ? announcementUrlFromPayload(getFeatureFlagPayload(FEATURE_FLAGS.FLAG_CALLED_MOVE_NOTICES))
+ : null,
+ ],
+ }),
+ listeners({
+ reportBannerShown: ({ artifactType }) => {
+ // pinned: analytics event name and property. Renaming them breaks the insights that count banner views.
+ posthog.capture('flag called rebuild banner shown', { artifact_type: artifactType })
+ },
+ }),
+])
diff --git a/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx b/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx
index d7daa9a6ebb5..fe93055695dd 100644
--- a/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx
+++ b/frontend/src/scenes/activity/explore/eventsSceneLogic.tsx
@@ -10,6 +10,7 @@ import { tabUiStateLogic } from 'lib/logic/tabUiStateLogic'
import { objectsEqual } from 'lib/utils/objects'
import { applyTestAccountFilter, getDefaultEventsSceneQuery } from 'scenes/activity/explore/defaults'
import {
+ FEATURE_FLAG_CALLED_EVENT,
reachesPastFlagEvaluationsRetention,
readsFlagEvaluationsTable,
} from 'scenes/feature-flags/featureFlagUsageQueries'
@@ -29,7 +30,6 @@ import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import type { TeamPublicType, TeamType } from '../../../types'
const FLAG_EVALUATIONS_ONLY_MODE = FlagEvaluationsModeEnumApi.Number2
-const FEATURE_FLAG_CALLED_EVENT = '$feature_flag_called'
export type FlagCallsNote = 'stored-separately' | 'retention'
diff --git a/frontend/src/scenes/cohorts/CohortEdit.tsx b/frontend/src/scenes/cohorts/CohortEdit.tsx
index ebb0f5b972e7..2f7567030def 100644
--- a/frontend/src/scenes/cohorts/CohortEdit.tsx
+++ b/frontend/src/scenes/cohorts/CohortEdit.tsx
@@ -27,6 +27,8 @@ import {
} from '@posthog/lemon-ui'
import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'
+import { cohortReadsFlagCalls } from 'lib/components/FlagCalledRebuildBanner/flagCalledDependencies'
+import { FlagCalledRebuildBanner } from 'lib/components/FlagCalledRebuildBanner/FlagCalledRebuildBanner'
import { NotFound } from 'lib/components/NotFound'
import { SceneAddToNotebookDropdownMenu } from 'lib/components/Scenes/InsightOrDashboard/SceneAddToNotebookDropdownMenu'
import { SceneFile } from 'lib/components/Scenes/SceneFile'
@@ -846,6 +848,17 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
) : (
<>
<SceneDivider />
+ {!isNewCohort && (
+ <FlagCalledRebuildBanner
+ artifactType="cohort"
+ readsFlagCalls={cohortReadsFlagCalls(cohort)}
+ >
+ This cohort has a criterion on Feature flag called, directly or through an
+ action. That criterion won't see flag calls made after your organization's
+ flag calls move out of the events table, so the cohort can include or leave
+ out the wrong people. Remove that criterion.
+ </FlagCalledRebuildBanner>
+ )}
{!isNewCohort && cohort.experiment_set && cohort.experiment_set.length > 0 && (
<LemonBanner type="info">
This cohort manages exposure for an experiment. Editing this cohort may
diff --git a/frontend/src/scenes/dashboard/Dashboard.tsx b/frontend/src/scenes/dashboard/Dashboard.tsx
index 572251bbc1a9..b54bdff98d4b 100644
--- a/frontend/src/scenes/dashboard/Dashboard.tsx
+++ b/frontend/src/scenes/dashboard/Dashboard.tsx
@@ -31,6 +31,7 @@ import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'
import { teamLogic } from '../teamLogic'
import { addInsightToDashboardLogic } from './addInsightToDashboardModalLogic'
+import { DashboardFlagCalledBanner } from './DashboardFlagCalledBanner'
import { DashboardHeader } from './DashboardHeader'
import { DashboardEmbeddedShareButton } from './DashboardHeaderActions'
import { DashboardModalLoading } from './DashboardModalLoading'
@@ -240,6 +241,7 @@ function DashboardScene({
</LemonBanner>
)}
<DashboardRetentionBanner />
+ <DashboardFlagCalledBanner />
<DashboardQueryScanBanner />
<SceneStickyBar showBorderBottom={false} className="flex gap-2 space-y-0">
diff --git a/frontend/src/scenes/dashboard/DashboardFlagCalledBanner.tsx b/frontend/src/scenes/dashboard/DashboardFlagCalledBanner.tsx
new file mode 100644
index 000000000000..e3ac5e5e5cbf
--- /dev/null
+++ b/frontend/src/scenes/dashboard/DashboardFlagCalledBanner.tsx
@@ -0,0 +1,51 @@
+import { useValues } from 'kea'
+
+import { Link } from '@posthog/lemon-ui'
+
+import { insightReadsFlagCalls } from 'lib/components/FlagCalledRebuildBanner/flagCalledDependencies'
+import { FlagCalledRebuildBanner } from 'lib/components/FlagCalledRebuildBanner/FlagCalledRebuildBanner'
+import { pluralize } from 'lib/utils/strings'
+import { urls } from 'scenes/urls'
+
+import { DashboardPlacement } from '~/types'
+
+import { dashboardLogic } from './dashboardLogic'
+
+export function DashboardFlagCalledBanner(): JSX.Element | null {
+ const { insightTiles, placement } = useValues(dashboardLogic)
+
+ // Shared and exported views have nobody who can rebuild the insights.
+ // A flag's Usage tab renders the usage dashboard that PostHog generated, which the customer did not build.
+ if (
+ placement === DashboardPlacement.Public ||
+ placement === DashboardPlacement.Export ||
+ placement === DashboardPlacement.FeatureFlag
+ ) {
+ return null
+ }
+ // A viewer without access to an insight gets its tile without a query.
+ const affectedInsights = (insightTiles ?? []).flatMap(({ insight }) =>
+ insight?.query && insightReadsFlagCalls(insight.query) ? [insight] : []
+ )
+
+ return (
+ <FlagCalledRebuildBanner
+ artifactType="dashboard"
+ readsFlagCalls={affectedInsights.length > 0}
+ className="mt-4 mb-2"
+ >
+ Feature flag called feeds <span>{pluralize(affectedInsights.length, 'insight')}</span> on this dashboard.
+ Results for any period after your organization's flag calls move out of the events table are wrong. Open
+ each one to rebuild it:{' '}
+ {/* Elements, not bare text, so page translation can't break list updates (react#11538). */}
+ {affectedInsights.map((insight, index) => (
+ <span key={insight.short_id}>
+ {index > 0 && <span>, </span>}
+ <Link to={urls.insightView(insight.short_id)}>
+ {insight.name || insight.derived_name || 'Untitled'}
+ </Link>
+ </span>
+ ))}
+ </FlagCalledRebuildBanner>
+ )
+}
diff --git a/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts
index f182764be789..46e8265e09d2 100644
--- a/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts
@@ -204,6 +204,8 @@ 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
}
diff --git a/frontend/src/scenes/insights/InsightAsScene.tsx b/frontend/src/scenes/insights/InsightAsScene.tsx
index b374a43735f6..76c96691a254 100644
--- a/frontend/src/scenes/insights/InsightAsScene.tsx
+++ b/frontend/src/scenes/insights/InsightAsScene.tsx
@@ -19,6 +19,7 @@ import { InsightHomeGuide } from 'products/product_analytics/frontend/insights/h
import { teamLogic } from '../teamLogic'
import { InsightRetentionBanner } from './dataRetention/InsightRetentionBanner'
import { insightDataLogic } from './insightDataLogic'
+import { InsightFlagCalledBanner } from './InsightFlagCalledBanner'
import { insightLogic } from './insightLogic'
import { InsightQueryScanBanner } from './InsightQueryScanBanner'
import { InsightSceneHeader } from './InsightSceneHeader'
@@ -97,6 +98,8 @@ export function InsightAsScene({ insightId, attachTo }: InsightAsSceneProps): JS
<InsightRetentionBanner insightProps={insightProps} />
+ <InsightFlagCalledBanner insightProps={insightProps} />
+
{!isBIVisualizationNode(query) && <InsightQueryScanBanner insightProps={insightProps} />}
<SqlInsightFilters query={query} setQuery={setQuery}>
diff --git a/frontend/src/scenes/insights/InsightFlagCalledBanner.tsx b/frontend/src/scenes/insights/InsightFlagCalledBanner.tsx
new file mode 100644
index 000000000000..0854a0690c0f
--- /dev/null
+++ b/frontend/src/scenes/insights/InsightFlagCalledBanner.tsx
@@ -0,0 +1,38 @@
+import { useValues } from 'kea'
+
+import { insightReadsFlagCalls } from 'lib/components/FlagCalledRebuildBanner/flagCalledDependencies'
+import { FlagCalledRebuildBanner } from 'lib/components/FlagCalledRebuildBanner/FlagCalledRebuildBanner'
+import { insightSceneLogic } from 'scenes/insights/insightSceneLogic'
+import { urls } from 'scenes/urls'
+
+import { InsightLogicProps, ItemMode } from '~/types'
+
+import { insightDataLogic } from './insightDataLogic'
+import { insightLogic } from './insightLogic'
+
+export function InsightFlagCalledBanner({ insightProps }: { insightProps: InsightLogicProps }): JSX.Element {
+ const { insightMode } = useValues(insightSceneLogic)
+ const { insight, canEditInsight } = useValues(insightLogic(insightProps))
+ // Reads the live query, so the banner clears as soon as the editor rebuilds the series.
+ const { query } = useValues(insightDataLogic(insightProps))
+
+ return (
+ <FlagCalledRebuildBanner
+ artifactType="insight"
+ readsFlagCalls={insightReadsFlagCalls(query)}
+ action={
+ insightMode !== ItemMode.Edit && canEditInsight && insight.short_id
+ ? {
+ children: 'Edit insight',
+ to: urls.insightEdit(insight.short_id),
+ 'data-attr': 'flag-called-rebuild-banner-edit-insight',
+ }
+ : undefined
+ }
+ >
+ This insight uses Feature flag called, so its results are wrong for any period after your organization's
+ flag calls move out of the events table. To rebuild it, select Feature flag called again in each series,
+ funnel step and retention event that uses it, and remove any funnel exclusion on it.
+ </FlagCalledRebuildBanner>
+ )
+}
diff --git a/products/actions/frontend/pages/ActionEdit.tsx b/products/actions/frontend/pages/ActionEdit.tsx
index 279b8015fb00..474b840eb7ca 100644
--- a/products/actions/frontend/pages/ActionEdit.tsx
+++ b/products/actions/frontend/pages/ActionEdit.tsx
@@ -7,6 +7,11 @@ import { IconCopy, IconPlus, IconTrash } from '@posthog/icons'
import { LemonCollapse } from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
+import {
+ actionOnlyReadsFlagCalls,
+ actionReadsFlagCalls,
+} from 'lib/components/FlagCalledRebuildBanner/flagCalledDependencies'
+import { FlagCalledRebuildBanner } from 'lib/components/FlagCalledRebuildBanner/FlagCalledRebuildBanner'
import { NotFound } from 'lib/components/NotFound'
import { SceneFile } from 'lib/components/Scenes/SceneFile'
import { SceneMenuBarFileItems } from 'lib/components/Scenes/SceneMenuBarFileItems'
@@ -308,6 +313,14 @@ export function ActionEdit({ action: loadedAction, id, actionLoading, attachTo }
}
/>
+ {loadedAction && (
+ <FlagCalledRebuildBanner artifactType="action" readsFlagCalls={actionReadsFlagCalls(loadedAction)}>
+ {actionOnlyReadsFlagCalls(loadedAction)
+ ? "Every step in this action is on Feature flag called, so it won't match flag calls made after your organization's flag calls move out of the events table. Rebuild everything listed under Used in analytics with Feature flag called, then delete this action."
+ : "This action has a step on Feature flag called, which won't match flag calls made after your organization's flag calls move out of the events table. Remove the step, and chart flag calls in insights with Feature flag called instead."}
+ </FlagCalledRebuildBanner>
+ )}
+
<LemonCollapse
defaultActiveKey="match-groups"
panels={[