: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(experiments): resolve the exposure event in buckets and freeze scan (#76920)
Marcel Poelkerb3390332d075
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex d3e40f773fc5..3d4a55509541 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -60,6 +60,7 @@ from products.experiments.backend.hogql_queries.experiment_metric_fingerprint imfrom products.experiments.backend.hogql_queries.exposure_query_logic import (build_exposure_event_conditions,get_exposure_event_and_property,+ resolve_default_exposure_event,)from products.experiments.backend.hogql_queries.funnel_validation import FunnelDWValidatorfrom products.experiments.backend.metric_utils import filter_metric_group_ids_by_event@@ -2226,9 +2227,10 @@ class ExperimentService:"""Return the UUIDs of persons already exposed to the experiment, bounded by time and count.Runs a synchronous scan of the experiment's exposure events, honoring- ``exposure_criteria`` (custom exposure event or action plus its property filters) via the- same helpers the metrics pipeline uses, and requiring the exposure to have landed a- variant — so the snapshot is the analyzed population, not everyone who fired the event.+ ``exposure_criteria`` (custom exposure event or action plus its property filters) and the+ $experiment_exposure rollout resolution via the same helpers the metrics pipeline uses,+ and requiring the exposure to have landed a variant — so the snapshot is the analyzed+ population, not everyone who fired the event.Capped at FREEZE_EXPOSURE_QUERY_TIMEOUT_SECONDS and returning at mostFREEZE_EXPOSURE_MAX_EXPOSED_USERS + 1 rows so an over-cap set can be detected and rejected.@@ -2242,7 +2244,13 @@ class ExperimentService:assert start_date is not Noneflag_key = experiment.get_feature_flag_key()- _, variant_property = get_exposure_event_and_property(flag_key, experiment.exposure_criteria)+ # The same rollout resolution the analysis queries apply: a post-cutoff experiment frozen+ # off $feature_flag_called would snapshot nobody once the two events stop being emitted+ # together, and an empty snapshot un-enrolls everyone.+ default_exposure_event = resolve_default_exposure_event(self.team, start_date)+ _, variant_property = get_exposure_event_and_property(+ flag_key, experiment.exposure_criteria, default_exposure_event=default_exposure_event+ )variant_keys = [variant["key"] for variant in experiment.feature_flag.variants]conditions: list[ast.Expr] = [@@ -2251,7 +2259,9 @@ class ExperimentService:left=ast.Field(chain=["timestamp"]),right=ast.Constant(value=start_date),),- *build_exposure_event_conditions(experiment.exposure_criteria, self.team, flag_key),+ *build_exposure_event_conditions(+ experiment.exposure_criteria, self.team, flag_key, default_exposure_event=default_exposure_event+ ),]if variant_keys:conditions.append(diff --git a/products/experiments/backend/hogql_queries/exposure_query_logic.py b/products/experiments/backend/hogql_queries/exposure_query_logic.pyindex e60e3745c4a2..e26e48a292f6 100644--- a/products/experiments/backend/hogql_queries/exposure_query_logic.py+++ b/products/experiments/backend/hogql_queries/exposure_query_logic.py@@ -22,7 +22,6 @@ from posthog.hogql import astfrom posthog.hogql.parser import parse_exprfrom posthog.hogql.property import action_to_expr, property_to_expr-from posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.models.team.team import Teamfrom products.actions.backend.models.action import Action@@ -196,7 +195,10 @@ def get_test_accounts_filter(def get_exposure_event_and_property(- feature_flag_key: str, exposure_criteria: Union[ExperimentExposureCriteria, dict, None] = None+ feature_flag_key: str,+ exposure_criteria: Union[ExperimentExposureCriteria, dict, None] = None,+ *,+ default_exposure_event: str,) -> tuple[Optional[str], str]:"""Determines which event and feature flag variant property to use for exposures.@@ -204,6 +206,10 @@ def get_exposure_event_and_property(Args:feature_flag_key: The feature flag keyexposure_criteria: Experiment exposure criteria configuration+ default_exposure_event: What the experiment's default exposure resolves to+ (`resolve_default_exposure_event`). Required so every consumer makes the rollout+ decision explicitly: resolve it for the experiment being served, or pass+ DEFAULT_EXPOSURE_EVENT where staying on the legacy event is the deliberate choice.Returns:Tuple of (event_name, feature_flag_variant_property)@@ -217,34 +223,47 @@ def get_exposure_event_and_property(# Handle ActionsNodeif isinstance(exposure_config, ActionsNode):# For actions, we don't filter by event name (actions can match multiple events)- # The action filter will be applied in build_common_exposure_conditions+ # The action filter will be applied in build_exposure_event_conditionsfeature_flag_variant_property = f"$feature/{feature_flag_key}"event = Noneelif (exposure_configand hasattr(exposure_config, "event")and exposure_config.event- and exposure_config.event != "$feature_flag_called"+ and exposure_config.event not in (DEFAULT_EXPOSURE_EVENT, EXPERIMENT_EXPOSURE_EVENT)):# For custom exposure events, we extract the event name from the exposure config# and get the variant from the $feature/<key> propertyfeature_flag_variant_property = f"$feature/{feature_flag_key}"event = exposure_config.eventelse:- # For the default $feature_flag_called event, we need to get the variant from $feature_flag_response+ # $experiment_exposure is an ingestion-side duplicate of $feature_flag_called and carries+ # the same properties, so both resolve the variant from $feature_flag_response. A config+ # naming $feature_flag_called is the stored default rather than a custom choice, so it+ # follows the resolved default event the same way an absent config does.feature_flag_variant_property = "$feature_flag_response"- event = DEFAULT_EXPOSURE_EVENT+ if exposure_config is not None and getattr(exposure_config, "event", None) == EXPERIMENT_EXPOSURE_EVENT:+ event = EXPERIMENT_EXPOSURE_EVENT+ else:+ event = default_exposure_eventreturn event, feature_flag_variant_property-def _get_event_name_from_config(exposure_config: Optional[Union[ActionsNode, ExperimentEventExposureConfig]]) -> str:- """Extract event name from exposure config, defaulting to DEFAULT_EXPOSURE_EVENT."""+def _get_event_name_from_config(+ exposure_config: Optional[Union[ActionsNode, ExperimentEventExposureConfig]],+ default_exposure_event: str,+) -> str:+ """Extract event name from exposure config, defaulting to the resolved default exposure event."""if not exposure_config or not hasattr(exposure_config, "event"):- return DEFAULT_EXPOSURE_EVENT+ return default_exposure_eventevent = exposure_config.event- return str(event) if event and event != "$feature_flag_called" else "$feature_flag_called"+ # An explicit $feature_flag_called config is the stored default, so it resolves like an+ # absent config instead of pinning the pre-rollout event.+ if not event or event == DEFAULT_EXPOSURE_EVENT:+ return default_exposure_event+ return str(event)def _build_action_filter(action_id: int, team: Team) -> ast.Expr:@@ -261,6 +280,7 @@ def _build_event_filters(exposure_config: Optional[Union[ActionsNode, ExperimentEventExposureConfig]],team: Team,feature_flag_key: Optional[str],+ default_exposure_event: str,) -> list[ast.Expr]:"""Build event/action filters based on exposure config."""# Handle action-based exposure@@ -268,7 +288,7 @@ def _build_event_filters(return [_build_action_filter(int(exposure_config.id), team)]# Handle event-based exposure- event = _get_event_name_from_config(exposure_config)+ event = _get_event_name_from_config(exposure_config, default_exposure_event)filters: list[ast.Expr] = [ast.CompareOperation(op=ast.CompareOperationOp.Eq,@@ -277,8 +297,10 @@ def _build_event_filters()]- # Add feature flag key filter for $feature_flag_called events- if event == "$feature_flag_called" and feature_flag_key:+ # Add feature flag key filter for $feature_flag_called events. $experiment_exposure gets the+ # same treatment: ingestion emits it for every experiment, so without this filter exposures+ # of other experiments would count too.+ if event in (DEFAULT_EXPOSURE_EVENT, EXPERIMENT_EXPOSURE_EVENT) and feature_flag_key:filters.append(ast.CompareOperation(op=ast.CompareOperationOp.Eq,@@ -305,68 +327,27 @@ def build_exposure_event_conditions(exposure_criteria: Union[ExperimentExposureCriteria, dict, None],team: Team,feature_flag_key: Optional[str],+ *,+ default_exposure_event: str,) -> list[ast.Expr]:"""- Builds the event/action and property filters that define what counts as an exposure event —- the exposure-identity subset of build_common_exposure_conditions, without the analysis-only- conditions (date range, variant filter, test-account exclusion). Used directly by consumers- that need "who was exposed" for serving decisions rather than metric analysis, such as the- freeze-exposure snapshot scan.+ Builds the event/action and property filters that define what counts as an exposure event,+ without the analysis-only conditions (date range, variant filter, test-account exclusion).+ Used by consumers that need "who was exposed" for serving decisions rather than metric+ analysis, such as the freeze-exposure snapshot scan.++ `default_exposure_event` follows the same contract as in `get_exposure_event_and_property`:+ resolve it per experiment to honor the $experiment_exposure rollout, or pass+ DEFAULT_EXPOSURE_EVENT where staying on the legacy event is the deliberate choice."""criteria = normalize_to_exposure_criteria(exposure_criteria)exposure_config = criteria.exposure_config if criteria else Nonereturn [- *_build_event_filters(exposure_config, team, feature_flag_key),+ *_build_event_filters(exposure_config, team, feature_flag_key, default_exposure_event),*_build_property_filters(exposure_config, team),]-def build_common_exposure_conditions(- feature_flag_variant_property: str,- variants: list[str],- date_range_query: QueryDateRange,- team: Team,- exposure_criteria: Union[ExperimentExposureCriteria, dict, None] = None,- feature_flag_key: Optional[str] = None,-) -> list[ast.Expr]:- """- Builds common exposure conditions that are shared across exposure queries.-- Args:- feature_flag_variant_property: Property containing the variant value- variants: List of valid variant keys- date_range_query: Date range for the query- team: Team object for test account filtering- exposure_criteria: Experiment exposure criteria configuration- feature_flag_key: Feature flag key (required for $feature_flag_called events)- """- criteria = normalize_to_exposure_criteria(exposure_criteria)-- return [- # Date range filters- ast.CompareOperation(- op=ast.CompareOperationOp.GtEq,- left=ast.Field(chain=["timestamp"]),- right=ast.Constant(value=date_range_query.date_from()),- ),- ast.CompareOperation(- op=ast.CompareOperationOp.LtEq,- left=ast.Field(chain=["timestamp"]),- right=ast.Constant(value=date_range_query.date_to()),- ),- # Variant filter- ast.CompareOperation(- op=ast.CompareOperationOp.In,- left=ast.Field(chain=["properties", feature_flag_variant_property]),- right=ast.Constant(value=variants),- ),- # Test accounts filter- *get_test_accounts_filter(team, criteria),- # Event/action and property filters- *build_exposure_event_conditions(criteria, team, feature_flag_key),- ]--def get_entity_key(group_type_index: Optional[int]) -> str:"""Returns the appropriate entity key based on whether we're dealing with groups or persons.diff --git a/products/experiments/backend/hogql_queries/test/test_exposure_query_logic.py b/products/experiments/backend/hogql_queries/test/test_exposure_query_logic.pyindex 2ee376f98e8c..142c5d92e32f 100644--- a/products/experiments/backend/hogql_queries/test/test_exposure_query_logic.py+++ b/products/experiments/backend/hogql_queries/test/test_exposure_query_logic.py@@ -1,8 +1,71 @@import pytest+from parameterized import parameterized+from posthog.schema import ExperimentEventExposureConfig, ExperimentExposureCriteria-from products.experiments.backend.hogql_queries.exposure_query_logic import normalize_to_exposure_criteria+from products.experiments.backend.hogql_queries.exposure_query_logic import (+ DEFAULT_EXPOSURE_EVENT,+ EXPERIMENT_EXPOSURE_EVENT,+ get_exposure_event_and_property,+ normalize_to_exposure_criteria,+)+++def _event_config(event):+ return {"exposure_config": {"kind": "ExperimentEventExposureConfig", "event": event, "properties": []}}+++class TestGetExposureEventAndProperty:+ @parameterized.expand(+ [+ # (name, exposure criteria, resolved default event, expected (event, variant property))+ # Default-shaped configs must follow the resolved event the analysis queries count on,+ # or the replay surfaces that resolve (session buckets) read a different population.+ ("no_config", None, EXPERIMENT_EXPOSURE_EVENT, (EXPERIMENT_EXPOSURE_EVENT, "$feature_flag_response")),+ (+ "stored_default_config",+ _event_config("$feature_flag_called"),+ EXPERIMENT_EXPOSURE_EVENT,+ (EXPERIMENT_EXPOSURE_EVENT, "$feature_flag_response"),+ ),+ # An explicit $experiment_exposure config keeps its event either side of the rollout,+ # with the variant on $feature_flag_response since the event duplicates flag calls.+ (+ "explicit_rollout_event_config",+ _event_config("$experiment_exposure"),+ DEFAULT_EXPOSURE_EVENT,+ (EXPERIMENT_EXPOSURE_EVENT, "$feature_flag_response"),+ ),+ # Custom events and actions are untouched by the rollout.+ (+ "custom_event",+ _event_config("checkout_started"),+ EXPERIMENT_EXPOSURE_EVENT,+ ("checkout_started", "$feature/my-flag"),+ ),+ (+ "action",+ {"exposure_config": {"kind": "ActionsNode", "id": 42}},+ EXPERIMENT_EXPOSURE_EVENT,+ (None, "$feature/my-flag"),+ ),+ # Callers that deliberately stay on the legacy event pass it explicitly.+ (+ "legacy_event_passed_explicitly",+ None,+ DEFAULT_EXPOSURE_EVENT,+ (DEFAULT_EXPOSURE_EVENT, "$feature_flag_response"),+ ),+ ]+ )+ def test_resolves_default_exposure_against_the_rollout_event(+ self, _name, exposure_criteria, default_exposure_event, expected+ ):+ assert (+ get_exposure_event_and_property("my-flag", exposure_criteria, default_exposure_event=default_exposure_event)+ == expected+ )class TestNormalizeToExposureCriteria:diff --git a/products/experiments/backend/session_buckets.py b/products/experiments/backend/session_buckets.pyindex 6507d58d8da4..78b718cc78ff 100644--- a/products/experiments/backend/session_buckets.py+++ b/products/experiments/backend/session_buckets.py@@ -17,7 +17,9 @@ variants. Not the exposure query's `exposure_session_id`, which is the person'sexposure session only: the playlist ANDs these ids with its own exposure filter, so ids itwould reject are wasted slots out of the cap, and the later sessions `exposure_session_id`omits are exactly where drop-off and conversion happen. `exposure_session_id` is the right-source for a future person-scoped bucket, not for a session-scoped one.+source for a future person-scoped bucket, not for a session-scoped one. The default exposure+event goes through the same `resolve_default_exposure_event` rollout resolution the analysis+queries apply, so an experiment whose results count `$experiment_exposure` is bucketed on it too.Whether an event can match sessions at all is decided here, from the same `EventProperty` factthe taxonomy `seen_together` endpoint serves the tab: an event never ingested with a@@ -63,10 +65,12 @@ from posthog.utils import get_safe_cache, safe_cache_setfrom products.access_control.backend.property_access_control import get_restricted_properties_for_teamfrom products.experiments.backend.hogql_queries.exposure_query_logic import (DEFAULT_EXPOSURE_EVENT,+ EXPERIMENT_EXPOSURE_EVENT,build_exposure_event_conditions,get_exposure_event_and_property,get_test_accounts_filter,normalize_to_exposure_criteria,+ resolve_default_exposure_event,)from products.experiments.backend.metric_events import (MetricEventSource,@@ -256,7 +260,12 @@ def get_experiment_session_bucket(limit = min(limit, MAX_SESSION_BUCKET_LIMIT)requested = _resolve_requested_metrics(experiment, metric_uuids)- exposure_event, _ = get_exposure_event_and_property(experiment.feature_flag.key, experiment.exposure_criteria)+ # The same rollout resolution the analysis queries apply, so the bucket population is counted+ # on the event the experiment's results actually read.+ default_exposure_event = resolve_default_exposure_event(team, experiment.start_date)+ exposure_event, _ = get_exposure_event_and_property(+ experiment.feature_flag.key, experiment.exposure_criteria, default_exposure_event=default_exposure_event+ )# One EventProperty read covers both linkability decisions — whether the exposure event can# match sessions at all, and which metrics can. The verdict must be the endpoint's own:@@ -271,16 +280,22 @@ def get_experiment_session_bucket(for metric in requested:lookup_names |= _concrete_event_names(metric)never_linked = _never_session_linked_events(team, lookup_names)- use_exposure_fallback = exposure_event == DEFAULT_EXPOSURE_EVENT and exposure_event in never_linked+ # Both default exposure events mean "this user was enrolled via the flag", which the stamped+ # flag property implies too, so either can take the fallback.+ use_exposure_fallback = (+ exposure_event in (DEFAULT_EXPOSURE_EVENT, EXPERIMENT_EXPOSURE_EVENT) and exposure_event in never_linked+ )if exposure_event in never_linked and not use_exposure_fallback:- # Only the default event has a stand-in. Custom criteria assert that something specific+ # Only the default events have a stand-in. Custom criteria assert that something specific# happened, which the stamped flag property doesn't imply, so falling back would answer# over "the flag was active in this session" — a wider population than the criteria name.raise SessionBucketUnavailable(CUSTOM_EXPOSURE_UNLINKABLE_REASON)considered, excluded = _partition_metrics(requested, bucket, never_linked)- cache_key = _cache_key(team, user, experiment, bucket, considered, variant, window_start, window_end, limit)+ cache_key = _cache_key(+ team, user, experiment, bucket, considered, variant, window_start, window_end, limit, default_exposure_event+ )cached = get_safe_cache(cache_key)if cached is not None:return cached@@ -296,6 +311,7 @@ def get_experiment_session_bucket(window_end=window_end,limit=limit,use_exposure_fallback=use_exposure_fallback,+ default_exposure_event=default_exposure_event,)result = SessionBucketScan(candidate_session_ids=candidate_session_ids,@@ -324,6 +340,7 @@ def _cache_key(window_start: datetime,window_end: datetime,limit: int,+ default_exposure_event: str,) -> str:# The version segment must be bumped whenever SessionBucketScan changes shape: entries are# pickled, so a deploy would otherwise restore instances missing the new fields.@@ -339,6 +356,9 @@ def _cache_key(# Part of the key even though the cut happens on read: the scan over-fetches a# multiple of the limit, so a larger one looks further than a cached smaller one did.limit,+ # The rollout flag can flip which event the default exposure reads mid-window, and a+ # scan computed on the other event must not be served after the flip.+ default_exposure_event,# Property restrictions are compiled into the SQL, so unlike recording access they# can't be re-filtered on read; a restriction change has to miss the cache instead.sorted(get_restricted_properties_for_team(user=user, team=team)),@@ -533,9 +553,12 @@ def _query_bucket_sessions(window_end: datetime,limit: int,use_exposure_fallback: bool,+ default_exposure_event: str,) -> tuple[list[str], bool]:flag_key = experiment.feature_flag.key- _event, variant_property = get_exposure_event_and_property(flag_key, experiment.exposure_criteria)+ _event, variant_property = get_exposure_event_and_property(+ flag_key, experiment.exposure_criteria, default_exposure_event=default_exposure_event+ )if use_exposure_fallback:variant_property = f"$feature/{flag_key}"@@ -558,7 +581,9 @@ def _query_bucket_sessions(# flag's value on each event rather than the exposure response.return variant_conditionconditions = [- *build_exposure_event_conditions(experiment.exposure_criteria, team, flag_key),+ *build_exposure_event_conditions(+ experiment.exposure_criteria, team, flag_key, default_exposure_event=default_exposure_event+ ),variant_condition,]return ast.And(exprs=conditions) if len(conditions) > 1 else conditions[0]diff --git a/products/experiments/backend/session_context.py b/products/experiments/backend/session_context.pyindex d67e1fb25b3a..a95f6b46b8a8 100644--- a/products/experiments/backend/session_context.py+++ b/products/experiments/backend/session_context.py@@ -53,6 +53,7 @@ from products.cohorts.backend.models.cohort import Cohort# module attribute so it always sees the same value the scan applies (tests patch it there).from products.experiments.backend import metric_eventsfrom products.experiments.backend.hogql_queries.exposure_query_logic import (+ DEFAULT_EXPOSURE_EVENT,build_exposure_event_conditions,get_exposure_event_and_property,normalize_to_exposure_criteria,@@ -576,8 +577,8 @@ def _compute_chunk_contexts(if experiment.end_date is not None and experiment.end_date < window.recording_start:continueflag_key = experiment.feature_flag.key- # Only the flag's defined variant keys count, mirroring the `variant IN variants` filter in- # build_common_exposure_conditions: a non-enrolled user's flag evaluation captures+ # Only the flag's defined variant keys count, mirroring the `variant IN variants` filter+ # in the analysis queries: a non-enrolled user's flag evaluation captures# `$feature_flag_response: false`, which must not surface as a variant named "false".defined_variants = resolved.variant_keys_by_id.get(experiment.pk, set())exposure_rows = [row for row in session_exposures.get(experiment.pk, []) if row[0] in defined_variants]@@ -721,7 +722,13 @@ def _resolve_exposure(flag_key: str, exposure_criteria: Optional[dict]) -> _Resoexcept pydantic.ValidationError:criteria = Noneexposure_config = criteria.exposure_config if criteria else None- event, variant_property = get_exposure_event_and_property(flag_key, criteria)+ # This surface deliberately stays on the legacy default rather than resolving the+ # $experiment_exposure rollout per experiment: its shared flag-evaluations query reads+ # $feature_flag_called, and while ingestion emits both events every exposure still lands on+ # the same sessions, so the legacy event stays correct here for now.+ event, variant_property = get_exposure_event_and_property(+ flag_key, criteria, default_exposure_event=DEFAULT_EXPOSURE_EVENT+ )# Only experiments whose criteria resolve to the plain `$feature_flag_called` shape (no# extra property filters) can share the batched query. The literal is deliberate — it names# the batched query's shape, not the default: if DEFAULT_EXPOSURE_EVENT ever changes in@@ -825,7 +832,10 @@ def _query_exposure_event_branches(# Built here, after the branch cap, so classification stays DB-free for experiments# the slice discards (action-based conditions cost a Postgres lookup each).try:- conditions = build_exposure_event_conditions(resolution.criteria, team, resolution.flag_key)+ # The same deliberate legacy-event choice as `_resolve_exposure` above.+ conditions = build_exposure_event_conditions(+ resolution.criteria, team, resolution.flag_key, default_exposure_event=DEFAULT_EXPOSURE_EVENT+ )except (Cohort.DoesNotExist, BaseHogQLError):# Criteria this project can't resolve — a cohort filter whose cohort doesn't exist# here (e.g. a duplicated experiment carrying the source project's cohort id), or adiff --git a/products/experiments/backend/test/test_freeze_exposure_clickhouse.py b/products/experiments/backend/test/test_freeze_exposure_clickhouse.pyindex 28f70c17abd3..8e565e7d682d 100644--- a/products/experiments/backend/test/test_freeze_exposure_clickhouse.py+++ b/products/experiments/backend/test/test_freeze_exposure_clickhouse.py@@ -1,15 +1,23 @@from datetime import datetime, timedelta+from typing import Any+from freezegun import freeze_timefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_eventsfrom unittest.mock import patchfrom django.utils import timezone+from parameterized import parameterizedfrom rest_framework.exceptions import ValidationErrorfrom posthog.models.person import Personfrom products.experiments.backend.experiment_service import ExperimentService+from products.experiments.backend.hogql_queries.exposure_query_logic import (+ EXPERIMENT_EXPOSURE_EVENT,+ EXPERIMENT_EXPOSURE_EVENT_CUTOFF,+ EXPERIMENT_EXPOSURE_EVENT_FLAG,+)from products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -19,7 +27,9 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlag# condition gates new users while enrolled users keep their variant) is owned by the Rust flags service —# see test_static_cohort_matching_* in rust/feature-flags/src/flags/test_flag_matching.rs.class TestFreezeExposureClickhouse(ClickhouseTestMixin, APIBaseTest):- def _create_running_experiment(self, flag_key: str, exposure_criteria: dict | None = None) -> Experiment:+ def _create_running_experiment(+ self, flag_key: str, exposure_criteria: dict | None = None, start_date: datetime | None = None+ ) -> Experiment:flag = FeatureFlag.objects.create(team=self.team,created_by=self.user,@@ -39,7 +49,7 @@ class TestFreezeExposureClickhouse(ClickhouseTestMixin, APIBaseTest):name=f"Experiment {flag_key}",team=self.team,feature_flag=flag,- start_date=timezone.now() - timedelta(days=7),+ start_date=start_date or (timezone.now() - timedelta(days=7)),created_by=self.user,exposure_criteria=exposure_criteria or {},)@@ -55,10 +65,11 @@ class TestFreezeExposureClickhouse(ClickhouseTestMixin, APIBaseTest):extra_properties: dict | None = None,) -> Person:"""Create a person plus an exposure event shaped like the real SDK payloads:- $feature_flag_called carries $feature_flag/$feature_flag_response, any other- (custom exposure) event carries the $feature/<key> enrollment property."""+ $feature_flag_called and its ingestion duplicate $experiment_exposure carry+ $feature_flag/$feature_flag_response, any other (custom exposure) event carries the+ $feature/<key> enrollment property."""person = _create_person(team=self.team, distinct_ids=[distinct_id])- if event == "$feature_flag_called":+ if event in ("$feature_flag_called", EXPERIMENT_EXPOSURE_EVENT):properties: dict = {"$feature_flag": flag_key}if variant is not None:properties["$feature_flag_response"] = variant@@ -124,6 +135,42 @@ class TestFreezeExposureClickhouse(ClickhouseTestMixin, APIBaseTest):assert uuids == [str(exposed.uuid)]+ @parameterized.expand(+ [+ # (name, rollout flag enabled, experiment start offset from the cutoff, expected event)+ ("after_cutoff", True, 7, EXPERIMENT_EXPOSURE_EVENT),+ ("after_cutoff_flag_disabled", False, 7, "$feature_flag_called"),+ ("before_cutoff", True, -7, "$feature_flag_called"),+ ]+ )+ @freeze_time(EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=10))+ def test_fetch_exposed_person_uuids_reads_the_resolved_exposure_event(+ self, _name: str, flag_enabled: bool, start_offset_days: int, expected_event: str+ ) -> None:+ experiment = self._create_running_experiment(+ "freeze-rollout-flag", start_date=EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=start_offset_days)+ )+ exposed_at = EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=8)+ new_event_person = self._expose_person(+ "new-event-user", "freeze-rollout-flag", exposed_at, event=EXPERIMENT_EXPOSURE_EVENT+ )+ legacy_event_person = self._expose_person("legacy-event-user", "freeze-rollout-flag", exposed_at)+ flush_persons_and_events()++ # Only answer for the exposure-event flag; returning True for every flag would flip+ # unrelated flag-gated behavior on and change what's under test.+ def fake_feature_enabled(flag_key: str, *args: Any, **kwargs: Any) -> bool:+ return flag_enabled if flag_key == EXPERIMENT_EXPOSURE_EVENT_FLAG else False++ with patch("posthoganalytics.feature_enabled", side_effect=fake_feature_enabled):+ uuids = self._service()._fetch_exposed_person_uuids(experiment)++ # The snapshot decides who keeps being served a variant, so it must count exposures on+ # the event the analysis resolves to: read off the other event, a post-cutoff experiment+ # would freeze an empty set once the two events stop being emitted together.+ expected_person = new_event_person if expected_event == EXPERIMENT_EXPOSURE_EVENT else legacy_event_person+ assert uuids == [str(expected_person.uuid)]+def test_fetch_exposed_person_uuids_ignores_test_account_filters(self) -> None:# filterTestAccounts shapes which exposures are *analyzed*; the snapshot decides who keeps# being *served* a variant. Applying it here would evict the team's own users at freezediff --git a/products/experiments/backend/test/test_session_buckets_api.py b/products/experiments/backend/test/test_session_buckets_api.pyindex cdbb5e246efb..e7559d98731a 100644--- a/products/experiments/backend/test/test_session_buckets_api.py+++ b/products/experiments/backend/test/test_session_buckets_api.py@@ -20,6 +20,11 @@ from posthog.session_recordings.models.session_recording import SessionRecordingfrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom products.actions.backend.models.action import Action+from products.experiments.backend.hogql_queries.exposure_query_logic import (+ EXPERIMENT_EXPOSURE_EVENT,+ EXPERIMENT_EXPOSURE_EVENT_CUTOFF,+ EXPERIMENT_EXPOSURE_EVENT_FLAG,+)from products.experiments.backend.models.experiment import Experimentfrom products.experiments.backend.session_buckets import MAX_BUCKET_METRICS, MAX_BUCKET_SCAN_DAYS, MAX_BUCKET_SOURCESfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -158,6 +163,7 @@ class TestExperimentSessionBuckets(ClickhouseTestMixin, APILicensedTest):at: datetime = datetime(2026, 1, 9, 10, 0, 0, tzinfo=UTC),with_recording: bool = True,flag_key: str = "checkout-cta",+ exposure_event: str = "$feature_flag_called",distinct_id: str = "user1",properties: Optional[dict[str, Any]] = None,) -> str:@@ -178,7 +184,7 @@ class TestExperimentSessionBuckets(ClickhouseTestMixin, APILicensedTest):if variant is not None:_create_event(team=self.team,- event="$feature_flag_called",+ event=exposure_event,distinct_id=distinct_id,timestamp=at,properties={@@ -200,7 +206,7 @@ class TestExperimentSessionBuckets(ClickhouseTestMixin, APILicensedTest):# captured with a $session_id here must leave the same trace they would in production.ingested = {event for event, _ in events or []}if variant is not None:- ingested.add("$feature_flag_called")+ ingested.add(exposure_event)for event_name in ingested:EventProperty.objects.get_or_create(team=self.team, project_id=self.team.project_id, event=event_name, property="$session_id"@@ -495,6 +501,92 @@ class TestExperimentSessionBuckets(ClickhouseTestMixin, APILicensedTest):# must not widen to "the flag was active".assert purchased not in str(response.json())+ @parameterized.expand(+ [+ # (name, rollout flag enabled, experiment start offset from the cutoff, expected event)+ ("after_cutoff", True, 7, EXPERIMENT_EXPOSURE_EVENT),+ ("after_cutoff_flag_disabled", False, 7, "$feature_flag_called"),+ ("before_cutoff", True, -7, "$feature_flag_called"),+ ]+ )+ @freeze_time(EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=10))+ def test_bucket_population_reads_the_resolved_exposure_event(+ self, _name: str, flag_enabled: bool, start_offset_days: int, expected_event: str+ ) -> None:+ # setUp logged in under the class-level freeze, months before this test's frozen clock,+ # so that session has expired; log in again inside the window.+ self.client.force_login(self.user)+ experiment = self._create_experiment(+ metrics=[PURCHASE_METRIC],+ start_date=EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=start_offset_days),+ )+ at = EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=8)+ purchase_at = at + timedelta(minutes=5)+ new_event_session = self._session(+ exposure_event=EXPERIMENT_EXPOSURE_EVENT, at=at, events=[("purchase", purchase_at)]+ )+ legacy_event_session = self._session(+ exposure_event="$feature_flag_called", at=at, distinct_id="user2", events=[("purchase", purchase_at)]+ )+ other_flag_session = self._session(+ exposure_event=EXPERIMENT_EXPOSURE_EVENT,+ flag_key="unrelated-flag",+ at=at,+ distinct_id="user3",+ events=[("purchase", purchase_at)],+ )+ flush_persons_and_events()++ # Only answer for the exposure-event flag; returning True for every flag would flip+ # unrelated HogQL query modifiers on and break the query under test.+ def fake_feature_enabled(flag_key: str, *args: Any, **kwargs: Any) -> bool:+ return flag_enabled if flag_key == EXPERIMENT_EXPOSURE_EVENT_FLAG else False++ with patch("posthoganalytics.feature_enabled", side_effect=fake_feature_enabled):+ response = self._post_bucket(experiment, bucket="fired_any", metric_uuids=[PURCHASE_METRIC["uuid"]])++ # The analysis queries resolve the default exposure event per experiment+ # (resolve_default_exposure_event), and the playlist ANDs these ids with an exposure+ # filter the frontend builds from the same resolved event. A bucket read off the other+ # event intersects two different populations once the two events stop being emitted+ # together.+ assert response.status_code == status.HTTP_200_OK, response.json()+ expected_session = new_event_session if expected_event == EXPERIMENT_EXPOSURE_EVENT else legacy_event_session+ assert response.json()["session_ids"] == [expected_session]+ # $experiment_exposure is emitted for every experiment, so matching it must still require+ # this experiment's flag key.+ assert other_flag_session not in response.json()["session_ids"]+ assert response.json()["used_exposure_fallback"] is False++ @freeze_time(EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=10))+ def test_rollout_exposure_event_captured_server_side_keeps_the_stamped_property_fallback(self) -> None:+ self.client.force_login(self.user)+ experiment = self._create_experiment(+ metrics=[PURCHASE_METRIC],+ start_date=EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=7),+ )+ at = EXPERIMENT_EXPOSURE_EVENT_CUTOFF + timedelta(days=8)+ purchased = self._session(+ variant=None,+ at=at,+ events=[("purchase", at + timedelta(minutes=5))],+ properties={"$feature/checkout-cta": "test"},+ )+ flush_persons_and_events()++ def fake_feature_enabled(flag_key: str, *args: Any, **kwargs: Any) -> bool:+ return flag_key == EXPERIMENT_EXPOSURE_EVENT_FLAG++ with patch("posthoganalytics.feature_enabled", side_effect=fake_feature_enabled):+ response = self._post_bucket(experiment, bucket="fired_any", metric_uuids=[PURCHASE_METRIC["uuid"]])++ # Under the rollout $experiment_exposure is the default exposure, not a custom choice, so+ # exposure evaluated in a backend SDK must keep the stamped-property fallback rather than+ # being refused the way a custom event is.+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["session_ids"] == [purchased]+ assert response.json()["used_exposure_fallback"] is True+@parameterized.expand([("custom_event",), ("action",)])def test_session_linkable_custom_exposure_defines_the_population(self, exposure_kind: str) -> None:if exposure_kind == "action":