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(experiments): switch the recordings tab to person-scoped exposure (#82588)

Marcel Poelker0b286b31b065
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index b537a24ec0cf..85e9e3f586db 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -122,14 +122,13 @@ export enum GraphSeriesAddedSource {
}
/**
- * Whether the experiment's recordings tab can do its job at all, captured once the session
- * linkability check has resolved. An unmatchable exposure event makes the tab a dead page, and
- * a fallback or an empty selectable-metric list makes it a weaker one, so these are the numbers
- * that say how often the feature is useless to somebody rather than how often it is opened.
+ * How much of the experiment's recordings tab works for this viewer, captured once the session
+ * linkability check has resolved. The exposure population is resolved server-side per person,
+ * so the list itself always has a source; an empty selectable-metric list is what still makes
+ * the tab a weaker page, and these numbers say how often that happens rather than how often
+ * the tab is opened.
*/
export interface ExperimentRecordingsTabContext {
- exposure_unlinkable: boolean
- using_exposure_fallback: boolean
variant_count: number
metric_count: number
linkable_metric_count: number
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
index 93e4111223f4..ff8207a3e5f3 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
@@ -25,7 +25,6 @@ import { Experiment } from '~/types'
import { SummarizeSessionReplaysButton } from '../components/SummarizeSessionReplaysButton'
import { isLaunched } from '../experimentStatus'
import { NOT_A_FUNNEL_REASON } from '../utils'
-import { EXPOSURE_FALLBACK_NOTICE, EXPOSURE_UNLINKABLE_REASON } from '../viewRecordingsLinkabilityLogic'
import { ExperimentBehaviorComparison, ExperimentBehaviorComparisonToggle } from './ExperimentBehaviorComparison'
import {
ExperimentReplayMetricFilterMode,
@@ -40,6 +39,12 @@ import { VariantTag } from './VariantTag'
// variant — a variant literally named "all" just renders as its own option after the built-in "All".
const ALL_VARIANTS = '$all'
+// What the unfiltered list is, said once above it. The second sentence carries the part that
+// isn't guessable: exposure is resolved per person, matching who the analysis counts, so
+// sessions appear even when the exposure event fired server-side or in an earlier session.
+const POPULATION_CAPTION =
+ "Showing sessions of exposed participants from their first exposure onward. The exposure event itself doesn't have to be in the session."
+
// A session fires a metric's events, never the metric — the caption spells that out where it
// has the room the trigger doesn't.
const MODE_SUMMARIES: Record<ExperimentReplayMetricFilterMode, string> = {
@@ -167,8 +172,6 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):
effectiveVariantKey,
variantKeys,
recordingsFilters,
- exposureUnlinkable,
- usingExposureFallback,
effectiveMetricUuids,
metricOptions,
metricFilterMode,
@@ -207,10 +210,6 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):
return <LemonBanner type="info">Launch the experiment to see recordings of participants.</LemonBanner>
}
- if (exposureUnlinkable) {
- return <LemonBanner type="warning">{EXPOSURE_UNLINKABLE_REASON}</LemonBanner>
- }
-
// Selectable metrics render as checkboxes. The rest move to labelled sections that explain
// once, via a section tooltip, why they can't be matched — instead of repeating the same
// reason on every row. One section per distinct reason, since metrics can be unmatchable for
@@ -233,11 +232,6 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):
return (
<div data-attr="experiment-recordings-tab">
- {usingExposureFallback && (
- <LemonBanner type="info" className="mb-2">
- {EXPOSURE_FALLBACK_NOTICE}
- </LemonBanner>
- )}
<div className="mb-2 flex flex-wrap gap-2">
<LemonSegmentedButton
size="small"
@@ -326,24 +320,26 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):
</div>
{/* The default mode also uses the endpoint for a single multi-source metric, so the
caption follows the request, not the mode. */}
- {(sessionBucketRequest || metricFilterMode !== 'fired_all') && (
- <div className="mb-2 flex items-center gap-2 text-xs text-secondary">
- {!sessionBucketRequest ? (
- <span>{unappliedModeReason(metricFilterMode)}</span>
- ) : sessionBucketError !== null ? (
- <>
- <span>Couldn't work out which sessions match this filter: {sessionBucketError}</span>
- <LemonButton size="xsmall" type="secondary" onClick={() => loadSessionBucket()}>
- Try again
- </LemonButton>
- </>
- ) : sessionBucketLoading || !sessionBucket ? (
- <span>Finding matching sessions…</span>
- ) : (
- <span data-attr="experiment-recordings-bucket-caption">{bucketCaption(sessionBucket)}</span>
- )}
- </div>
- )}
+ <div className="mb-2 flex items-center gap-2 text-xs text-secondary">
+ {!sessionBucketRequest && metricFilterMode === 'fired_all' ? (
+ effectiveMetricUuids.length === 0 ? (
+ <span data-attr="experiment-recordings-population-caption">{POPULATION_CAPTION}</span>
+ ) : null
+ ) : !sessionBucketRequest ? (
+ <span>{unappliedModeReason(metricFilterMode)}</span>
+ ) : sessionBucketError !== null ? (
+ <>
+ <span>Couldn't work out which sessions match this filter: {sessionBucketError}</span>
+ <LemonButton size="xsmall" type="secondary" onClick={() => loadSessionBucket()}>
+ Try again
+ </LemonButton>
+ </>
+ ) : sessionBucketLoading || !sessionBucket ? (
+ <span>Finding matching sessions…</span>
+ ) : (
+ <span data-attr="experiment-recordings-bucket-caption">{bucketCaption(sessionBucket)}</span>
+ )}
+ </div>
<ExperimentBehaviorComparison experiment={experiment} onWatchRecording={watchRecording} />
<div className="SessionRecordingPlaylistHeightWrapper">
<SessionRecordingsPlaylist
diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
index 2e23f59a4c34..38ebbf7b9f08 100644
--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
@@ -8,13 +8,7 @@ import { playerSidebarLogic } from 'scenes/session-recordings/player/sidebar/pla
import { ExperimentMetricType, NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
-import {
- Experiment,
- FilterLogicalOperator,
- PropertyFilterType,
- PropertyOperator,
- SessionRecordingSidebarTab,
-} from '~/types'
+import { Experiment, FilterLogicalOperator, SessionRecordingSidebarTab } from '~/types'
import {
experimentsSessionBucketsCreate,
@@ -22,11 +16,7 @@ import {
experimentsSessionEventDeltasCreate,
} from 'products/experiments/frontend/generated/api'
-import {
- FUNNEL_DATA_WAREHOUSE_COMPLETION_REASON,
- FUNNEL_SERVER_SIDE_COMPLETION_REASON,
- getViewRecordingFiltersForVariant,
-} from '../utils'
+import { FUNNEL_DATA_WAREHOUSE_COMPLETION_REASON, FUNNEL_SERVER_SIDE_COMPLETION_REASON } from '../utils'
import { RETENTION_UNLINKABLE_REASON, viewRecordingsLinkabilityLogic } from '../viewRecordingsLinkabilityLogic'
import { type ExperimentReplayRecording, experimentReplayTabLogic } from './experimentReplayTabLogic'
@@ -129,6 +119,13 @@ const ALL_LINKABLE = {
client_step: true,
}
+// Exposure narrowing lives in `experiment_exposure`, not the filter tree, so an unfiltered
+// tab carries an empty group.
+const EMPTY_FILTER_GROUP = {
+ type: FilterLogicalOperator.And,
+ values: [{ type: FilterLogicalOperator.And, values: [] }],
+}
+
describe('experimentReplayTabLogic', () => {
let logic: ReturnType<typeof experimentReplayTabLogic.build>
let seenTogetherSpy: jest.SpyInstance
@@ -159,22 +156,18 @@ describe('experimentReplayTabLogic', () => {
})
})
- it('builds an exposure-only filter pinned to the run window', () => {
+ it('pins the person-scoped exposure filter to the run window', () => {
const { recordingsFilters } = logic.values
+ // RecordingsQuery defaults to "-3d", which would silently hide older exposed sessions,
+ // so the window must come from the experiment.
expect(recordingsFilters.date_from).toBe('2026-01-01T00:00:00Z')
expect(recordingsFilters.date_to).toBe('2026-02-01T00:00:00Z')
expect(recordingsFilters.filter_test_accounts).toBe(true)
- // All facet: the inner filter is the exposure helper's "all variants" output, nothing metric-shaped.
- expect(recordingsFilters.filter_group).toEqual({
- type: FilterLogicalOperator.And,
- values: [
- {
- type: FilterLogicalOperator.And,
- values: getViewRecordingFiltersForVariant(EXPERIMENT, undefined),
- },
- ],
- })
+ // All facet: the population is the server-resolved exposure filter, and nothing
+ // event-shaped stands in for it in the filter tree.
+ expect(recordingsFilters.experiment_exposure).toEqual({ experiment_id: 42 })
+ expect(recordingsFilters.filter_group).toEqual(EMPTY_FILTER_GROUP)
})
it('keeps the selected variant across remounts, in step with the playlist persisting its filters', async () => {
@@ -215,12 +208,7 @@ describe('experimentReplayTabLogic', () => {
expect(remounted.values.selectedVariantKey).toBe('test')
expect(remounted.values.effectiveVariantKey).toBeNull()
// The stale key must not leak into the query; the filter falls back to all variants.
- expect(remounted.values.recordingsFilters.filter_group.values).toEqual([
- {
- type: FilterLogicalOperator.And,
- values: getViewRecordingFiltersForVariant(renamed, undefined),
- },
- ])
+ expect(remounted.values.recordingsFilters.experiment_exposure).toEqual({ experiment_id: 42 })
remounted.unmount()
})
@@ -231,63 +219,24 @@ describe('experimentReplayTabLogic', () => {
const { recordingsFilters } = logic.values
expect(recordingsFilters.date_from).toBe('2026-01-01T00:00:00Z')
- expect(recordingsFilters.filter_group.values).toEqual([
- {
- type: FilterLogicalOperator.And,
- values: getViewRecordingFiltersForVariant(EXPERIMENT, 'test'),
- },
- ])
+ expect(recordingsFilters.experiment_exposure).toEqual({ experiment_id: 42, variant: 'test' })
})
- it('falls back to the flag-value property filter when the default exposure event is server-side', async () => {
+ it('keeps the person-scoped filter when the exposure event is server-side', async () => {
+ // The case the person-scoped filter exists for: a server-side exposure event carries no
+ // session id, and any client-side downgrade of the query on that signal would reintroduce
+ // the empty tab this filter replaced.
seenTogetherSpy.mockResolvedValue({ $feature_flag_called: false })
// Distinct id: both this logic and the linkability lookup are keyed by experiment id.
const serverSide = experimentReplayTabLogic({ experiment: { ...EXPERIMENT, id: 43 } as Experiment })
serverSide.mount()
- await expectLogic(serverSide)
- .toFinishAllListeners()
- .toMatchValues({ exposureUnlinkable: false, usingExposureFallback: true })
- expect(serverSide.values.recordingsFilters.filter_group.values).toEqual([
- {
- type: FilterLogicalOperator.And,
- values: [
- {
- key: '$feature/my-flag',
- type: PropertyFilterType.Event,
- value: ['control', 'test'],
- operator: PropertyOperator.Exact,
- },
- ],
- },
- ])
- serverSide.unmount()
- })
-
- it('flags a server-side custom exposure event as unlinkable, so the tab can explain the empty list', async () => {
- seenTogetherSpy.mockResolvedValue({ signed_up: false })
- const customExposure = {
- ...EXPERIMENT,
- id: 44,
- exposure_criteria: {
- exposure_config: { kind: NodeKind.ExperimentEventExposureConfig, event: 'signed_up', properties: [] },
- },
- } as unknown as Experiment
- const serverSide = experimentReplayTabLogic({ experiment: customExposure })
- serverSide.mount()
-
- await expectLogic(serverSide)
- .toFinishAllListeners()
- .toMatchValues({ exposureUnlinkable: true, usingExposureFallback: false })
+ await expectLogic(serverSide).toFinishAllListeners()
+ expect(serverSide.values.recordingsFilters.experiment_exposure).toEqual({ experiment_id: 43 })
+ expect(serverSide.values.recordingsFilters.filter_group).toEqual(EMPTY_FILTER_GROUP)
serverSide.unmount()
})
- it('keeps the list when the exposure event is session-linkable', async () => {
- await expectLogic(logic)
- .toFinishAllListeners()
- .toMatchValues({ exposureUnlinkable: false, usingExposureFallback: false })
- })
-
it('ANDs each selected metric filter onto the exposure filter, and ignores unknown metric uuids', async () => {
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.metricOptions.map((option) => option.uuid)).toEqual(['metric-purchase', 'metric-funnel'])
@@ -297,10 +246,7 @@ describe('experimentReplayTabLogic', () => {
expect(logic.values.recordingsFilters.filter_group.values).toEqual([
{
type: FilterLogicalOperator.And,
- values: [
- ...getViewRecordingFiltersForVariant(EXPERIMENT, undefined),
- { id: 'purchase', name: 'purchase', type: 'events', properties: [] },
- ],
+ values: [{ id: 'purchase', name: 'purchase', type: 'events', properties: [] }],
},
])
@@ -311,7 +257,6 @@ describe('experimentReplayTabLogic', () => {
{
type: FilterLogicalOperator.And,
values: [
- ...getViewRecordingFiltersForVariant(EXPERIMENT, undefined),
{ id: 'purchase', name: 'purchase', type: 'events', properties: [] },
{ id: 'server_side_step', name: 'server_side_step', type: 'events', properties: [] },
],
@@ -323,12 +268,7 @@ describe('experimentReplayTabLogic', () => {
// A persisted uuid whose metric has since been removed must not leak into the query.
logic.actions.setMetricSelected('ghost', true)
expect(logic.values.effectiveMetricUuids).toEqual([])
- expect(logic.values.recordingsFilters.filter_group.values).toEqual([
- {
- type: FilterLogicalOperator.And,
- values: getViewRecordingFiltersForVariant(EXPERIMENT, undefined),
- },
- ])
+ expect(logic.values.recordingsFilters.filter_group).toEqual(EMPTY_FILTER_GROUP)
})
it('lists a retention metric as unmatchable instead of dropping it silently', async () => {
@@ -362,12 +302,7 @@ describe('experimentReplayTabLogic', () => {
})
withRetention.actions.setMetricSelected('metric-retention', true)
expect(withRetention.values.effectiveMetricUuids).toEqual([])
- expect(withRetention.values.recordingsFilters.filter_group.values).toEqual([
- {
- type: FilterLogicalOperator.And,
- values: getViewRecordingFiltersForVariant(EXPERIMENT, undefined),
- },
- ])
+ expect(withRetention.values.recordingsFilters.filter_group).toEqual(EMPTY_FILTER_GROUP)
withRetention.unmount()
})
@@ -383,12 +318,7 @@ describe('experimentReplayTabLogic', () => {
serverSideMetric.actions.setMetricSelected('metric-purchase', true)
expect(serverSideMetric.values.effectiveMetricUuids).toEqual([])
// The unlinkable event would zero the whole AND-combined query — it must never appear.
- expect(serverSideMetric.values.recordingsFilters.filter_group.values).toEqual([
- {
- type: FilterLogicalOperator.And,
- values: getViewRecordingFiltersForVariant(EXPERIMENT, undefined),
- },
- ])
+ expect(serverSideMetric.values.recordingsFilters.filter_group).toEqual(EMPTY_FILTER_GROUP)
serverSideMetric.unmount()
})
@@ -425,10 +355,7 @@ describe('experimentReplayTabLogic', () => {
expect(logic.values.recordingsFilters.filter_group.values).toEqual([
{
type: FilterLogicalOperator.And,
- values: [
- ...getViewRecordingFiltersForVariant(EXPERIMENT, undefined),
- { id: 'purchase', name: 'purchase', type: 'events', properties: [] },
- ],
+ values: [{ id: 'purchase', name: 'purchase', type: 'events', properties: [] }],
},
])
@@ -472,22 +399,14 @@ describe('experimentReplayTabLogic', () => {
pending.mount()
pending.actions.setMetricSelected('metric-purchase', true)
- expect(pending.values.recordingsFilters.filter_group.values).toEqual([
- {
- type: FilterLogicalOperator.And,
- values: getViewRecordingFiltersForVariant(EXPERIMENT, undefined),
- },
- ])
+ expect(pending.values.recordingsFilters.filter_group).toEqual(EMPTY_FILTER_GROUP)
resolveSeenTogether(ALL_LINKABLE)
await expectLogic(pending).toFinishAllListeners()
expect(pending.values.recordingsFilters.filter_group.values).toEqual([
{
type: FilterLogicalOperator.And,
- values: [
- ...getViewRecordingFiltersForVariant(EXPERIMENT, undefined),
- { id: 'purchase', name: 'purchase', type: 'events', properties: [] },
- ],
+ values: [{ id: 'purchase', name: 'purchase', type: 'events', properties: [] }],
},
])
pending.unmount()
@@ -516,8 +435,6 @@ describe('experimentReplayTabLogic', () => {
expect(tabViews()).toHaveLength(1)
expect(tabViews()[0][1]).toMatchObject({
experiment_id: 51,
- exposure_unlinkable: false,
- using_exposure_fallback: false,
variant_count: 2,
metric_count: 2,
linkable_metric_count: 1,
@@ -558,8 +475,6 @@ describe('experimentReplayTabLogic', () => {
expect(tabViews()).toHaveLength(1)
expect(tabViews()[0][1]).toMatchObject({
experiment_id: 52,
- exposure_unlinkable: false,
- using_exposure_fallback: false,
linkable_metric_count: 2,
})
opened.unmount()
@@ -576,10 +491,7 @@ describe('experimentReplayTabLogic', () => {
expect(failed.values.recordingsFilters.filter_group.values).toEqual([
{
type: FilterLogicalOperator.And,
- values: [
- ...getViewRecordingFiltersForVariant(EXPERIMENT, undefined),
- { id: 'purchase', name: 'purchase', type: 'events', properties: [] },
- ],
+ values: [{ id: 'purchase', name: 'purchase', type: 'events', properties: [] }],
},
])
failed.unmount()
@@ -675,13 +587,10 @@ describe('experimentReplayTabLogic', () => {
const { recordingsFilters } = logic.values
expect(recordingsFilters.session_ids).toEqual(['bucket-1', 'bucket-2'])
// The returned set already encodes the metric condition; ANDing the event filters back in
- // would narrow it a second time.
- expect(recordingsFilters.filter_group.values).toEqual([
- {
- type: FilterLogicalOperator.And,
- values: getViewRecordingFiltersForVariant(EXPERIMENT, 'test'),
- },
- ])
+ // would narrow it a second time. The person-scoped filter stays alongside: bucket ids say
+ // the session saw the experiment, not that its person is in the analysis population.
+ expect(recordingsFilters.experiment_exposure).toEqual({ experiment_id: 42, variant: 'test' })
+ expect(recordingsFilters.filter_group).toEqual(EMPTY_FILTER_GROUP)
})
it('follows the playlist\'s own "Show all" back to the unbucketed list', async () => {
@@ -974,14 +883,10 @@ describe('experimentReplayTabLogic', () => {
// The card's sessions are picked with no duration floor, so the default active-seconds
// filter must not thin out the list the card's count promises.
expect(logic.values.recordingsFilters.duration).toEqual([])
- // The card's ids already encode the event condition, so no event filter is added on top —
- // only the exposure filter stays, keeping the list's definition visible.
- expect(logic.values.recordingsFilters.filter_group.values).toEqual([
- {
- type: FilterLogicalOperator.And,
- values: [...getViewRecordingFiltersForVariant(EXPERIMENT, 'test')],
- },
- ])
+ // The card's ids already encode the event condition, so no event filter is added on top;
+ // the population definition rides `experiment_exposure`, following the card's variant.
+ expect(logic.values.recordingsFilters.filter_group).toEqual(EMPTY_FILTER_GROUP)
+ expect(logic.values.recordingsFilters.experiment_exposure).toEqual({ experiment_id: 42, variant: 'test' })
})
it.each([
diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
index fcfedd1f9502..e5f100799b36 100644
--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
@@ -65,12 +65,9 @@ import type { ExperimentIdType } from '../../../types'
import type { ExperimentSavedMetric } from '../experimentLogic'
import { getDefaultMetricTitle } from '../MetricsView/shared/utils'
import {
- applySessionLinkability,
getExperimentVariants,
- getExposureFallbackFilter,
getFunnelDropoffReason,
getMetricSessionFilters,
- getViewRecordingFiltersForVariant,
isUnlinkableEventFilter,
} from '../utils'
import {
@@ -174,7 +171,6 @@ export interface experimentReplayTabLogicValues {
bucketSessionIds: string[] | undefined
effectiveMetricUuids: string[]
effectiveVariantKey: string | null
- exposureUnlinkable: boolean
loadedRecordings: ExperimentReplayRecording[]
loadedRecordingsById: Map<string, ExperimentReplayRecording>
metricFilterMode: ExperimentReplayMetricFilterMode
@@ -190,7 +186,6 @@ export interface experimentReplayTabLogicValues {
sessionEventDeltas: ExperimentSessionEventDeltaResponseApi | null
sessionEventDeltasError: string | null
sessionEventDeltasLoading: boolean
- usingExposureFallback: boolean
variantKeys: string[]
}
@@ -355,8 +350,6 @@ export interface experimentReplayTabLogicMeta {
loadedRecordingsById: (loadedRecordings: ExperimentReplayRecording[]) => Map<string, ExperimentReplayRecording>
variantKeys: (arg: any) => string[]
behaviorComparisonAvailable: (featureFlags: FeatureFlagsSet) => boolean
- exposureUnlinkable: (linkabilityLoaded: boolean, unlinkableEventNames: Set<string>, arg: any) => boolean
- usingExposureFallback: (linkabilityLoaded: boolean, unlinkableEventNames: Set<string>, arg: any) => boolean
effectiveVariantKey: (selectedVariantKey: string | null, variantKeys: string[]) => string | null
metricOptions: (
linkabilityLoaded: boolean,
@@ -372,7 +365,6 @@ export interface experimentReplayTabLogicMeta {
metricFilterMode: ExperimentReplayMetricFilterMode,
effectiveMetricUuids: string[],
effectiveVariantKey: string | null,
- exposureUnlinkable: boolean,
metricOptions: ExperimentReplayMetricOption[]
) => ExperimentSessionBucketRequest | null
bucketSessionIds: (
@@ -636,34 +628,6 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
(s) => [s.featureFlags],
(featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.EXPERIMENT_BEHAVIOR_COMPARISON],
],
- // Exposure is the whole list here, so an unmatchable exposure event with no fallback means
- // there is nothing to show at all. Only custom exposure criteria end up here: the default
- // exposure branch always has the `$feature/<flag_key>` fallback. Fails open while the
- // check is in flight, matching the metric buttons.
- exposureUnlinkable: [
- (s) => [s.linkabilityLoaded, s.unlinkableEventNames, (_, props) => props.experiment],
- (linkabilityLoaded: boolean, unlinkableEventNames: Set<string>, experiment: Experiment): boolean =>
- // Fail open while the check is in flight, matching the metric buttons' posture.
- linkabilityLoaded &&
- applySessionLinkability(
- getViewRecordingFiltersForVariant(experiment),
- unlinkableEventNames,
- getExposureFallbackFilter(experiment)
- ).exposureUnlinkable,
- ],
- // True when the list is built from the `$feature/<flag_key>` fallback rather than the
- // exposure event, so the tab can explain that sessions show the flag being active, not
- // the exposure moment.
- usingExposureFallback: [
- (s) => [s.linkabilityLoaded, s.unlinkableEventNames, (_, props) => props.experiment],
- (linkabilityLoaded: boolean, unlinkableEventNames: Set<string>, experiment: Experiment): boolean =>
- linkabilityLoaded &&
- applySessionLinkability(
- getViewRecordingFiltersForVariant(experiment),
- unlinkableEventNames,
- getExposureFallbackFilter(experiment)
- ).usedExposureFallback,
- ],
effectiveVariantKey: [
(s) => [s.selectedVariantKey, s.variantKeys],
(selectedVariantKey: string | null, variantKeys: string[]): string | null =>
@@ -766,23 +730,13 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
* silently matches the primary event only.
*/
sessionBucketRequest: [
- (s) => [
- s.metricFilterMode,
- s.effectiveMetricUuids,
- s.effectiveVariantKey,
- s.exposureUnlinkable,
- s.metricOptions,
- ],
+ (s) => [s.metricFilterMode, s.effectiveMetricUuids, s.effectiveVariantKey, s.metricOptions],
(
metricFilterMode: ExperimentReplayMetricFilterMode,
effectiveMetricUuids: string[],
effectiveVariantKey: string | null,
- exposureUnlinkable: boolean,
metricOptions: ExperimentReplayMetricOption[]
): ExperimentSessionBucketRequest | null => {
- if (exposureUnlinkable) {
- return null
- }
const request = (bucket: ExperimentSessionBucketEnumApi): ExperimentSessionBucketRequest => ({
bucket,
metric_uuids: effectiveMetricUuids,
@@ -848,13 +802,12 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
selectedWatchCard: ExperimentWatchCardApi | null,
experiment: Experiment
): RecordingUniversalFilters => {
- // A recordings query carries a single AND/OR operand across the whole flattened
- // filter tree (see `deriveOperand`), so "exposed to the variant AND (any of the
- // metric's events)" can't be expressed — an OR anywhere flips the exposure filter to
- // OR too. Each selected metric matches on its primary event (the first
- // session-linkable source: a mean metric's event, a funnel's entry step, a ratio's
- // numerator) rather than ANDing every source, which used to require a session to
- // fire *all* funnel steps. Multiple selected metrics AND together — each narrows.
+ // The filter tree carries a single AND/OR operand (see `deriveOperand`), so
+ // OR-shaped questions go to the bucket endpoint rather than into these filters.
+ // Each selected metric matches on its primary event (the first session-linkable
+ // source: a mean metric's event, a funnel's entry step, a ratio's numerator)
+ // rather than ANDing every source, which used to require a session to fire *all*
+ // funnel steps. Multiple selected metrics AND together, and each narrows.
//
// While the linkability check is in flight, metric filters stay out of the query:
// a persisted selection of a metric that turns out unlinkable would otherwise fire
@@ -883,22 +836,14 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
seenFilters.add(JSON.stringify(filter))
return true
})
- // When the default exposure event can't match sessions, the fallback filter on
- // `$feature/<flag_key>` takes its place (see `getExposureFallbackFilter`). While
- // the check is in flight the unlinkable set is empty, so the exposure filter
- // passes through untouched (fail open).
- const exposureFilters = applySessionLinkability(
- getViewRecordingFiltersForVariant(experiment, effectiveVariantKey ?? undefined),
- unlinkableEventNames,
- getExposureFallbackFilter(experiment, effectiveVariantKey ?? undefined)
- ).filters
return {
...DEFAULT_RECORDING_FILTERS,
- // The exposure filter stays in place alongside the bucket or card: their ids
- // are a subset of the exposed sessions, so this only keeps the list's
- // definition visible in the filter UI. A card's recordings are pre-checked
- // against replay existence, so unlike an event filter this list can't come
- // back empty.
+ // The person-scoped filter stays in place alongside the bucket or card ids.
+ // A bucket session carries an in-session exposure event, but its person can
+ // still be outside the analysis population (excluded for seeing multiple
+ // variants, for example); the AND keeps the shown set honest to who the
+ // analysis counts. A card's recordings are pre-checked against replay
+ // existence, so unlike an event filter this list can't come back empty.
session_ids: selectedWatchCard ? selectedWatchCard.session_ids : bucketSessionIds,
// A card's sessions are picked with no duration floor, so the default "more
// than 5 active seconds" filter would silently drop the short ones (a rage
@@ -908,12 +853,23 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
date_from: experiment.start_date ?? DEFAULT_RECORDING_FILTERS.date_from,
date_to: experiment.end_date ?? null,
filter_test_accounts: experiment.exposure_criteria?.filterTestAccounts ?? false,
+ // Resolved server-side from the experiment (same population the analysis
+ // counts), so it works even when exposure events are fired server-side and
+ // shows exposed users' whole journey, not just sessions containing the
+ // exposure event. Deliberately not an event filter in `filter_group`.
+ experiment_exposure:
+ typeof experiment.id === 'number'
+ ? {
+ experiment_id: experiment.id,
+ ...(effectiveVariantKey !== null ? { variant: effectiveVariantKey } : {}),
+ }
+ : undefined,
filter_group: {
type: FilterLogicalOperator.And,
values: [
{
type: FilterLogicalOperator.And,
- values: [...exposureFilters, ...metricFilters],
+ values: metricFilters,
},
],
},
@@ -1045,8 +1001,6 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
}
cache.reportedTabView = true
actions.reportExperimentRecordingsTabViewed(props.experiment.id, {
- exposure_unlinkable: values.exposureUnlinkable,
- using_exposure_fallback: values.usingExposureFallback,
variant_count: values.variantKeys.length,
metric_count: values.metricOptions.length,
linkable_metric_count: values.metricOptions.filter((option) => !option.unlinkable).length,
diff --git a/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts b/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts
index c92fb3e87738..33589dd54622 100644
--- a/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts
+++ b/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts
@@ -17,9 +17,6 @@ export interface ViewRecordingsLinkabilityLogicProps {
export const EXPOSURE_UNLINKABLE_REASON =
"This experiment's exposure event is captured server-side without a session ID, so recordings can't be matched."
-export const EXPOSURE_FALLBACK_NOTICE =
- "This experiment's exposure event is captured server-side without a session ID, so exact exposures can't be matched. Showing sessions where the feature flag was active instead."
-
export const METRIC_UNLINKABLE_REASON =
"This metric's events are captured server-side without a session ID, so recordings can't be matched."
diff --git a/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.test.ts b/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.test.ts
index 1263bd9942b6..0a644ac99452 100644
--- a/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.test.ts
+++ b/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.test.ts
@@ -230,6 +230,13 @@ describe('convertUniversalFiltersToRecordingsQuery ∘ recordingsQueryToUniversa
expect(back.actions).toEqual([])
expect(back.properties).toEqual([])
})
+
+ it('preserves experiment_exposure, which no filter pill represents', () => {
+ // Dropped on the round-trip, a saved filter or scanner carrying it would silently
+ // widen from the experiment's exposed sessions to every recording.
+ const query = rq({ experiment_exposure: { experiment_id: 42, variant: 'test' } })
+ expect(roundTrip(query).experiment_exposure).toEqual({ experiment_id: 42, variant: 'test' })
+ })
})
describe('convertUniversalFiltersToRecordingsQuery operand derivation', () => {
diff --git a/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.ts b/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.ts
index 6a91ca9512db..2650c7ca710e 100644
--- a/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.ts
+++ b/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.ts
@@ -159,6 +159,7 @@ export function convertUniversalFiltersToRecordingsQuery(universalFilters: Recor
operand: deriveOperand(universalFilters.filter_group),
limit: universalFilters.limit,
session_ids: universalFilters.session_ids,
+ experiment_exposure: universalFilters.experiment_exposure,
}
}
@@ -192,5 +193,8 @@ export function recordingsQueryToUniversalFilters(
type: (query?.operand as FilterLogicalOperator) ?? FilterLogicalOperator.And,
values: [{ type: FilterLogicalOperator.And, values }],
},
+ // Not editable in the universal-filters UI, but a stored scanner query can carry it;
+ // dropping it on the round-trip would silently widen the scanner to every recording.
+ experiment_exposure: query?.experiment_exposure,
}
}
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 3479d5395c2e..43b43810116a 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -1567,6 +1567,12 @@ export interface RecordingUniversalFilters {
order?: RecordingsQuery['order']
order_direction?: RecordingsQuery['order_direction']
limit?: RecordingsQuery['limit']
+ /**
+ * Server-resolved population narrowing (sessions of persons exposed to the experiment).
+ * Not part of `filter_group`, so the filter-pill editor neither renders nor edits it;
+ * it rides through conversions so saved filters and scanners keep the narrowing.
+ */
+ experiment_exposure?: RecordingsQuery['experiment_exposure']
}
export interface UniversalFiltersGroup {
diff --git a/posthog/session_recordings/playlist_filters.py b/posthog/session_recordings/playlist_filters.py
index 61c41f4554a6..15a399a23a88 100644
--- a/posthog/session_recordings/playlist_filters.py
+++ b/posthog/session_recordings/playlist_filters.py
@@ -243,6 +243,9 @@ def convert_filters_to_recordings_query(filters: dict[str, Any]) -> RecordingsQu
filter_test_accounts=filters.get("filter_test_accounts"),
operand=_derive_operand(filters.get("filter_group")),
limit=filters.get("limit"),
+ # Mirrors the frontend converter: dropping it would make a saved playlist count
+ # every recording instead of the exposed population it displays.
+ experiment_exposure=filters.get("experiment_exposure"),
)
except ValidationError as e:
# we were seeing errors here and it was hard to debug
diff --git a/posthog/session_recordings/queries/session_recording_list_from_query.py b/posthog/session_recordings/queries/session_recording_list_from_query.py
index d2713dc6990a..673c2e7ff7cd 100644
--- a/posthog/session_recordings/queries/session_recording_list_from_query.py
+++ b/posthog/session_recordings/queries/session_recording_list_from_query.py
@@ -1,5 +1,5 @@
from datetime import UTC, datetime, timedelta
-from typing import Any, Literal, Union, cast
+from typing import TYPE_CHECKING, Any, Literal, Optional, Union, cast
import structlog
from dateutil.relativedelta import relativedelta
@@ -39,6 +39,9 @@ from posthog.session_recordings.queries.utils import (
)
from posthog.types import AnyPropertyFilter
+if TYPE_CHECKING:
+ from products.experiments.backend.facade.replay import ExperimentExposureLinkage
+
logger = structlog.get_logger(__name__)
tracer = trace.get_tracer(__name__)
@@ -214,9 +217,14 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
self._extra_having_predicates = extra_having_predicates or []
self._session_ids_to_exclude = session_ids_to_exclude
self._skip_negative_blocklists = skip_negative_blocklists
+ self._experiment_exposure_linkage: Optional[ExperimentExposureLinkage] = None
@tracer.start_as_current_span("SessionRecordingListFromQuery.run")
def run(self) -> SessionRecordingQueryResult:
+ # Resolved before query construction: the resolution validates the experiment and can
+ # run preaggregation-job bookkeeping and synchronous ClickHouse inserts, which is run
+ # work, not AST building.
+ self._resolve_experiment_exposure()
query = self.get_query()
with tracer.start_as_current_span("SessionRecordingListFromQuery.paginate"):
@@ -298,6 +306,34 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
]
return parsed_query
+ def _resolve_experiment_exposure(self) -> None:
+ """Resolve the experiment-exposure linkage once per query instance.
+
+ run() resolves eagerly, but composition callers (to_query(), the replay-vision
+ candidate query) consume get_query() without run(), so _join_experiment_exposure
+ resolves too; the cached linkage keeps the resolution from running twice.
+ """
+ if self._query.experiment_exposure is None or self._experiment_exposure_linkage is not None:
+ return
+ # Deferred: the experiments facade package imports posthog.api on init, which
+ # circles back into this module through the replay-deletion temporal activities.
+ from products.experiments.backend.facade.replay import ( # noqa: PLC0415
+ resolve_exposure_linkage,
+ validate_experiment_exposure_access,
+ )
+
+ try:
+ validate_experiment_exposure_access(self._team, self._user, self._query.experiment_exposure.experiment_id)
+ except UserAccessControlError as error:
+ # Only the /query pipeline renders UserAccessControlError; on the recordings API
+ # it would surface as a 500, so translate to what DRF renders as a 403.
+ raise PermissionDenied(str(error))
+ self._experiment_exposure_linkage = resolve_exposure_linkage(
+ self._team,
+ experiment_id=self._query.experiment_exposure.experiment_id,
+ variant=self._query.experiment_exposure.variant,
+ )
+
def _join_experiment_exposure(self, parsed_query: ast.SelectQuery) -> None:
"""Restrict the list to sessions of persons exposed to the queried experiment.
@@ -312,18 +348,10 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
"""
# Deferred: the experiments facade package imports posthog.api on init, which
# circles back into this module through the replay-deletion temporal activities.
- from products.experiments.backend.facade.replay import ( # noqa: PLC0415
- exposed_distinct_ids_select,
- validate_experiment_exposure_access,
- )
+ from products.experiments.backend.facade.replay import exposed_distinct_ids_select # noqa: PLC0415
- assert self._query.experiment_exposure is not None
- try:
- validate_experiment_exposure_access(self._team, self._user, self._query.experiment_exposure.experiment_id)
- except UserAccessControlError as error:
- # Only the /query pipeline renders UserAccessControlError; on the recordings API
- # it would surface as a 500, so translate to what DRF renders as a 403.
- raise PermissionDenied(str(error))
+ self._resolve_experiment_exposure()
+ assert self._experiment_exposure_linkage is not None
join = parsed_query.select_from
assert join is not None
while join.next_join is not None:
@@ -332,11 +360,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
# GLOBAL: the subquery scans events over the whole experiment window; without it,
# every shard of the sharded replay table re-evaluates that scan independently.
join_type="GLOBAL INNER JOIN",
- table=exposed_distinct_ids_select(
- self._team,
- experiment_id=self._query.experiment_exposure.experiment_id,
- variant=self._query.experiment_exposure.variant,
- ),
+ table=exposed_distinct_ids_select(self._experiment_exposure_linkage),
alias="exposure",
constraint=ast.JoinConstraint(
expr=ast.CompareOperation(
diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_experiment_exposure.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_experiment_exposure.py
index c4aa837b5915..62db55a69e11 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_experiment_exposure.py
+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_experiment_exposure.py
@@ -3,6 +3,7 @@ from datetime import UTC, datetime, timedelta
from freezegun import freeze_time
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+from unittest.mock import patch
from parameterized import parameterized
from rest_framework.exceptions import PermissionDenied, ValidationError
@@ -13,6 +14,7 @@ from posthog.clickhouse.client import sync_execute
from posthog.constants import AvailableFeature
from posthog.models import User
from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.rbac.user_access_control import UserAccessControlError
from posthog.session_recordings.models.session_recording import SessionRecording
@@ -28,7 +30,10 @@ from posthog.session_recordings.session_recording_api import list_recordings_fro
from posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL
from posthog.test.persons import create_person
+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult
+from products.experiments.backend.hogql_queries.experiment_exposure_query_builder import ExposureQueryBuilder
from products.experiments.backend.models.experiment import Experiment
+from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from ee.models.rbac.access_control import AccessControl
@@ -112,6 +117,11 @@ class TestSessionRecordingsListByExperimentExposure(ClickhouseTestMixin, APIBase
def _assert_query_matches_session_ids(self, query: dict, expected: list[str]) -> None:
assert_query_matches_session_ids(team=self.team, query=query, expected=expected, user=self.user)
+ def _enable_precomputation(self) -> None:
+ config = get_or_create_team_extension(self.team, TeamExperimentsConfig)
+ config.experiment_precomputation_enabled = True
+ config.save()
+
def test_filters_to_sessions_of_exposed_persons_ending_at_or_after_first_exposure(self) -> None:
experiment = self._create_experiment()
create_person(team=self.team, distinct_ids=["exposed-user"])
@@ -444,6 +454,101 @@ class TestSessionRecordingsListByExperimentExposure(ClickhouseTestMixin, APIBase
assert [recording.session_id for recording in result.recordings] == ["session-of-exposed"]
+ def test_precomputing_teams_read_exposures_from_the_preaggregated_table(self) -> None:
+ # The default start_date is 34 hours before the frozen now, past the minimum
+ # precompute runtime, so the preaggregated read is the required path here.
+ self._enable_precomputation()
+ experiment = self._create_experiment()
+ create_person(team=self.team, distinct_ids=["exposed-user"])
+ create_person(team=self.team, distinct_ids=["other-user"])
+ exposure_time = BASE_TIME + timedelta(hours=2)
+ self._create_exposure_event("exposed-user", exposure_time, "test")
+ flush_persons_and_events()
+
+ session_start = exposure_time + timedelta(hours=1)
+ self._produce_recording(
+ "exposed-user", "session-of-exposed", session_start, session_start + timedelta(minutes=10)
+ )
+ self._produce_recording("exposed-user", "session-ended-before", BASE_TIME, BASE_TIME + timedelta(minutes=30))
+ self._produce_recording(
+ "other-user", "session-of-unexposed", session_start, session_start + timedelta(minutes=10)
+ )
+
+ # The live scan raising proves the population came from the preaggregated table; the
+ # ensure-side insert builds from its own query template, so it is unaffected. Broken
+ # job-id threading would silently fall back to the events scan precomputation exists
+ # to avoid, which is exactly what this catches.
+ with patch.object(
+ ExposureQueryBuilder,
+ "_build_exposure_select_query",
+ side_effect=AssertionError("live exposure scan used despite precomputation"),
+ ):
+ self._assert_query_matches_session_ids(
+ {"experiment_exposure": {"experiment_id": experiment.id}},
+ ["session-of-exposed"],
+ )
+
+ def test_rejects_instead_of_scanning_live_when_the_preaggregated_read_is_unavailable(self) -> None:
+ self._enable_precomputation()
+ experiment = self._create_experiment()
+
+ # On precomputing teams the live scan is the query that cannot complete, so an
+ # unavailable preaggregated read must refuse rather than fall back to it.
+ with patch(
+ "products.experiments.backend.replay_linkage.ensure_precomputed",
+ return_value=LazyComputationResult(ready=False, job_ids=[]),
+ ):
+ with self.assertRaises(ValidationError) as error_context:
+ filter_recordings_by(
+ team=self.team,
+ recordings_filter={"experiment_exposure": {"experiment_id": experiment.id}},
+ user=self.user,
+ )
+ self.assertIn("still being computed", str(error_context.exception.detail))
+
+ def test_rejects_activation_mode_on_precomputing_teams(self) -> None:
+ self._enable_precomputation()
+ experiment = self._create_experiment(
+ exposure_criteria={
+ "activation_config": {
+ "kind": "ExperimentEventExposureConfig",
+ "event": "task_completed",
+ "properties": [],
+ }
+ }
+ )
+
+ with self.assertRaises(ValidationError) as error_context:
+ filter_recordings_by(
+ team=self.team,
+ recordings_filter={"experiment_exposure": {"experiment_id": experiment.id}},
+ user=self.user,
+ )
+ self.assertIn("activation event", str(error_context.exception.detail))
+
+ def test_young_experiments_scan_live_even_on_precomputing_teams(self) -> None:
+ # Started 6 hours before the frozen now, under the 12-hour precompute minimum. The
+ # fail-fast guard must not reach these: their scan window is hours wide, and the
+ # current-day cache TTL would hide fresh exposures right when users watch the tab.
+ self._enable_precomputation()
+ experiment = self._create_experiment(start_date=BASE_TIME + timedelta(hours=4))
+ create_person(team=self.team, distinct_ids=["exposed-user"])
+ exposure_time = BASE_TIME + timedelta(hours=5)
+ self._create_exposure_event("exposed-user", exposure_time, "test")
+ flush_persons_and_events()
+
+ session_start = exposure_time + timedelta(hours=1)
+ self._produce_recording(
+ "exposed-user", "session-of-exposed", session_start, session_start + timedelta(minutes=10)
+ )
+
+ with patch("products.experiments.backend.replay_linkage.ensure_precomputed") as ensure_mock:
+ self._assert_query_matches_session_ids(
+ {"experiment_exposure": {"experiment_id": experiment.id}},
+ ["session-of-exposed"],
+ )
+ ensure_mock.assert_not_called()
+
def _create_denied_experiment_and_viewer(self) -> tuple[Experiment, User]:
self.organization.available_product_features = [
{"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
diff --git a/posthog/session_recordings/session_recording_playlist_api.py b/posthog/session_recordings/session_recording_playlist_api.py
index 85f7bccfd5f7..51620fc3b56b 100644
--- a/posthog/session_recordings/session_recording_playlist_api.py
+++ b/posthog/session_recordings/session_recording_playlist_api.py
@@ -37,7 +37,7 @@ from posthog.models.team.team import Team
from posthog.models.utils import UUIDT
from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
-from posthog.rbac.user_access_control import UserAccessControlSerializerMixin
+from posthog.rbac.user_access_control import UserAccessControlError, UserAccessControlSerializerMixin
from posthog.redis import get_client
from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylistViewed
from posthog.session_recordings.session_recording_api import (
@@ -548,6 +548,25 @@ class SessionRecordingPlaylistSerializer(serializers.ModelSerializer, UserAccess
return recordings_counts
+ def validate_filters(self, value: Any) -> Any:
+ experiment_exposure = value.get("experiment_exposure") if isinstance(value, dict) else None
+ experiment_id = experiment_exposure.get("experiment_id") if isinstance(experiment_exposure, dict) else None
+ if isinstance(experiment_id, int):
+ # Deferred: the experiments facade package imports posthog.api on init, which
+ # circles back into this module through the API router registration.
+ from products.experiments.backend.facade.replay import validate_experiment_exposure_access # noqa: PLC0415
+
+ try:
+ validate_experiment_exposure_access(
+ self.context["get_team"](), self.context["request"].user, experiment_id
+ )
+ except UserAccessControlError:
+ raise ValidationError(
+ "These filters reference an experiment you don't have access to. "
+ "Ask for access to the experiment to save them."
+ )
+ return value
+
def create(self, validated_data: dict, *args, **kwargs) -> SessionRecordingPlaylist:
request = self.context["request"]
team = self.context["get_team"]()
diff --git a/posthog/session_recordings/test/test_playlist_filters.py b/posthog/session_recordings/test/test_playlist_filters.py
index 858dff2bd56a..7159a20dccc2 100644
--- a/posthog/session_recordings/test/test_playlist_filters.py
+++ b/posthog/session_recordings/test/test_playlist_filters.py
@@ -32,6 +32,16 @@ class TestConvertFiltersToRecordingsQuery(SimpleTestCase):
query = convert_filters_to_recordings_query(_filters(outer, inner, [_visited_page("/cart")]))
assert query.operand == expected
+ def test_experiment_exposure_survives_conversion(self):
+ # Dropped here, a saved playlist carrying the filter would count every recording in
+ # the project instead of the exposed population it displays.
+ filters = _filters("AND", "AND", [])
+ filters["experiment_exposure"] = {"experiment_id": 42, "variant": "test"}
+ query = convert_filters_to_recordings_query(filters)
+ assert query.experiment_exposure is not None
+ assert query.experiment_exposure.experiment_id == 42
+ assert query.experiment_exposure.variant == "test"
+
def test_visited_page_becomes_recording_property_not_event(self):
filters = _filters("OR", "OR", [_visited_page("/cart"), _visited_page("/orders")])
query = convert_filters_to_recordings_query(filters)
diff --git a/posthog/session_recordings/test/test_session_recording_playlist.py b/posthog/session_recordings/test/test_session_recording_playlist.py
index 9f977c9a106f..feeaa8b953c1 100644
--- a/posthog/session_recordings/test/test_session_recording_playlist.py
+++ b/posthog/session_recordings/test/test_session_recording_playlist.py
@@ -18,6 +18,7 @@ from parameterized import parameterized
from rest_framework import status
from posthog import redis
+from posthog.constants import AvailableFeature
from posthog.models import Organization, PersonalAPIKey, SessionRecording, SessionRecordingPlaylistItem, Team
from posthog.models.file_system.file_system import FileSystem
from posthog.models.user import User
@@ -46,6 +47,11 @@ from posthog.settings import (
OBJECT_STORAGE_SECRET_ACCESS_KEY,
)
+from products.experiments.backend.models.experiment import Experiment
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+from ee.models.rbac.access_control import AccessControl
+
TEST_BUCKET = "test_storage_bucket-ee.TestSessionRecordingPlaylist"
@@ -421,6 +427,60 @@ class TestSessionRecordingPlaylist(APIBaseTest, QueryMatchingTest):
assert response.status_code == status.HTTP_404_NOT_FOUND
assert SessionRecordingPlaylistViewed.objects.count() == 0
+ def _create_denied_experiment_and_viewer(self) -> tuple[Experiment, User]:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ flag = FeatureFlag.objects.create(
+ team=self.team, key="playlist-exposure-flag", created_by=self.user, filters={}
+ )
+ experiment = Experiment.objects.create(
+ team=self.team,
+ name="playlist exposure experiment",
+ feature_flag=flag,
+ created_by=self.user,
+ exposure_criteria={},
+ metrics=[],
+ )
+ AccessControl.objects.create(
+ team=self.team, resource="experiment", resource_id=str(experiment.pk), access_level="none"
+ )
+ return experiment, self._create_user("[email protected]")
+
+ def test_rejects_saving_filters_that_reference_an_experiment_the_saver_cannot_view(self) -> None:
+ experiment, denied_user = self._create_denied_experiment_and_viewer()
+ exposure_filters = {"date_from": "-30d", "experiment_exposure": {"experiment_id": experiment.id}}
+ self.client.force_login(denied_user)
+ plain_playlist = self._create_playlist({"type": "filters", "filters": {"date_from": "-30d"}})
+
+ create_response = self.client.post(
+ f"/api/projects/{self.team.id}/session_recording_playlists",
+ data={"name": "exposed sessions", "type": "filters", "filters": exposure_filters},
+ )
+ assert create_response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "experiment you don't have access to" in create_response.json()["detail"]
+
+ update_response = self.client.patch(
+ f"/api/projects/{self.team.id}/session_recording_playlists/{plain_playlist.json()['short_id']}",
+ {"filters": exposure_filters},
+ )
+ assert update_response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "experiment you don't have access to" in update_response.json()["detail"]
+
+ def test_saves_filters_that_reference_an_experiment_the_saver_can_view(self) -> None:
+ # The experiment's creator keeps viewer access despite the team-wide "none", so the
+ # save-time check must let their save through.
+ experiment, _ = self._create_denied_experiment_and_viewer()
+
+ self._create_playlist(
+ {
+ "name": "exposed sessions",
+ "type": "filters",
+ "filters": {"date_from": "-30d", "experiment_exposure": {"experiment_id": experiment.id}},
+ }
+ )
+
def test_updates_playlist(self):
create_response = self._create_playlist(
{
diff --git a/posthog/temporal/session_replay/count_playlist_items/counting_logic.py b/posthog/temporal/session_replay/count_playlist_items/counting_logic.py
index fbe2d6d9e8e5..892f9ca301da 100644
--- a/posthog/temporal/session_replay/count_playlist_items/counting_logic.py
+++ b/posthog/temporal/session_replay/count_playlist_items/counting_logic.py
@@ -123,6 +123,13 @@ def safe_seconds_difference(dt1: datetime, dt2: datetime) -> int:
def should_skip_task(existing_value: dict[str, Any], playlist_filters: dict[str, Any]) -> bool:
+ # The exposure filter refuses userless callers because cached counts reach playlist
+ # viewers without an access check, and this task has no principal to offer. Skip rather
+ # than error into the park/retry cycle; counting these needs a principal-scoped recount.
+ if (playlist_filters or {}).get("experiment_exposure"):
+ REPLAY_TEAM_PLAYLIST_COUNT_SKIPPED.labels(reason="experiment_exposure").inc()
+ return True
+
# if we have results from the last hour we don't need to run the query
if existing_value.get("refreshed_at"):
last_refreshed_at = datetime.fromisoformat(existing_value["refreshed_at"])
diff --git a/posthog/temporal/tests/session_replay/count_playlist_items/test_counting_logic.py b/posthog/temporal/tests/session_replay/count_playlist_items/test_counting_logic.py
index 1cefd041d395..1d57f9d79154 100644
--- a/posthog/temporal/tests/session_replay/count_playlist_items/test_counting_logic.py
+++ b/posthog/temporal/tests/session_replay/count_playlist_items/test_counting_logic.py
@@ -42,6 +42,27 @@ class TestRecordingsThatMatchPlaylistFilters(APIBaseTest, QueryMatchingTest):
assert self.redis_client.get(f"{PLAYLIST_COUNT_REDIS_PREFIX}there_is_no_short_id") is None
mock_capture_exception.assert_not_called()
+ @patch("posthoganalytics.capture_exception")
+ def test_skips_exposure_playlists_without_counting_or_erroring(self, mock_capture_exception: MagicMock):
+ # The task runs userless and the exposure filter refuses userless callers, so counting
+ # can only fail. The skip must fire before any query runs, whether or not the
+ # experiment still exists, and must not feed the error cooldown.
+ playlist = SessionRecordingPlaylist.objects.create(
+ team=self.team,
+ name="exposed sessions",
+ filters={
+ "date_from": "-30d",
+ "filter_test_accounts": False,
+ "filter_group": {"type": "AND", "values": [{"type": "AND", "values": []}]},
+ "experiment_exposure": {"experiment_id": 999999},
+ },
+ )
+
+ count_recordings_that_match_playlist_filters(playlist.id)
+
+ assert self.redis_client.get(f"{PLAYLIST_COUNT_REDIS_PREFIX}{playlist.short_id}") is None
+ mock_capture_exception.assert_not_called()
+
@patch("posthoganalytics.capture_exception")
@patch("posthog.temporal.session_replay.count_playlist_items.counting_logic.list_recordings_from_query")
def test_count_recordings_that_match_no_recordings(
diff --git a/products/experiments/backend/facade/replay.py b/products/experiments/backend/facade/replay.py
index a6eb217b06a9..a292616e2d4b 100644
--- a/products/experiments/backend/facade/replay.py
+++ b/products/experiments/backend/facade/replay.py
@@ -1,5 +1,15 @@
"""Replay linkage capability, re-exported for callers outside the experiments product."""
-from products.experiments.backend.replay_linkage import exposed_distinct_ids_select, validate_experiment_exposure_access
+from products.experiments.backend.replay_linkage import (
+ ExperimentExposureLinkage,
+ exposed_distinct_ids_select,
+ resolve_exposure_linkage,
+ validate_experiment_exposure_access,
+)
-__all__ = ["exposed_distinct_ids_select", "validate_experiment_exposure_access"]
+__all__ = [
+ "ExperimentExposureLinkage",
+ "exposed_distinct_ids_select",
+ "resolve_exposure_linkage",
+ "validate_experiment_exposure_access",
+]
diff --git a/products/experiments/backend/replay_linkage.py b/products/experiments/backend/replay_linkage.py
index b465779279d6..3585813390ce 100644
--- a/products/experiments/backend/replay_linkage.py
+++ b/products/experiments/backend/replay_linkage.py
@@ -10,12 +10,29 @@ session, is what keeps server-fired exposure events linkable: they carry no usab
``$session_id`` (none at all, or a context-generated one that matches no recording), but the
person's other distinct ids do appear on recordings. Expanding the exposed persons through
``raw_person_distinct_ids`` also covers cross-device sessions and anonymous pre-identify ids.
+
+The work splits in two, because recordings queries build their AST separately from running it:
+
+- :func:`resolve_exposure_linkage` validates the experiment and decides how the exposed
+ population will be read. On teams with experiment precomputation enabled it resolves
+ preaggregation job ids through the same ``ensure_precomputed`` path the analysis queries
+ use, which reads and writes job state and can run ClickHouse inserts synchronously. That
+ is runner work, so callers must invoke it from their run path, never while building an AST.
+- :func:`exposed_distinct_ids_select` is pure AST construction from a resolved linkage.
+
+The exposure scan window is deliberately the full experiment window, unbounded. Narrowing it
+would change who counts as exposed relative to the analysis. The expensive cases are handled
+instead: precomputing teams read the preaggregated table (converging in TTL-capped chunks for
+long-running experiments), and where neither the preaggregated read nor an affordable live
+scan is available the query is refused with a ValidationError rather than left to time out.
"""
+from dataclasses import dataclass
from datetime import UTC, datetime
from django.contrib.auth.models import AnonymousUser
+import structlog
from rest_framework.exceptions import ValidationError
from posthog.schema import IntervalType
@@ -23,19 +40,45 @@ from posthog.schema import IntervalType
from posthog.hogql import ast
from posthog.hogql.parser import parse_select
+from posthog.clickhouse.query_tagging import tag_queries, tags_context
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
+from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.rbac.user_access_control import UserAccessControl, UserAccessControlError
from posthog.synthetic_user import SyntheticUser
-from products.experiments.backend.hogql_queries.base_query_utils import experiment_window
+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
+ LazyComputationTable,
+ ensure_precomputed,
+)
+from products.experiments.backend.hogql_queries.base_query_utils import experiment_window, experiment_window_end
from products.experiments.backend.hogql_queries.cuped_config import CupedQueryConfig
from products.experiments.backend.hogql_queries.experiment_exposure_query_builder import ExposureQueryBuilder
from products.experiments.backend.hogql_queries.experiment_query_builder import get_exposure_config_params_for_builder
from products.experiments.backend.hogql_queries.experiment_query_context import ExperimentQueryContext
-from products.experiments.backend.hogql_queries.exposure_query_logic import get_entity_key
+from products.experiments.backend.hogql_queries.experiment_query_runner import (
+ experiment_has_min_runtime_for_precomputation,
+ experiment_precompute_ttl_schedule,
+ has_uncalculated_cohorts,
+)
+from products.experiments.backend.hogql_queries.exposure_query_logic import get_entity_key, has_activation_config
from products.experiments.backend.models.experiment import Experiment
+from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
+
+logger = structlog.get_logger(__name__)
+
+EXPOSURES_STILL_COMPUTING_MESSAGE = (
+ "Exposed users for this experiment are still being computed. Try again in a few minutes."
+)
+ACTIVATION_NOT_PRECOMPUTABLE_MESSAGE = (
+ "This experiment counts exposure from an activation event, which can't be precomputed, "
+ "and this project is too large to resolve its exposed users live."
+)
+COHORT_NOT_CALCULATED_MESSAGE = (
+ "This experiment's exposure criteria reference a cohort that hasn't finished calculating. "
+ "Try again when the cohort is ready."
+)
def validate_experiment_exposure_access(
@@ -56,7 +99,7 @@ def validate_experiment_exposure_access(
are non-User principals outside object-level RBAC and pass; they are gated by API scope
plus project membership, and by the sharing publish gate, respectively. An unknown
experiment also passes, because there is no object to protect and
- :func:`exposed_distinct_ids_select` reports it as a ValidationError.
+ :func:`resolve_exposure_linkage` reports it as a ValidationError.
Returns True, or raises UserAccessControlError (the query-runner access contract).
"""
@@ -72,12 +115,28 @@ def validate_experiment_exposure_access(
return True
-def exposed_distinct_ids_select(team: Team, *, experiment_id: int, variant: str | None) -> ast.SelectQuery:
- """One row per exposed distinct id: (distinct_id, first_exposure_time).
+@dataclass(frozen=True, kw_only=True)
+class ExperimentExposureLinkage:
+ """A validated experiment-exposure filter, resolved to how its population will be read.
+
+ Opaque to callers outside this product: obtained from :func:`resolve_exposure_linkage`
+ and handed back to :func:`exposed_distinct_ids_select`.
+ """
+
+ context: ExperimentQueryContext
+ requested_variants: list[str]
+ # Set = read the preaggregated exposures written by these jobs. None = live events scan.
+ preaggregation_job_ids: list[str] | None
+
+
+def resolve_exposure_linkage(team: Team, *, experiment_id: int, variant: str | None) -> ExperimentExposureLinkage:
+ """Validate the experiment and resolve how its exposed population will be read.
Raises ValidationError for experiments the linkage can't answer for: unknown or draft
- experiments, and group-aggregated ones, whose exposed entities are groups rather than
- persons and so never match a recording's distinct id.
+ experiments, group-aggregated ones (whose exposed entities are groups rather than
+ persons and so never match a recording's distinct id), unknown variants, and
+ experiments whose exposures can be resolved neither from the preaggregated table nor
+ with a live scan the team can afford.
"""
try:
experiment = Experiment.objects.get(id=experiment_id, team=team, deleted=False)
@@ -133,7 +192,84 @@ def exposed_distinct_ids_select(team: Team, *, experiment_id: int, variant: str
cuped_config=CupedQueryConfig(),
activation_config=exposure_params.activation_config,
)
- exposure_select = ExposureQueryBuilder(context=context).select_query()
+ return ExperimentExposureLinkage(
+ context=context,
+ requested_variants=requested_variants,
+ preaggregation_job_ids=_resolve_preaggregation_job_ids(team, experiment, context),
+ )
+
+
+def _resolve_preaggregation_job_ids(
+ team: Team, experiment: Experiment, context: ExperimentQueryContext
+) -> list[str] | None:
+ """Preaggregation job ids covering the experiment window, or None for a live scan.
+
+ The eligibility gates mirror the exposures-chart runner's, but the fallback posture
+ inverts: the analysis can always fall back to a direct scan, because it runs through
+ the async query pipeline with generous limits. This linkage runs inside a synchronous
+ recordings-list GET, where the production assessment showed the live scan cannot
+ complete on the largest teams. Precomputation being enabled is the team-level marker
+ for exactly those teams, so on them an unavailable preaggregated read is refused
+ instead of silently attempting the scan that precomputation exists to avoid.
+ """
+ config = get_or_create_team_extension(team, TeamExperimentsConfig)
+ # Below the minimum runtime the analysis skips precomputation too: the scan window is
+ # hours wide (cheap on any team), and the current-day cache TTL would hide exposures
+ # from the tab for up to 15 minutes right when users watch it most.
+ if not config.experiment_precomputation_enabled or not experiment_has_min_runtime_for_precomputation(
+ experiment.start_date, experiment.end_date
+ ):
+ tag_queries(experiment_exposures_path="direct_scan")
+ return None
+
+ if has_activation_config(experiment.exposure_criteria):
+ # The flag-to-activation ordering crosses the per-day cache buckets, so activation
+ # exposures can't be precomputed. A per-experiment live path for them is deliberately
+ # not built: activation mode is a negligible slice of running experiments.
+ raise ValidationError(ACTIVATION_NOT_PRECOMPUTABLE_MESSAGE)
+ if has_uncalculated_cohorts(team, experiment.exposure_criteria):
+ # A build during the cohort's first materialization would freeze a torn membership
+ # snapshot for the frozen-band TTL; transient, so the error says to retry.
+ raise ValidationError(COHORT_NOT_CALCULATED_MESSAGE)
+
+ query_string, placeholders = ExposureQueryBuilder(context=context).precomputation_query()
+ assert experiment.start_date is not None
+ try:
+ with tags_context(experiment_query_surface="precompute_build", experiment_precompute_table="exposures"):
+ result = ensure_precomputed(
+ team=team,
+ insert_query=query_string,
+ time_range_start=experiment.start_date,
+ time_range_end=experiment_window_end(experiment, experiment.end_date or datetime.now(UTC)),
+ ttl_seconds=experiment_precompute_ttl_schedule(team.timezone),
+ table=LazyComputationTable.EXPERIMENT_EXPOSURES_PREAGGREGATED,
+ placeholders=placeholders,
+ sentinel_placeholders={"experiment_date_to"},
+ spill_to_disk=True,
+ )
+ except Exception:
+ logger.exception("exposure_lazy_computation_failed", experiment_id=experiment.id)
+ raise ValidationError(EXPOSURES_STILL_COMPUTING_MESSAGE)
+ if not result.ready:
+ # Cold long-running experiments converge across successive requests: each ensure
+ # call persists the chunk jobs it completed, so retrying eventually succeeds.
+ logger.warning("exposure_lazy_computation_not_ready", experiment_id=experiment.id)
+ raise ValidationError(EXPOSURES_STILL_COMPUTING_MESSAGE)
+
+ tag_queries(experiment_exposures_path="precomputed")
+ return [str(job_id) for job_id in result.job_ids]
+
+
+def exposed_distinct_ids_select(linkage: ExperimentExposureLinkage) -> ast.SelectQuery:
+ """One row per exposed distinct id: (distinct_id, first_exposure_time).
+
+ Pure AST construction; :func:`resolve_exposure_linkage` carries the validation and the
+ precompute decision, so callers can build query ASTs without side effects.
+ """
+ exposure_select = ExposureQueryBuilder(
+ context=linkage.context,
+ preaggregation_job_ids=linkage.preaggregation_job_ids,
+ ).select_query()
# The WHERE on variant also drops entities attributed MULTIPLE_VARIANT_KEY under "exclude"
# handling, matching who the analysis counts. Both join sides are pre-grouped, so each
@@ -158,9 +294,9 @@ def exposed_distinct_ids_select(team: Team, *, experiment_id: int, variant: str
GROUP BY pdi.distinct_id
""",
placeholders={
- "team_id": ast.Constant(value=team.pk),
+ "team_id": ast.Constant(value=linkage.context.team.pk),
"exposure_select": exposure_select,
- "requested_variants": ast.Constant(value=requested_variants),
+ "requested_variants": ast.Constant(value=linkage.requested_variants),
},
)
assert isinstance(query, ast.SelectQuery)
diff --git a/products/experiments/backend/session_buckets.py b/products/experiments/backend/session_buckets.py
index af7ba84abd96..26621cc2c94d 100644
--- a/products/experiments/backend/session_buckets.py
+++ b/products/experiments/backend/session_buckets.py
@@ -11,22 +11,25 @@ metric. The analysis counts per person over the whole run window, while a record
session of one person, so copy built on this must stay session-scoped ("in this session") and
must never claim the analysis counted or discounted anyone.
-The population is the same session-scoped exposure evidence the tab's own list is built from —
-an event matching the experiment's exposure criteria, carrying one of the flag's defined
-variants. Not the exposure query's `exposure_session_id`, which is the person's *first*
-exposure session only: the playlist ANDs these ids with its own exposure filter, so ids it
-would 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. 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.
+The population is session-scoped exposure evidence: an event matching the experiment's
+exposure criteria, carrying one of the flag's defined variants, inside the session. That is a
+deliberate choice, kept even though the tab's own list is person-scoped
+(`RecordingsQuery.experiment_exposure`): every bucket asks what happened *in the session*, and
+"fired none of these metrics" only means something over sessions that demonstrably saw the
+experiment, whereas over all of an exposed person's sessions it would surface their unrelated
+browsing. The playlist ANDs the returned ids with its person-scoped filter, so a bucket session
+whose person the analysis excludes (multiple variants, for example) drops out there rather than
+widening the shown set; ids spent on such sessions are wasted slots out of the cap, which is
+the price of staying session-scoped. 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` fact
the taxonomy `seen_together` endpoint serves the tab: an event never ingested with a
`$session_id` (backend-fired exposure, server-side metrics) can only ever match zero sessions.
For the default exposure event the population falls back to the stamped `$feature/<flag_key>`
-property — the same fallback the tab's list uses — flagged in the response as
-`used_exposure_fallback`. Custom criteria get no such stand-in: they assert that something
+property — the same fallback the per-variant "View recordings" links use — flagged in the
+response as `used_exposure_fallback`. Custom criteria get no such stand-in: they assert that something
specific happened, which the stamped property doesn't imply, so a custom exposure event that
can't be matched is refused with a reason rather than answered over a wider population.
Metrics whose every source is such an event are excluded with a reason instead of silently