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): block new action steps and cohort criteria on $feature_flag_called (#114061)

Phil Haackdb16796cc1a2
diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/hiddenEvents.test.ts b/frontend/src/lib/components/TaxonomicFilter/utils/hiddenEvents.test.ts
index 504e102e9e49..bf5cd0781e29 100644
--- a/frontend/src/lib/components/TaxonomicFilter/utils/hiddenEvents.test.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/utils/hiddenEvents.test.ts
@@ -1,7 +1,9 @@
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import {
+ eventsWithMoveNotice,
hiddenEventMatchingSearch,
hiddenEventNames,
+ moveAnnouncementUrl,
withHiddenEventsExcluded,
} from 'lib/components/TaxonomicFilter/utils/hiddenEvents'
@@ -26,6 +28,30 @@ describe('events hidden from query builders', () => {
expect(hiddenEventNames(mode, includeHiddenEvents)).toEqual([])
})
+ it.each([
+ ['mode 0 with the notices on', FlagEvaluationsModeEnumApi.Number0, true, ['$feature_flag_called']],
+ ['no mode with the notices on', undefined, true, ['$feature_flag_called']],
+ ['mode 0 with the notices off', FlagEvaluationsModeEnumApi.Number0, false, []],
+ ['mode 1 with the notices on', FlagEvaluationsModeEnumApi.Number1, true, []],
+ ])('warns about moving events on %s', (_label, mode, moveNoticesEnabled, expected) => {
+ expect(eventsWithMoveNotice(mode, moveNoticesEnabled)).toEqual(expected)
+ })
+
+ it.each([
+ [
+ 'an https link',
+ { url: 'https://posthog.com/changelog/flag-calls' },
+ 'https://posthog.com/changelog/flag-calls',
+ ],
+ ['no link yet', { url: null }, null],
+ ['no payload', undefined, null],
+ ['text that is not a URL', { url: 'soon' }, null],
+ ['an http link', { url: 'http://posthog.com/changelog/flag-calls' }, null],
+ ['a javascript link', { url: 'javascript:alert(1)' }, null],
+ ])('links the announcement for %s', (_label, payload, expected) => {
+ expect(moveAnnouncementUrl(payload)).toEqual(expected)
+ })
+
describe('withHiddenEventsExcluded', () => {
// Cohort pickers exclude "All events" as null, so appending must not replace what came in.
it('adds the hidden names to the Events group and keeps the ones the caller passed', () => {
diff --git a/frontend/src/lib/components/TaxonomicFilter/utils/hiddenEvents.ts b/frontend/src/lib/components/TaxonomicFilter/utils/hiddenEvents.ts
index 9bd16bb4a817..b2063cdbf1fd 100644
--- a/frontend/src/lib/components/TaxonomicFilter/utils/hiddenEvents.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/utils/hiddenEvents.ts
@@ -47,6 +47,28 @@ export function hiddenEventNames(
return HIDDEN_EVENT_NAMES
}
+/** The https link in the move notices flag's payload, or null while there is no announcement to link to. */
+export function moveAnnouncementUrl(payload: unknown): string | null {
+ const url = typeof payload === 'object' && payload !== null && 'url' in payload ? payload.url : null
+ if (typeof url !== 'string') {
+ return null
+ }
+ try {
+ const { protocol, host } = new URL(url)
+ return protocol === 'https:' && host ? url : null
+ } catch {
+ return null
+ }
+}
+
+/** The hidden events that a mode 0 action or cohort editor warns about. Empty until the move is announced. */
+export function eventsWithMoveNotice(
+ flagEvaluationsMode: FlagEvaluationsModeEnumApi | undefined,
+ moveNoticesEnabled: boolean
+): string[] {
+ return moveNoticesEnabled && (flagEvaluationsMode ?? EVENTS_MODE) === EVENTS_MODE ? HIDDEN_EVENT_NAMES : []
+}
+
/**
* The hidden event this search was looking for, or null. Lets a picker explain an absence it caused
* rather than reporting no results.
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 7bd08c813e99..818a2c4bcd15 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -363,6 +363,7 @@ export const FEATURE_FLAGS = {
FEATURE_FLAG_REQUEST_USAGE: 'feature-flag-request-usage', // owner: #team-feature-flags
FEATURE_FLAG_RULES_V2_EDITOR: 'feature-flag-rules-v2-editor', // owner: @andehen #team-feature-flags, entry points of the rules v2 flag editor
FIELD_NOTES: 'field-notes', // owner: @adamleithp
+ FLAG_CALLED_MOVE_NOTICES: 'flag-called-move-notices', // owner: #team-feature-flags, shows in-app warnings about the upcoming $feature_flag_called move. Turn on only after the move is announced, because the warnings describe it as planned
FLAG_EVALUATION_TAGS: 'flag-evaluation-tags', // owner: @dmarticus #team-feature-flags
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
diff --git a/frontend/src/queries/nodes/DataTable/EventRowActions.tsx b/frontend/src/queries/nodes/DataTable/EventRowActions.tsx
index a3ddf0d3d446..69373477e087 100644
--- a/frontend/src/queries/nodes/DataTable/EventRowActions.tsx
+++ b/frontend/src/queries/nodes/DataTable/EventRowActions.tsx
@@ -1,7 +1,9 @@
+import { useValues } from 'kea'
import React from 'react'
import { IconLlmAnalytics, IconWarning } from '@posthog/icons'
+import { hiddenEventNames } from 'lib/components/TaxonomicFilter/utils/hiddenEvents'
import ViewRecordingButton, { RecordingPlayerType } from 'lib/components/ViewRecordingButton/ViewRecordingButton'
import { IconLink } from 'lib/lemon-ui/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
@@ -46,6 +48,7 @@ export function EventRowActions({
function EventRowActionsDropdown({ event }: { event: EventType }): JSX.Element {
const insightUrl = insightUrlForEvent(event)
+ const { currentTeam } = useValues(teamLogic)
return (
<>
@@ -54,6 +57,11 @@ function EventRowActionsDropdown({ event }: { event: EventType }): JSX.Element {
onClick={() =>
saveActionFromEvent(event, teamLogic.findMounted()?.values.currentTeam?.data_attributes || [])
}
+ disabledReason={
+ hiddenEventNames(currentTeam?.flag_evaluations_mode).includes(event.event)
+ ? 'PostHog still collects this event, but its data is moving, so a new action on it would stop working.'
+ : undefined
+ }
fullWidth
data-attr="events-table-create-action"
>
diff --git a/frontend/src/scenes/cohorts/CohortFilters/CohortCriteriaRowBuilder.tsx b/frontend/src/scenes/cohorts/CohortFilters/CohortCriteriaRowBuilder.tsx
index ed64f7cf31d3..6fd25f4794de 100644
--- a/frontend/src/scenes/cohorts/CohortFilters/CohortCriteriaRowBuilder.tsx
+++ b/frontend/src/scenes/cohorts/CohortFilters/CohortCriteriaRowBuilder.tsx
@@ -1,18 +1,24 @@
import './CohortCriteriaRowBuilder.scss'
import clsx from 'clsx'
-import { useActions } from 'kea'
+import { useActions, useValues } from 'kea'
import { Field as KeaField } from 'kea-forms'
import { IconCopy, IconTrash } from '@posthog/icons'
import { LemonDivider } from '@posthog/lemon-ui'
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { eventsWithMoveNotice, moveAnnouncementUrl } from 'lib/components/TaxonomicFilter/utils/hiddenEvents'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { getFeatureFlagPayload } from 'lib/logic/featureFlagLogic'
import { CohortLogicProps, cohortEditLogic } from 'scenes/cohorts/cohortEditLogic'
import { getRowShape, renderField } from 'scenes/cohorts/CohortFilters/constants'
import { BehavioralFilterType, CohortFieldProps, Field, FilterType } from 'scenes/cohorts/CohortFilters/types'
import { cleanCriteria } from 'scenes/cohorts/cohortUtils'
+import { teamLogic } from 'scenes/teamLogic'
import { AnyCohortCriteriaType, BehavioralEventType, FilterLogicalOperator } from '~/types'
@@ -37,6 +43,16 @@ export function CohortCriteriaRowBuilder({
onChangeType,
}: CohortCriteriaRowBuilderProps): JSX.Element {
const { setCriteria, duplicateFilter, removeFilter } = useActions(cohortEditLogic)
+ const { currentTeam } = useValues(teamLogic)
+ const moveNoticeEvents = eventsWithMoveNotice(
+ currentTeam?.flag_evaluations_mode,
+ useFeatureFlag('FLAG_CALLED_MOVE_NOTICES')
+ )
+ const announcementUrl = moveAnnouncementUrl(getFeatureFlagPayload(FEATURE_FLAGS.FLAG_CALLED_MOVE_NOTICES))
+ const showsMoveNotice =
+ (criteria.event_type === TaxonomicFilterGroupType.Events && moveNoticeEvents.includes(String(criteria.key))) ||
+ (criteria.seq_event_type === TaxonomicFilterGroupType.Events &&
+ moveNoticeEvents.includes(String(criteria.seq_event)))
// Falling back to another row's fields would let an edit merge into the unmapped criterion,
// which cleanCriteria then strips to undefined. An empty row keeps the type selector as the
// recovery path.
@@ -167,6 +183,21 @@ export function CohortCriteriaRowBuilder({
</div>
</div>
)}
+ {showsMoveNotice && (
+ <LemonBanner
+ className="my-2"
+ type="warning"
+ action={
+ announcementUrl
+ ? { children: 'Learn more', to: announcementUrl, targetBlank: true }
+ : undefined
+ }
+ >
+ Feature flag called is moving out of the events table. Once your organization starts the
+ move, you can't add new criteria on it. When the move finishes, this criterion stops
+ matching new flag calls. To see how a flag is used, open the flag and check its Usage tab.
+ </LemonBanner>
+ )}
</>
</KeaField>
</div>
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index c17bbb65ae60..4f33f91ff0bb 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -84,6 +84,7 @@ from posthog.models.utils import UUIDT
from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.ph_client import feature_enabled_or_false
from posthog.renderers import SafeJSONRenderer
+from posthog.taxonomy.hidden_events import HIDDEN_EVENT_REASON, added_hidden_event
from posthog.utils import format_query_params_absolute_url, str_to_bool
from products.cohorts.backend.models.calculation_history import CohortCalculationHistory
@@ -112,6 +113,7 @@ from products.cohorts.backend.realtime_state import (
resolve_realtime_readiness,
)
from products.feature_flags.backend.facade.config import ConfigFormatError, UnsupportedConfig, decode_config
+from products.feature_flags.backend.facade.flags import hides_flag_calls_from_query_builders
from products.feature_flags.backend.facade.references import references
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.feature_flags.backend.models.team_feature_flags_config import (
@@ -661,6 +663,33 @@ class CohortConditionTypeField(serializers.JSONField):
REALTIME_READINESS_CONTEXT_KEY = "realtime_readiness"
# Caches the product flag's answer for the request, so a list page evaluates it once.
REALTIME_TARGETING_ENABLED_CONTEXT_KEY = "realtime_targeting_enabled"
+# Lets a caller save new criteria on an event hidden in query builders. An experiment's exposure cohort
+# sets it, because that cohort counts the same event as the experiment's default exposure.
+ALLOW_HIDDEN_EVENT_CRITERIA_CONTEXT_KEY = "allow_hidden_event_criteria"
+
+
+def _is_empty_filters(filters: object) -> bool:
+ if not filters:
+ return True
+ properties = filters.get("properties") if isinstance(filters, dict) else None
+ return isinstance(properties, dict) and isinstance(properties.get("values", []), list)
+
+
+def _flat_properties(filters: object) -> list[Property]:
+ # A static cohort saved before validate_filters checked the shape of empty filters can store any JSON.
+ if not isinstance(filters, dict) or not cohort_filters_have_values(filters):
+ return []
+ return parse_property_group_data(filters["properties"]).flat
+
+
+def _behavioral_event_names(properties: Iterable[Property]) -> Iterator[object]:
+ for prop in properties:
+ if prop.type != "behavioral":
+ continue
+ if prop.event_type == "events":
+ yield prop.key
+ if prop.seq_event_type == "events":
+ yield prop.seq_event
def _team_from_serializer_context(context: dict[str, Any]) -> Optional[Team]:
@@ -1274,7 +1303,7 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
"""
cohort_will_be_static = self._cohort_will_be_static()
- if cohort_will_be_static and not cohort_filters_have_values(raw):
+ if cohort_will_be_static and not cohort_filters_have_values(raw) and _is_empty_filters(raw):
return raw
if not isinstance(raw, dict) or "properties" not in raw:
raise ValidationError(
@@ -1358,6 +1387,7 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
attrs = super().validate(attrs)
self._validate_warehouse_access(attrs)
+ self._validate_no_new_hidden_event_criteria(attrs)
if self.context["request"].method != "PATCH" or self.instance is None:
return attrs
@@ -1370,6 +1400,25 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
return attrs
+ def _validate_no_new_hidden_event_criteria(self, attrs: dict) -> None:
+ if self.context.get(ALLOW_HIDDEN_EVENT_CRITERIA_CONTEXT_KEY):
+ return
+ if self.instance is not None and "filters" not in attrs and "groups" not in attrs:
+ return
+ team = _team_from_serializer_context(self.context)
+ # Passing no attrs reads the stored definition. Cohort.properties would rewrite the stored
+ # legacy groups in place.
+ existing = self._effective_filters_after_update({}, team=team)
+ hidden_event = added_hidden_event(
+ _behavioral_event_names(_flat_properties(self._effective_filters_after_update(attrs, team=team))),
+ _behavioral_event_names(_flat_properties(existing)),
+ )
+ if hidden_event and team is not None and hides_flag_calls_from_query_builders(team.organization_id):
+ raise ValidationError(
+ {"filters": f"You can't add a new criterion on {hidden_event}. {HIDDEN_EVENT_REASON}"},
+ code="hidden_event",
+ )
+
@staticmethod
def _cohort_error_message(exc: PydanticValidationError) -> str:
"""
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index 9d083d67bba8..fb7e9dde81ad 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -51,7 +51,9 @@ from products.cohorts.backend.models.cohort import Cohort, CohortType
from products.cohorts.backend.models.dependencies import cohort_backfill_pending_key, find_behavioral_cohorts
from products.cohorts.backend.models.util import count_cohort_members, list_cohort_member_ids
from products.exports.backend.api.test.test_exports import TestExportMixin
+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfig
from products.product_analytics.backend.facade.models import Insight
from ee.clickhouse.materialized_columns.analyze import materialize
@@ -79,6 +81,17 @@ def _cohort_member_distinct_ids(team_id: int, cohort: Cohort) -> set[str]:
return distinct_ids
+_FLAG_CALLED_CRITERION = {
+ "key": "$feature_flag_called",
+ "type": "behavioral",
+ "value": "performed_event",
+ "event_type": "events",
+ "time_value": 30,
+ "time_interval": "day",
+}
+_PAGEVIEW_CRITERION = {**_FLAG_CALLED_CRITERION, "key": "$pageview"}
+
+
class TestCohort(TestExportMixin, ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
# select all queries for snapshots
def capture_select_queries(self):
@@ -4415,6 +4428,123 @@ [email protected],
"Missing required keys for behavioral filter: event_type",
)
+ @parameterized.expand(
+ [
+ ("non_list_values", {"properties": {"type": "OR", "values": 5}}),
+ ("non_object_filters", [1]),
+ ]
+ )
+ @patch("posthog.api.cohort.report_user_action")
+ def test_create_static_cohort_with_malformed_filters_is_a_validation_error(self, _name, filters, patch_capture):
+ self._set_flag_evaluations_mode(FlagEvaluationsMode.READ_FLAG_EVALUATIONS)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts", data={"name": "static", "is_static": True, "filters": filters}
+ )
+
+ self.assertEqual(response.status_code, 400, response.json())
+
+ def _set_flag_evaluations_mode(self, mode: FlagEvaluationsMode) -> None:
+ OrganizationFeatureFlagsConfig.objects.update_or_create(
+ organization=self.organization, defaults={"flag_evaluations_mode": mode}
+ )
+
+ @parameterized.expand(
+ [
+ (
+ "event",
+ {"filters": {"properties": {"type": "OR", "values": [_FLAG_CALLED_CRITERION]}}},
+ FlagEvaluationsMode.READ_FLAG_EVALUATIONS,
+ 400,
+ ),
+ (
+ "sequence_event",
+ {
+ "filters": {
+ "properties": {
+ "type": "OR",
+ "values": [
+ {
+ "key": "$pageview",
+ "type": "behavioral",
+ "value": "performed_event_sequence",
+ "event_type": "events",
+ "time_value": 30,
+ "time_interval": "day",
+ "seq_event": "$feature_flag_called",
+ "seq_event_type": "events",
+ "seq_time_value": 1,
+ "seq_time_interval": "day",
+ }
+ ],
+ }
+ }
+ },
+ FlagEvaluationsMode.READ_FLAG_EVALUATIONS,
+ 400,
+ ),
+ (
+ "legacy_groups",
+ {"groups": [{"event_id": "$feature_flag_called", "days": 30}]},
+ FlagEvaluationsMode.READ_FLAG_EVALUATIONS,
+ 400,
+ ),
+ (
+ "events_mode",
+ {"filters": {"properties": {"type": "OR", "values": [_FLAG_CALLED_CRITERION]}}},
+ FlagEvaluationsMode.EVENTS,
+ 201,
+ ),
+ ]
+ )
+ @patch("posthog.api.cohort.report_user_action")
+ def test_create_cohort_with_criterion_on_hidden_event(
+ self, _name, definition, mode, expected_status, patch_capture
+ ):
+ self._set_flag_evaluations_mode(mode)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts", data={"name": "flag callers", **definition}
+ )
+
+ self.assertEqual(response.status_code, expected_status, response.json())
+ created = Cohort.objects.filter(team=self.team, name="flag callers").exists()
+ self.assertEqual(created, expected_status == 201)
+ if not created:
+ self.assertEqual(response.json()["code"], "hidden_event")
+
+ @parameterized.expand(
+ [
+ ("adds_first", [_PAGEVIEW_CRITERION], [_PAGEVIEW_CRITERION, _FLAG_CALLED_CRITERION], 400),
+ ("adds_second", [_FLAG_CALLED_CRITERION], [_FLAG_CALLED_CRITERION, _FLAG_CALLED_CRITERION], 400),
+ ("edits_existing", [_FLAG_CALLED_CRITERION], [{**_FLAG_CALLED_CRITERION, "time_value": 7}], 200),
+ ]
+ )
+ @patch("posthog.api.cohort.report_user_action")
+ def test_update_cohort_criteria_on_hidden_event(
+ self, _name, stored_criteria, criteria, expected_status, patch_capture
+ ):
+ self._set_flag_evaluations_mode(FlagEvaluationsMode.READ_FLAG_EVALUATIONS)
+ cohort = Cohort.objects.create(
+ team=self.team,
+ name="flag callers",
+ filters={"properties": {"type": "OR", "values": stored_criteria}},
+ )
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/cohorts/{cohort.pk}",
+ data={"name": "flag callers renamed", "filters": {"properties": {"type": "OR", "values": criteria}}},
+ )
+
+ self.assertEqual(response.status_code, expected_status, response.json())
+ cohort.refresh_from_db()
+ if expected_status == 200:
+ self.assertEqual(cohort.name, "flag callers renamed")
+ self.assertEqual(cohort.filters["properties"]["values"][0]["time_value"], 7)
+ else:
+ self.assertEqual(response.json()["code"], "hidden_event")
+ self.assertEqual(cohort.filters["properties"]["values"], stored_criteria)
+
@patch("posthog.api.cohort.report_user_action")
def test_cohort_property_validation_nested_groups(self, patch_capture):
response = self.client.post(
diff --git a/posthog/taxonomy/hidden_events.py b/posthog/taxonomy/hidden_events.py
new file mode 100644
index 000000000000..470d053c4055
--- /dev/null
+++ b/posthog/taxonomy/hidden_events.py
@@ -0,0 +1,27 @@
+from collections import Counter
+from collections.abc import Iterable
+
+from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP
+
+EVENTS_HIDDEN_IN_QUERY_BUILDERS: frozenset[str] = frozenset(
+ name
+ for name, defn in CORE_FILTER_DEFINITIONS_BY_GROUP.get("events", {}).items()
+ if defn.get("hidden_in_query_builders")
+)
+
+HIDDEN_EVENT_REASON = (
+ "PostHog still collects this event, but its data is moving, so anything new built on it would stop working. "
+ "To see how a flag is used, open the flag and check its Usage tab."
+)
+
+
+def added_hidden_event(new_event_names: Iterable[object], existing_event_names: Iterable[object]) -> str | None:
+ """The hidden event that a save adds a reference to, or None.
+
+ A save may keep, edit or drop the references that the stored object already has. Only a count above
+ the stored count is an addition.
+ """
+ new = Counter(name for name in new_event_names if name in EVENTS_HIDDEN_IN_QUERY_BUILDERS)
+ existing = Counter(name for name in existing_event_names if name in EVENTS_HIDDEN_IN_QUERY_BUILDERS)
+ added = new - existing
+ return str(next(iter(added))) if added else None
diff --git a/posthog/taxonomy/test/test_hidden_events.py b/posthog/taxonomy/test/test_hidden_events.py
new file mode 100644
index 000000000000..6ce63eae3055
--- /dev/null
+++ b/posthog/taxonomy/test/test_hidden_events.py
@@ -0,0 +1,20 @@
+import pytest
+
+from posthog.taxonomy.hidden_events import added_hidden_event
+
+
+ "new_event_names,existing_event_names,expected",
+ [
+ (["$pageview", "$feature_flag_called"], [], "$feature_flag_called"),
+ (["$feature_flag_called", "$feature_flag_called"], ["$feature_flag_called"], "$feature_flag_called"),
+ (["$feature_flag_called", "$pageview"], ["$feature_flag_called"], None),
+ ([], ["$feature_flag_called"], None),
+ (["$pageview", None, 42], [], None),
+ ],
+ ids=["new_reference", "second_reference", "kept_reference", "dropped_reference", "no_hidden_event"],
+)
+def test_added_hidden_event(
+ new_event_names: list[object], existing_event_names: list[object], expected: str | None
+) -> None:
+ assert added_hidden_event(new_event_names, existing_event_names) == expected
diff --git a/products/actions/backend/api/action.py b/products/actions/backend/api/action.py
index 2f0ddcbdec98..a4482a5638f7 100644
--- a/products/actions/backend/api/action.py
+++ b/products/actions/backend/api/action.py
@@ -36,6 +36,7 @@ from posthog.models import Team
from posthog.models.event.event import Selector
from posthog.models.property.util import build_selector_regex
from posthog.resource_limits import LimitKey, check_count_limit
+from posthog.taxonomy.hidden_events import HIDDEN_EVENT_REASON, added_hidden_event
from products.access_control.backend.presentation.access_control import (
AccessControlViewSetMixin,
@@ -46,6 +47,7 @@ from products.actions.backend.models.selector_match_change import ActionSelector
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.models.experiment import Experiment
+from products.feature_flags.backend.facade.flags import hides_flag_calls_from_query_builders
from products.product_analytics.backend.facade.models import Insight
logger = structlog.get_logger(__name__)
@@ -298,6 +300,15 @@ class ActionSerializer(
{"steps": f"This filter uses the table '{denied_table}', which you don't have access to."},
code="permission_denied",
)
+ hidden_event = added_hidden_event(
+ (step.get("event") for step in attrs["steps"]),
+ instance.get_step_events() if instance else [],
+ )
+ if hidden_event and hides_flag_calls_from_query_builders(self.context["get_team"]().organization_id):
+ raise serializers.ValidationError(
+ {"steps": f"You can't add a new step on {hidden_event}. {HIDDEN_EVENT_REASON}"},
+ code="hidden_event",
+ )
return attrs
diff --git a/products/actions/backend/api/test/test_action.py b/products/actions/backend/api/test/test_action.py
index 035ea453dc54..e0be203abad2 100644
--- a/products/actions/backend/api/test/test_action.py
+++ b/products/actions/backend/api/test/test_action.py
@@ -23,6 +23,8 @@ from products.actions.backend.models.action import Action
from products.actions.backend.models.selector_match_change import ActionSelectorMatchChange
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.cohorts.backend.models.cohort import Cohort
+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
+from products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfig
from products.product_analytics.backend.facade.models import Insight
@@ -320,6 +322,76 @@ class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.json()["steps"]), 0)
+ def _set_flag_evaluations_mode(self, mode: FlagEvaluationsMode) -> None:
+ OrganizationFeatureFlagsConfig.objects.update_or_create(
+ organization=self.organization, defaults={"flag_evaluations_mode": mode}
+ )
+
+ @parameterized.expand(
+ [
+ ("events_mode", FlagEvaluationsMode.EVENTS, status.HTTP_201_CREATED),
+ ("read_flag_evaluations_mode", FlagEvaluationsMode.READ_FLAG_EVALUATIONS, status.HTTP_400_BAD_REQUEST),
+ ]
+ )
+ def test_create_action_with_step_on_hidden_event(self, _name, mode, expected_status):
+ self._set_flag_evaluations_mode(mode)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/actions/",
+ data={"name": "flag checks", "steps": [{"event": "$pageview"}, {"event": "$feature_flag_called"}]},
+ )
+
+ assert response.status_code == expected_status, response.json()
+ created = Action.objects.filter(team=self.team, name="flag checks").exists()
+ assert created == (expected_status == status.HTTP_201_CREATED)
+ if not created:
+ assert (response.json()["code"], response.json()["attr"]) == ("hidden_event", "steps")
+
+ @parameterized.expand(
+ [
+ (
+ "adds_first",
+ [{"event": "$pageview"}],
+ [{"event": "$pageview"}, {"event": "$feature_flag_called"}],
+ status.HTTP_400_BAD_REQUEST,
+ ),
+ (
+ "adds_second",
+ [{"event": "$feature_flag_called"}],
+ [{"event": "$feature_flag_called"}, {"event": "$feature_flag_called"}],
+ status.HTTP_400_BAD_REQUEST,
+ ),
+ (
+ "edits_existing",
+ [{"event": "$feature_flag_called"}],
+ [
+ {
+ "event": "$feature_flag_called",
+ "properties": [{"key": "$feature_flag", "value": "beta", "type": "event"}],
+ }
+ ],
+ status.HTTP_200_OK,
+ ),
+ ]
+ )
+ def test_update_action_steps_on_hidden_event(self, _name, stored_steps, steps, expected_status):
+ self._set_flag_evaluations_mode(FlagEvaluationsMode.READ_FLAG_EVALUATIONS)
+ action = Action.objects.create(name="flag checks", team=self.team, steps_json=stored_steps)
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/actions/{action.pk}/",
+ data={"name": "flag checks renamed", "steps": steps},
+ )
+
+ assert response.status_code == expected_status, response.json()
+ action.refresh_from_db()
+ if expected_status == status.HTTP_200_OK:
+ assert action.name == "flag checks renamed"
+ assert [step.properties for step in action.steps] == [step.get("properties") for step in steps]
+ else:
+ assert response.json()["code"] == "hidden_event"
+ assert action.name == "flag checks"
+
# This case happens when someone is running behind a proxy, but hasn't set `IS_BEHIND_PROXY`
def test_http_to_https(self, *args):
response = self.client.post(
diff --git a/products/actions/frontend/components/ActionStep.tsx b/products/actions/frontend/components/ActionStep.tsx
index 8b716b81651b..33f65a5c6d7a 100644
--- a/products/actions/frontend/components/ActionStep.tsx
+++ b/products/actions/frontend/components/ActionStep.tsx
@@ -9,10 +9,16 @@ import { AuthorizedUrlListType } from 'lib/components/AuthorizedUrlList/authoriz
import { OperandTag } from 'lib/components/PropertyFilters/components/OperandTag'
import { DEFAULT_TAXONOMIC_GROUP_TYPES } from 'lib/components/PropertyFilters/components/TaxonomicPropertyFilter'
import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'
+import { eventsWithMoveNotice, moveAnnouncementUrl } from 'lib/components/TaxonomicFilter/utils/hiddenEvents'
import { URL_MATCHING_HINTS } from 'lib/components/UrlMatchingHints'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { IconOpenInApp } from 'lib/lemon-ui/icons'
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { LemonLabel } from 'lib/lemon-ui/LemonLabel/LemonLabel'
+import { getFeatureFlagPayload } from 'lib/logic/featureFlagLogic'
+import { teamLogic } from 'scenes/teamLogic'
import { groupsModel } from '~/models/groupsModel'
import {
@@ -56,6 +62,12 @@ export function ActionStep({
onChange: sendStep,
}: Props): JSX.Element {
const { groupsTaxonomicTypes } = useValues(groupsModel)
+ const { currentTeam } = useValues(teamLogic)
+ const moveNoticeEvents = eventsWithMoveNotice(
+ currentTeam?.flag_evaluations_mode,
+ useFeatureFlag('FLAG_CALLED_MOVE_NOTICES')
+ )
+ const announcementUrl = moveAnnouncementUrl(getFeatureFlagPayload(FEATURE_FLAGS.FLAG_CALLED_MOVE_NOTICES))
return (
<div className="bg-surface-primary rounded border p-3 relative">
@@ -110,6 +122,25 @@ export function ActionStep({
allEventsOption="explicit"
disabled={!!disabledReason}
/>
+ {typeof step.event === 'string' && moveNoticeEvents.includes(step.event) && (
+ <LemonBanner
+ type="warning"
+ action={
+ announcementUrl
+ ? {
+ children: 'Learn more',
+ to: announcementUrl,
+ targetBlank: true,
+ }
+ : undefined
+ }
+ >
+ Feature flag called is moving out of the events table. Once your organization starts
+ the move, you can't add new steps on it. When the move finishes, this step stops
+ matching new flag calls. To see how a flag is used, open the flag and check its
+ Usage tab.
+ </LemonBanner>
+ )}
<Link to="https://posthog.com/docs/libraries" target="_blank">
See documentation
diff --git a/products/actions/frontend/logics/actionEditLogic.tsx b/products/actions/frontend/logics/actionEditLogic.tsx
index 11431b4b4fcb..1bb2b86fe5ad 100644
--- a/products/actions/frontend/logics/actionEditLogic.tsx
+++ b/products/actions/frontend/logics/actionEditLogic.tsx
@@ -298,6 +298,10 @@ export const actionEditLogic = kea<actionEditLogicType>([
lemonToast.error('Action name cannot be empty.')
return { ...updatedAction }
}
+ if (response.code === 'hidden_event') {
+ lemonToast.error(response.detail)
+ return { ...updatedAction }
+ }
throw response
}
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 8869ab5a2b20..1fd3bb0b0369 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -28,7 +28,7 @@ from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
from posthog.hogql.query import execute_hogql_query
-from posthog.api.cohort import CohortSerializer, get_active_flags_using_cohort
+from posthog.api.cohort import ALLOW_HIDDEN_EVENT_CRITERIA_CONTEXT_KEY, CohortSerializer, get_active_flags_using_cohort
from posthog.api.utils import ServiceRequest
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.event_usage import EventSource, report_user_action
@@ -4166,7 +4166,7 @@ class ExperimentService:
context = serializer_context or self._build_serializer_context()
# CohortSerializer expects "team" directly in context
- cohort_context = {**context, "team": self.team}
+ cohort_context = {**context, "team": self.team, ALLOW_HIDDEN_EVENT_CRITERIA_CONTEXT_KEY: True}
cohort_serializer = CohortSerializer(
data={
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index 6ca31da95711..37c7b7c94120 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -63,8 +63,10 @@ from products.experiments.backend.models.web_experiment import WebExperiment
from products.experiments.backend.presentation.serializers import EXPERIMENT_HEALTH_FINDINGS_FLAG, ExperimentSerializer
from products.experiments.backend.presentation.views import LIST_DEFERRED_FIELDS, EnterpriseExperimentsViewSet
from products.experiments.backend.setup_context import EXPERIMENT_SETUP_CONTEXT_FLAG
+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
from products.feature_flags.backend.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext
from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfig
from ee.api.test.base import APILicensedTest
@@ -6763,6 +6765,11 @@ class TestExperimentAuxiliaryEndpoints(_HoistFlagConfigClientMixin, ClickhouseTe
@patch("django.db.transaction.on_commit", side_effect=lambda func: func())
def test_create_exposure_cohort_for_experiment(self, patch_on_commit: MagicMock):
+ # From mode 1 on, the cohorts API rejects new criteria on $feature_flag_called, and the exposure cohort must still save.
+ OrganizationFeatureFlagsConfig.objects.update_or_create(
+ organization=self.organization,
+ defaults={"flag_evaluations_mode": FlagEvaluationsMode.READ_FLAG_EVALUATIONS},
+ )
response = self._generate_experiment("2024-01-01T10:23")
created_experiment = response.json()["id"]
diff --git a/products/feature_flags/backend/facade/flags.py b/products/feature_flags/backend/facade/flags.py
index c7369f3114a1..f26f2681646f 100644
--- a/products/feature_flags/backend/facade/flags.py
+++ b/products/feature_flags/backend/facade/flags.py
@@ -45,6 +45,13 @@ def get_flag_evaluations_read_mode(organization_id: UUID) -> int:
return mode
+def hides_flag_calls_from_query_builders(organization_id: UUID) -> bool:
+ """Whether the organization's pickers leave out events marked hidden_in_query_builders, and the actions and
+ cohorts APIs reject a new use of them. It reads the same mode as the team API's flag_evaluations_mode, which the
+ frontend's hiddenEventNames reads, so the pickers and the APIs agree."""
+ return get_flag_evaluations_read_mode(organization_id) != FlagEvaluationsMode.EVENTS
+
+
def is_flag_evaluations_table_enabled(team: "Team") -> bool:
"""Gate every surface that exposes `posthog.flag_evaluations` through here.