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(cohorts): allow flag-call criteria that read from flag_evaluations (#124498)

Phil Haack7f43624a0b2d
diff --git a/frontend/src/lib/components/TaxonomicFilter/types.ts b/frontend/src/lib/components/TaxonomicFilter/types.ts
index 79e9f257950b..723fb99193ce 100644
--- a/frontend/src/lib/components/TaxonomicFilter/types.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/types.ts
@@ -147,8 +147,9 @@ export interface TaxonomicFilterProps {
/**
* Keep offering events whose data is moving out of the `events` table. Set it where the surface
* still needs such an event: it reads live capture, it matches events as they arrive (destinations
- * and workflows), or it measures experiment exposure. Leave it unset everywhere else, so a picker
- * stops saving queries that return nothing once the data moves.
+ * and workflows), it measures experiment exposure, or it is a cohort criterion type that the cohorts
+ * API accepts on the event. Leave it unset everywhere else, so a picker stops saving queries that
+ * return nothing once the data moves.
*/
includeHiddenEvents?: boolean
/** use to indicate if a result in a group is selected */
diff --git a/frontend/src/scenes/cohorts/CohortFilters/CohortCriteriaRowBuilder.tsx b/frontend/src/scenes/cohorts/CohortFilters/CohortCriteriaRowBuilder.tsx
index b01291fec98c..f01701e5d017 100644
--- a/frontend/src/scenes/cohorts/CohortFilters/CohortCriteriaRowBuilder.tsx
+++ b/frontend/src/scenes/cohorts/CohortFilters/CohortCriteriaRowBuilder.tsx
@@ -7,7 +7,6 @@ import { Field as KeaField } from 'kea-forms'
import { IconCopy, IconTrash } from '@posthog/icons'
import { LemonDivider, Tooltip } 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'
@@ -23,6 +22,12 @@ import { teamLogic } from 'scenes/teamLogic'
import { AnyCohortCriteriaType, BehavioralEventType, FilterLogicalOperator } from '~/types'
+import {
+ FlagCallCriterionProblem,
+ MAX_LOOKBACK_DAYS,
+ moveNoticeProblem,
+} from 'products/cohorts/frontend/criteria/flagCallCriterionProblem'
+
export interface CohortCriteriaRowBuilderProps {
id: CohortLogicProps['id']
criteria: AnyCohortCriteriaType
@@ -34,6 +39,17 @@ export interface CohortCriteriaRowBuilderProps {
onChangeType?: (nextType: BehavioralFilterType) => void
}
+const MOVE_NOTICE_EFFECTS: Record<FlagCallCriterionProblem, string> = {
+ type: 'When the move finishes, this criterion stops matching new flag calls. To keep it matching, change it to "Completed event", "Did not complete event" or "Completed an event multiple times".',
+ window: `When the move finishes, this criterion counts every flag call only if its range is relative to today and goes back ${MAX_LOOKBACK_DAYS} days or less, such as "Last 30 days".`,
+ filters:
+ 'When the move finishes, PostHog may not be able to calculate this cohort. To keep it working, filter this criterion on event properties only.',
+}
+
+function moveNoticeText(problem: FlagCallCriterionProblem): string {
+ return `Feature flag called is moving out of the events table. ${MOVE_NOTICE_EFFECTS[problem]}`
+}
+
export function CohortCriteriaRowBuilder({
type,
groupIndex,
@@ -50,10 +66,7 @@ export function CohortCriteriaRowBuilder({
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)))
+ const flagCallProblem = moveNoticeProblem(criteria, moveNoticeEvents)
// 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.
@@ -184,7 +197,7 @@ export function CohortCriteriaRowBuilder({
</div>
</div>
)}
- {showsMoveNotice && (
+ {flagCallProblem !== null && (
<LemonBanner
className="my-2"
type="warning"
@@ -194,9 +207,7 @@ export function CohortCriteriaRowBuilder({
: 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.
+ {moveNoticeText(flagCallProblem)}
</LemonBanner>
)}
</>
diff --git a/frontend/src/scenes/cohorts/CohortFilters/CohortField.tsx b/frontend/src/scenes/cohorts/CohortFilters/CohortField.tsx
index 338621d78c96..6dd7065b4642 100644
--- a/frontend/src/scenes/cohorts/CohortFilters/CohortField.tsx
+++ b/frontend/src/scenes/cohorts/CohortFilters/CohortField.tsx
@@ -162,6 +162,7 @@ export function CohortTaxonomicField({
criteria,
taxonomicGroupTypes = [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.Actions],
hideUnsupportedRecentOperators,
+ includeHiddenEvents,
placeholder = 'Choose event',
onChange: _onChange,
}: CohortTaxonomicFieldProps): JSX.Element {
@@ -218,6 +219,7 @@ export function CohortTaxonomicField({
[TaxonomicFilterGroupType.Events]: [null], // "All events" isn't supported by Cohorts currently
}}
excludedOperators={excludedOperators}
+ includeHiddenEvents={includeHiddenEvents}
groupTypes={taxonomicGroupTypes}
placeholder={placeholder}
data-attr={`cohort-taxonomic-field-${fieldKey}`}
diff --git a/frontend/src/scenes/cohorts/CohortFilters/renderField.tsx b/frontend/src/scenes/cohorts/CohortFilters/renderField.tsx
index bb763b50099a..43e8cb60cc5d 100644
--- a/frontend/src/scenes/cohorts/CohortFilters/renderField.tsx
+++ b/frontend/src/scenes/cohorts/CohortFilters/renderField.tsx
@@ -23,6 +23,8 @@ import {
import { PropertyOperator } from '~/types'
+import { CRITERIA_ACCEPTING_HIDDEN_EVENTS } from 'products/cohorts/frontend/criteria/flagCallCriterionProblem'
+
// Building blocks of a row
export const renderField: Record<FilterType, (props: CohortFieldProps) => JSX.Element> = {
[FilterType.Behavioral]: function _renderField(p) {
@@ -74,6 +76,7 @@ export const renderField: Record<FilterType, (props: CohortFieldProps) => JSX.El
{...(p as CohortTaxonomicFieldProps)}
taxonomicGroupTypes={[TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.Actions]}
placeholder="Choose event or action"
+ includeHiddenEvents={CRITERIA_ACCEPTING_HIDDEN_EVENTS.includes(String(p.criteria.value))}
/>
)
},
diff --git a/frontend/src/scenes/cohorts/CohortFilters/types.ts b/frontend/src/scenes/cohorts/CohortFilters/types.ts
index ca2d14c1c246..b2eacb28ef93 100644
--- a/frontend/src/scenes/cohorts/CohortFilters/types.ts
+++ b/frontend/src/scenes/cohorts/CohortFilters/types.ts
@@ -104,6 +104,7 @@ export interface CohortTaxonomicFieldProps extends Omit<CohortFieldBaseProps, 'f
placeholder?: string
taxonomicGroupTypes?: TaxonomicFilterGroupType[]
hideUnsupportedRecentOperators?: boolean
+ includeHiddenEvents?: boolean
fieldOptionGroupTypes: never
}
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index d5b83fed3dee..d77b98e120e6 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -1,9 +1,11 @@
import io
+import re
import csv
import json
import time
import uuid
import hashlib
+import collections
from collections import defaultdict
from collections.abc import Iterable, Iterator, Sequence
from typing import Annotated, Any, ClassVar, Literal, NoReturn, Optional, Union, cast
@@ -36,9 +38,10 @@ from posthog.schema import ActorsQuery, HogQLQuery, ProductKey
from posthog.hogql.compiler.bytecode import create_bytecode
from posthog.hogql.constants import CSV_EXPORT_LIMIT, LimitContext
from posthog.hogql.context import HogQLContext
-from posthog.hogql.errors import TableAccessDeniedError
+from posthog.hogql.errors import BaseHogQLError, TableAccessDeniedError
from posthog.hogql.printer import prepare_ast_for_printing
from posthog.hogql.property import PERSON_METADATA_FIELDS, property_to_expr
+from posthog.hogql.transforms.flag_calls_from_flag_evaluations import FLAG_EVALUATIONS_COMPLETE_DAYS
from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.routing import TeamAndOrgViewSetMixin
@@ -62,7 +65,12 @@ from posthog.helpers.trigram_search import (
normalize_search_term,
)
from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner
-from posthog.hogql_queries.hogql_cohort_query import HogQLCohortQuery
+from posthog.hogql_queries.hogql_cohort_query import (
+ FlagCallReads,
+ HogQLCohortQuery,
+ batch_flag_call_reads,
+ behavioral_date_range,
+)
from posthog.hogql_queries.query_runner import ExecutionMode, get_query_runner
from posthog.hogql_queries.serialized_actors import get_serialized_people
from posthog.metrics import LABEL_TEAM_ID
@@ -82,9 +90,15 @@ from posthog.models.activity_logging.activity_page import (
)
from posthog.models.async_deletion import AsyncDeletion, DeletionType
from posthog.models.filters.utils import earliest_timestamp_func
+from posthog.models.flag_evaluations.sql import FLAG_EVALUATIONS_SOURCE_EVENT, FLAG_EVALUATIONS_TTL_DAYS
from posthog.models.person.util import get_person_by_uuid, validate_person_uuids_exist
from posthog.models.property.parse import expand_cohort_properties, parse_property_group_data
-from posthog.models.property.property import SEMVER_OPERATORS, STRING_PREFIX_SUFFIX_OPERATORS, Property
+from posthog.models.property.property import (
+ SEMVER_OPERATORS,
+ STRING_PREFIX_SUFFIX_OPERATORS,
+ BehavioralPropertyType,
+ Property,
+)
from posthog.models.property.relative_date import determine_parsed_date_for_property_matching
from posthog.models.team.team import DEPRECATED_ATTRS, Team
from posthog.models.utils import UUIDT
@@ -93,7 +107,7 @@ 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.scopes import scopes_not_covered
-from posthog.taxonomy.hidden_events import HIDDEN_EVENT_REASON, added_hidden_event
+from posthog.taxonomy.hidden_events import EVENTS_HIDDEN_IN_QUERY_BUILDERS, HIDDEN_EVENT_REASON
from posthog.utils import format_query_params_absolute_url, safe_int, str_to_bool
from products.access_control.backend.facade.user_access_control import UserAccessControl
@@ -129,7 +143,8 @@ 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.enums import FlagEvaluationsMode
+from products.feature_flags.backend.facade.flags import get_flag_evaluations_read_mode
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 (
@@ -462,16 +477,21 @@ _COMPUTED_FILTER_KEYS = frozenset({"bytecode", "bytecode_error", "conditionHash"
def _canonical_criteria(node: Any) -> Any:
- """The criteria with server-computed keys removed and single-child groups collapsed.
+ """The criteria with server-computed keys and a false negation removed, and single-child groups collapsed.
The editor wraps conditions in an extra group and the server recompiles bytecode on every save,
- so comparing raw filters would count a save that touched no criteria as a change.
+ so comparing raw filters would count a save that touched no criteria as a change. The validator
+ adds `negation: false` to every criterion, and a criterion without the key means the same thing.
"""
if isinstance(node, list):
return [_canonical_criteria(item) for item in node]
if not isinstance(node, dict):
return node
- canonical = {key: _canonical_criteria(value) for key, value in node.items() if key not in _COMPUTED_FILTER_KEYS}
+ canonical = {
+ key: _canonical_criteria(value)
+ for key, value in node.items()
+ if key not in _COMPUTED_FILTER_KEYS and not (key == "negation" and value is False)
+ }
values = canonical.get("values")
if (
canonical.get("type") in ("AND", "OR")
@@ -976,14 +996,192 @@ def _flat_properties(filters: object) -> list[Property]:
return parse_property_group_data(filters["properties"]).flat
-def _behavioral_event_names(properties: Iterable[Property]) -> Iterator[object]:
+def _hidden_event_references(properties: Iterable[Property]) -> Iterator[tuple[str, Property]]:
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
+ for event_type, event in ((prop.event_type, prop.key), (prop.seq_event_type, prop.seq_event)):
+ if event_type == "events" and event in EVENTS_HIDDEN_IN_QUERY_BUILDERS:
+ yield str(event), prop
+
+
+# products/cohorts/frontend/criteria/flagCallCriterionProblem.ts copies the type, window and filter rules for the
+# cohort move notice. A change to these rules needs the same change there.
+
+# The criterion types whose flag calls the batch calculation reads from flag_evaluations.
+_FLAG_CALL_CRITERION_TYPES = frozenset(
+ {BehavioralPropertyType.PERFORMED_EVENT, BehavioralPropertyType.PERFORMED_EVENT_MULTIPLE}
+)
+# flag_evaluations holds every flag call only from UTC midnight FLAG_EVALUATIONS_COMPLETE_DAYS back. The batch
+# calculation starts a window at midnight in the team's timezone. That midnight can fall on the previous UTC day. So a
+# window of N days reads every flag call in it at every hour only when N + 1 days fit.
+_MAX_FLAG_CALL_LOOKBACK_HOURS = (FLAG_EVALUATIONS_COMPLETE_DAYS - 1) * 24
+_RELATIVE_DATE_UNIT_MAX_HOURS = {"h": 1, "d": 24, "w": 7 * 24, "m": 31 * 24}
+_RELATIVE_DATE_PATTERN = re.compile(r"-(\d+)([hdwm])")
+
+_FLAG_CALL_CRITERION_TYPE_REASON = (
+ 'Only "Completed event", "Did not complete event" and "Completed an event multiple times" can use this event.'
+)
+_FLAG_CALL_WINDOW_REASON = (
+ f"PostHog keeps this event for {FLAG_EVALUATIONS_TTL_DAYS} days, so pick a range relative to today that goes back "
+ f'{_MAX_FLAG_CALL_LOOKBACK_HOURS // 24} days or less, such as "Last 30 days".'
+)
+_FLAG_CALL_KEY_REASON = (
+ 'Add an event property filter where "Feature flag" equals one or more flag keys, and filter only on event '
+ "properties."
+)
+_FLAG_CALL_REALTIME_REASON = (
+ "Real-time cohorts can't use this event on your organization yet. "
+ "To see who called a flag, open the flag and check its Usage tab."
+)
+_FLAG_CALL_COMPILE_REASON = "PostHog can't calculate this criterion. Check its count and its event property filters."
+_FLAG_CALL_FILTER_REASON = "Use event property filters on this event instead of a SQL expression."
+_FLAG_CALL_SQL_EXPRESSION_REASON = (
+ "A SQL expression filter on another criterion in this cohort reads this event in a way PostHog can't "
+ "calculate. Change that filter, or filter on event properties instead."
+)
+
+
+def _flag_call_window_fits_retention(prop: Property) -> bool:
+ try:
+ date_from, _ = behavioral_date_range(prop)
+ except ValidationError:
+ return False
+ match = _RELATIVE_DATE_PATTERN.fullmatch(date_from)
+ if match is None:
+ return False
+ count, unit = match.groups()
+ return int(count) * _RELATIVE_DATE_UNIT_MAX_HOURS[unit] <= _MAX_FLAG_CALL_LOOKBACK_HOURS
+
+
+def _has_hogql_filter(prop: Property) -> bool:
+ return bool(prop.event_filters) and any(
+ event_filter.type == "hogql" for event_filter in parse_property_group_data(prop.event_filters).flat
+ )
+
+
+def flag_call_criterion_shape_problem(prop: Property) -> str | None:
+ """Why a criterion on $feature_flag_called has a type, window or filter that flag_evaluations can't serve, or
+ None."""
+ if prop.value not in _FLAG_CALL_CRITERION_TYPES:
+ return _FLAG_CALL_CRITERION_TYPE_REASON
+ if not _flag_call_window_fits_retention(prop):
+ return _FLAG_CALL_WINDOW_REASON
+ # A SQL expression can read flag calls through a saved view, a function predicate, or a subquery that reads
+ # calls from before the window starts. The compile check counts none of these, so the guard refuses the expression.
+ if _has_hogql_filter(prop):
+ return _FLAG_CALL_FILTER_REASON
+ return None
+
+
+@frozen
+class HiddenEventRefusal:
+ event: str
+ reason: str
+
+
+def _static_hidden_event_reasons(references: Iterable[tuple[str, Property]]) -> collections.Counter[HiddenEventRefusal]:
+ reasons: collections.Counter[HiddenEventRefusal] = collections.Counter()
+ for event, prop in references:
+ reason = (
+ flag_call_criterion_shape_problem(prop) if event == FLAG_EVALUATIONS_SOURCE_EVENT else HIDDEN_EVENT_REASON
+ )
+ if reason is not None:
+ reasons[HiddenEventRefusal(event=event, reason=reason)] += 1
+ return reasons
+
+
+def _flag_call_reads_or_none(criteria: Sequence[Property], team: Team) -> FlagCallReads | None:
+ """The batch query's flag-call reads for these criteria, or None when it doesn't compile.
+
+ The batch calculation keeps the flag_evaluations swap only when the whole rewritten query resolves. So one
+ criterion that reads a field flag_evaluations lacks sends every flag-call criterion in the cohort to events, and
+ the criteria compile together. On an organization whose flag calls are only in flag_evaluations, that criterion
+ makes the whole query fail to compile instead.
+ """
+ # The query reads the same events scans with or without negation. A cohort can't negate every criterion.
+ values = [{**prop.to_dict(), "negation": False} for prop in criteria]
+ try:
+ return batch_flag_call_reads(Cohort(team=team, filters={"properties": {"type": "OR", "values": values}}), team)
+ except (BaseHogQLError, ValidationError, ValueError):
+ return None
+ except Exception as error:
+ # A malformed filter value can fail an assert in the HogQL printer. The guard refuses the save, so the API
+ # returns 400 instead of 500.
+ capture_exception(error, additional_properties={"team_id": team.id})
+ return None
+
+
+def _is_flag_call_criterion(prop: Property) -> bool:
+ return any(event == FLAG_EVALUATIONS_SOURCE_EVENT for event, _ in _hidden_event_references([prop]))
+
+
+def _criteria_that_may_read_flag_calls(properties: Iterable[Property]) -> list[Property]:
+ """The criteria whose scans decide the batch query's flag_evaluations swap: criteria on $feature_flag_called, and
+ criteria with a SQL expression filter, which can query flag calls in a subquery."""
+ return [
+ prop
+ for prop in properties
+ if _is_flag_call_criterion(prop) or (prop.type == "behavioral" and _has_hogql_filter(prop))
+ ]
+
+
+def _another_criterions_sql_expression_blocks_swap(candidates: Sequence[Property], team: Team) -> bool:
+ """Whether another criterion's SQL expression filter causes the refusal: the cohort has one, and the flag-call
+ criteria compile and read no flag calls from events without it."""
+ flag_call_criteria = [prop for prop in candidates if _is_flag_call_criterion(prop)]
+ if len(flag_call_criteria) == len(candidates):
+ return False
+ if not flag_call_criteria:
+ return True
+ reads = _flag_call_reads_or_none(flag_call_criteria, team)
+ return reads is not None and reads.reads_from_events == 0
+
+
+def _criteria_counts(properties: Iterable[Property]) -> collections.Counter[str]:
+ return collections.Counter(_criteria_key(prop.to_dict()) for prop in properties)
+
+
+def _flag_call_criterion_counts(properties: Iterable[Property]) -> collections.Counter[str]:
+ return _criteria_counts(
+ prop for event, prop in _hidden_event_references(properties) if event == FLAG_EVALUATIONS_SOURCE_EVENT
+ )
+
+
+def _added_unsupported_hidden_event_reference(
+ new_properties: Sequence[Property], existing_properties: Sequence[Property], team: Team
+) -> HiddenEventRefusal | None:
+ """A reference to a hidden event that a save adds and the batch calculation can't count in full, with the
+ reason, or None.
+
+ A save may keep or edit an unsupported reference that the stored cohort already has. Only a count above the
+ stored count is an addition. A compile failure that the stored cohort already has is not an addition either.
+ """
+ new_references = list(_hidden_event_references(new_properties))
+ existing_references = list(_hidden_event_references(existing_properties))
+ added = _static_hidden_event_reasons(new_references) - _static_hidden_event_reasons(existing_references)
+ if added:
+ return next(iter(added))
+
+ new_candidates = _criteria_that_may_read_flag_calls(new_properties)
+ existing_candidates = _criteria_that_may_read_flag_calls(existing_properties)
+ if _criteria_counts(new_candidates) == _criteria_counts(existing_candidates):
+ return None
+ new_reads = _flag_call_reads_or_none(new_candidates, team)
+ if new_reads is not None and new_reads.reads_from_events == 0:
+ return None
+ existing_reads = _flag_call_reads_or_none(existing_candidates, team) if existing_candidates else None
+ if new_reads is None:
+ if existing_candidates and existing_reads is None:
+ return None
+ reason = _FLAG_CALL_COMPILE_REASON
+ elif existing_reads is not None and new_reads.reads_from_events <= existing_reads.reads_from_events:
+ return None
+ else:
+ reason = _FLAG_CALL_KEY_REASON
+ if _another_criterions_sql_expression_blocks_swap(new_candidates, team):
+ reason = _FLAG_CALL_SQL_EXPRESSION_REASON
+ return HiddenEventRefusal(event=FLAG_EVALUATIONS_SOURCE_EVENT, reason=reason)
def _team_from_serializer_context(context: dict[str, Any]) -> Optional[Team]:
@@ -1786,19 +1984,59 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
if self.instance is not None and "filters" not in attrs and "groups" not in attrs:
return
team = _team_from_serializer_context(self.context)
+ new_properties = _flat_properties(self._effective_filters_after_update(attrs))
+ if team is None or next(_hidden_event_references(new_properties), None) is None:
+ return
+ mode = get_flag_evaluations_read_mode(team.organization_id)
+ if mode == FlagEvaluationsMode.EVENTS:
+ return
# Passing no attrs reads the stored definition. Cohort.properties would rewrite the stored
# legacy groups in place.
- existing = self._effective_filters_after_update({})
- hidden_event = added_hidden_event(
- _behavioral_event_names(_flat_properties(self._effective_filters_after_update(attrs))),
- _behavioral_event_names(_flat_properties(existing)),
- )
- if hidden_event and team is not None and hides_flag_calls_from_query_builders(team.organization_id):
+ existing_properties = _flat_properties(self._effective_filters_after_update({}))
+ added = _added_unsupported_hidden_event_reference(new_properties, existing_properties, team)
+ if added is None and mode == FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY:
+ added = self._added_realtime_flag_call_criterion(attrs, new_properties, existing_properties, team)
+ if added is not None:
raise ValidationError(
- {"filters": f"You can't add a new criterion on {hidden_event}. {HIDDEN_EVENT_REASON}"},
+ {"filters": f"You can't save this criterion on {added.event}. {added.reason}"},
code="hidden_event",
)
+ def _added_realtime_flag_call_criterion(
+ self, attrs: dict, new_properties: list[Property], existing_properties: list[Property], team: Team
+ ) -> HiddenEventRefusal | None:
+ """A flag-call criterion that a save puts on a realtime cohort, or None.
+
+ On FLAG_EVALUATIONS_ONLY, events holds no flag calls, and cohort-seeder backfills a realtime cohort from
+ events. A new or edited criterion starts a backfill, and so does a cohort that becomes realtime.
+ """
+ if not self._saves_realtime_cohort(attrs, team):
+ return None
+ instance = cast(Optional[Cohort], self.instance)
+ was_realtime = instance is not None and not instance.is_static and instance.cohort_type == CohortType.REALTIME
+ added = _flag_call_criterion_counts(new_properties)
+ if was_realtime:
+ added -= _flag_call_criterion_counts(existing_properties)
+ if not added:
+ return None
+ return HiddenEventRefusal(event=FLAG_EVALUATIONS_SOURCE_EVENT, reason=_FLAG_CALL_REALTIME_REASON)
+
+ def _saves_realtime_cohort(self, attrs: dict, team: Team) -> bool:
+ # Mirrors how create() and update() set cohort_type.
+ instance = cast(Optional[Cohort], self.instance)
+ if attrs.get("is_static", instance.is_static if instance is not None else False):
+ return False
+ filters = attrs.get("filters")
+ if not filters:
+ return instance is not None and instance.cohort_type == CohortType.REALTIME
+ _, cohort_type, _ = validate_filters_and_compute_realtime_support(
+ filters,
+ team,
+ current_cohort_type=attrs.get("cohort_type", instance.cohort_type if instance is not None else None),
+ cohort_count=instance.count if instance is not None else None,
+ )
+ return cohort_type == CohortType.REALTIME
+
@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 0a9a99f9c5f2..34bd9bfcc962 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -1,6 +1,6 @@
import json
from collections.abc import Callable
-from datetime import datetime, timedelta
+from datetime import UTC, datetime, timedelta
from typing import Any, Optional
from uuid import uuid4
@@ -22,7 +22,7 @@ from django.test import SimpleTestCase, override_settings
from django.test.client import Client
from django.utils import timezone
-from parameterized import parameterized
+from parameterized import param, parameterized
from rest_framework import status
from posthog.schema import PersonsOnEventsMode, PropertyOperator
@@ -32,6 +32,7 @@ from posthog.api.cohort import (
AddPersonsToStaticCohortRequestSerializer,
CohortFilters,
CohortViewSet,
+ flag_call_criterion_shape_problem,
)
from posthog.clickhouse.client.execute import sync_execute
from posthog.constants import AvailableFeature
@@ -40,7 +41,7 @@ from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.async_deletion.async_deletion import AsyncDeletion
from posthog.models.file_system.file_system import FileSystem
from posthog.models.person.util import get_person_by_id
-from posthog.models.property import BehavioralPropertyType
+from posthog.models.property import BehavioralPropertyType, Property
from posthog.models.team.team import Team
from posthog.redis import get_client as get_redis_client
from posthog.tasks.calculate_cohort import (
@@ -98,7 +99,7 @@ def _cohort_member_distinct_ids(team_id: int, cohort: Cohort) -> set[str]:
return distinct_ids
-_FLAG_CALLED_CRITERION = {
+_FLAG_CALLED_ANY_FLAG_CRITERION = {
"key": "$feature_flag_called",
"type": "behavioral",
"value": "performed_event",
@@ -106,7 +107,41 @@ _FLAG_CALLED_CRITERION = {
"time_value": 30,
"time_interval": "day",
}
-_PAGEVIEW_CRITERION = {**_FLAG_CALLED_CRITERION, "key": "$pageview"}
+_FLAG_KEY_FILTER = {"key": "$feature_flag", "type": "event", "value": "beta-feature", "operator": "exact"}
+_FLAG_CALLED_CRITERION = {**_FLAG_CALLED_ANY_FLAG_CRITERION, "event_filters": [_FLAG_KEY_FILTER]}
+_PAGEVIEW_CRITERION = {**_FLAG_CALLED_ANY_FLAG_CRITERION, "key": "$pageview"}
+
+
+def _pageview_with_hogql_filter(expression: str) -> dict[str, Any]:
+ return {**_PAGEVIEW_CRITERION, "event_filters": [{"key": expression, "type": "hogql"}]}
+
+
+_FLAG_CALLED_PAST_RETENTION_CRITERION = {**_FLAG_CALLED_CRITERION, "time_value": 180}
+_FLAG_CALLED_UNRESOLVABLE_CRITERION = {
+ **_FLAG_CALLED_CRITERION,
+ "event_filters": [_FLAG_KEY_FILTER, {"key": "goe_0.properties.plan = 'pro'", "type": "hogql"}],
+}
+# The rewrite swaps the flag-call subquery and then can't resolve it, because flag_evaluations stores no group properties.
+_PAGEVIEW_WITH_UNRESOLVABLE_FLAG_CALLS_CRITERION = _pageview_with_hogql_filter(
+ "distinct_id IN (SELECT distinct_id FROM events WHERE event = '$feature_flag_called' "
+ "AND properties.$feature_flag = 'beta-feature' AND timestamp > now() - INTERVAL 7 DAY "
+ "AND goe_0.properties.plan = 'pro')"
+)
+_PAGEVIEW_WITH_HOGQL_FILTER_CRITERION = _pageview_with_hogql_filter("properties.plan = 'pro'")
+_FLAG_CALLED_MULTIPLE_TIMES_ZERO_CRITERION = {
+ **_FLAG_CALLED_CRITERION,
+ "value": "performed_event_multiple",
+ "operator": "gte",
+ "operator_value": 0,
+}
+_HIDDEN_EVENT_REFUSAL = "its data is moving"
+_FLAG_CALL_TYPE_REFUSAL = "can use this event"
+_FLAG_CALL_WINDOW_REFUSAL = "88 days or less"
+_FLAG_CALL_KEY_REFUSAL = '"Feature flag" equals'
+_FLAG_CALL_COMPILE_REFUSAL = "can't calculate this criterion"
+_FLAG_CALL_FILTER_REFUSAL = "instead of a SQL expression"
+_FLAG_CALL_SQL_EXPRESSION_REFUSAL = "on another criterion"
+_FLAG_CALL_REALTIME_REFUSAL = "Real-time cohorts can't use this event"
class TestCohort(TestExportMixin, ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
@@ -4982,100 +5017,373 @@ [email protected],
@parameterized.expand(
[
+ ("event", [_FLAG_CALLED_CRITERION], FlagEvaluationsMode.READ_FLAG_EVALUATIONS, None),
+ (
+ "multiple_times",
+ [
+ {
+ **_FLAG_CALLED_CRITERION,
+ "value": "performed_event_multiple",
+ "operator": "gte",
+ "operator_value": 2,
+ }
+ ],
+ FlagEvaluationsMode.READ_FLAG_EVALUATIONS,
+ None,
+ ),
+ (
+ "did_not_complete_event",
+ [_PAGEVIEW_CRITERION, {**_FLAG_CALLED_CRITERION, "negation": True}],
+ FlagEvaluationsMode.READ_FLAG_EVALUATIONS,
+ None,
+ ),
(
- "event",
- {"filters": {"properties": {"type": "OR", "values": [_FLAG_CALLED_CRITERION]}}},
+ "multiple_times_without_flag_key",
+ [
+ {
+ **_FLAG_CALLED_ANY_FLAG_CRITERION,
+ "value": "performed_event_multiple",
+ "operator": "gte",
+ "operator_value": 2,
+ }
+ ],
FlagEvaluationsMode.READ_FLAG_EVALUATIONS,
- 400,
+ _FLAG_CALL_KEY_REFUSAL,
+ ),
+ (
+ "any_flag_in_flag_evaluations_only_mode",
+ [_FLAG_CALLED_ANY_FLAG_CRITERION],
+ FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY,
+ None,
),
(
"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",
- }
- ],
- }
+ [
+ {
+ "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,
+ _FLAG_CALL_TYPE_REFUSAL,
+ ),
+ (
+ "multiple_times_zero",
+ [_FLAG_CALLED_MULTIPLE_TIMES_ZERO_CRITERION],
+ FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY,
+ _FLAG_CALL_COMPILE_REFUSAL,
+ ),
+ (
+ "hogql_filter",
+ [_FLAG_CALLED_UNRESOLVABLE_CRITERION],
+ FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY,
+ _FLAG_CALL_FILTER_REFUSAL,
+ ),
+ (
+ "hogql_filter_on_another_criterion",
+ [_FLAG_CALLED_CRITERION, _PAGEVIEW_WITH_HOGQL_FILTER_CRITERION],
+ FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY,
+ None,
+ ),
+ (
+ "malformed_hogql_filter_on_another_criterion",
+ [
+ _FLAG_CALLED_CRITERION,
+ _pageview_with_hogql_filter("properties.x = ("),
+ ],
+ FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY,
+ _FLAG_CALL_SQL_EXPRESSION_REFUSAL,
+ ),
+ (
+ "unresolvable_flag_calls_in_another_criterion_in_flag_evaluations_only_mode",
+ [_FLAG_CALLED_CRITERION, _PAGEVIEW_WITH_UNRESOLVABLE_FLAG_CALLS_CRITERION],
+ FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY,
+ _FLAG_CALL_SQL_EXPRESSION_REFUSAL,
),
(
- "legacy_groups",
- {"groups": [{"event_id": "$feature_flag_called", "days": 30}]},
+ "unresolvable_flag_call_criterion_beside_hogql_filter",
+ [_FLAG_CALLED_MULTIPLE_TIMES_ZERO_CRITERION, _PAGEVIEW_WITH_HOGQL_FILTER_CRITERION],
+ FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY,
+ _FLAG_CALL_COMPILE_REFUSAL,
+ ),
+ (
+ "date_filter_with_a_number",
+ [
+ {
+ **_FLAG_CALLED_CRITERION,
+ "event_filters": [
+ _FLAG_KEY_FILTER,
+ {"key": "$sent_at", "type": "event", "operator": "is_date_after", "value": 123},
+ ],
+ }
+ ],
FlagEvaluationsMode.READ_FLAG_EVALUATIONS,
- 400,
+ _FLAG_CALL_COMPILE_REFUSAL,
),
(
"events_mode",
- {"filters": {"properties": {"type": "OR", "values": [_FLAG_CALLED_CRITERION]}}},
+ [_FLAG_CALLED_ANY_FLAG_CRITERION],
FlagEvaluationsMode.EVENTS,
- 201,
+ None,
),
]
)
@patch("posthog.api.cohort.report_user_action")
- def test_create_cohort_with_criterion_on_hidden_event(
- self, _name, definition, mode, expected_status, patch_capture
- ):
+ def test_create_cohort_with_criterion_on_hidden_event(self, _name, criteria, mode, expected_refusal, patch_capture):
self._set_flag_evaluations_mode(mode)
response = self.client.post(
- f"/api/projects/{self.team.id}/cohorts", data={"name": "flag callers", **definition}
+ f"/api/projects/{self.team.id}/cohorts",
+ data={
+ "name": "flag callers",
+ # A cohort that filters out test accounts is a batch cohort.
+ # The realtime block refuses only realtime cohorts.
+ "filters": {"properties": {"type": "OR", "values": criteria}, "filterTestAccounts": True},
+ },
)
- 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:
+ if expected_refusal is None:
+ self.assertEqual(response.status_code, 201, response.json())
+ self.assertTrue(created)
+ else:
+ self.assertEqual(response.status_code, 400, response.json())
+ self.assertFalse(created)
self.assertEqual(response.json()["code"], "hidden_event")
+ self.assertIn(expected_refusal, response.json()["detail"])
+
+ @patch("posthog.api.cohort.report_user_action")
+ def test_create_cohort_with_legacy_group_on_hidden_event(self, patch_capture):
+ self._set_flag_evaluations_mode(FlagEvaluationsMode.READ_FLAG_EVALUATIONS)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "flag callers", "groups": [{"event_id": "$feature_flag_called", "days": 30}]},
+ )
+
+ self.assertEqual(response.status_code, 400, response.json())
+ self.assertIn(_FLAG_CALL_KEY_REFUSAL, response.json()["detail"])
@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),
+ ("adds_within_retention", [_PAGEVIEW_CRITERION], [_PAGEVIEW_CRITERION, _FLAG_CALLED_CRITERION], None),
+ (
+ "adds_past_retention",
+ [_PAGEVIEW_CRITERION],
+ [_PAGEVIEW_CRITERION, _FLAG_CALLED_PAST_RETENTION_CRITERION],
+ _FLAG_CALL_WINDOW_REFUSAL,
+ ),
+ (
+ "adds_second_past_retention",
+ [_FLAG_CALLED_PAST_RETENTION_CRITERION],
+ [_FLAG_CALLED_PAST_RETENTION_CRITERION, _FLAG_CALLED_PAST_RETENTION_CRITERION],
+ _FLAG_CALL_WINDOW_REFUSAL,
+ ),
+ (
+ "widens_past_retention",
+ [_FLAG_CALLED_CRITERION],
+ [_FLAG_CALLED_PAST_RETENTION_CRITERION],
+ _FLAG_CALL_WINDOW_REFUSAL,
+ ),
+ ("drops_flag_key", [_FLAG_CALLED_CRITERION], [_FLAG_CALLED_ANY_FLAG_CRITERION], _FLAG_CALL_KEY_REFUSAL),
+ (
+ "adds_beside_unresolvable",
+ [_FLAG_CALLED_UNRESOLVABLE_CRITERION],
+ [_FLAG_CALLED_UNRESOLVABLE_CRITERION, _FLAG_CALLED_CRITERION],
+ _FLAG_CALL_KEY_REFUSAL,
+ ),
+ (
+ "adds_unresolvable_flag_calls_in_another_criterion",
+ [_FLAG_CALLED_CRITERION],
+ [_FLAG_CALLED_CRITERION, _PAGEVIEW_WITH_UNRESOLVABLE_FLAG_CALLS_CRITERION],
+ _FLAG_CALL_SQL_EXPRESSION_REFUSAL,
+ ),
+ (
+ "keeps_unresolvable_flag_calls_in_another_criterion",
+ [_FLAG_CALLED_CRITERION, _PAGEVIEW_WITH_UNRESOLVABLE_FLAG_CALLS_CRITERION],
+ [{**_FLAG_CALLED_CRITERION, "time_value": 7}, _PAGEVIEW_WITH_UNRESOLVABLE_FLAG_CALLS_CRITERION],
+ None,
+ ),
+ param(
+ "edits_hogql_filter_beside_uncompilable_flag_call_criterion",
+ [_FLAG_CALLED_UNRESOLVABLE_CRITERION, _PAGEVIEW_WITH_HOGQL_FILTER_CRITERION],
+ [
+ _FLAG_CALLED_UNRESOLVABLE_CRITERION,
+ _pageview_with_hogql_filter("properties.plan = 'free'"),
+ ],
+ None,
+ mode=FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY,
+ ),
+ param(
+ "adds_criterion_that_breaks_the_compile",
+ [_FLAG_CALLED_CRITERION, _PAGEVIEW_WITH_HOGQL_FILTER_CRITERION],
+ [
+ _FLAG_CALLED_CRITERION,
+ _PAGEVIEW_WITH_HOGQL_FILTER_CRITERION,
+ _FLAG_CALLED_MULTIPLE_TIMES_ZERO_CRITERION,
+ ],
+ _FLAG_CALL_COMPILE_REFUSAL,
+ mode=FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY,
+ ),
+ (
+ "edits_any_flag",
+ [_FLAG_CALLED_ANY_FLAG_CRITERION],
+ [{**_FLAG_CALLED_ANY_FLAG_CRITERION, "time_value": 7}],
+ None,
+ ),
+ (
+ "edits_past_retention",
+ [_FLAG_CALLED_PAST_RETENTION_CRITERION],
+ [{**_FLAG_CALLED_PAST_RETENTION_CRITERION, "time_value": 120}],
+ None,
+ ),
]
)
@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,
+ _name,
+ stored_criteria,
+ criteria,
+ expected_refusal,
+ patch_capture,
+ mode=FlagEvaluationsMode.READ_FLAG_EVALUATIONS,
):
- self._set_flag_evaluations_mode(FlagEvaluationsMode.READ_FLAG_EVALUATIONS)
+ self._set_flag_evaluations_mode(mode)
+ # A cohort that filters out test accounts is a batch cohort.
+ # The realtime block refuses only realtime cohorts.
cohort = Cohort.objects.create(
team=self.team,
name="flag callers",
- filters={"properties": {"type": "OR", "values": stored_criteria}},
+ filters={"properties": {"type": "OR", "values": stored_criteria}, "filterTestAccounts": True},
)
response = self.client.patch(
f"/api/projects/{self.team.id}/cohorts/{cohort.pk}",
- data={"name": "flag callers renamed", "filters": {"properties": {"type": "OR", "values": criteria}}},
+ data={
+ "name": "flag callers renamed",
+ "filters": {"properties": {"type": "OR", "values": criteria}, "filterTestAccounts": True},
+ },
)
- self.assertEqual(response.status_code, expected_status, response.json())
cohort.refresh_from_db()
- if expected_status == 200:
+ if expected_refusal is None:
+ self.assertEqual(response.status_code, 200, response.json())
self.assertEqual(cohort.name, "flag callers renamed")
- self.assertEqual(cohort.filters["properties"]["values"][0]["time_value"], 7)
+ self.assertEqual(
+ [(value["key"], value["time_value"]) for value in cohort.filters["properties"]["values"]],
+ [(criterion["key"], criterion["time_value"]) for criterion in criteria],
+ )
else:
+ self.assertEqual(response.status_code, 400, response.json())
self.assertEqual(response.json()["code"], "hidden_event")
+ self.assertIn(expected_refusal, response.json()["detail"])
self.assertEqual(cohort.filters["properties"]["values"], stored_criteria)
+ @parameterized.expand(
+ [
+ ("realtime", None, None, False, [_FLAG_CALLED_CRITERION], _FLAG_CALL_REALTIME_REFUSAL),
+ ("batch", None, None, True, [_FLAG_CALLED_CRITERION], None),
+ ("becomes_realtime", True, None, False, [_FLAG_CALLED_CRITERION], _FLAG_CALL_REALTIME_REFUSAL),
+ ("stays_batch", True, None, True, [_FLAG_CALLED_CRITERION], None),
+ (
+ "realtime_keeps_stored_criterion",
+ False,
+ CohortType.REALTIME,
+ False,
+ [_FLAG_CALLED_CRITERION, _PAGEVIEW_CRITERION],
+ None,
+ ),
+ (
+ "realtime_edits_stored_criterion",
+ False,
+ CohortType.REALTIME,
+ False,
+ [{**_FLAG_CALLED_CRITERION, "time_value": 7}],
+ _FLAG_CALL_REALTIME_REFUSAL,
+ ),
+ ]
+ )
+ @patch("posthog.api.cohort.report_user_action")
+ def test_flag_call_criterion_on_realtime_cohort_in_flag_evaluations_only_mode(
+ self,
+ _name,
+ stored_filter_test_accounts,
+ stored_cohort_type,
+ filter_test_accounts,
+ criteria,
+ expected_refusal,
+ patch_capture,
+ ):
+ self._set_flag_evaluations_mode(FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY)
+ filters = {
+ "properties": {"type": "OR", "values": criteria},
+ "filterTestAccounts": filter_test_accounts,
+ }
+
+ if stored_filter_test_accounts is None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts", data={"name": "flag callers", "filters": filters}
+ )
+ else:
+ cohort = Cohort.objects.create(
+ team=self.team,
+ name="flag callers",
+ # A criterion stored without the validator has no negation key.
+ filters={
+ "properties": {"type": "OR", "values": [_FLAG_CALLED_CRITERION]},
+ "filterTestAccounts": stored_filter_test_accounts,
+ },
+ cohort_type=stored_cohort_type,
+ )
+ response = self.client.patch(f"/api/projects/{self.team.id}/cohorts/{cohort.pk}", data={"filters": filters})
+
+ if expected_refusal is None:
+ self.assertIn(response.status_code, (200, 201), response.json())
+ self.assertEqual(response.json()["cohort_type"] == "realtime", stored_cohort_type == CohortType.REALTIME)
+ else:
+ self.assertEqual(response.status_code, 400, response.json())
+ self.assertIn(expected_refusal, response.json()["detail"])
+
+ @parameterized.expand([("farthest_east", "Pacific/Kiritimati"), ("farthest_west", "Pacific/Pago_Pago")])
+ @patch("posthog.api.cohort.report_user_action")
+ def test_create_cohort_with_longest_flag_call_window_at_the_tightest_hour(self, _name, timezone, patch_capture):
+ self._set_flag_evaluations_mode(FlagEvaluationsMode.READ_FLAG_EVALUATIONS)
+ self.team.timezone = timezone
+ self.team.save()
+ criterion = {**_FLAG_CALLED_CRITERION, "time_value": 88}
+
+ with time_machine.travel(datetime(2026, 10, 27, 0, 30, tzinfo=UTC), tick=False):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "flag callers", "filters": {"properties": {"type": "OR", "values": [criterion]}}},
+ )
+
+ self.assertEqual(response.status_code, 201, response.json())
+
+ @patch("posthog.api.cohort.EVENTS_HIDDEN_IN_QUERY_BUILDERS", frozenset({"$feature_flag_called", "$other_hidden"}))
+ @patch("posthog.api.cohort.report_user_action")
+ def test_create_cohort_refuses_a_hidden_event_flag_evaluations_does_not_store(self, patch_capture):
+ self._set_flag_evaluations_mode(FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY)
+ criterion = {**_FLAG_CALLED_CRITERION, "key": "$other_hidden"}
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/cohorts",
+ data={"name": "other", "filters": {"properties": {"type": "OR", "values": [criterion]}}},
+ )
+
+ self.assertEqual(response.status_code, 400, response.json())
+ self.assertEqual(response.json()["code"], "hidden_event")
+ self.assertIn(_HIDDEN_EVENT_REFUSAL, response.json()["detail"])
+
@patch("posthog.api.cohort.report_user_action")
def test_cohort_property_validation_nested_groups(self, patch_capture):
response = self.client.post(
@@ -7982,18 +8290,29 @@ class TestCohortTypeIntegration(APIBaseTest):
{"name": "Renamed", "value": "@posthog.com", "regrouped": True},
200,
),
+ (
+ "rename_resending_the_same_criteria_stored_without_negation",
+ "active",
+ {"name": "Renamed", "value": "@posthog.com", "stored_without_negation": True},
+ 200,
+ ),
]
)
def test_criteria_edit_is_blocked_by_active_workflows_using_it(self, _name, status, change, expected_status):
cohort_id = self._create_realtime_cohort()
self._create_workflow_using_cohort(cohort_id, "trigger", status)
- if "stored_value" in change:
+ if "stored_value" in change or change.get("stored_without_negation"):
stored_filters = Cohort.objects.get(id=cohort_id).filters
assert stored_filters is not None
- stored_filters["properties"]["values"][0]["value"] = change["stored_value"]
+ if "stored_value" in change:
+ stored_filters["properties"]["values"][0]["value"] = change["stored_value"]
+ if change.get("stored_without_negation"):
+ stored_filters["properties"]["values"][0].pop("negation", None)
Cohort.objects.filter(id=cohort_id).update(filters=stored_filters)
payload: dict[str, Any] = {
- key: value for key, value in change.items() if key not in ("value", "regrouped", "stored_value")
+ key: value
+ for key, value in change.items()
+ if key not in ("value", "regrouped", "stored_value", "stored_without_negation")
}
if "value" in change:
condition = {"type": "person", "key": "email", "operator": "icontains", "value": change["value"]}
@@ -8614,3 +8933,61 @@ class TestAddPersonsToStaticCohortRequestSerializer(SimpleTestCase):
assert not serializer.is_valid()
assert serializer.errors["person_ids"][0].code == expected_code
+
+
+class TestFlagCallCriterionShapeProblem(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("last_88_days", {"time_value": 88, "time_interval": "day"}, False),
+ ("last_89_days", {"time_value": 89, "time_interval": "day"}, True),
+ ("relative_12_weeks", {"explicit_datetime": "-12w"}, False),
+ ("relative_13_weeks", {"explicit_datetime": "-13w"}, True),
+ ("relative_2_months", {"explicit_datetime": "-2m"}, False),
+ ("relative_3_months", {"explicit_datetime": "-3m"}, True),
+ ("relative_1_year", {"explicit_datetime": "-1y"}, True),
+ ("absolute_start", {"explicit_datetime": "2026-09-01"}, True),
+ (
+ "explicit_datetime_wins",
+ {"explicit_datetime": "-180d", "time_value": 30, "time_interval": "day"},
+ True,
+ ),
+ ("unknown_interval", {"time_value": 30, "time_interval": "fortnight"}, True),
+ ("not_performed", {"negation": True, "explicit_datetime": "-30d"}, False),
+ (
+ "performed_multiple_times",
+ {
+ "value": "performed_event_multiple",
+ "operator": "gte",
+ "operator_value": 2,
+ "explicit_datetime": "-30d",
+ },
+ False,
+ ),
+ ("first_time", {"value": "performed_event_first_time", "explicit_datetime": "-30d"}, True),
+ (
+ "event_property_filter",
+ {
+ "explicit_datetime": "-30d",
+ "event_filters": [{"key": "$browser", "type": "event", "value": "Chrome", "operator": "exact"}],
+ },
+ False,
+ ),
+ (
+ "hogql_filter",
+ {"explicit_datetime": "-30d", "event_filters": [{"key": "properties.plan = 'pro'", "type": "hogql"}]},
+ True,
+ ),
+ ]
+ )
+ def test_flags_shapes_flag_evaluations_cannot_serve(self, _name: str, overrides: dict, unsupported: bool) -> None:
+ criterion = Property(
+ **{
+ "key": "$feature_flag_called",
+ "type": "behavioral",
+ "value": "performed_event",
+ "event_type": "events",
+ **overrides,
+ }
+ )
+
+ assert (flag_call_criterion_shape_problem(criterion) is not None) == unsupported
diff --git a/posthog/hogql/flag_called_warnings.py b/posthog/hogql/flag_called_warnings.py
index ae5b47404c6e..6b1c5b9fee9a 100644
--- a/posthog/hogql/flag_called_warnings.py
+++ b/posthog/hogql/flag_called_warnings.py
@@ -72,6 +72,16 @@ def _flag_called_constants(expr: ast.Expr) -> list[ast.Constant]:
return []
+def count_flag_calls_read_from_events(resolved: ast.AST) -> int:
+ """How many `$feature_flag_called` literals a resolved query compares to the events table's `event` column.
+
+ Unlike the warnings below, it counts a literal that a query builder made, which has no span.
+ """
+ finder = _FlagCalledLiteralFinder(EventsTable)
+ finder.visit(resolved)
+ return len(finder.literals)
+
+
def flag_called_on_events_warnings(
node: ast.SelectQuery | ast.SelectSetQuery, context: HogQLContext
) -> list[HogQLNotice]:
diff --git a/posthog/hogql_queries/hogql_cohort_query.py b/posthog/hogql_queries/hogql_cohort_query.py
index b7c799ff3584..a89341252bcd 100644
--- a/posthog/hogql_queries/hogql_cohort_query.py
+++ b/posthog/hogql_queries/hogql_cohort_query.py
@@ -36,12 +36,14 @@ from posthog.hogql import ast
from posthog.hogql.ast import SelectQuery, SelectSetNode, SelectSetQuery
from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
from posthog.hogql.context import HogQLContext
+from posthog.hogql.flag_called_warnings import count_flag_calls_read_from_events
from posthog.hogql.parser import parse_select
from posthog.hogql.printer import prepare_and_print_ast
from posthog.hogql.property import get_property_type
from posthog.hogql.query import HogQLQueryExecutor
from posthog.constants import PropertyOperatorType
+from posthog.dataclasses import frozen
from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner
from posthog.hogql_queries.events_query_runner import EventsQueryRunner
from posthog.models import Property, Team, User
@@ -81,7 +83,7 @@ def parse_and_validate_positive_integer(value: Optional[Union[str, int]], value_
return parsed_value
-def _behavioral_date_range(prop: Property) -> tuple[str, Optional[str]]:
+def behavioral_date_range(prop: Property) -> tuple[str, Optional[str]]:
if prop.explicit_datetime:
# Explicit datetime filter, can be a relative or absolute date, follows same convention
# as all analytics datetime filters
@@ -344,7 +346,7 @@ class HogQLCohortQuery:
filter = parse_property_group_data(prop.event_filters)
series[0].properties = filter
- date_from, date_to = _behavioral_date_range(prop)
+ date_from, date_to = behavioral_date_range(prop)
trends_query = TrendsQuery(
dateRange=DateRange(date_from=date_from, date_to=date_to),
@@ -357,7 +359,7 @@ class HogQLCohortQuery:
def get_performed_event_multiple(self, prop: Property) -> ast.SelectQuery:
count = parse_and_validate_positive_integer(prop.operator_value, "operator_value")
- date_from, date_to = _behavioral_date_range(prop)
+ date_from, date_to = behavioral_date_range(prop)
events_query = EventsQuery(after=date_from, before=date_to, select=["person_id", "count()"])
if prop.event_type == "events":
@@ -414,7 +416,7 @@ class HogQLCohortQuery:
else:
raise ValueError(f"Event type must be 'events' or 'actions'")
- date_from, date_to = _behavioral_date_range(prop)
+ date_from, date_to = behavioral_date_range(prop)
date_value = parse_and_validate_positive_integer(prop.seq_time_value, "seq_time_value")
date_interval = validate_interval(prop.seq_time_interval)
@@ -793,3 +795,22 @@ class HogQLCohortQuery:
if condition.negation:
raise ValidationError("Top level condition cannot be negated", str(self.property_groups))
return condition.query
+
+
+@frozen
+class FlagCallReads:
+ reads_from_events: int
+
+
+def batch_flag_call_reads(cohort: Cohort, team: Team) -> FlagCallReads:
+ """How many flag-call reads the batch query for this cohort leaves on events.
+
+ It compiles the cohort the way the batch calculation does, so it follows the rewrite's rules and its fallback to
+ events when a field doesn't resolve on flag_evaluations. It raises whatever the compile raises.
+ """
+ executor = HogQLCohortQuery(cohort=cohort, team=team).get_query_executor(bypass_warehouse_access_control=True)
+ executor.generate_clickhouse_sql()
+ prepared = executor.clickhouse_prepared_ast
+ return FlagCallReads(
+ reads_from_events=count_flag_calls_read_from_events(prepared) if prepared is not None else 0,
+ )
diff --git a/products/cohorts/frontend/criteria/flagCallCriterionProblem.test.ts b/products/cohorts/frontend/criteria/flagCallCriterionProblem.test.ts
new file mode 100644
index 000000000000..f23471e33abc
--- /dev/null
+++ b/products/cohorts/frontend/criteria/flagCallCriterionProblem.test.ts
@@ -0,0 +1,98 @@
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { BehavioralFilterKey } from 'scenes/cohorts/CohortFilters/types'
+
+import {
+ BehavioralEventType,
+ BehavioralLifecycleType,
+ CohortCriteriaType,
+ EventPropertyFilter,
+ PropertyFilterType,
+ PropertyOperator,
+ TimeUnitType,
+} from '~/types'
+
+import {
+ FlagCallCriterionProblem,
+ flagCallCriterionProblem,
+ moveNoticeProblem,
+} from 'products/cohorts/frontend/criteria/flagCallCriterionProblem'
+
+const FLAG_KEY_FILTER: EventPropertyFilter = {
+ key: '$feature_flag',
+ type: PropertyFilterType.Event,
+ operator: PropertyOperator.Exact,
+ value: 'beta-feature',
+}
+
+function flagCallCriterion(overrides: Partial<CohortCriteriaType>): CohortCriteriaType {
+ return {
+ id: 'criterion',
+ key: '$feature_flag_called',
+ type: BehavioralFilterKey.Behavioral,
+ event_type: TaxonomicFilterGroupType.Events,
+ value: BehavioralEventType.PerformEvent,
+ time_value: 30,
+ time_interval: TimeUnitType.Day,
+ event_filters: [FLAG_KEY_FILTER],
+ ...overrides,
+ }
+}
+
+describe('flagCallCriterionProblem', () => {
+ it.each<[string, Partial<CohortCriteriaType>, FlagCallCriterionProblem | null]>([
+ // Type
+ ['completed event', {}, null],
+ ['did not complete event', { negation: true }, null],
+ ['completed an event multiple times', { value: BehavioralEventType.PerformMultipleEvents }, null],
+ ['a sequence', { value: BehavioralEventType.PerformSequenceEvents }, 'type'],
+ ['completed an event for the first time', { value: BehavioralLifecycleType.PerformEventFirstTime }, 'type'],
+ // Window: a relative start at most 88 days back, with a month counted as 31 days
+ ['88 days', { time_value: 88 }, null],
+ ['89 days', { time_value: 89 }, 'window'],
+ ['12 weeks', { time_value: 12, time_interval: TimeUnitType.Week }, null],
+ ['13 weeks', { time_value: 13, time_interval: TimeUnitType.Week }, 'window'],
+ ['2 months', { time_value: 2, time_interval: TimeUnitType.Month }, null],
+ ['3 months', { time_value: 3, time_interval: TimeUnitType.Month }, 'window'],
+ ['a year', { time_value: 1, time_interval: TimeUnitType.Year }, 'window'],
+ ['an explicit start over a longer time value', { explicit_datetime: '-30d', time_value: 180 }, null],
+ ['2112 hours', { explicit_datetime: '-2112h' }, null],
+ ['2113 hours', { explicit_datetime: '-2113h' }, 'window'],
+ ['an absolute start', { explicit_datetime: '2026-09-01' }, 'window'],
+ ['no window', { time_value: null, time_interval: null }, 'window'],
+ // Filters: event property filters only, with or without a flag key
+ ['no filters', { event_filters: [] }, null],
+ [
+ 'a HogQL filter beside the flag key',
+ {
+ event_filters: [
+ FLAG_KEY_FILTER,
+ { key: "goe_0.properties.plan = 'pro'", type: PropertyFilterType.HogQL },
+ ],
+ },
+ 'filters',
+ ],
+ ])('%s', (_, overrides, expected) => {
+ expect(flagCallCriterionProblem(flagCallCriterion(overrides))).toBe(expected)
+ })
+})
+
+describe('moveNoticeProblem', () => {
+ it.each<[string, Partial<CohortCriteriaType>, string[], FlagCallCriterionProblem | null]>([
+ ['a criterion that keeps counting every call', {}, ['$feature_flag_called'], null],
+ ['a range past the limit', { time_value: 180 }, ['$feature_flag_called'], 'window'],
+ ['a range past the limit once nothing is moving', { time_value: 180 }, [], null],
+ [
+ 'a sequence step on the moving event',
+ {
+ key: '$pageview',
+ value: BehavioralEventType.PerformSequenceEvents,
+ seq_event: '$feature_flag_called',
+ seq_event_type: TaxonomicFilterGroupType.Events,
+ },
+ ['$feature_flag_called'],
+ 'type',
+ ],
+ ])('%s', (_, overrides, movingEvents, expected) => {
+ expect(moveNoticeProblem(flagCallCriterion(overrides), movingEvents)).toBe(expected)
+ })
+})
diff --git a/products/cohorts/frontend/criteria/flagCallCriterionProblem.ts b/products/cohorts/frontend/criteria/flagCallCriterionProblem.ts
new file mode 100644
index 000000000000..d78ae1f5f2fd
--- /dev/null
+++ b/products/cohorts/frontend/criteria/flagCallCriterionProblem.ts
@@ -0,0 +1,71 @@
+import { isEventPropertyFilter } from 'lib/components/PropertyFilters/utils'
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+
+import { AnyCohortCriteriaType, BehavioralEventType } from '~/types'
+
+// The criterion types the cohorts API accepts on an event hidden in query builders. "Did not complete
+// event" stores PerformEvent with negation.
+export const CRITERIA_ACCEPTING_HIDDEN_EVENTS: string[] = [
+ BehavioralEventType.PerformEvent,
+ BehavioralEventType.PerformMultipleEvents,
+]
+
+export const MAX_LOOKBACK_DAYS = 88
+const MAX_LOOKBACK_HOURS = MAX_LOOKBACK_DAYS * 24
+const UNIT_MAX_HOURS: Record<string, number> = { h: 1, d: 24, w: 7 * 24, m: 31 * 24 }
+const RELATIVE_DATE_PATTERN = /^-(\d+)([hdwm])$/
+
+export type FlagCallCriterionProblem = 'type' | 'window' | 'filters'
+
+/**
+ * Why the batch calculation can't count every matching call for this "Feature flag called" criterion once flag calls
+ * are only in flag_evaluations, or null.
+ *
+ * Mirrors the type, window and filter checks in `posthog/api/cohort.py`, which explain the 88-day limit and why the
+ * API refuses a SQL expression filter on this event. The filter check also flags element filters, which the API
+ * accepts.
+ */
+export function flagCallCriterionProblem(criteria: AnyCohortCriteriaType): FlagCallCriterionProblem | null {
+ if (!CRITERIA_ACCEPTING_HIDDEN_EVENTS.includes(String(criteria.value))) {
+ return 'type'
+ }
+ if (!windowFitsRetention(criteria)) {
+ return 'window'
+ }
+ if (!(criteria.event_filters ?? []).every(isEventPropertyFilter)) {
+ return 'filters'
+ }
+ return null
+}
+
+/** The problem to warn about when the criterion names one of the events that are moving, or null. */
+export function moveNoticeProblem(
+ criteria: AnyCohortCriteriaType,
+ moveNoticeEvents: string[]
+): FlagCallCriterionProblem | null {
+ const namesMovingEvent =
+ (criteria.event_type === TaxonomicFilterGroupType.Events && moveNoticeEvents.includes(String(criteria.key))) ||
+ (criteria.seq_event_type === TaxonomicFilterGroupType.Events &&
+ moveNoticeEvents.includes(String(criteria.seq_event)))
+ return namesMovingEvent ? flagCallCriterionProblem(criteria) : null
+}
+
+function windowStart(criteria: AnyCohortCriteriaType): string | null {
+ if (criteria.explicit_datetime) {
+ return criteria.explicit_datetime
+ }
+ const count = Number(criteria.time_value)
+ if (!Number.isInteger(count) || count <= 0 || !criteria.time_interval) {
+ return null
+ }
+ return `-${count}${criteria.time_interval[0]}`
+}
+
+function windowFitsRetention(criteria: AnyCohortCriteriaType): boolean {
+ const match = windowStart(criteria)?.match(RELATIVE_DATE_PATTERN)
+ if (!match) {
+ return false
+ }
+ const [, count, unit] = match
+ return Number(count) * UNIT_MAX_HOURS[unit] <= MAX_LOOKBACK_HOURS
+}