: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
feat(experiments): resolve exposure criteria in replay session context (#70390)
Marcel Poelker4288be6408ad
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex a15c8ad5d4a4..92e3b078f189 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4883,9 +4883,9 @@ snapshots:replay-overview-tab--wide-overview-tab--light:hash: v1.k794b7964.deb71477c91ae3fb89eaa9c6c9a45e665db4fa8363df4de30b3737c655930825.n5T9fmKBWN7qXDwbX9sYPEtdRgVYiaUgrJfvtail2tgreplay-overview-tab-experiments--default--dark:- hash: v1.k794b7964.5cbc26da39e7718b62460092dbce59b08b84c3612ff69a70ee9a4170bd81fdf0.xgwevIZkU275d5dfBQDpVPyqMN2yuMD8jtssHXaGcqA+ hash: v1.k794b7964.25a125f1ccda9f810a1e6d396031977f27bdb0871bccaa500afbbdfe495d551d.1yCi_OiCfAFcalukt75bILwNnkYCfyi07maDMAtzqYAreplay-overview-tab-experiments--default--light:- hash: v1.k794b7964.6239732354e9a97789dfaf32ed69dea36280207beb8d053f20481ed2af3ac007.6W8kIpHPVpu7W_lpIvfqNGPf7j12I5vidjJEx2Arr6w+ hash: v1.k794b7964.ab0755b8da5c67099503a8ae53ee63e34c0ea513dd3b7fd1baa0905067a7ea01.iSLqrIDxgzlGZ1DT7vgBu8DtMPs56SESNRW7avoHa8greplay-overview-tab-experiments--empty--dark:hash: v1.k794b7964.13e51a486b40a1455fde0075af333e3dff21f25491d06cc59ab10c24200eb1d2.Fn0OHVeRm39HLB3-xcZUZavR375CxuNraJZdmfxTS-Ureplay-overview-tab-experiments--empty--light:diff --git a/frontend/src/scenes/session-recordings/__mocks__/experiment_session_context.ts b/frontend/src/scenes/session-recordings/__mocks__/experiment_session_context.tsindex d267d4a9f29a..9f8b7b53997f 100644--- a/frontend/src/scenes/session-recordings/__mocks__/experiment_session_context.ts+++ b/frontend/src/scenes/session-recordings/__mocks__/experiment_session_context.ts@@ -12,13 +12,13 @@ export const makeExperimentSessionContextItem = (variant: 'test',variants_seen: ['test'],multiple_variants: false,- first_flag_evaluation_timestamp: '2023-05-01T14:46:24.000000Z',+ first_exposure_timestamp: '2023-05-01T14:46:24.000000Z',experiment_start_date: '2023-04-01T00:00:00Z',experiment_end_date: null,...overrides,})-/** One of each interesting state: single variant, multi-variant warning, carried-over assignment. */+/** One of each interesting state: single variant, multi-variant warning, no in-session exposure event. */export const experimentSessionContextResponse: ExperimentSessionContextResponseApi = {session_id: 'experiment-context-session',results: [@@ -35,7 +35,7 @@ export const experimentSessionContextResponse: ExperimentSessionContextResponseAexperiment_id: 103,experiment_name: 'Onboarding checklist',flag_key: 'onboarding-checklist',- first_flag_evaluation_timestamp: null,+ first_exposure_timestamp: null,}),],}diff --git a/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.test.ts b/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.test.tsindex 007af3b12d53..15450fe6229a 100644--- a/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.test.ts+++ b/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.test.ts@@ -20,7 +20,7 @@ const experimentContextResponse = {variant: 'test',variants_seen: ['test'],multiple_variants: false,- first_flag_evaluation_timestamp: '2023-08-11T12:03:40.000Z',+ first_exposure_timestamp: '2023-08-11T12:03:40.000Z',experiment_start_date: '2023-08-01T00:00:00Z',experiment_end_date: null,},@@ -31,7 +31,7 @@ const experimentContextResponse = {variant: 'control',variants_seen: ['control'],multiple_variants: false,- first_flag_evaluation_timestamp: null,+ first_exposure_timestamp: null,experiment_start_date: '2023-08-01T00:00:00Z',experiment_end_date: null,},@@ -249,7 +249,7 @@ describe('playerInspectorLogic', () => {logic.mount()}- it('synthesizes one marker per context item with a flag-evaluation timestamp', async () => {+ it('synthesizes one marker per context item with a first-exposure timestamp', async () => {remountWithFlagState(true)const contextLogic = sessionRecordingExperimentContextLogic({ sessionRecordingId: '1' })diff --git a/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.ts b/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.tsindex f861db78bcc4..d87d9f7ac4e9 100644--- a/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.ts+++ b/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.ts@@ -207,7 +207,7 @@ export type InspectorListItemExperimentVariant = InspectorListItemBase & {type: 'experiment-variant'data: {// Synthesized client-side from the experiments session_context endpoint response- // (first_flag_evaluation_timestamp) — there is no backend event for this item, so it is+ // (first_exposure_timestamp) — there is no backend event for this item, so it is// not part of the loaded event stream. `id` keeps the same keying contract as// event/comment items in the seekbar.id: string@@ -1269,13 +1269,13 @@ export const playerInspectorLogic = kea<playerInspectorLogicType>([): InspectorListItemExperimentVariant[] => {const items: InspectorListItemExperimentVariant[] = []for (const item of experimentItems || []) {- // Without a $feature_flag_called event there is no in-session moment to mark —- // the assignment carried over from an earlier session.- if (!item.first_flag_evaluation_timestamp) {+ // Without an exposure event in this session there is no in-session moment+ // to mark — the variant is only known from stamped flag properties.+ if (!item.first_exposure_timestamp) {continue}const { timestamp, timeInRecording } = timeRelativeToStart(- { timestamp: item.first_flag_evaluation_timestamp },+ { timestamp: item.first_exposure_timestamp },start)items.push({@@ -1405,7 +1405,7 @@ export const playerInspectorLogic = kea<playerInspectorLogicType>([items.push(item)}- // Add experiment variant-assignment markers (flag-evaluation moments)+ // Add experiment first-exposure markersfor (const item of experimentVariantItems) {items.push(item)}diff --git a/frontend/src/scenes/session-recordings/player/player-meta/PlayerMetaExperimentTags.tsx b/frontend/src/scenes/session-recordings/player/player-meta/PlayerMetaExperimentTags.tsxindex db1a3674e149..47d618d9a655 100644--- a/frontend/src/scenes/session-recordings/player/player-meta/PlayerMetaExperimentTags.tsx+++ b/frontend/src/scenes/session-recordings/player/player-meta/PlayerMetaExperimentTags.tsx@@ -25,7 +25,7 @@ export function PlayerMetaExperimentTags(): JSX.Element | null {const { setSidebarOpen } = useActions(playerSettingsLogic)// Only surface the chip when something experiment-related happened *in this recording*.- // Enrollments carried over from earlier sessions have nothing visible to watch, so they+ // Enrollments without an in-session exposure event have nothing visible to watch, so they// live in the overview sidebar rather than cluttering the player header.if (seenCount === 0) {return null@@ -62,7 +62,7 @@ export function PlayerMetaExperimentTags(): JSX.Element | null {<Tooltiptitle={`Enrolled in ${enrolledCount} experiment${enrolledCount === 1 ? '' : 's'- }, carried over from earlier sessions. Click to view.`}+ } without an exposure event in this recording. Click to view.`}><LemonTag type="muted" onClick={openOverview} forceClickable>Enrolled in {enrolledCount} experiment{enrolledCount === 1 ? '' : 's'}diff --git a/frontend/src/scenes/session-recordings/player/player-meta/sessionRecordingExperimentContextLogic.test.ts b/frontend/src/scenes/session-recordings/player/player-meta/sessionRecordingExperimentContextLogic.test.tsindex d8d079d038a1..87288b19ad3e 100644--- a/frontend/src/scenes/session-recordings/player/player-meta/sessionRecordingExperimentContextLogic.test.ts+++ b/frontend/src/scenes/session-recordings/player/player-meta/sessionRecordingExperimentContextLogic.test.ts@@ -18,7 +18,7 @@ const mockResponse = {variant: 'test',variants_seen: ['control', 'test'],multiple_variants: true,- first_flag_evaluation_timestamp: '2026-07-01T10:02:11Z',+ first_exposure_timestamp: '2026-07-01T10:02:11Z',experiment_start_date: '2026-06-01T00:00:00Z',experiment_end_date: null,},diff --git a/frontend/src/scenes/session-recordings/player/player-meta/sessionRecordingExperimentContextLogic.ts b/frontend/src/scenes/session-recordings/player/player-meta/sessionRecordingExperimentContextLogic.tsindex c39cac6cdeba..ce292d768188 100644--- a/frontend/src/scenes/session-recordings/player/player-meta/sessionRecordingExperimentContextLogic.ts+++ b/frontend/src/scenes/session-recordings/player/player-meta/sessionRecordingExperimentContextLogic.ts@@ -134,26 +134,25 @@ export const sessionRecordingExperimentContextLogic = kea<sessionRecordingExperi(experimentContext: ExperimentSessionContextResponseApi | null): ExperimentSessionContextItemApi[] =>experimentContext?.results ?? [],],- // Experiments whose flag was evaluated during this recording — these have a moment on the timeline to jump to.+ // Experiments with an exposure event during this recording — these have a moment on the timeline to jump to.seenItems: [(s) => [s.experimentItems],(experimentItems: ExperimentSessionContextItemApi[]): ExperimentSessionContextItemApi[] =>experimentItems- .filter((item) => item.first_flag_evaluation_timestamp != null)+ .filter((item) => item.first_exposure_timestamp != null).sort((a, b) =>experimentSignalRank(a) - experimentSignalRank(b) ||- (a.first_flag_evaluation_timestamp ?? '').localeCompare(- b.first_flag_evaluation_timestamp ?? ''- )+ (a.first_exposure_timestamp ?? '').localeCompare(b.first_exposure_timestamp ?? '')),],- // Experiments the person is enrolled in but with no flag evaluation in this session (carried over from an earlier one).+ // Experiments the person is enrolled in but with no exposure event in this session — the variant+ // is only known from stamped flag properties.enrolledItems: [(s) => [s.experimentItems],(experimentItems: ExperimentSessionContextItemApi[]): ExperimentSessionContextItemApi[] =>experimentItems- .filter((item) => item.first_flag_evaluation_timestamp == null)+ .filter((item) => item.first_exposure_timestamp == null).sort((a, b) =>experimentSignalRank(a) - experimentSignalRank(b) ||@@ -169,8 +168,8 @@ export const sessionRecordingExperimentContextLogic = kea<sessionRecordingExperi(s) => [s.experimentItems],(experimentItems: ExperimentSessionContextItemApi[]): boolean => experimentItems.length > 0,],- // Scoped to seenItems: this warns the chip that summarizes only in-recording experiments, so a- // carried-over enrollment that saw multiple variants must not trigger the warning.+ // Scoped to seenItems: this warns the chip that summarizes only in-recording experiments, so an+ // enrollment without an in-session exposure that saw multiple variants must not trigger the warning.hasMultipleVariantWarning: [(s) => [s.seenItems],(seenItems: ExperimentSessionContextItemApi[]): boolean => seenItems.some((item) => item.multiple_variants),diff --git a/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.tsx b/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.tsxindex 6935e8223059..41b4d14deccd 100644--- a/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.tsx+++ b/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.tsx@@ -87,25 +87,25 @@ export function PlayerSidebarExperimentsSection(): JSX.Element | null {<h4 className="font-semibold text-xs mb-0">Experiments</h4>{seenItems.map((item) => {- const evaluatedAtMs = item.first_flag_evaluation_timestamp- ? dayjs(item.first_flag_evaluation_timestamp).valueOf()+ const exposedAtMs = item.first_exposure_timestamp+ ? dayjs(item.first_exposure_timestamp).valueOf(): null- // The backend can return a flag-evaluation timestamp from its ±1h slack around the+ // The backend can return an exposure timestamp from its ±1h slack around the// recording; seeking to an out-of-bounds time silently clamps to a boundary, so only// offer the jump when the moment falls inside the playable recording.const canSeek =- evaluatedAtMs != null &&+ exposedAtMs != null &&recordingStartMs != null &&recordingEndMs != null &&- evaluatedAtMs >= recordingStartMs &&- evaluatedAtMs <= recordingEndMs+ exposedAtMs >= recordingStartMs &&+ exposedAtMs <= recordingEndMsreturn (<div key={item.experiment_id} className="flex flex-row items-center gap-x-2 min-w-0">{canSeek ? (<LinkclassName="truncate flex-1 min-w-0"title="Jump to when this session matched the experiment's exposure criteria"- onClick={() => evaluatedAtMs != null && seekToTimestamp(evaluatedAtMs)}+ onClick={() => exposedAtMs != null && seekToTimestamp(exposedAtMs)}data-attr="replay-experiment-context-jump-to-first-exposure">{item.experiment_name}@@ -126,7 +126,7 @@ export function PlayerSidebarExperimentsSection(): JSX.Element | null {panels={[{key: 'enrolled',- header: `Also enrolled, carried over (${enrolledItems.length})`,+ header: `Also enrolled, not exposed in this session (${enrolledItems.length})`,content: (<div className="flex flex-col gap-y-1">{enrolledItems.map((item) => (diff --git a/products/experiments/backend/hogql_queries/exposure_query_logic.py b/products/experiments/backend/hogql_queries/exposure_query_logic.pyindex 48494653c7e5..a9405af65d97 100644--- a/products/experiments/backend/hogql_queries/exposure_query_logic.py+++ b/products/experiments/backend/hogql_queries/exposure_query_logic.py@@ -27,6 +27,13 @@ from products.experiments.backend.hogql_queries import MULTIPLE_VARIANT_KEYlogger = logging.getLogger(__name__)+# The event an experiment counts exposures on when its criteria don't name one. If the default+# ever changes (e.g. to a dedicated exposure event), flip it here — consumers that resolve+# criteria through this module's helpers key off this constant. Note the variant-property+# pairing in `get_exposure_event_and_property` (and the handling of configs that explicitly+# name `$feature_flag_called`) must move with it.+DEFAULT_EXPOSURE_EVENT = "$feature_flag_called"+def _is_actions_node_dict(config: dict) -> bool:"""@@ -180,15 +187,15 @@ def get_exposure_event_and_property(else:# For the default $feature_flag_called event, we need to get the variant from $feature_flag_responsefeature_flag_variant_property = "$feature_flag_response"- event = "$feature_flag_called"+ event = DEFAULT_EXPOSURE_EVENTreturn event, feature_flag_variant_propertydef _get_event_name_from_config(exposure_config: Optional[Union[ActionsNode, ExperimentEventExposureConfig]]) -> str:- """Extract event name from exposure config, defaulting to $feature_flag_called."""+ """Extract event name from exposure config, defaulting to DEFAULT_EXPOSURE_EVENT."""if not exposure_config or not hasattr(exposure_config, "event"):- return "$feature_flag_called"+ return DEFAULT_EXPOSURE_EVENTevent = exposure_config.eventreturn str(event) if event and event != "$feature_flag_called" else "$feature_flag_called"diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 7f58cf2c02df..d752464b9e0f 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -1419,8 +1419,9 @@ class ExperimentSessionContextItemSerializer(serializers.Serializer):flag_key = serializers.CharField(help_text="Key of the experiment's feature flag.")variant = serializers.CharField(help_text=(- "Variant the session saw. Taken from the earliest $feature_flag_called event in the session when one "- "exists, otherwise from the $feature/<key> property stamped on the session's events."+ "Variant the session saw. Taken from the earliest event matching the experiment's exposure criteria "+ "when one exists, otherwise from the earliest flag evaluation in the session, otherwise from the "+ "$feature/<key> property stamped on the session's events."))variants_seen = serializers.ListField(@@ -1434,13 +1435,15 @@ class ExperimentSessionContextItemSerializer(serializers.Serializer):multiple_variants = serializers.BooleanField(help_text="True when the session saw more than one variant of this flag.")- first_flag_evaluation_timestamp = serializers.DateTimeField(+ first_exposure_timestamp = serializers.DateTimeField(allow_null=True,help_text=(- "Timestamp of the first $feature_flag_called event for this flag in the session — the moment the flag "- "was evaluated to the variant. Null when the variant is only known from stamped $feature/<key> "- "properties (e.g. the assignment carried over from an earlier session). For experiments with custom "- "exposure criteria this is not the experiment's exposure moment."+ "Timestamp of the first event in the session matching the experiment's exposure criteria — "+ "the default exposure event ($feature_flag_called), or the configured custom event/action. Null when "+ "no event in the session matched the criteria; the variant is then known from flag evaluations or "+ "stamped $feature/<key> properties. "+ "Session-scoped: the experiment analysis counts exposure per person across the whole run window, "+ "so the person's counted first exposure may lie in an earlier session."),)experiment_start_date = serializers.DateTimeField(allow_null=True, help_text="When the experiment was launched.")diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex c80badb216ff..663b3b5a257c 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -1248,7 +1248,11 @@ class EnterpriseExperimentsViewSet(experiments = self.user_access_control.filter_queryset_by_access_level(Experiment.objects.filter(team_id=self.team.pk))- items = get_session_experiment_context(team=self.team, session_id=session_id, experiments=experiments)+ # user threads through to the HogQL queries: exposure criteria can filter on arbitrary+ # properties, which must respect the viewer's property-level access control.+ items = get_session_experiment_context(+ team=self.team, session_id=session_id, experiments=experiments, user=cast(User, request.user)+ )if items is None:raise NotFound("Recording not found")diff --git a/products/experiments/backend/session_context.py b/products/experiments/backend/session_context.pyindex 9da5ed8dd30b..366bac5de6bb 100644--- a/products/experiments/backend/session_context.py+++ b/products/experiments/backend/session_context.py@@ -1,15 +1,22 @@"""Resolve which experiments (and variants) a session recording saw.-Variants come from the flag, via two complementary event signals:--- `$feature_flag_called` exposure events (carry `$feature_flag`, `$feature_flag_response`,- `$session_id`, and a timestamp — the flag-evaluation moment).+Variants come from the flag, via complementary event signals:++- `$feature_flag_called` flag evaluations: variant evidence for every experiment — the replay+ shows exactly what the session was served, whatever the exposure criteria say — and the+ exposure moment for experiments with the default criteria shape (variant in+ `$feature_flag_response`).+- Exposure events resolved per experiment from custom exposure criteria through the shared+ `exposure_query_logic` helpers: the configured event/action defines the exposure moment+ (variant in the stamped `$feature/<key>` property).- `$feature/<key>` properties stamped on every captured event by posthog-js. These cover theSDK dedupe gap: a returning user's later sessions may carry no exposure event at all.-Flag evaluation is not the same thing as the experiment's exposure criteria (custom exposure-events, holdouts, and the run window all differ), so callers must present this as what the-session *saw*, not what the experiment analysis counts.+The exposure timestamp follows each experiment's exposure criteria, but only within this+session: the experiment analysis counts exposure per person across the whole run window+(and applies test-account filtering and multiple-variant handling, which are deliberately+not applied here — this surface shows the raw session truth). Callers must present this as+what the session *saw*, not what the experiment analysis counts."""from dataclasses import dataclass@@ -18,13 +25,25 @@ from typing import Optionalfrom django.db.models import Q, QuerySet+import pydantic++from posthog.schema import ExperimentEventExposureConfig, ExperimentExposureCriteria+from posthog.hogql import ast+from posthog.hogql.errors import BaseHogQLErrorfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.models.team.team import Team+from posthog.models.user import Userfrom posthog.session_recordings.queries.session_replay_events import SessionReplayEvents+from products.cohorts.backend.models.cohort import Cohort+from products.experiments.backend.hogql_queries.exposure_query_logic import (+ build_exposure_event_conditions,+ get_exposure_event_and_property,+ normalize_to_exposure_criteria,+)from products.experiments.backend.models.experiment import Experiment# Slack around the recording bounds — flag evaluation can be captured slightly outside the@@ -38,6 +57,20 @@ MAX_CANDIDATE_EXPERIMENTS = 50MAX_EXPOSURE_ROWS = 10_000+@dataclass(frozen=True)+class _ResolvedExposure:+ """An experiment's exposure criteria resolved to what its exposure query needs: which+ property carries the variant, whether the experiment can share the batched default+ `$feature_flag_called` query, and the normalized criteria + flag key from which the+ per-experiment branch conditions are built — lazily, after the branch cap, since+ action-based conditions cost a Postgres lookup each."""++ flag_key: str+ variant_property: str+ criteria: Optional[ExperimentExposureCriteria]+ batchable: bool++@dataclass(frozen=True)class ExperimentSessionContextItem:experiment_id: int@@ -46,18 +79,21 @@ class ExperimentSessionContextItem:variant: strvariants_seen: list[str]multiple_variants: bool- first_flag_evaluation_timestamp: Optional[datetime]+ first_exposure_timestamp: Optional[datetime]experiment_start_date: Optional[datetime]experiment_end_date: Optional[datetime]def get_session_experiment_context(- team: Team, session_id: str, experiments: QuerySet[Experiment]+ team: Team, session_id: str, experiments: QuerySet[Experiment], user: User) -> Optional[list[ExperimentSessionContextItem]]:"""Returns the experiments the session saw, or None when the recording doesn't exist for this team.`experiments` is the caller's base queryset — the view passes it through object-levelaccess control so private experiments never surface in another user's session context.+ `user` is the viewer: exposure criteria can filter on arbitrary event/person properties,+ and the queries must enforce that user's property-level access control (as the experiment+ query runners do) — userless execution would apply only the default property rules."""metadata = SessionReplayEvents().get_metadata(session_id, team)if metadata is None:@@ -85,32 +121,74 @@ def get_session_experiment_context(window_end = recording_end + EVENT_WINDOW_SLACK# Every overlapping experiment's flag key (uncapped — the rescue below must be able to see- # beyond the candidate cap) and the union of their defined variant names. Filtering the- # exposure query to these bounds its cardinality by real configuration: sessions call+ # beyond the candidate cap), its exposure criteria, and its defined variant names. Filtering+ # the exposure queries to these bounds their cardinality by real configuration: sessions call# plenty of non-experiment flags, and event payloads can carry arbitrary keys/variants.- flag_meta = list(overlapping.values_list("feature_flag__key", "feature_flag__filters"))- experiment_flag_keys = {key for key, _ in flag_meta}- defined_variants = {variant for _, filters in flag_meta for variant in _variant_keys_from_filters(filters)}- if not defined_variants:+ flag_meta = list(+ overlapping.order_by("-start_date").values_list(+ "id", "feature_flag__key", "feature_flag__filters", "exposure_criteria"+ )+ )+ # Each experiment's exposure criteria resolve (through the shared helpers) to what counts+ # as its exposure event and which property carries the variant. Experiments with the plain+ # default shape take their exposure moment straight from the shared flag-evaluations query;+ # the rest get one union branch each. Everything is keyed by experiment id, since two+ # experiments can share a flag with different criteria.+ flag_key_by_id: dict[int, str] = {}+ variant_keys_by_id: dict[int, set[str]] = {}+ batchable_ids: set[int] = set()+ all_variant_keys: set[str] = set()+ branch_meta: list[tuple[int, _ResolvedExposure, set[str]]] = []+ for experiment_id, flag_key, filters, exposure_criteria in flag_meta:+ variant_keys = _variant_keys_from_filters(filters)+ if not variant_keys:+ continue+ flag_key_by_id[experiment_id] = flag_key+ variant_keys_by_id[experiment_id] = variant_keys+ all_variant_keys |= variant_keys+ resolution = _resolve_exposure(flag_key, exposure_criteria)+ if resolution.batchable:+ batchable_ids.add(experiment_id)+ else:+ branch_meta.append((experiment_id, resolution, variant_keys))+ if not flag_key_by_id:# No overlapping experiment defines variants, so nothing could surface a variant seen.return []- exposures = _query_exposure_events(- team, session_id, window_start, window_end, experiment_flag_keys, defined_variants+ # Flag evaluations are variant evidence for every experiment — the replay shows exactly+ # what the session was served, whatever the exposure criteria say — and double as the+ # exposure moment for experiments with the default criteria shape.+ flag_evaluations = _query_flag_evaluations(+ team, user, session_id, window_start, window_end, set(flag_key_by_id.values()), all_variant_keys+ )+ exposures: dict[int, list[tuple[str, datetime]]] = {+ experiment_id: flag_evaluations[flag_key]+ for experiment_id, flag_key in flag_key_by_id.items()+ if experiment_id in batchable_ids and flag_key in flag_evaluations+ }+ # Same width backstop as the candidate cap — each branch experiment adds a union branch, so+ # (unlike the constant-width flag-evaluations query) non-batchable experiments beyond the+ # cap are deliberately not queried: they get no criteria-driven exposure moment, though+ # flag evaluations still evidence (and rescue) them like any other experiment.+ exposures.update(+ _query_exposure_event_branches(+ team, user, session_id, window_start, window_end, branch_meta[:MAX_CANDIDATE_EXPERIMENTS]+ ))- # The exposure query covers every overlapping experiment's flag (not just the capped+ # The exposure queries cover every overlapping experiment's flag (not just the capped# candidates), so a flag with verifiable in-session evidence rescues its experiment even# when it fell outside the cap above. Rescued keys join the stamped-property query too —# it stays bounded, since rescues are limited to real overlapping experiments the session# demonstrably called.+ evidenced_keys = set(flag_evaluations) | {flag_key_by_id[experiment_id] for experiment_id in exposures}candidate_keys = {experiment.feature_flag.key for experiment in candidates}- rescued_keys = set(exposures) - candidate_keys+ rescued_keys = evidenced_keys - candidate_keysif rescued_keys:candidates += list(overlapping.filter(feature_flag__key__in=sorted(rescued_keys)))candidate_keys = {experiment.feature_flag.key for experiment in candidates}- stamped = _query_stamped_flag_properties(team, session_id, candidate_keys, window_start, window_end)+ stamped = _query_stamped_flag_properties(team, user, session_id, candidate_keys, window_start, window_end)items: list[ExperimentSessionContextItem] = []for experiment in candidates:@@ -118,20 +196,25 @@ def get_session_experiment_context(# 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# `$feature_flag_response: false`, which must not surface as a variant named "false".- defined_variants = _defined_variant_keys(experiment)- exposure_rows = [row for row in exposures.get(flag_key, []) if row[0] in defined_variants]+ defined_variants = variant_keys_by_id.get(experiment.pk, set())+ exposure_rows = [row for row in exposures.get(experiment.pk, []) if row[0] in defined_variants]+ flag_rows = [row for row in flag_evaluations.get(flag_key, []) if row[0] in defined_variants]stamped_values = [value for value in stamped.get(flag_key, []) if value in defined_variants]- variants_seen = sorted({variant for variant, _ in exposure_rows} | set(stamped_values))+ variants_seen = sorted(+ {variant for variant, _ in exposure_rows} | {variant for variant, _ in flag_rows} | set(stamped_values)+ )if not variants_seen:continue+ first_exposure_timestamp: Optional[datetime] = Noneif exposure_rows:- earliest_variant, first_seen = min(exposure_rows, key=lambda row: row[1])- variant = earliest_variant- first_flag_evaluation_timestamp: Optional[datetime] = first_seen+ variant, first_exposure_timestamp = min(exposure_rows, key=lambda row: row[1])+ elif flag_rows:+ # The session was demonstrably served this variant, but no event matched the+ # experiment's exposure criteria — so there is no exposure moment to point at.+ variant = min(flag_rows, key=lambda row: row[1])[0]else:variant = variants_seen[0]- first_flag_evaluation_timestamp = Noneitems.append(ExperimentSessionContextItem(@@ -141,7 +224,7 @@ def get_session_experiment_context(variant=variant,variants_seen=variants_seen,multiple_variants=len(variants_seen) > 1,- first_flag_evaluation_timestamp=first_flag_evaluation_timestamp,+ first_exposure_timestamp=first_exposure_timestamp,experiment_start_date=experiment.start_date,experiment_end_date=experiment.end_date,)@@ -150,17 +233,40 @@ def get_session_experiment_context(return sorted(items, key=lambda item: item.experiment_name.lower())+def _resolve_exposure(flag_key: str, exposure_criteria: Optional[dict]) -> _ResolvedExposure:+ """Resolve an experiment's exposure criteria through the shared `exposure_query_logic`+ helpers — the single seam that keeps this surface in sync with the experiment analysis.+ Malformed stored criteria fall back to the default exposure event rather than failing the+ whole surface for one broken experiment."""+ criteria: Optional[ExperimentExposureCriteria]+ try:+ criteria = normalize_to_exposure_criteria(exposure_criteria)+ except pydantic.ValidationError:+ criteria = None+ exposure_config = criteria.exposure_config if criteria else None+ event, variant_property = get_exposure_event_and_property(flag_key, criteria)+ # 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+ # `exposure_query_logic`, criteria-less experiments resolve to the new event here and+ # automatically take the per-experiment branch path, which follows the criteria.+ has_property_filters = isinstance(exposure_config, ExperimentEventExposureConfig) and bool(+ exposure_config.properties+ )+ batchable = event == "$feature_flag_called" and not has_property_filters+ return _ResolvedExposure(+ flag_key=flag_key, variant_property=variant_property, criteria=criteria, batchable=batchable+ )++def _variant_keys_from_filters(filters: Optional[dict]) -> set[str]:multivariate = (filters or {}).get("multivariate") or {}return {variant["key"] for variant in multivariate.get("variants", []) if variant.get("key")}-def _defined_variant_keys(experiment: Experiment) -> set[str]:- return _variant_keys_from_filters(experiment.feature_flag.filters)---def _query_exposure_events(+def _query_flag_evaluations(team: Team,+ user: User,session_id: str,window_start: datetime,window_end: datetime,@@ -168,7 +274,17 @@ def _query_exposure_events(variants: set[str],) -> dict[str, list[tuple[str, datetime]]]:"""The session's `$feature_flag_called` events for the given experiment flag keys and- defined variant names, as flag_key -> [(variant, first_seen)]."""+ defined variant names, as flag_key -> [(variant, first_seen)]. Serves two roles: variant+ evidence for every experiment (the replay shows what the session was served, whatever the+ exposure criteria say), and the exposure moment for experiments whose criteria resolve to+ the plain default shape (`$feature_flag_called` with no extra property filters).++ Shape-bound to `$feature_flag_called` on purpose — the `$feature_flag` batching key and+ the `$feature_flag_response` variant property come with that event, so all three are+ hardcoded together. If DEFAULT_EXPOSURE_EVENT changes in `exposure_query_logic`, this+ query needs no rewrite: flag evaluations stay `$feature_flag_called` events, and+ `_resolve_exposure` stops classifying criteria-less experiments as batchable, so their+ exposure moments move to the branch path."""query = parse_select("""SELECT properties.$feature_flag AS flag_key,@@ -193,7 +309,7 @@ def _query_exposure_events("max_rows": ast.Constant(value=MAX_EXPOSURE_ROWS),},)- response = execute_hogql_query(query, team=team)+ response = execute_hogql_query(query, team=team, user=user)exposures: dict[str, list[tuple[str, datetime]]] = {}for flag_key, variant, first_seen in response.results or []:@@ -203,8 +319,87 @@ def _query_exposure_events(return exposures+def _query_exposure_event_branches(+ team: Team,+ user: User,+ session_id: str,+ window_start: datetime,+ window_end: datetime,+ branch_meta: list[tuple[int, _ResolvedExposure, set[str]]],+) -> dict[int, list[tuple[str, datetime]]]:+ """The session's exposure events for experiments whose criteria don't fit the batched+ default query (a custom event, an action, or the default event narrowed by property+ filters), as experiment_id -> [(variant, first_seen)].++ One union branch per experiment: the event/action and property filters come from the+ experiment's exposure criteria via `build_exposure_event_conditions`, and the variant from+ the property `get_exposure_event_and_property` dictates — the stamped `$feature/<key>`+ property for custom events and actions (they carry no `$feature_flag_response`),+ `$feature_flag_response` for the default event.+ """+ branches: list[ast.SelectQuery] = []+ for experiment_id, resolution, variants in branch_meta:+ # 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)+ 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 a+ # property filter HogQL can't compile — must not fail the whole surface. Match+ # nothing instead, like `_build_action_filter` does for missing actions: the+ # experiment still surfaces through stamped properties and flag evaluations, and no+ # exposure moment is fabricated from criteria the analysis can't honor either.+ conditions = [ast.Constant(value=False)]+ branch = parse_select(+ """+ SELECT {experiment_id} AS experiment_id,+ toString({variant_field}) AS variant,+ min(timestamp) AS first_seen+ FROM events+ WHERE {exposure_conditions}+ AND $session_id = {session_id}+ AND toString({variant_field}) IN {variants}+ AND timestamp >= {window_start}+ AND timestamp <= {window_end}+ GROUP BY variant+ """,+ placeholders={+ "experiment_id": ast.Constant(value=experiment_id),+ "variant_field": ast.Field(chain=["properties", resolution.variant_property]),+ "exposure_conditions": ast.And(exprs=conditions) if conditions else ast.Constant(value=True),+ "session_id": ast.Constant(value=session_id),+ "variants": ast.Constant(value=sorted(variants)),+ "window_start": ast.Constant(value=window_start),+ "window_end": ast.Constant(value=window_end),+ },+ )+ assert isinstance(branch, ast.SelectQuery)+ # The backstop must sit on each branch: HogQL stamps an implicit LIMIT 100 on every+ # union branch whose limit is unset (`_apply_limit` walks the branches), so a set-level+ # limit alone would not prevent per-branch truncation. Real branches stay far below+ # this — each groups by one flag's defined variants.+ branch.limit = ast.Constant(value=MAX_EXPOSURE_ROWS)+ branches.append(branch)++ if not branches:+ return {}++ query = ast.SelectSetQuery.create_from_queries(branches, "UNION ALL")+ query.limit = ast.Constant(value=MAX_EXPOSURE_ROWS)+ response = execute_hogql_query(query, team=team, user=user)++ exposures: dict[int, list[tuple[str, datetime]]] = {}+ for experiment_id, variant, first_seen in response.results or []:+ if not variant:+ continue+ exposures.setdefault(int(experiment_id), []).append((str(variant), first_seen))+ return exposures++def _query_stamped_flag_properties(team: Team,+ user: User,session_id: str,flag_keys: set[str],window_start: datetime,@@ -246,7 +441,7 @@ def _query_stamped_flag_properties(]),)- response = execute_hogql_query(query, team=team)+ response = execute_hogql_query(query, team=team, user=user)row = response.results[0] if response.results else [[] for _ in sorted_keys]return {key: [value for value in row[index] if value] for index, key in enumerate(sorted_keys)}diff --git a/products/experiments/backend/test/test_session_context_api.py b/products/experiments/backend/test/test_session_context_api.pyindex 752b0804305b..44554194a003 100644--- a/products/experiments/backend/test/test_session_context_api.py+++ b/products/experiments/backend/test/test_session_context_api.py@@ -8,11 +8,14 @@ from unittest.mock import patchfrom rest_framework import statusfrom posthog.constants import AvailableFeature-from posthog.models import Team, User+from posthog.models import PropertyDefinition, Team, Userfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_value, uuid7from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary+from products.access_control.backend.facade.api import upsert_property_access_control+from products.access_control.backend.facade.contracts import PropertyAccessLevel, UpsertPropertyAccessControlInput+from products.actions.backend.models.action import Actionfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -43,6 +46,7 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):start_date: datetime = datetime(2025, 12, 1, tzinfo=UTC),end_date: Optional[datetime] = None,created_by: Optional[User] = None,+ exposure_criteria: Optional[dict[str, Any]] = None,) -> Experiment:team = team or self.teamflag = FeatureFlag.objects.create(@@ -66,12 +70,13 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):created_by=created_by or self.user,start_date=start_date,end_date=end_date,+ exposure_criteria=exposure_criteria or {},)- def _enable_access_controls(self) -> None:+ def _enable_access_controls(self, feature: str = AvailableFeature.ACCESS_CONTROL) -> None:features = self.organization.available_product_features or []- if not any(feature["key"] == AvailableFeature.ACCESS_CONTROL for feature in features):- features.append({"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL})+ if not any(existing["key"] == feature for existing in features):+ features.append({"key": feature, "name": feature})self.organization.available_product_features = featuresself.organization.save()@@ -134,7 +139,7 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):assert result["variant"] == "test"assert result["variants_seen"] == ["test"]assert result["multiple_variants"] is False- assert result["first_flag_evaluation_timestamp"] == "2026-01-01T10:02:11Z"+ assert result["first_exposure_timestamp"] == "2026-01-01T10:02:11Z"assert result["experiment_end_date"] is Nonedef test_resolves_variant_from_stamped_properties_when_no_exposure_event(self) -> None:@@ -154,7 +159,7 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):assert results[0]["variant"] == "test"assert results[0]["variants_seen"] == ["test"]assert results[0]["multiple_variants"] is False- assert results[0]["first_flag_evaluation_timestamp"] is None+ assert results[0]["first_exposure_timestamp"] is Nonedef test_multiple_variants_detected(self) -> None:self._create_recording()@@ -176,7 +181,247 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):assert results[0]["variant"] == "control"assert sorted(results[0]["variants_seen"]) == ["control", "test"]assert results[0]["multiple_variants"] is True- assert results[0]["first_flag_evaluation_timestamp"] == "2026-01-01T10:02:11Z"+ assert results[0]["first_exposure_timestamp"] == "2026-01-01T10:02:11Z"++ def test_custom_exposure_event_defines_exposure_timestamp(self) -> None:+ self._create_recording()+ self._create_experiment(+ exposure_criteria={+ "exposure_config": {+ "kind": "ExperimentEventExposureConfig",+ "event": "checkout started",+ "properties": [],+ }+ }+ )+ # The flag evaluation happens first, but with a custom exposure event configured it+ # must not define the exposure moment.+ self._create_session_event(+ timestamp="2026-01-01T10:02:11Z",+ properties={"$feature_flag": "checkout-cta", "$feature_flag_response": "test"},+ )+ self._create_session_event(+ event="checkout started",+ timestamp="2026-01-01T10:05:00Z",+ properties={"$feature/checkout-cta": "test"},+ )+ flush_persons_and_events()++ response = self._get_session_context()+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]+ assert len(results) == 1+ assert results[0]["variant"] == "test"+ assert results[0]["variants_seen"] == ["test"]+ assert results[0]["first_exposure_timestamp"] == "2026-01-01T10:05:00Z"++ def test_custom_exposure_event_absent_yields_null_timestamp(self) -> None:+ self._create_recording()+ self._create_experiment(+ exposure_criteria={+ "exposure_config": {+ "kind": "ExperimentEventExposureConfig",+ "event": "checkout started",+ "properties": [],+ }+ }+ )+ # The session evaluated the flag but never fired the custom exposure event — the+ # flag-evaluation moment must not masquerade as an exposure timestamp.+ self._create_session_event(+ properties={"$feature_flag": "checkout-cta", "$feature_flag_response": "test"},+ )+ self._create_session_event(event="$pageview", properties={"$feature/checkout-cta": "test"})+ flush_persons_and_events()++ response = self._get_session_context()+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]+ assert len(results) == 1+ assert results[0]["variant"] == "test"+ assert results[0]["first_exposure_timestamp"] is None++ def test_flag_evaluation_evidences_variant_for_custom_criteria(self) -> None:+ self._create_recording()+ self._create_experiment(+ exposure_criteria={+ "exposure_config": {+ "kind": "ExperimentEventExposureConfig",+ "event": "checkout started",+ "properties": [],+ }+ }+ )+ # Only a flag evaluation — no custom exposure event, no stamped properties (e.g.+ # server-evaluated flags). The replay still shows what the session was served, so the+ # experiment must surface with its variant; only the exposure moment stays undefined.+ self._create_session_event(+ properties={"$feature_flag": "checkout-cta", "$feature_flag_response": "test"},+ )+ flush_persons_and_events()++ response = self._get_session_context()+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]+ assert len(results) == 1+ assert results[0]["variant"] == "test"+ assert results[0]["variants_seen"] == ["test"]+ assert results[0]["first_exposure_timestamp"] is None++ def test_default_event_with_property_filters_defines_exposure_timestamp(self) -> None:+ self._create_recording()+ self._create_experiment(+ exposure_criteria={+ "exposure_config": {+ "kind": "ExperimentEventExposureConfig",+ "event": "$feature_flag_called",+ "properties": [{"key": "plan", "value": ["premium"], "operator": "exact", "type": "event"}],+ }+ }+ )+ # The experiment analysis applies the property filters even on the default event, so+ # the earlier non-matching flag call must not define the exposure moment — and the+ # variant must still come from $feature_flag_response (nothing stamps $feature/<key>).+ self._create_session_event(+ timestamp="2026-01-01T10:02:11Z",+ properties={"$feature_flag": "checkout-cta", "$feature_flag_response": "test"},+ )+ self._create_session_event(+ timestamp="2026-01-01T10:06:00Z",+ properties={"$feature_flag": "checkout-cta", "$feature_flag_response": "test", "plan": "premium"},+ )+ flush_persons_and_events()++ response = self._get_session_context()+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]+ assert len(results) == 1+ assert results[0]["variant"] == "test"+ assert results[0]["first_exposure_timestamp"] == "2026-01-01T10:06:00Z"++ def test_property_filters_respect_viewer_property_access_control(self) -> None:+ self._enable_access_controls(AvailableFeature.PROPERTY_ACCESS_CONTROL)+ self._create_recording()+ self._create_experiment(+ exposure_criteria={+ "exposure_config": {+ "kind": "ExperimentEventExposureConfig",+ "event": "$feature_flag_called",+ "properties": [{"key": "plan", "value": ["premium"], "operator": "exact", "type": "event"}],+ }+ }+ )+ # A user-specific denial leaves the default rules permissive, so it is only enforced+ # when the viewer threads through to the exposure queries — userless execution would+ # let the denied property's filter match and leak an exposure signal.+ plan_prop = PropertyDefinition.objects.create(+ team=self.team, name="plan", property_type="String", type=PropertyDefinition.Type.EVENT+ )+ upsert_property_access_control(+ team_id=self.team.id,+ created_by_id=self.user.id,+ input=UpsertPropertyAccessControlInput(+ property_definition_id=str(plan_prop.id),+ access_level=PropertyAccessLevel.NONE,+ organization_member_id=self.organization_membership.id,+ ),+ )+ self._create_session_event(+ timestamp="2026-01-01T10:06:00Z",+ properties={"$feature_flag": "checkout-cta", "$feature_flag_response": "test", "plan": "premium"},+ )+ self._create_session_event(event="$pageview", properties={"$feature/checkout-cta": "test"})+ flush_persons_and_events()++ response = self._get_session_context()+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]+ assert len(results) == 1+ assert results[0]["variant"] == "test"+ assert results[0]["first_exposure_timestamp"] is None++ def test_unresolvable_property_filter_fails_soft(self) -> None:+ self._create_recording()+ # A duplicated experiment can carry a cohort id from its source project; resolving that+ # filter raises. One such experiment must not 500 the endpoint — it degrades to+ # stamped-property evidence with no exposure moment.+ self._create_experiment(+ exposure_criteria={+ "exposure_config": {+ "kind": "ExperimentEventExposureConfig",+ "event": "checkout started",+ "properties": [{"key": "id", "value": 999999, "type": "cohort"}],+ }+ }+ )+ self._create_session_event(event="$pageview", properties={"$feature/checkout-cta": "test"})+ flush_persons_and_events()++ response = self._get_session_context()+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]+ assert len(results) == 1+ assert results[0]["variant"] == "test"+ assert results[0]["first_exposure_timestamp"] is None++ def test_default_and_custom_experiments_sharing_a_flag_resolve_independently(self) -> None:+ self._create_recording()+ default_experiment = self._create_experiment(name="Default criteria")+ # Two experiments on one flag with different criteria — exposure evidence must stay+ # keyed by experiment id, not flag key: each takes its exposure moment from its own path.+ custom_experiment = Experiment.objects.create(+ team=self.team,+ name="Custom criteria",+ feature_flag=default_experiment.feature_flag,+ created_by=self.user,+ start_date=datetime(2025, 12, 1, tzinfo=UTC),+ exposure_criteria={+ "exposure_config": {+ "kind": "ExperimentEventExposureConfig",+ "event": "checkout started",+ "properties": [],+ }+ },+ )+ self._create_session_event(+ timestamp="2026-01-01T10:02:11Z",+ properties={"$feature_flag": "checkout-cta", "$feature_flag_response": "test"},+ )+ self._create_session_event(+ event="checkout started",+ timestamp="2026-01-01T10:05:00Z",+ properties={"$feature/checkout-cta": "test"},+ )+ flush_persons_and_events()++ response = self._get_session_context()+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]+ assert len(results) == 2+ by_id = {result["experiment_id"]: result for result in results}+ assert by_id[default_experiment.id]["first_exposure_timestamp"] == "2026-01-01T10:02:11Z"+ assert by_id[custom_experiment.id]["first_exposure_timestamp"] == "2026-01-01T10:05:00Z"+ assert all(result["variant"] == "test" for result in results)++ def test_action_exposure_criteria_defines_exposure_timestamp(self) -> None:+ self._create_recording()+ action = Action.objects.create(team=self.team, name="Purchased", steps_json=[{"event": "purchase"}])+ self._create_experiment(+ exposure_criteria={"exposure_config": {"kind": "ActionsNode", "id": action.pk}},+ )+ self._create_session_event(+ event="purchase",+ timestamp="2026-01-01T10:07:00Z",+ properties={"$feature/checkout-cta": "control"},+ )+ flush_persons_and_events()++ response = self._get_session_context()+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]+ assert len(results) == 1+ assert results[0]["variant"] == "control"+ assert results[0]["first_exposure_timestamp"] == "2026-01-01T10:07:00Z"def test_exposure_event_rescues_experiment_beyond_candidate_cap(self) -> None:self._create_recording()diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 8c166aace921..d694c7019638 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -2122,17 +2122,17 @@ export interface ExperimentSessionContextItemApi {experiment_name: string/** Key of the experiment's feature flag. */flag_key: string- /** Variant the session saw. Taken from the earliest $feature_flag_called event in the session when one exists, otherwise from the $feature/<key> property stamped on the session's events. */+ /** Variant the session saw. Taken from the earliest event matching the experiment's exposure criteria when one exists, otherwise from the earliest flag evaluation in the session, otherwise from the $feature/<key> property stamped on the session's events. */variant: string/** All distinct variant values observed for this flag during the session, sorted alphabetically. Only the flag's defined variant keys count; non-enrollment responses (false) are ignored. More than one value means the session saw multiple variants — a signal of multi-exposure bias. */variants_seen: string[]/** True when the session saw more than one variant of this flag. */multiple_variants: boolean/**- * Timestamp of the first $feature_flag_called event for this flag in the session — the moment the flag was evaluated to the variant. Null when the variant is only known from stamped $feature/<key> properties (e.g. the assignment carried over from an earlier session). For experiments with custom exposure criteria this is not the experiment's exposure moment.+ * Timestamp of the first event in the session matching the experiment's exposure criteria — the default exposure event ($feature_flag_called), or the configured custom event/action. Null when no event in the session matched the criteria; the variant is then known from flag evaluations or stamped $feature/<key> properties. Session-scoped: the experiment analysis counts exposure per person across the whole run window, so the person's counted first exposure may lie in an earlier session.* @nullable*/- first_flag_evaluation_timestamp: string | null+ first_exposure_timestamp: string | null/*** When the experiment was launched.* @nullablediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d43806a36c33..3865665043f1 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -25192,17 +25192,17 @@ export namespace Schemas {experiment_name: string;/** Key of the experiment's feature flag. */flag_key: string;- /** Variant the session saw. Taken from the earliest $feature_flag_called event in the session when one exists, otherwise from the $feature/<key> property stamped on the session's events. */+ /** Variant the session saw. Taken from the earliest event matching the experiment's exposure criteria when one exists, otherwise from the earliest flag evaluation in the session, otherwise from the $feature/<key> property stamped on the session's events. */variant: string;/** All distinct variant values observed for this flag during the session, sorted alphabetically. Only the flag's defined variant keys count; non-enrollment responses (false) are ignored. More than one value means the session saw multiple variants — a signal of multi-exposure bias. */variants_seen: string[];/** True when the session saw more than one variant of this flag. */multiple_variants: boolean;/**- * Timestamp of the first $feature_flag_called event for this flag in the session — the moment the flag was evaluated to the variant. Null when the variant is only known from stamped $feature/<key> properties (e.g. the assignment carried over from an earlier session). For experiments with custom exposure criteria this is not the experiment's exposure moment.+ * Timestamp of the first event in the session matching the experiment's exposure criteria — the default exposure event ($feature_flag_called), or the configured custom event/action. Null when no event in the session matched the criteria; the variant is then known from flag evaluations or stamped $feature/<key> properties. Session-scoped: the experiment analysis counts exposure per person across the whole run window, so the person's counted first exposure may lie in an earlier session.* @nullable*/- first_flag_evaluation_timestamp: string | null;+ first_exposure_timestamp: string | null;/*** When the experiment was launched.* @nullablediff --git a/tach.toml b/tach.tomlindex 786778a2c6c2..528112bee50e 100644--- a/tach.toml+++ b/tach.toml@@ -352,6 +352,7 @@ depends_on = ["products.cohorts","ee","posthog",+ "products.access_control","products.actions","products.approvals","products.ai_observability",