: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): add opt-in in-session exposure scope to recordings (#83999)
Marcel Poelkerc97d14223879
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 5387f6c8dc0b..c0ea954b7098 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6869,29 +6869,29 @@ snapshots:scenes-app-experiments--experiment-frequentist-two-variants--light:hash: v1.k794b7964.c3d7500050335234dac2b12a58ae26fe68611d4f4fb040ab162a0b22aa2816c4.yZkCSjTEKndRt6r5t2hSlLwgfIwnnDg5or8MZX0tAz0scenes-app-experiments--experiment-replay-scanner-backlink--dark:- hash: v1.k794b7964.7efe310d3bf7b9c4d5462d30ae611e6248804e02857e97bb5a112c76fd1b66fe.aDk-Mc3Vtc8YcmQ4tpT7MpVrYARzKCdcwiKj4PFlxic+ hash: v1.k794b7964.a664d49360b53c7b5d9688b274653ab9f8ce2c5d4fbd9c88c074501079e58a80.4xrkavfqRBFfrvK6NUJx7i5vUpdlvsoIwYhPPvpeOBIscenes-app-experiments--experiment-replay-scanner-backlink--light:- hash: v1.k794b7964.2dc5ae6c50622395d0e6faebae14181a3a26b304acaafcff67a9b9fcc4307bda.lxOQLxGPUK14YY86vol2qQN_x4w0Uy6zERaXaSDAnVQ+ hash: v1.k794b7964.2ac397a742be0c9a40665935c2c3564ff25253117f5dae171b2ff5bc2e7c0fc4.sK7WzwkpIAHDXzJC2TZPAzndt-xZ7SSY5hJJIh-RK9sscenes-app-experiments--experiment-stopped-with-conclusion--dark:hash: v1.k794b7964.e347bbe9e217d7cbd915b09b362a9d995285c1f6492229235ce3dcef74e49f30.5xV99CaEDXp-xFACHoS4M9vQ6zFGOjestb-iW79F5Q4scenes-app-experiments--experiment-stopped-with-conclusion--light:hash: v1.k794b7964.793a4b6109b2c0ab65b07d9eaefd1c8862f12bfc7f33b2f452ad20044396b2a7.6B0Meq7yO75vBEoBmuP2dNl2oKTugzzr_IKTcJHhEi0scenes-app-experiments--experiment-watch-shelf-no-recordings--dark:- hash: v1.k794b7964.23dd38a3ed596831fbf5022d13eeb37f09aedccb5eeafc28b2c6423dbb50758d.qKdB73mL0ZWdJwd18Fs0DL-urGDQza2fJiaD-C-qKqg+ hash: v1.k794b7964.2ac26f9773399f7c2a0897fe7bf079342e196d96e005d5398c90cab279f00ef0.XeWSLYIaWO0-9S0Gu37FahYgZRooHWJbZuQo1CV-gK8scenes-app-experiments--experiment-watch-shelf-no-recordings--light:- hash: v1.k794b7964.a30a978bbe3f0656e39a333e1bc62d8a25b114b06ac6cc35bf4d56a48d7fc96a.6toGGh_OTOWfGNqaZoSv4US5VmPzCEJo9hkaoFVV6g8+ hash: v1.k794b7964.e55c98187c7b3fd9fa55401c0baa5f56e29cd831b89c2fbe79754cf3c9da9fcf.uSX-AvXhBvhKYjXYKPnPio1Uunf851HG-S-6TatD2fAscenes-app-experiments--experiment-watch-shelf-no-separation--dark:- hash: v1.k794b7964.2d772420fca270a4f5401d430774bc75a640c78b88dddffde3b5263fadde8320.NBHKFm8SXwIqQwXwrAmbSObZ0UVdZ6s_mnMh8oQg-xM+ hash: v1.k794b7964.67610e0b1840bf8fa6bb23ca5790864acfac146e2aa7af7533bb29795b1087e0.LQx2eb_qo4CPMlIlmlqiBuFj-Nutb0xfsfr9ls_b5_wscenes-app-experiments--experiment-watch-shelf-no-separation--light:- hash: v1.k794b7964.f36d972629410063b0f0ccc13272ab9d2802d9077f9ee5789b2d0204e7bda550.kiRkN0uo7zUn6weRtI1E4khblBrt0hqke1B8WbaIrsQ+ hash: v1.k794b7964.9905e631412d75f05a9c1ccd7d450ef543bb3707b88512f22a74b9e2d8740750.QY7_c_0BnayEhoKEkIwbOUy_lXhGSo_z6qHBAFXSy54scenes-app-experiments--experiment-watch-shelf-no-session-linked-exposures--dark:- hash: v1.k794b7964.68a2b8c41b6847b60423d3f9056b0fcce37a272037a6097cbd6ccd9c8cd87f3d.1gbzdu3wsZN0ccD2Aveqa-rlD49kKt6AgHuGu9phMI0+ hash: v1.k794b7964.efed1414511ba693b62e9ef699eb46eebc974f71b04ff3ab196acee3d41bf8ff.vW1xzGD58MKp9kOF62u82jA4goSpqGzI4aN9JMudCDIscenes-app-experiments--experiment-watch-shelf-no-session-linked-exposures--light:- hash: v1.k794b7964.59f5d5a13ece43ab0465b9ad13dbf4226beeda02f5509cca77ab760edae81aed.GJyU3IrtCWsEMSJxDvIKuXDOO-YBLs4cdI3PAc02J98+ hash: v1.k794b7964.d13537ae58ffc2d03e58fd792394e4d7726b5d6bc466931048b5d47226105422.XU1jTNjk6MlyoUqFEcfptrbZAD_MMF7Gjiu_Mj1lEr4scenes-app-experiments--experiment-watch-shelf-too-early--dark:- hash: v1.k794b7964.2b35c19fde639d37a5a7f3c7f2dea6cc7fef89b3193ab1f5339d08d74a9fcc96.i_mB3mn1EMijlpQm3aFR0reQWkbFMfMHezb799HdsP4+ hash: v1.k794b7964.1b88cc8cd64ba1bccfcaed317ac501bf200ba341e92116db27f90d82ae49c73a.SMrxC03vvYcGHvkNeohFps_ewZMmt62ym-wvgn_M6DEscenes-app-experiments--experiment-watch-shelf-too-early--light:- hash: v1.k794b7964.951b08362f266ac3f1a8de854badbdb15407d3aef0737da9a6190630065a244e.yGqMV6Q3H-klHSgARIs5FvXFHzVTzRt8SNLw-gQ2I-g+ hash: v1.k794b7964.e058db803b56cf08ca5ee991f4fbb027c0356403bdd65d7dc48e005c949ace33.dmKGtzopSbXAZbJNQ9wkZKko6X2RRDtvbS3Bk-FPkUkscenes-app-experiments--experiment-with-funnel-metric--dark:hash: v1.k794b7964.fd0d0ad7569f50079a322a8901513f854823ce694796a2a24a1e6714ac9c5902.fBtAQkm1LZ7xYp6DTXoQSDqDFjsUkxMCP-aNAZJ1Fmcscenes-app-experiments--experiment-with-funnel-metric--light:diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.tsindex a4f2c792b076..58a8c008a81b 100644--- a/frontend/src/lib/utils/eventUsageLogic.ts+++ b/frontend/src/lib/utils/eventUsageLogic.ts@@ -125,21 +125,31 @@ export enum GraphSeriesAddedSource {/*** 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.+ * linkability and in-session availability checks have 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. The scope and availability fields+ * live here and not only on the opened-recording context, because a session whose list came back+ * empty opens nothing, and empty lists are the outcome the in-session scope most affects.*/export interface ExperimentRecordingsTabContext {variant_count: numbermetric_count: numberlinkable_metric_count: number+ /** Kept as a string rather than the tab's union so telemetry doesn't import from the scene. */+ exposure_scope: string+ /** Null when the availability check failed, so a transient error never reads as unavailable. */+ in_session_available: boolean | null+ in_session_unavailable_reason: string | null+ in_session_uses_stamped_fallback: boolean | null}/** The facets the recordings list was narrowed by when a recording was opened from it. */export interface ExperimentRecordingsFilterContext {variant: string | null/** Kept as a string rather than the tab's union so telemetry doesn't import from the scene. */+ exposure_scope: string+ /** Kept as a string rather than the tab's union so telemetry doesn't import from the scene. */metric_filter_mode: stringselected_metric_count: number/** True when the list is a server-computed session set rather than client-side event filters. */diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex fbe2075de81c..e9359785174d 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -49754,6 +49754,10 @@"$ref": "#/definitions/integer","description": "Experiment whose exposed persons' sessions to show. Must belong to the environment the query runs in."},+ "in_session": {+ "description": "Only sessions carrying in-session exposure evidence: an event matching the experiment's exposure criteria inside the session (with the stamped `$feature/<flag_key>` property standing in when the exposure event was never captured with a session id). Defaults to all exposed persons' sessions from first exposure onward.",+ "type": "boolean"+ },"variant": {"description": "Narrow to persons exposed to this variant. Defaults to all of the experiment's variants.","type": "string"diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 0f6958a16ecc..e5c89a4e5648 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -700,6 +700,12 @@ export interface RecordingsQueryExperimentExposureFilter {experiment_id: integer/** Narrow to persons exposed to this variant. Defaults to all of the experiment's variants. */variant?: string+ /**+ * Only sessions carrying in-session exposure evidence: an event matching the experiment's exposure criteria+ * inside the session (with the stamped `$feature/<flag_key>` property standing in when the exposure event was+ * never captured with a session id). Defaults to all exposed persons' sessions from first exposure onward.+ */+ in_session?: boolean}export interface RecordingsQuery extends DataNode<RecordingsQueryResponse> {diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsxindex d6a5f2475c16..12c1025ed42e 100644--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx@@ -50,12 +50,42 @@ const ALL_VARIANTS = '$all'// turned down scanners for this experiment did not ask to be told again in purple.const SCANNER_CROSS_SELL_DISMISS_KEY = 'experiment-replay-vision-scanner-cross-sell'-// 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 =+// The 'all_exposed' caption 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 ALL_EXPOSED_CAPTION ="Showing sessions of exposed participants from their first exposure onward. The exposure event itself doesn't have to be in the session."+// The copy varies with what the in-session evidence is. 'stamped' means the flag property stands+// in for the exposure event, so the flag was active in the session rather than the exposure event+// being captured there, and the copy must not claim more than the query delivers (wording mirrors+// the behavior-comparison shelf). 'unknown' covers the availability check still pending or failed,+// where the copy claims only what both kinds share. The scopeLockedReason strings park the control+// while a bucket or watch card supplies the session set, which carries in-session evidence by+// construction, so the control could neither widen nor narrow it.+type InSessionEvidenceKind = 'event' | 'stamped' | 'unknown'+const IN_SESSION_COPY: Record<InSessionEvidenceKind, { tooltip: string; caption: string; scopeLockedReason: string }> =+ {+ event: {+ tooltip: 'Only sessions where an exposure event for this experiment was captured in the session.',+ caption: 'Showing sessions of exposed participants where the exposure was captured in the session.',+ scopeLockedReason:+ 'This metric filter already narrows to sessions where the exposure was captured in the session.',+ },+ stamped: {+ tooltip:+ 'Sessions where the feature flag was active. No exposure event can be matched to a recording for this experiment, so the flag being active stands in.',+ caption:+ 'Showing sessions of exposed participants where the feature flag was active, since no exposure event can be matched to a recording here.',+ scopeLockedReason: 'This metric filter already narrows to sessions where the feature flag was active.',+ },+ unknown: {+ tooltip: 'Only sessions carrying in-session exposure evidence for this experiment.',+ caption: 'Showing sessions of exposed participants carrying in-session exposure evidence.',+ scopeLockedReason: 'This metric filter already narrows to sessions carrying in-session exposure evidence.',+ },+ }+// 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> = {@@ -235,6 +265,10 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):const logic = experimentReplayTabLogic({ experiment })const {effectiveVariantKey,+ effectiveExposureScope,+ exposureInSessionUnavailableReason,+ inSessionExposure,+ playlistHeldForChecks,variantKeys,recordingsFilters,effectiveMetricUuids,@@ -249,6 +283,7 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):} = useValues(logic)const {setSelectedVariantKey,+ setExposureScope,setMetricSelected,setMetricFilterMode,loadSessionBucket,@@ -258,6 +293,9 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):scannerCrossSellClicked,} = useActions(logic)const scannerCrossSellEnabled = useFeatureFlag('VISION_ENTRYPOINT_EXPERIMENTS')+ // Which in-session copy applies, from the evidence kind the availability check resolved.+ const inSessionCopy =+ IN_SESSION_COPY[inSessionExposure ? (inSessionExposure.uses_stamped_fallback ? 'stamped' : 'event') : 'unknown']// One object feeds both the playlist below and the findMounted lookup, because the logic's// kea key is derived from these props: hand-duplicating them at the two sites would let the@@ -343,6 +381,28 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):...variantKeys.map((key) => ({ value: key, label: <VariantTag variantKey={key} /> })),]}/>+ <LemonSegmentedButton+ size="small"+ value={effectiveExposureScope}+ onChange={(value) => setExposureScope(value)}+ disabledReason={sessionBucketRequest !== null ? inSessionCopy.scopeLockedReason : undefined}+ options={[+ {+ value: 'in_session' as const,+ label: 'Exposed in session',+ tooltip: inSessionCopy.tooltip,+ disabledReason: exposureInSessionUnavailableReason ?? undefined,+ 'data-attr': 'experiment-recordings-exposure-scope-in-session',+ },+ {+ value: 'all_exposed' as const,+ label: 'All sessions',+ tooltip:+ 'Every session of exposed participants from their first exposure onward, including sessions without the exposure event.',+ 'data-attr': 'experiment-recordings-exposure-scope-all',+ },+ ]}+ />{metricOptions.length > 0 && (<DropdownMenu><DropdownMenuTrigger@@ -421,7 +481,9 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):<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>+ <span data-attr="experiment-recordings-population-caption">+ {effectiveExposureScope === 'in_session' ? inSessionCopy.caption : ALL_EXPOSED_CAPTION}+ </span>) : null) : !sessionBucketRequest ? (<span>{unappliedModeReason(metricFilterMode)}</span>@@ -440,14 +502,21 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):</div><ExperimentBehaviorComparison experiment={experiment} onWatchRecording={watchRecording} /><div className="SessionRecordingPlaylistHeightWrapper">- <SessionRecordingsPlaylist- {...playlistLogicProps}- analyticsSource="experiment-recordings-tab"- filters={recordingsFilters}- onFiltersChange={(filters) => playlistFiltersChanged(filters)}- onRecordingsLoaded={(recordings) => recordingsLoaded(recordings)}- onRecordingSelected={(recordingId) => recordingOpened(recordingId)}- />+ {playlistHeldForChecks ? (+ // A persisted in-session choice waits for the availability and linkability+ // checks: mounted now, the playlist would fire the heavy all-sessions listing+ // only to replace it when the scope confirms and the filters flip.+ <LemonSkeleton className="h-full" active />+ ) : (+ <SessionRecordingsPlaylist+ {...playlistLogicProps}+ analyticsSource="experiment-recordings-tab"+ filters={recordingsFilters}+ onFiltersChange={(filters) => playlistFiltersChanged(filters)}+ onRecordingsLoaded={(recordings) => recordingsLoaded(recordings)}+ onRecordingSelected={(recordingId) => recordingOpened(recordingId)}+ />+ )}</div></div>)diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.tsindex 34481daf0180..631b0ed76d5d 100644--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts@@ -11,6 +11,7 @@ import { initKeaTests } from '~/test/init'import { Experiment, FilterLogicalOperator, SessionRecordingSidebarTab } from '~/types'import {+ experimentsInSessionExposureRetrieve,experimentsSessionBucketsCreate,experimentsSessionContextsCreate,experimentsSessionEventDeltasCreate,@@ -26,6 +27,7 @@ jest.mock('lib/utils/product-intents', () => ({}))jest.mock('products/experiments/frontend/generated/api', () => ({+ experimentsInSessionExposureRetrieve: jest.fn(),experimentsSessionContextsCreate: jest.fn().mockResolvedValue({ results: [] }),experimentsSessionBucketsCreate: jest.fn(),experimentsSessionEventDeltasCreate: jest.fn(),@@ -127,6 +129,19 @@ const ALL_LINKABLE = {client_step: true,}+type InSessionExposureResponse = {+ available: boolean+ unavailable_reason: string | null+ uses_stamped_fallback: boolean+}++// The common case: in-session evidence is the exposure event itself, and the scope can answer.+const IN_SESSION_AVAILABLE: InSessionExposureResponse = {+ available: true,+ unavailable_reason: null,+ uses_stamped_fallback: false,+}+// Exposure narrowing lives in `experiment_exposure`, not the filter tree, so an unfiltered// tab carries an empty group.const EMPTY_FILTER_GROUP = {@@ -149,6 +164,8 @@ describe('experimentReplayTabLogic', () => {;(experimentsSessionEventDeltasCreate as jest.Mock).mockResolvedValue(DELTA_RESPONSE);(visionScannersList as jest.Mock).mockClear();(visionScannersList as jest.Mock).mockResolvedValue({ results: [] })+ ;(experimentsInSessionExposureRetrieve as jest.Mock).mockClear()+ ;(experimentsInSessionExposureRetrieve as jest.Mock).mockResolvedValue(IN_SESSION_AVAILABLE)seenTogetherSpy = jest.spyOn(api.propertyDefinitions, 'seenTogether')seenTogetherSpy.mockResolvedValue(ALL_LINKABLE)logic = experimentReplayTabLogic({ experiment: EXPERIMENT })@@ -166,7 +183,8 @@ describe('experimentReplayTabLogic', () => {})})- it('pins the person-scoped exposure filter to the run window', () => {+ it('pins the person-scoped exposure filter to the run window', async () => {+ await expectLogic(logic).toFinishAllListeners()const { recordingsFilters } = logic.values// RecordingsQuery defaults to "-3d", which would silently hide older exposed sessions,@@ -225,26 +243,110 @@ describe('experimentReplayTabLogic', () => {it('narrows the filter to the selected variant, keeping the run window', async () => {await expectLogic(logic, () => {logic.actions.setSelectedVariantKey('test')- }).toMatchValues({ selectedVariantKey: 'test' })+ }).toFinishAllListeners()const { recordingsFilters } = logic.valuesexpect(recordingsFilters.date_from).toBe('2026-01-01T00:00:00Z')expect(recordingsFilters.experiment_exposure).toEqual({ experiment_id: 42, variant: 'test' })})- 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()+ it('defaults to all sessions and narrows when in-session exposure is available', async () => {+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.recordingsFilters.experiment_exposure).toEqual({ experiment_id: 42 })++ logic.actions.setExposureScope('in_session')+ expect(logic.values.recordingsFilters.experiment_exposure).toEqual({ experiment_id: 42, in_session: true })+ })++ it('holds the in-session narrowing out of the query until the availability check lands', async () => {+ // Sent before the backend confirms availability, in_session can hit a refusal for an+ // experiment whose exposure can't be pinned to a session; exposure-only is the correct+ // superset until then.+ let resolveCheck!: (response: InSessionExposureResponse) => void+ ;(experimentsInSessionExposureRetrieve as jest.Mock).mockReturnValue(+ new Promise((resolve) => (resolveCheck = resolve))+ )+ const pending = experimentReplayTabLogic({ experiment: { ...EXPERIMENT, id: 51 } as Experiment })+ pending.mount()+ pending.actions.setExposureScope('in_session')++ expect(pending.values.recordingsFilters.experiment_exposure).toEqual({ experiment_id: 51 })+ // The playlist waits too: mounted now it would fire the all-sessions listing only to+ // replace it the moment the scope confirms.+ expect(pending.values.playlistHeldForChecks).toBe(true)++ resolveCheck(IN_SESSION_AVAILABLE)+ await expectLogic(pending).toFinishAllListeners()+ expect(pending.values.recordingsFilters.experiment_exposure).toEqual({ experiment_id: 51, in_session: true })+ expect(pending.values.playlistHeldForChecks).toBe(false)+ pending.unmount()+ })- 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('disables in-session and stays on all sessions when the backend reports it unavailable', async () => {+ // The backend refuses in_session for experiments whose exposure can't be pinned to a+ // session (activation, or a custom event with no session-linked stand-in, or a fallback+ // scan too large for the project). The tab mirrors that from the same check: the option is+ // disabled with the reason, and a picked or persisted choice falls back to all sessions+ // instead of drawing a backend 400.+ ;(experimentsInSessionExposureRetrieve as jest.Mock).mockResolvedValue({+ available: false,+ unavailable_reason:+ 'This experiment uses an activation event, so its exposure can span more than one session.',+ uses_stamped_fallback: false,+ })+ const unavailable = experimentReplayTabLogic({ experiment: { ...EXPERIMENT, id: 52 } as Experiment })+ unavailable.mount()+ await expectLogic(unavailable).toFinishAllListeners()+ unavailable.actions.setExposureScope('in_session')++ expect(unavailable.values.exposureInSessionUnavailableReason).not.toBeNull()+ expect(unavailable.values.effectiveExposureScope).toBe('all_exposed')+ expect(unavailable.values.recordingsFilters.experiment_exposure).toEqual({ experiment_id: 52 })+ unavailable.unmount()+ })++ it('falls back to all sessions when the availability check fails', async () => {+ // A failed check can't confirm the scope is safe to send, so the option isn't disabled (the+ // failure is transient) but the query still holds at the all-sessions superset, never+ // sending a narrowing the backend might refuse.+ ;(experimentsInSessionExposureRetrieve as jest.Mock).mockRejectedValue(new Error('network error'))+ const failed = experimentReplayTabLogic({ experiment: { ...EXPERIMENT, id: 54 } as Experiment })+ failed.mount()+ await expectLogic(failed).toFinishAllListeners()+ failed.actions.setExposureScope('in_session')++ expect(failed.values.exposureInSessionUnavailableReason).toBeNull()+ expect(failed.values.effectiveExposureScope).toBe('all_exposed')+ expect(failed.values.recordingsFilters.experiment_exposure).toEqual({ experiment_id: 54 })+ await expectLogic(failed).toFinishAllListeners()++ // Picking the scope again retries the check, so recovery doesn't wait for a remount.+ ;(experimentsInSessionExposureRetrieve as jest.Mock).mockResolvedValue(IN_SESSION_AVAILABLE)+ failed.actions.setExposureScope('in_session')+ await expectLogic(failed).toFinishAllListeners()+ expect(failed.values.effectiveExposureScope).toBe('in_session')+ expect(failed.values.recordingsFilters.experiment_exposure).toEqual({ experiment_id: 54, in_session: true })+ failed.unmount()+ })++ it('narrows but labels sessions as flag-active when the backend evidence is the stamped fallback', async () => {+ // Server-side default exposure: the event carries no session id, so the backend matches on+ // the stamped $feature/<key> property. The narrowing still applies (tighter than all+ // sessions), but the copy must say the flag was active, not that the exposure was captured.+ ;(experimentsInSessionExposureRetrieve as jest.Mock).mockResolvedValue({+ available: true,+ unavailable_reason: null,+ uses_stamped_fallback: true,+ })+ const fallback = experimentReplayTabLogic({ experiment: { ...EXPERIMENT, id: 43 } as Experiment })+ fallback.mount()+ await expectLogic(fallback).toFinishAllListeners()+ fallback.actions.setExposureScope('in_session')++ expect(fallback.values.inSessionExposure?.uses_stamped_fallback).toBe(true)+ expect(fallback.values.recordingsFilters.experiment_exposure).toEqual({ experiment_id: 43, in_session: true })+ expect(fallback.values.recordingsFilters.filter_group).toEqual(EMPTY_FILTER_GROUP)+ fallback.unmount()})it('ANDs each selected metric filter onto the exposure filter, and ignores unknown metric uuids', async () => {@@ -422,9 +524,10 @@ describe('experimentReplayTabLogic', () => {pending.unmount()})- it('reports the tab view once, after the linkability check has decided the tab is usable', async () => {- // Reported from `afterMount` instead, every view would carry the fail-open defaults, and an- // experiment whose exposure event can never match recordings would look like a healthy one.+ it('reports the tab view once, after the linkability and availability checks have both settled', async () => {+ // Reported from `afterMount` instead, every view would carry the fail-open defaults and+ // null scope fields, an experiment whose exposure event can never match recordings would+ // look like a healthy one, and empty-list sessions could not be split by exposure scope.const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)// Scoped to this experiment: the logic mounted in `beforeEach` reports its own view too.const tabViews = (): any[] =>@@ -435,11 +538,20 @@ describe('experimentReplayTabLogic', () => {let resolveSeenTogether!: (map: Record<string, boolean>) => voidseenTogetherSpy.mockReturnValue(new Promise((resolve) => (resolveSeenTogether = resolve)))+ let resolveAvailability!: (response: InSessionExposureResponse) => void+ ;(experimentsInSessionExposureRetrieve as jest.Mock).mockReturnValue(+ new Promise((resolve) => (resolveAvailability = resolve))+ )const pending = experimentReplayTabLogic({ experiment: { ...EXPERIMENT, id: 51 } as Experiment })pending.mount()expect(tabViews()).toHaveLength(0)+ // The linkability half settled, but the scope fields aren't known yet, so no report.resolveSeenTogether({ ...ALL_LINKABLE, purchase: false })+ await expectLogic(pending).toDispatchActions(['loadSeenTogetherSuccess', 'reportTabViewed'])+ expect(tabViews()).toHaveLength(0)++ resolveAvailability({ ...IN_SESSION_AVAILABLE, uses_stamped_fallback: true })await expectLogic(pending).toFinishAllListeners()expect(tabViews()).toHaveLength(1)@@ -448,6 +560,10 @@ describe('experimentReplayTabLogic', () => {variant_count: 2,metric_count: 2,linkable_metric_count: 1,+ exposure_scope: 'all_exposed',+ in_session_available: true,+ in_session_unavailable_reason: null,+ in_session_uses_stamped_fallback: true,})// The check is shared with the metrics tab and reloads when the experiment's metrics change,@@ -458,11 +574,35 @@ describe('experimentReplayTabLogic', () => {pending.unmount()})+ it('flushes the tab view at unmount when the availability check has not settled', async () => {+ // A bounce before the availability round trip completes must still count as a view; the+ // verdict fields stay null, meaning unknown rather than unavailable.+ const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)+ const tabViews = (): any[] =>+ captureSpy.mock.calls.filter(+ ([event, properties]) =>+ event === 'experiment recordings tab viewed' && (properties as any)?.experiment_id === 55+ )+ ;(experimentsInSessionExposureRetrieve as jest.Mock).mockReturnValue(new Promise(() => {}))+ const bounced = experimentReplayTabLogic({ experiment: { ...EXPERIMENT, id: 55 } as Experiment })+ bounced.mount()+ await expectLogic(bounced).toDispatchActions(['loadSeenTogetherSuccess'])+ expect(tabViews()).toHaveLength(0)++ bounced.unmount()+ expect(tabViews()).toHaveLength(1)+ expect(tabViews()[0][1]).toMatchObject({+ experiment_id: 55,+ in_session_available: null,+ in_session_uses_stamped_fallback: null,+ })+ })+it('reports the tab view when the linkability check had already failed before the tab opened', async () => {// The shared check can settle as a failure while the user is still on the metrics tab.- // No load action follows once this tab mounts, so the view must be reported from- // `afterMount` — with the fail-open defaults, the same posture as a failure that lands- // while the tab is open.+ // No linkability load action follows once this tab mounts, so the availability check's+ // completion is what sends the report, with the fail-open defaults, the same posture as+ // a failure that lands while the tab is open.const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)const tabViews = (): any[] =>captureSpy.mock.calls.filter(@@ -891,6 +1031,7 @@ describe('experimentReplayTabLogic', () => {it.each([['the variant facet moves', (): void => logic.actions.setSelectedVariantKey('control')],+ ['the exposure scope moves', (): void => logic.actions.setExposureScope('in_session')],['a metric is picked', (): void => logic.actions.setMetricSelected('metric-purchase', true)],['the shelf is closed', (): void => logic.actions.toggleBehaviorComparison()],])('drops the selected card when %s', async (_name: string, moveFacet: () => void) => {diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.tsindex c517f55fdaf8..79dd2e893fb1 100644--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts@@ -49,12 +49,14 @@ import {} from '~/types'import {+ experimentsInSessionExposureRetrieve,experimentsSessionBucketsCreate,experimentsSessionContextsCreate,experimentsSessionEventDeltasCreate,} from 'products/experiments/frontend/generated/api'import { ExperimentWatchCardKindEnumApi } from 'products/experiments/frontend/generated/api.schemas'import type {+ ExperimentInSessionExposureApi,ExperimentSessionBucketResponseApi,ExperimentSessionBucketEnumApi,ExperimentSessionEventDeltaResponseApi,@@ -115,6 +117,14 @@ export interface ExperimentReplayMetricOption {*/export type ExperimentReplayMetricFilterMode = 'fired_all' | 'fired_any' | 'no_metric_activity' | 'funnel_dropoff'+/**+ * Which of an exposed participant's sessions the list shows: every session from first exposure+ * onward (the default, matching the population the analysis counts), or only the ones carrying+ * in-session exposure evidence, for opting out of the long tail of an exposed person's sessions+ * that never touch the feature under test.+ */+export type ExperimentReplayExposureScope = 'in_session' | 'all_exposed'+/** What the tab asks the bucket endpoint for, and the spec a loaded response belongs to. */export interface ExperimentSessionBucketRequest {bucket: ExperimentSessionBucketEnumApi@@ -182,14 +192,20 @@ export interface experimentReplayTabLogicValues {behaviorComparisonAvailable: booleanbehaviorComparisonOpen: booleanbucketSessionIds: string[] | undefined+ effectiveExposureScope: ExperimentReplayExposureScopeeffectiveMetricUuids: string[]effectiveVariantKey: string | null+ exposureInSessionUnavailableReason: string | null+ exposureScope: ExperimentReplayExposureScope+ inSessionExposure: ExperimentInSessionExposureApi | null+ inSessionExposureLoading: booleanlinkedScanners: LinkedScanner[]linkedScannersLoading: booleanloadedRecordings: ExperimentReplayRecording[]loadedRecordingsById: Map<string, ExperimentReplayRecording>metricFilterMode: ExperimentReplayMetricFilterModemetricOptions: ExperimentReplayMetricOption[]+ playlistHeldForChecks: booleanrecordingsFilters: RecordingUniversalFiltersselectedMetricUuids: string[]selectedVariantKey: string | null@@ -201,6 +217,7 @@ export interface experimentReplayTabLogicValues {sessionEventDeltas: ExperimentSessionEventDeltaResponseApi | nullsessionEventDeltasError: string | nullsessionEventDeltasLoading: boolean+ tabViewContext: ExperimentRecordingsTabContextvariantKeys: string[]}@@ -293,6 +310,21 @@ export interface experimentReplayTabLogicActions {payload?: anyseenTogetherMap: Record<string, boolean>} // viewRecordingsLinkabilityLogic+ loadInSessionExposure: (_?: unknown) => unknown+ loadInSessionExposureFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadInSessionExposureSuccess: (+ inSessionExposure: ExperimentInSessionExposureApi | null,+ payload?: unknown+ ) => {+ inSessionExposure: ExperimentInSessionExposureApi | null+ payload?: unknown+ }loadLinkedScanners: (_?: unknown) => unknownloadLinkedScannersFailure: (error: string,@@ -375,6 +407,9 @@ export interface experimentReplayTabLogicActions {selectWatchCard: (card: ExperimentWatchCardApi | null) => {card: ExperimentWatchCardApi | null}+ setExposureScope: (scope: ExperimentReplayExposureScope) => {+ scope: ExperimentReplayExposureScope+ }setMetricFilterMode: (mode: ExperimentReplayMetricFilterMode) => {mode: ExperimentReplayMetricFilterMode}@@ -411,6 +446,23 @@ export interface experimentReplayTabLogicMeta {variantKeys: (arg: any) => string[]behaviorComparisonAvailable: (featureFlags: FeatureFlagsSet) => booleaneffectiveVariantKey: (selectedVariantKey: string | null, variantKeys: string[]) => string | null+ exposureInSessionUnavailableReason: (inSessionExposure: ExperimentInSessionExposureApi | null) => string | null+ effectiveExposureScope: (+ exposureScope: ExperimentReplayExposureScope,+ inSessionExposure: ExperimentInSessionExposureApi | null+ ) => ExperimentReplayExposureScope+ playlistHeldForChecks: (+ exposureScope: ExperimentReplayExposureScope,+ inSessionExposureLoading: boolean,+ linkabilityLoaded: boolean,+ seenTogetherMapLoading: boolean+ ) => boolean+ tabViewContext: (+ variantKeys: string[],+ metricOptions: ExperimentReplayMetricOption[],+ effectiveExposureScope: ExperimentReplayExposureScope,+ inSessionExposure: ExperimentInSessionExposureApi | null+ ) => ExperimentRecordingsTabContextmetricOptions: (linkabilityLoaded: boolean,unlinkableEventNames: Set<string>,@@ -434,6 +486,7 @@ export interface experimentReplayTabLogicMeta {) => string[] | undefinedrecordingsFilters: (effectiveVariantKey: string | null,+ effectiveExposureScope: ExperimentReplayExposureScope,effectiveMetricUuids: string[],metricOptions: ExperimentReplayMetricOption[],unlinkableEventNames: Set<string>,@@ -496,6 +549,7 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([})),actions({setSelectedVariantKey: (variantKey: string | null) => ({ variantKey }),+ setExposureScope: (scope: ExperimentReplayExposureScope) => ({ scope }),setMetricSelected: (metricUuid: string, selected: boolean) => ({ metricUuid, selected }),setMetricFilterMode: (mode: ExperimentReplayMetricFilterMode) => ({ mode }),playlistFiltersChanged: (filters: RecordingUniversalFilters) => ({ filters }),@@ -622,6 +676,33 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([},},],+ inSessionExposure: [+ null as ExperimentInSessionExposureApi | null,+ {+ // Whether the in-session scope can answer for this experiment, and whether its+ // evidence is the stamped-property fallback. Resolved server-side through the same+ // seam the recordings query refuses on, so the control disables exactly what a query+ // would be refused for, and the caption can tell "the exposure was captured here"+ // from "the flag was active here". Fail-soft to null, read as "not yet available"+ // by the selectors below, so a failed check never sends a narrowing the backend+ // would reject.+ loadInSessionExposure: async (_: unknown = null, breakpoint) => {+ let response: ExperimentInSessionExposureApi | null+ try {+ response = await experimentsInSessionExposureRetrieve(+ String(values.currentProjectId),+ Number(props.experiment.id)+ )+ } catch {+ response = null+ }+ // Outside the try, so a superseding dispatch or an unmount cancels this load+ // instead of the catch turning the cancellation into a success(null).+ breakpoint()+ return response+ },+ },+ ],})),reducers({// null = "All" (every exposed session, regardless of variant). Persisted (keyed per@@ -639,6 +720,16 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([selectWatchCard: (state: string | null, { card }) => (card ? card.variant : state),},],+ // Persisted like the variant facet. The default shows exposed persons' whole journey+ // from first exposure, matching the population the analysis counts; 'in_session'+ // narrows out the long tail of their sessions that never touch the feature under test.+ exposureScope: [+ 'all_exposed' as ExperimentReplayExposureScope,+ { persist: true },+ {+ setExposureScope: (_, { scope }) => scope,+ },+ ],// Empty = no metric filter. Every selected metric narrows the playlist further (AND) —// OR across metrics is inexpressible, since the recordings query carries a single// operator shared with the exposure filter. Persisted for the same reason as the@@ -723,6 +814,7 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([// trigger and the caption.setMetricFilterMode: () => null,setSelectedVariantKey: () => null,+ setExposureScope: () => null,setMetricSelected: () => null,// Closing the shelf takes away the only way to deselect, so the list would stay// narrowed with nothing on screen saying why.@@ -749,6 +841,64 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([(selectedVariantKey: string | null, variantKeys: string[]): string | null =>selectedVariantKey !== null && variantKeys.includes(selectedVariantKey) ? selectedVariantKey : null,],+ // Why the in-session scope can't answer for this experiment, from the server-side check:+ // the single seam the recordings query refuses on, so the option is disabled for exactly+ // the experiments a query would be refused for (activation, or a custom event with no+ // stand-in, or a fallback scan too large for this project). Null while the check loads or+ // fails, so the option isn't disabled on a transient error; the query still stays on all+ // sessions until the check confirms availability (see effectiveExposureScope).+ exposureInSessionUnavailableReason: [+ (s) => [s.inSessionExposure],+ (inSessionExposure: ExperimentInSessionExposureApi | null): string | null =>+ inSessionExposure?.unavailable_reason ?? null,+ ],+ effectiveExposureScope: [+ (s) => [s.exposureScope, s.inSessionExposure],+ (+ exposureScope: ExperimentReplayExposureScope,+ inSessionExposure: ExperimentInSessionExposureApi | null+ ): ExperimentReplayExposureScope =>+ // Narrow only on the server's confirmed-available verdict. While the check is in+ // flight or if it failed (null), or when it reports the scope unavailable, hold at+ // the all-sessions superset so no narrowing the backend would refuse reaches the+ // query. The query gate and the caption both read this, so they stay in step.+ exposureScope === 'in_session' && inSessionExposure?.available ? 'in_session' : 'all_exposed',+ ],+ // Holds the playlist while a persisted in-session choice waits on the checks: mounted+ // immediately, it would fire the heavy all-sessions listing only to discard it seconds+ // later when the scope confirms and the filters flip to in_session.+ playlistHeldForChecks: [+ (s) => [s.exposureScope, s.inSessionExposureLoading, s.linkabilityLoaded, s.seenTogetherMapLoading],+ (+ exposureScope: ExperimentReplayExposureScope,+ inSessionExposureLoading: boolean,+ linkabilityLoaded: boolean,+ seenTogetherMapLoading: boolean+ ): boolean =>+ exposureScope === 'in_session' &&+ (inSessionExposureLoading || (!linkabilityLoaded && seenTogetherMapLoading)),+ ],+ // The `experiment recordings tab viewed` payload, in a selector so the settled-checks+ // report and the beforeUnmount flush send the same shape.+ tabViewContext: [+ (s) => [s.variantKeys, s.metricOptions, s.effectiveExposureScope, s.inSessionExposure],+ (+ variantKeys: string[],+ metricOptions: ExperimentReplayMetricOption[],+ effectiveExposureScope: ExperimentReplayExposureScope,+ inSessionExposure: ExperimentInSessionExposureApi | null+ ): ExperimentRecordingsTabContext => ({+ variant_count: variantKeys.length,+ metric_count: metricOptions.length,+ linkable_metric_count: metricOptions.filter((option) => !option.unlinkable).length,+ // The effective scope, so an in-session choice held back by an unavailable verdict+ // records the population the list actually showed.+ exposure_scope: effectiveExposureScope,+ in_session_available: inSessionExposure?.available ?? null,+ in_session_unavailable_reason: inSessionExposure?.unavailable_reason ?? null,+ in_session_uses_stamped_fallback: inSessionExposure?.uses_stamped_fallback ?? null,+ }),+ ],// Every uuid-carrying metric: inline primary + secondary, then saved/shared metrics (their// definition lives in `saved_metrics[].query`) — the same set the backend// `resolve_metric_events` scans, deduped by uuid so a shared metric linked more than once@@ -900,6 +1050,7 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([recordingsFilters: [(s) => [s.effectiveVariantKey,+ s.effectiveExposureScope,s.effectiveMetricUuids,s.metricOptions,s.unlinkableEventNames,@@ -910,6 +1061,7 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([],(effectiveVariantKey: string | null,+ effectiveExposureScope: ExperimentReplayExposureScope,effectiveMetricUuids: string[],metricOptions: ExperimentReplayMetricOption[],unlinkableEventNames: Set<string>,@@ -970,14 +1122,23 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([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`.+ // counts), so it works even when exposure events are fired server-side.+ // Deliberately not an event filter in `filter_group`. The in-session+ // narrowing waits for the linkability check like the metric filters do+ // (exposure-only is the correct superset until it lands), and stays out of+ // bucket and card queries, whose session sets carry in-session exposure+ // evidence by construction.experiment_exposure:typeof experiment.id === 'number'? {experiment_id: experiment.id,...(effectiveVariantKey !== null ? { variant: effectiveVariantKey } : {}),+ ...(effectiveExposureScope === 'in_session' &&+ !seenTogetherMapLoading &&+ bucketSessionIds === undefined &&+ selectedWatchCard === null+ ? { in_session: true }+ : {}),}: undefined,filter_group: {@@ -1009,6 +1170,14 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([actions.loadSessionBucket()}},+ // A failed availability check leaves the in-session option enabled but inert, because the+ // scope holds at all sessions until a verdict confirms. Retry on the pick, so recovery+ // doesn't wait for a remount.+ setExposureScope: ({ scope }) => {+ if (scope === 'in_session' && values.inSessionExposure === null && !values.inSessionExposureLoading) {+ actions.loadInSessionExposure()+ }+ },// The shared playlist renders its own "Showing N selected recordings · Show all" control// whenever session_ids are set. Clearing it there is the same intent as leaving the// bucket, so follow it instead of pushing the ids straight back. Only when the tab has@@ -1089,6 +1258,7 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([)actions.reportExperimentRecordingOpened(props.experiment.id, {variant: values.effectiveVariantKey,+ exposure_scope: values.effectiveExposureScope,metric_filter_mode: values.metricFilterMode,selected_metric_count: values.effectiveMetricUuids.length,is_bucketed: values.bucketSessionIds !== undefined,@@ -1096,13 +1266,18 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([})},// Both outcomes of the linkability check report the view, since a failed check leaves the- // tab running on its fail-open defaults rather than leaving it unusable.+ // tab running on its fail-open defaults rather than leaving it unusable. The availability+ // check reports too (it fail-softs to null, so success is its only outcome), and the gates+ // in reportTabViewed let whichever check settles last send the report.loadSeenTogetherSuccess: () => {actions.reportTabViewed()},loadSeenTogetherFailure: () => {actions.reportTabViewed()},+ loadInSessionExposureSuccess: () => {+ actions.reportTabViewed()+ },reportTabViewed: () => {// The linkability logic is shared with the metrics tab's "View recordings" buttons and// reloads when the experiment's metrics change, so its success can arrive more than once@@ -1110,12 +1285,18 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([if (cache.reportedTabView) {return}+ // Hold the report until both checks settle: linkable_metric_count needs the linkability+ // map, and the scope fields need the availability verdict. Each check's completion+ // re-dispatches this action, so the last one to settle passes both gates. A visit that+ // ends before then is flushed from beforeUnmount instead.+ if (!values.linkabilityLoaded && values.seenTogetherMapLoading) {+ return+ }+ if (values.inSessionExposureLoading) {+ return+ }cache.reportedTabView = true- actions.reportExperimentRecordingsTabViewed(props.experiment.id, {- variant_count: values.variantKeys.length,- metric_count: values.metricOptions.length,- linkable_metric_count: values.metricOptions.filter((option) => !option.unlinkable).length,- })+ actions.reportExperimentRecordingsTabViewed(props.experiment.id, values.tabViewContext)},scannerCrossSellClicked: () => {void addProductIntentForCrossSell({@@ -1153,6 +1334,10 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([})),afterMount(({ values, actions }) => {actions.setDefaultTab(SessionRecordingSidebarTab.OVERVIEW)+ // Resolve whether the in-session scope can answer before the viewer picks it, so the option+ // is disabled (not left to fail as a query error) when it can't, and the caption knows+ // whether evidence is the stamped-property fallback. A Postgres-only read on the backend.+ actions.loadInSessionExposure()// Only the vision entry point renders the watching-scanners card, so don't spend the lookup// for everyone else who opens this tab without the flag.if (values.featureFlags[FEATURE_FLAGS.VISION_ENTRYPOINT_EXPERIMENTS]) {@@ -1164,14 +1349,10 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([actions.loadSessionBucket()}- // The linkability check is shared with the metrics tab, so it can already have settled —- // loaded, or failed with no reload coming — before this tab is opened, in which case no- // load action follows to report the view off. A check started by this mount is already- // loading here, so it reports from the load listeners instead; a prior failure reports- // the fail-open defaults, the same posture as a failure that lands while the tab is open.- if (values.linkabilityLoaded || !values.seenTogetherMapLoading) {- actions.reportTabViewed()- }+ // No reportTabViewed call here: the availability check dispatched above settles after+ // mount and its success listener sends the report once the linkability check (which can+ // settle before mount, or fail) has too. beforeUnmount flushes the report for visits+ // that end before the checks settle.// Opening the tab is a session-replay cross-sell from experiments.void addProductIntentForCrossSell({@@ -1180,9 +1361,18 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([intent_context: ProductIntentContext.EXPERIMENT_VIEW_RECORDINGS,})}),- // The sidebar singleton normally unmounts alongside this logic and resets itself; this covers the- // case where another player keeps it mounted, so the experiment default doesn't leak to it.- beforeUnmount(({ actions }) => {+ beforeUnmount(({ actions, values, cache, props }) => {+ // A view that ends before the checks settle still counts, with null verdict fields meaning+ // the check hadn't landed. Sent through the connected action directly: this logic's own+ // listeners no longer run during beforeUnmount, while connected logics are still mounted.+ // The dedup cache keeps an already-sent report from repeating.+ if (!cache.reportedTabView) {+ cache.reportedTabView = true+ actions.reportExperimentRecordingsTabViewed(props.experiment.id, values.tabViewContext)+ }+ // The sidebar singleton normally unmounts alongside this logic and resets itself; this+ // covers the case where another player keeps it mounted, so the experiment default+ // doesn't leak to it.actions.setDefaultTab(SessionRecordingSidebarTab.INSPECTOR)}),])diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex b6a0a7d63fef..a05401b1188c 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -478,6 +478,10 @@ class QueryTags(BaseModel):# DEPRECATED: alias of experiment_exposures_path, kept so external tooling keeps working.experiment_execution_path: Optional[str] = None # "direct_scan" or "precomputed"experiment_exposures_path: Optional[str] = None # "direct_scan" or "precomputed"+ # Set on a recordings-list read that narrows the exposed population to sessions carrying+ # in-session exposure evidence, which adds a live events scan and a GLOBAL IN set on top of the+ # population read. Separates that heavier read from a plain exposure listing in the query log.+ experiment_exposures_in_session: Optional[bool] = Noneexperiment_metric_events_path: Optional[str] = None # "direct_scan", "precomputed", or "not_applicable"experiment_query_surface: Optional[str] = None # "metric", "exposures_timeseries", "actors", "precompute_build"experiment_precompute_table: Optional[str] = None # on precompute_build rows: "exposures" or "metric_events"diff --git a/posthog/schema.py b/posthog/schema.pyindex d4742540b48d..ca9144879dec 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -6733,6 +6733,16 @@ class RecordingsQueryExperimentExposureFilter(BaseModel):"Experiment whose exposed persons' sessions to show. Must belong to the environment the query runs in."),)+ in_session: bool | None = Field(+ default=None,+ description=(+ "Only sessions carrying in-session exposure evidence: an event matching the"+ " experiment's exposure criteria inside the session (with the stamped"+ " `$feature/<flag_key>` property standing in when the exposure event was"+ " never captured with a session id). Defaults to all exposed persons'"+ " sessions from first exposure onward."+ ),+ )variant: str | None = Field(default=None,description=("Narrow to persons exposed to this variant. Defaults to all of the experiment's variants."),diff --git a/posthog/session_recordings/queries/session_recording_list_from_query.py b/posthog/session_recordings/queries/session_recording_list_from_query.pyindex 332b870f378a..97b4baeba231 100644--- a/posthog/session_recordings/queries/session_recording_list_from_query.py+++ b/posthog/session_recordings/queries/session_recording_list_from_query.py@@ -20,6 +20,7 @@ from posthog.hogql.parser import parse_selectfrom posthog.hogql.property import property_to_exprfrom posthog.clickhouse.client.connection import ClickHouseUser+from posthog.clickhouse.query_tagging import tags_contextfrom posthog.exceptions_capture import capture_exceptionfrom posthog.hogql_queries.paginators import HogQLCursorPaginator, HogQLHasMorePaginatorfrom posthog.models import Team, User@@ -238,7 +239,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):self._resolve_experiment_exposure()query = self.get_query()- settings_args: dict[str, int] = {}+ settings_args: dict[str, int | str] = {}if self._max_execution_time is not None:settings_args["max_execution_time"] = self._max_execution_timelinkage = self._experiment_exposure_linkage@@ -249,17 +250,27 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):# with its status, machine code, and narrow-your-filters guidance, is honest for# every cause.settings_args["max_memory_usage"] = linkage.live_scan_max_memory_bytes+ in_session_narrowed = linkage is not None and linkage.session_exposure is not None+ if in_session_narrowed:+ # Under a "break" timeout profile a timed-out evidence subquery would return a partial+ # session set, silently listing fewer in-session recordings. A partial result is worse+ # than an error here, so the execution-time kill must throw.+ settings_args["timeout_overflow_mode"] = "throw"with tracer.start_as_current_span("SessionRecordingListFromQuery.paginate"):- paginated_response = self._paginator.execute_hogql_query(- # TODO I guess the paginator needs to know how to handle union queries or all callers are supposed to collapse them or .... 🤷- query=cast(ast.SelectQuery, query),- team=self._team,- user=self._user,- query_type="SessionRecordingListQuery",- modifiers=self._hogql_query_modifiers,- settings=HogQLGlobalSettings(**settings_args),- )+ # Tagged around the listing execution only, so the tag marks exactly the queries that+ # carry the evidence scan and its GLOBAL IN set: the precompute builds that run during+ # linkage resolution and the blocklist probe below stay untagged.+ with tags_context(**({"experiment_exposures_in_session": True} if in_session_narrowed else {})):+ paginated_response = self._paginator.execute_hogql_query(+ # TODO I guess the paginator needs to know how to handle union queries or all callers are supposed to collapse them or .... 🤷+ query=cast(ast.SelectQuery, query),+ team=self._team,+ user=self._user,+ query_type="SessionRecordingListQuery",+ modifiers=self._hogql_query_modifiers,+ settings=HogQLGlobalSettings(**settings_args),+ )# After the results are in, check whether the exclusion blocklist hit its row cap,# because past the cap the query silently under-excludes. No-op without negated entities, and@@ -354,6 +365,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):self._team,experiment_id=self._query.experiment_exposure.experiment_id,variant=self._query.experiment_exposure.variant,+ in_session=bool(self._query.experiment_exposure.in_session),)if self._experiment_exposure_linkage.population_filters_test_accounts:# The exposure population already applies the team's test-account filters on the@@ -709,6 +721,44 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):if test_account_remaining:exprs.append(property_to_expr(test_account_remaining, team=self._team, scope="replay"))+ # The in-session narrowing composes with the exposure join rather than replacing it: the+ # join still decides who counts as exposed and bounds sessions to first exposure, this+ # predicate additionally requires the exposure evidence inside the session. GLOBAL for+ # the same reason as the join: the subquery scans events over the experiment window,+ # and without it every shard would re-evaluate that scan independently.+ if self._query.experiment_exposure is not None and self._query.experiment_exposure.in_session:+ # 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 exposed_session_ids_select # noqa: PLC0415++ self._resolve_experiment_exposure()+ assert self._experiment_exposure_linkage is not None+ # Evidence lives inside the sessions being listed, so scanning outside the query's own+ # range (with the ±1 day session buffer the console-logs subquery also uses) could only+ # nominate sessions the date predicates already exclude. Skipped when pinned session_ids+ # bypass the date window above: the listing then admits sessions from outside the range,+ # so their evidence must stay in scope too.+ clamp = not bypass_date_window+ exprs.append(+ ast.CompareOperation(+ op=ast.CompareOperationOp.GlobalIn,+ left=ast.Field(chain=["s", "session_id"]),+ right=exposed_session_ids_select(+ self._experiment_exposure_linkage,+ clamp_date_from=(+ self.query_date_range.date_from() - timedelta(days=1)+ if clamp and self._query.date_from+ else None+ ),+ clamp_date_to=(+ self.query_date_range.date_to() + timedelta(days=1)+ if clamp and self._query.date_to+ else None+ ),+ ),+ )+ )+return ast.And(exprs=exprs)@tracer.start_as_current_span("SessionRecordingListFromQuery._having_predicates")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.pyindex 46ec3f94d691..ebb14857bd49 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@@ -17,7 +17,7 @@ from posthog.clickhouse.client import sync_executefrom posthog.constants import AvailableFeaturefrom posthog.exceptions import ClickHouseQueryMemoryLimitExceededfrom posthog.hogql_queries.paginators import HogQLCursorPaginator-from posthog.models import User+from posthog.models import EventProperty, Userfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.utils import generate_random_token_personal, hash_key_value@@ -42,7 +42,10 @@ from products.cohorts.backend.models.cohort import Cohort# Importing the facade at module scope also keeps its transitive pydantic.v1 import outside the# class's frozen time: freezegun's FakeDate breaks pydantic.v1's metaclass construction, and the# runner otherwise defers this import to the first test that resolves a linkage.-from products.experiments.backend.facade.replay import ACTIVATION_LIVE_SCAN_MAX_MEMORY_BYTES+from products.experiments.backend.facade.replay import (+ ACTIVATION_LIVE_SCAN_MAX_MEMORY_BYTES,+ IN_SESSION_EVIDENCE_SCAN_MAX_MEMORY_BYTES,+)from products.experiments.backend.hogql_queries.experiment_exposure_query_builder import ExposureQueryBuilderfrom products.experiments.backend.models.experiment import Experimentfrom products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig@@ -440,6 +443,248 @@ class TestSessionRecordingsListByExperimentExposure(ClickhouseTestMixin, APIBase["session-after-custom"],)+ def test_in_session_narrows_to_sessions_containing_the_exposure_event(self) -> None:+ experiment = self._create_experiment()+ # Marks the exposure event as session-linkable, so the narrowing reads the event itself+ # rather than the stamped-property fallback.+ EventProperty.objects.create(team=self.team, event="$feature_flag_called", property="$session_id")+ create_person(team=self.team, distinct_ids=["exposed-user"])+ exposure_time = BASE_TIME + timedelta(hours=2)+ self._create_exposure_event(+ "exposed-user",+ exposure_time,+ "test",+ properties={"$session_id": "session-with-exposure"},+ )+ flush_persons_and_events()++ self._produce_recording(+ "exposed-user", "session-with-exposure", exposure_time, exposure_time + timedelta(minutes=10)+ )+ self._produce_recording(+ "exposed-user",+ "session-without-exposure",+ exposure_time + timedelta(hours=1),+ exposure_time + timedelta(hours=1, minutes=10),+ )++ self._assert_query_matches_session_ids(+ {"experiment_exposure": {"experiment_id": experiment.id}},+ ["session-with-exposure", "session-without-exposure"],+ )+ self._assert_query_matches_session_ids(+ {"experiment_exposure": {"experiment_id": experiment.id, "in_session": True}},+ ["session-with-exposure"],+ )++ def test_in_session_evidence_is_narrowed_to_the_requested_variant(self) -> None:+ experiment = self._create_experiment(exposure_criteria={"multiple_variant_handling": "first_seen"})+ EventProperty.objects.create(team=self.team, event="$feature_flag_called", property="$session_id")+ create_person(team=self.team, distinct_ids=["rebucketed-user"])+ exposure_time = BASE_TIME + timedelta(hours=2)+ self._create_exposure_event(+ "rebucketed-user", exposure_time, "test", properties={"$session_id": "session-test-evidence"}+ )+ # The same person later reads the flag as control; first-seen handling keeps them+ # attributed to test, so only the evidence narrowing can tell the two sessions apart.+ self._create_exposure_event(+ "rebucketed-user",+ exposure_time + timedelta(hours=1),+ "control",+ properties={"$session_id": "session-control-evidence"},+ )+ flush_persons_and_events()++ self._produce_recording(+ "rebucketed-user", "session-test-evidence", exposure_time, exposure_time + timedelta(minutes=10)+ )+ self._produce_recording(+ "rebucketed-user",+ "session-control-evidence",+ exposure_time + timedelta(hours=1),+ exposure_time + timedelta(hours=1, minutes=10),+ )++ self._assert_query_matches_session_ids(+ {"experiment_exposure": {"experiment_id": experiment.id, "variant": "test", "in_session": True}},+ ["session-test-evidence"],+ )++ def test_in_session_reads_the_stamped_flag_property_when_the_exposure_event_was_never_session_linked(self) -> None:+ experiment = self._create_experiment()+ create_person(team=self.team, distinct_ids=["backend-exposed-user"])+ exposure_time = BASE_TIME + timedelta(hours=2)+ # Server-fired exposure: no $session_id on the event, and no EventProperty row marks the+ # exposure event as ever carrying one, so the stamped flag property stands in as evidence.+ self._create_exposure_event("backend-exposed-user", exposure_time, "test")+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="backend-exposed-user",+ timestamp=exposure_time + timedelta(minutes=5),+ properties={"$session_id": "session-with-stamp", "$feature/recordings-linkage-flag": "test"},+ )+ flush_persons_and_events()++ self._produce_recording(+ "backend-exposed-user", "session-with-stamp", exposure_time, exposure_time + timedelta(minutes=10)+ )+ self._produce_recording(+ "backend-exposed-user",+ "session-without-stamp",+ exposure_time + timedelta(hours=1),+ exposure_time + timedelta(hours=1, minutes=10),+ )++ self._assert_query_matches_session_ids(+ {"experiment_exposure": {"experiment_id": experiment.id, "in_session": True}},+ ["session-with-stamp"],+ )++ def test_in_session_with_a_never_session_linked_custom_exposure_refuses(self) -> None:+ experiment = self._create_experiment(+ exposure_criteria={+ "exposure_config": {+ "kind": "ExperimentEventExposureConfig",+ "event": "backend_exposure",+ "properties": [],+ }+ }+ )++ with self.assertRaises(ValidationError):+ filter_recordings_by(+ team=self.team,+ recordings_filter={"experiment_exposure": {"experiment_id": experiment.id, "in_session": True}},+ user=self.user,+ )++ def test_in_session_with_activation_criteria_refuses(self) -> None:+ # Activation mode counts exposure from the activation event, which lands at or after the+ # flag call and often in a later session, while the in-session evidence matches the flag+ # event. The two can't agree inside one session, so in_session is refused rather than+ # listing the wrong session or nothing.+ experiment = self._create_experiment(+ exposure_criteria={+ "activation_config": {+ "kind": "ExperimentEventExposureConfig",+ "event": "task_completed",+ "properties": [],+ }+ }+ )++ with self.assertRaises(ValidationError):+ filter_recordings_by(+ team=self.team,+ recordings_filter={"experiment_exposure": {"experiment_id": experiment.id, "in_session": True}},+ user=self.user,+ )++ def test_in_session_stamped_fallback_is_refused_on_precomputing_teams(self) -> None:+ # The stamped-property fallback scan has no event name to prune on, so it reads every event+ # in the window. On teams where precomputation marks full-window live scans as a real cost,+ # that scan times out rather than answering, so in_session over the fallback is refused the+ # same way the population scan refuses, instead of being left to time out. The non-+ # precomputing case is covered by test_in_session_reads_the_stamped_flag_property_*.+ self._enable_precomputation()+ experiment = self._create_experiment()+ # No EventProperty row marks the default event as session-linked, so evidence falls back to+ # the stamped flag property.+ create_person(team=self.team, distinct_ids=["backend-exposed-user"])+ self._create_exposure_event("backend-exposed-user", BASE_TIME + timedelta(hours=2), "test")+ flush_persons_and_events()++ with self.assertRaises(ValidationError):+ filter_recordings_by(+ team=self.team,+ recordings_filter={"experiment_exposure": {"experiment_id": experiment.id, "in_session": True}},+ user=self.user,+ )++ def test_in_session_evidence_scan_is_memory_bounded_and_times_out_by_throwing(self) -> None:+ # The evidence scan and its GLOBAL IN set always run live, so the listing query must carry+ # the ceiling, and its timeout must throw rather than return a partial session set that+ # silently drops in-session recordings.+ experiment = self._create_experiment()+ EventProperty.objects.create(team=self.team, event="$feature_flag_called", property="$session_id")++ executed_settings: list[HogQLGlobalSettings] = []++ def record_settings_and_hit_the_ceiling(*args: object, **kwargs: object) -> None:+ executed_settings.append(cast(HogQLGlobalSettings, kwargs["settings"]))+ raise ClickHouseQueryMemoryLimitExceeded()++ with patch.object(HogQLCursorPaginator, "execute_hogql_query", side_effect=record_settings_and_hit_the_ceiling):+ with self.assertRaises(ClickHouseQueryMemoryLimitExceeded):+ filter_recordings_by(+ team=self.team,+ recordings_filter={"experiment_exposure": {"experiment_id": experiment.id, "in_session": True}},+ user=self.user,+ )+ self.assertEqual(executed_settings[0].max_memory_usage, IN_SESSION_EVIDENCE_SCAN_MAX_MEMORY_BYTES)+ self.assertEqual(executed_settings[0].timeout_overflow_mode, "throw")++ def test_in_session_narrowing_survives_a_query_date_range_covering_the_evidence(self) -> None:+ # The evidence scan clamps to the query's own date range (plus a session-length buffer). A+ # range covering the exposure must keep the in-session session, proving the clamp narrows+ # the scan without dropping evidence the listed window still holds.+ experiment = self._create_experiment()+ EventProperty.objects.create(team=self.team, event="$feature_flag_called", property="$session_id")+ create_person(team=self.team, distinct_ids=["exposed-user"])+ exposure_time = BASE_TIME + timedelta(hours=2)+ self._create_exposure_event(+ "exposed-user", exposure_time, "test", properties={"$session_id": "session-with-exposure"}+ )+ flush_persons_and_events()+ self._produce_recording(+ "exposed-user", "session-with-exposure", exposure_time, exposure_time + timedelta(minutes=10)+ )++ self._assert_query_matches_session_ids(+ {+ "date_from": (exposure_time - timedelta(hours=1)).isoformat(),+ "date_to": (exposure_time + timedelta(hours=1)).isoformat(),+ "experiment_exposure": {"experiment_id": experiment.id, "in_session": True},+ },+ ["session-with-exposure"],+ )++ def test_in_session_scan_is_unclamped_for_pinned_sessions_that_bypass_the_date_window(self) -> None:+ # The list endpoint pins explicitly selected session ids past the date window+ # (bypass_date_window_for_session_ids), so the evidence scan must widen with it: clamped to+ # the query range, a pinned session with older exposure evidence would list under+ # all-exposed but silently vanish under in-session.+ experiment = self._create_experiment(start_date=BASE_TIME - timedelta(days=10))+ EventProperty.objects.create(team=self.team, event="$feature_flag_called", property="$session_id")+ create_person(team=self.team, distinct_ids=["exposed-user"])+ exposure_time = BASE_TIME - timedelta(days=5)+ self._create_exposure_event(+ "exposed-user", exposure_time, "test", properties={"$session_id": "session-pinned-old"}+ )+ flush_persons_and_events()+ self._produce_recording(+ "exposed-user", "session-pinned-old", exposure_time, exposure_time + timedelta(minutes=10)+ )++ query = RecordingsQuery(+ session_ids=["session-pinned-old"],+ date_from=(BASE_TIME - timedelta(days=1)).isoformat(),+ experiment_exposure={"experiment_id": experiment.id, "in_session": True},+ )+ results = (+ SessionRecordingListFromQuery(+ team=self.team,+ query=query,+ hogql_query_modifiers=None,+ bypass_date_window_for_session_ids=True,+ user=self.user,+ )+ .run()+ .results+ )+ assert [recording["session_id"] for recording in results] == ["session-pinned-old"]+@parameterized.expand([("unknown_experiment", None, None),diff --git a/products/experiments/backend/facade/replay.py b/products/experiments/backend/facade/replay.pyindex fe33b614fc88..b5b29a8b57e4 100644--- a/products/experiments/backend/facade/replay.py+++ b/products/experiments/backend/facade/replay.py@@ -2,16 +2,24 @@from products.experiments.backend.replay_linkage import (ACTIVATION_LIVE_SCAN_MAX_MEMORY_BYTES,+ IN_SESSION_EVIDENCE_SCAN_MAX_MEMORY_BYTES,ExperimentExposureLinkage,+ InSessionExposureSemantics,exposed_distinct_ids_select,+ exposed_session_ids_select,resolve_exposure_linkage,+ resolve_in_session_exposure_semantics,validate_experiment_exposure_access,)__all__ = ["ACTIVATION_LIVE_SCAN_MAX_MEMORY_BYTES",+ "IN_SESSION_EVIDENCE_SCAN_MAX_MEMORY_BYTES","ExperimentExposureLinkage",+ "InSessionExposureSemantics","exposed_distinct_ids_select",+ "exposed_session_ids_select","resolve_exposure_linkage",+ "resolve_in_session_exposure_semantics","validate_experiment_exposure_access",]diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 5e8c718b16ef..1408d4014e39 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -1745,6 +1745,31 @@ class ExperimentSessionContextsResponseSerializer(serializers.Serializer):)+class ExperimentInSessionExposureSerializer(serializers.Serializer):+ """How the recordings tab's in-session exposure scope reads on this experiment."""++ available = serializers.BooleanField(+ help_text=(+ "Whether the in-session exposure scope can answer for this experiment. Mirrors the recordings "+ "query, which refuses `experiment_exposure.in_session` exactly when this is false."+ )+ )+ unavailable_reason = serializers.CharField(+ allow_null=True,+ help_text=(+ "Why the in-session scope can't answer for this experiment, worded for display next to the "+ "disabled option. Null when available."+ ),+ )+ uses_stamped_fallback = serializers.BooleanField(+ help_text=(+ "True when in-session evidence is the stamped `$feature/<flag_key>` property, which means the "+ "flag was active in the session, rather than the exposure event itself being captured there. "+ "Copy must not claim the exposure was captured in the session when this is set."+ )+ )++class ExperimentSessionBucketRequestSerializer(serializers.Serializer):"""Request body for the session-bucket endpoint."""diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex 9dddb1106349..2a61006cfcb5 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -62,6 +62,7 @@ from products.access_control.backend.facade.user_access_control import UserAccesfrom products.access_control.backend.presentation.access_control import AccessControlViewSetMixinfrom products.approvals.backend.mixins import ApprovalHandlingMixinfrom products.experiments.backend.experiment_service import ExperimentService, ExperimentVersionConflict+from products.experiments.backend.facade.replay import resolve_in_session_exposure_semanticsfrom products.experiments.backend.llm_metric_templates import build_template, list_templates# TODO: Route through facade instead of direct import@@ -82,6 +83,7 @@ from products.experiments.backend.presentation.serializers import (ExperimentBasicSerializer,ExperimentFlagCleanupTargetSerializer,ExperimentFlagCleanupTaskSerializer,+ ExperimentInSessionExposureSerializer,ExperimentMetricsRecalculationSerializer,ExperimentSerializer,ExperimentSessionBucketRequestSerializer,@@ -1502,6 +1504,23 @@ class EnterpriseExperimentsViewSet()return Response(serializer.data)+ @extend_schema(+ request=None,+ responses={200: OpenApiResponse(response=ExperimentInSessionExposureSerializer)},+ )+ @action(methods=["GET"], detail=True, url_path="in_session_exposure", required_scopes=["experiment:read"])+ def in_session_exposure(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """How the recordings tab's in-session exposure scope reads on this experiment.++ Resolved through the same seam as the recordings query's `in_session` refusal, so the+ scope control disables exactly what a query would be refused for, and the copy can say+ when sessions are matched on the stamped flag property rather than on the exposure event.+ Postgres reads only, so it can serve the tab's mount path.+ """+ experiment: Experiment = self.get_object()+ semantics = resolve_in_session_exposure_semantics(self.team, experiment)+ return Response(ExperimentInSessionExposureSerializer(semantics).data)+@validated_request(request_serializer=ExperimentSessionBucketRequestSerializer,responses={200: OpenApiResponse(response=ExperimentSessionBucketResponseSerializer)},diff --git a/products/experiments/backend/replay_linkage.py b/products/experiments/backend/replay_linkage.pyindex 831e7fc8f7dc..5e6ad5bd9515 100644--- a/products/experiments/backend/replay_linkage.py+++ b/products/experiments/backend/replay_linkage.py@@ -20,13 +20,24 @@ The work splits in two, because recordings queries build their AST separately fris 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.+Queries can additionally narrow the population's sessions to the ones carrying in-session+exposure evidence (:func:`exposed_session_ids_select`). What counts as evidence comes from the+shared session-exposure resolution, so this surface, the session buckets, and the watch shelf+all mean the same thing by "exposed in this session". Whether the narrowing can answer for an+experiment at all resolves through :func:`resolve_in_session_exposure_semantics`, which the+scope control reads too, so the tab disables exactly what a query would be refused for.+The exposure scan window is deliberately the full experiment window, unbounded. Narrowing itwould change who counts as exposed relative to the analysis. The expensive cases are handledinstead: precomputing teams read the preaggregated table (converging in TTL-capped chunks forlong-running experiments), activation-mode exposures always resolve with a live scan becausethey have no preaggregated form (carrying an explicit memory budget on precomputing teams),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.+is refused with a ValidationError rather than left to time out. The in-session evidence scan+follows the same posture: it always runs live under an explicit memory budget, callers can+intersect its window with their own date bounds (which never changes results), and its+stamped-property fallback flavor (the read with no event name to prune on) is refused on+precomputing teams rather than left to time out."""from dataclasses import dataclass@@ -43,6 +54,7 @@ from posthog.hogql import astfrom posthog.hogql.parser import parse_selectfrom posthog.clickhouse.query_tagging import tag_queries, tags_context+from posthog.dataclasses import frozenfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.team.team import Team@@ -67,6 +79,7 @@ from products.experiments.backend.hogql_queries.experiment_query_runner import (from products.experiments.backend.hogql_queries.exposure_query_logic import get_entity_key, has_activation_configfrom products.experiments.backend.models.experiment import Experimentfrom products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig+from products.experiments.backend.session_exposure import SessionExposure, resolve_session_exposurelogger = structlog.get_logger(__name__)@@ -77,11 +90,34 @@ COHORT_NOT_CALCULATED_MESSAGE = ("This experiment's exposure criteria reference a cohort that hasn't finished calculating. ""Try again when the cohort is ready.")+EXPERIMENT_HAS_NO_FLAG_MESSAGE = "This experiment has no feature flag, so exposures can't be resolved."+# Written to stand alone next to the scope control's disabled in-session option, which is how the+# tab surfaces them via :func:`resolve_in_session_exposure_semantics`.+IN_SESSION_EXPOSURE_UNMATCHABLE_REASON = (+ "This experiment's exposure event has only ever been captured server-side, where there is no "+ "session to record, so no session can contain it."+)+IN_SESSION_EXPOSURE_ACTIVATION_REASON = (+ "This experiment uses an activation event, so its exposure can span more than one session and "+ "can't be pinned to a single session."+)+IN_SESSION_EXPOSURE_FALLBACK_TOO_LARGE_REASON = (+ "This experiment's exposure event was never captured with a session ID, and this project is too "+ "large for the fallback that matches sessions on the feature flag being active."+)+# Appended when a query actually carries the narrowing, so the API error names the way out. The+# scope control shows the bare reason instead: its option is disabled, so there is nothing to remove.+_IN_SESSION_REFUSAL_QUERY_SUFFIX = " Remove the in-session narrowing to see exposed participants' sessions."# Sized an order of magnitude above the peak observed on the largest precompute-enabled team# (#83514), so it fires only for a scan far outside anything measured, and below the cluster's# default per-query limit, so the kill renders as the standard memory-limit error before the# scan becomes cluster-level pressure.ACTIVATION_LIVE_SCAN_MAX_MEMORY_BYTES = 4 * 1024**3+# The in-session evidence scan and its GLOBAL IN session-id set have no preaggregated form, so like+# the activation scan they run live under an explicit ceiling. Sized an order of magnitude above+# the evidence-session sets measured for the broadest experiments on the largest internal project,+# and below the cluster's default per-query limit, for the same graceful-kill reason as above.+IN_SESSION_EVIDENCE_SCAN_MAX_MEMORY_BYTES = 4 * 1024**3def validate_experiment_exposure_access(@@ -141,16 +177,107 @@ class ExperimentExposureLinkage:# population is already test-filtered at the person level. Queries that restrict their rows# to this population can skip re-applying the same filters to their own rows.population_filters_test_accounts: bool = False+ # Resolved only when the query narrows to in-session exposure evidence; None otherwise.+ # Carries which event and property the evidence reads and whether the stamped-property+ # fallback applies, resolved through the shared session-exposure seam so this surface+ # can't disagree with the session buckets and the watch shelf on what "exposed in this+ # session" means.+ session_exposure: SessionExposure | None = None+++@frozen+class InSessionExposureSemantics:+ """How the in-session narrowing reads on one experiment.++ One resolution serves both the recordings query's refusal and the tab's scope control, so the+ two can't drift: the control disables exactly what the query would refuse, and the copy can say+ when the evidence is the stamped-property stand-in rather than the exposure event itself.+ """++ # None exactly when ``unavailable_reason`` is set.+ session_exposure: SessionExposure | None+ # Why in-session narrowing can't answer for this experiment. None when it can.+ unavailable_reason: str | None++ @property+ def available(self) -> bool:+ """True when a query carrying the narrowing would be accepted."""+ return self.unavailable_reason is None++ @property+ def uses_stamped_fallback(self) -> bool:+ """True when the evidence is the stamped ``$feature/<key>`` property: it means the flag was+ active in the session, not that the exposure event was captured there."""+ return self.session_exposure is not None and self.session_exposure.used_fallback+++def _precomputation_covers_full_window(config: TeamExperimentsConfig, experiment: Experiment) -> bool:+ """The team-level marker that a full-window live events scan is a real cost here: precomputation+ is enabled and the experiment has run past the minimum runtime, so the analysis reads+ preaggregated data instead of scanning live. The population read and the in-session fallback+ refusal both key off this one predicate so their cost postures cannot drift.+ """+ return config.experiment_precomputation_enabled and experiment_has_min_runtime_for_precomputation(+ experiment.start_date, experiment.end_date+ )+++def _fallback_evidence_scan_is_unaffordable(team: Team, experiment: Experiment) -> bool:+ """Whether the stamped-property evidence scan must be refused for this team and experiment.++ Unlike the exposure-event scan, the fallback has no event name to prune on, so it reads every+ event in the experiment window. On the teams where precomputation marks full-window live scans+ as a real cost, that scan times out instead of answering, so refusing is the honest posture,+ the same one the population read takes, including its young-experiment exception, whose window+ is hours wide and cheap on any team.+ """+ if experiment.start_date is None:+ return False+ config = get_or_create_team_extension(team, TeamExperimentsConfig)+ return _precomputation_covers_full_window(config, experiment)-def resolve_exposure_linkage(team: Team, *, experiment_id: int, variant: str | None) -> ExperimentExposureLinkage:+def resolve_in_session_exposure_semantics(team: Team, experiment: Experiment) -> InSessionExposureSemantics:+ """Resolve whether the in-session narrowing can answer for this experiment, and how.++ Postgres reads only (taxonomy plus team config, no ClickHouse), so the tab can ask on mount+ and disable the option instead of letting a doomed query surface as an error.+ """+ if getattr(experiment, "feature_flag", None) is None:+ return InSessionExposureSemantics(session_exposure=None, unavailable_reason=EXPERIMENT_HAS_NO_FLAG_MESSAGE)+ if has_activation_config(experiment.exposure_criteria):+ # Activation mode counts exposure from the activation event, at or after the first flag+ # exposure and often in a later session, while the in-session evidence matches the flag+ # event. The two can't agree inside one session, so refuse rather than list the wrong+ # session or nothing.+ return InSessionExposureSemantics(+ session_exposure=None, unavailable_reason=IN_SESSION_EXPOSURE_ACTIVATION_REASON+ )+ # A Postgres EventProperty read, so it stays out of the common no-narrowing path.+ session_exposure = resolve_session_exposure(team, experiment, event_names=frozenset())+ if session_exposure.is_unmatchable:+ return InSessionExposureSemantics(+ session_exposure=None, unavailable_reason=IN_SESSION_EXPOSURE_UNMATCHABLE_REASON+ )+ if session_exposure.used_fallback and _fallback_evidence_scan_is_unaffordable(team, experiment):+ return InSessionExposureSemantics(+ session_exposure=None, unavailable_reason=IN_SESSION_EXPOSURE_FALLBACK_TOO_LARGE_REASON+ )+ return InSessionExposureSemantics(session_exposure=session_exposure, unavailable_reason=None)+++def resolve_exposure_linkage(+ team: Team, *, experiment_id: int, variant: str | None, in_session: bool = False+) -> 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 draftexperiments, group-aggregated ones (whose exposed entities are groups rather thanpersons and so never match a recording's distinct id), unknown variants, andexperiments whose exposures can be resolved neither from the preaggregated table nor- with a live scan the team can afford.+ with a live scan the team can afford. An `in_session` request is refused when the+ exposure event was never captured with a session id and nothing stands in for it+ (custom criteria get no stand-in), because every session would then read as unexposed."""try:experiment = Experiment.objects.get(id=experiment_id, team=team, deleted=False)@@ -159,7 +286,7 @@ def resolve_exposure_linkage(team: Team, *, experiment_id: int, variant: str | Nflag = getattr(experiment, "feature_flag", None)if flag is None:- raise ValidationError("This experiment has no feature flag, so exposures can't be resolved.")+ raise ValidationError(EXPERIMENT_HAS_NO_FLAG_MESSAGE)if experiment.start_date is None:raise ValidationError("This experiment hasn't launched, so it has no exposed sessions yet.")if (flag.filters or {}).get("aggregation_group_type_index") is not None:@@ -182,6 +309,13 @@ def resolve_exposure_linkage(team: Team, *, experiment_id: int, variant: str | Nelse:requested_variants = variant_keys+ session_exposure: SessionExposure | None = None+ if in_session:+ semantics = resolve_in_session_exposure_semantics(team, experiment)+ if semantics.unavailable_reason is not None:+ raise ValidationError(semantics.unavailable_reason + _IN_SESSION_REFUSAL_QUERY_SUFFIX)+ session_exposure = semantics.session_exposure+exposure_params = get_exposure_config_params_for_builder(experiment.exposure_criteria, team, experiment.start_date)date_range_query = QueryDateRange(date_range=experiment_window(experiment, team, as_of=experiment.end_date or datetime.now(UTC)),@@ -211,8 +345,16 @@ def resolve_exposure_linkage(team: Team, *, experiment_id: int, variant: str | Ncontext=context,requested_variants=requested_variants,preaggregation_job_ids=read.preaggregation_job_ids,- live_scan_max_memory_bytes=read.live_scan_max_memory_bytes,+ # The evidence scan always runs live whatever path the population resolves through, so a+ # narrowed listing carries the ceiling even where the population read needs none. Activation+ # (the other ceiling source) is refused with in_session, so the two never compete.+ live_scan_max_memory_bytes=(+ IN_SESSION_EVIDENCE_SCAN_MAX_MEMORY_BYTES+ if session_exposure is not None+ else read.live_scan_max_memory_bytes+ ),population_filters_test_accounts=exposure_params.filter_test_accounts,+ session_exposure=session_exposure,)@@ -241,9 +383,7 @@ def _resolve_exposure_read(team: Team, experiment: Experiment, context: Experime# 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- ):+ if not _precomputation_covers_full_window(config, experiment):tag_queries(experiment_exposures_path="direct_scan")return _ExposureRead(preaggregation_job_ids=None, live_scan_max_memory_bytes=None)@@ -361,3 +501,59 @@ def exposed_distinct_ids_select(linkage: ExperimentExposureLinkage) -> ast.Selec# live path to a single events scan and holds only the exposed rows in memory.query.ctes = {"exposures": ast.CTE(name="exposures", expr=exposure_select, cte_type="subquery", materialized=True)}return query+++def exposed_session_ids_select(+ linkage: ExperimentExposureLinkage,+ *,+ clamp_date_from: datetime | None = None,+ clamp_date_to: datetime | None = None,+) -> ast.SelectQuery:+ """Distinct ids of sessions carrying in-session exposure evidence, for narrowing the+ person-scoped population to the sessions where the exposure can be watched happening.++ Pure AST construction; the linkage must have been resolved with ``in_session=True``.++ The evidence condition comes from the shared session-exposure resolution, including the+ stamped ``$feature/<flag_key>`` fallback when the exposure event was never captured with a+ session id. This narrowing composes with the exposure join rather than replacing it: the+ join still decides who counts as exposed (and bounds sessions to first exposure), so+ deliberately no test-account filtering here, where it could only re-hide sessions of+ persons the analysis counts. The scan prunes by event name except on the fallback path,+ which reads the stamped property off every event in the window, the same read the session+ buckets run.++ The scan window is the experiment's, matching the population scan, intersected with the+ caller's clamp when given: evidence lives inside the sessions being listed, so a caller that+ bounds its sessions by date can pass those bounds (with its session-length buffer) and drop+ the part of the scan that could only nominate sessions it already excludes. Unlike a fixed+ recency clamp, the intersection never changes results: deduped first-exposure evidence+ stays in scope whenever the listed window covers it.++ Always a live events scan, whatever path the population resolves through: the+ preaggregated exposures table carries no session ids.+ """+ assert linkage.session_exposure is not None+ scan_date_from = linkage.context.date_range_query.date_from()+ scan_date_to = linkage.context.date_range_query.date_to()+ if clamp_date_from is not None:+ scan_date_from = max(scan_date_from, clamp_date_from)+ if clamp_date_to is not None:+ scan_date_to = min(scan_date_to, clamp_date_to)+ query = parse_select(+ """+ SELECT DISTINCT `$session_id` AS session_id+ FROM events+ WHERE timestamp >= {date_from}+ AND timestamp <= {date_to}+ AND `$session_id` != ''+ AND {evidence}+ """,+ placeholders={+ "date_from": ast.Constant(value=scan_date_from),+ "date_to": ast.Constant(value=scan_date_to),+ "evidence": linkage.session_exposure.condition(linkage.requested_variants),+ },+ )+ assert isinstance(query, ast.SelectQuery)+ return querydiff --git a/products/experiments/backend/session_exposure.py b/products/experiments/backend/session_exposure.pyindex 4105e206f73e..de4927fa36ae 100644--- a/products/experiments/backend/session_exposure.py+++ b/products/experiments/backend/session_exposure.py@@ -55,6 +55,11 @@ class SessionExposure:team: Teamexperiment: Experiment+ # The flag key with any soft-delete tombstone stripped, matching the key historical events+ # carry. A flag cleaned up after its experiment stopped is renamed to `<key>:deleted:<id>`, and+ # resolving conditions on that renamed key would match no session. Carried so `condition` and+ # the stamped fallback agree with the population query, which strips it the same way.+ flag_key: str# What this experiment's default exposure resolves to under the $experiment_exposure rollout.# Carried rather than re-resolved so every clause in one response agrees on the event, even if# the flag flips mid-request.@@ -107,7 +112,7 @@ class SessionExposure:*build_exposure_event_conditions(self.experiment.exposure_criteria,self.team,- self.experiment.feature_flag.key,+ self.flag_key,default_exposure_event=self.default_exposure_event,),variant_condition,@@ -122,7 +127,10 @@ def resolve_session_exposure(team: Team, experiment: Experiment, *, event_names:the same bounded `EventProperty` read as the exposure event's, so one query settles both whichmetrics a session can show and whether the exposure event can match a session at all."""- flag_key = experiment.feature_flag.key+ # Strip any soft-delete tombstone: a flag cleaned up after its experiment stopped is renamed to+ # `<key>:deleted:<id>`, but historical events still carry the original key, so conditions and the+ # stamped fallback must resolve against it, the same key the population query uses.+ flag_key = experiment.feature_flag.key_without_tombstone()default_exposure_event = resolve_default_exposure_event(team, experiment.start_date)exposure_event, variant_property = get_exposure_event_and_property(flag_key, experiment.exposure_criteria, default_exposure_event=default_exposure_event@@ -138,6 +146,7 @@ def resolve_session_exposure(team: Team, experiment: Experiment, *, event_names:return SessionExposure(team=team,experiment=experiment,+ flag_key=flag_key,default_exposure_event=default_exposure_event,exposure_event=exposure_event,variant_property=f"$feature/{flag_key}" if used_fallback else variant_property,diff --git a/products/experiments/backend/test/test_session_exposure.py b/products/experiments/backend/test/test_session_exposure.pynew file mode 100644index 000000000000..4d5276d9b9e3--- /dev/null+++ b/products/experiments/backend/test/test_session_exposure.py@@ -0,0 +1,212 @@+import dataclasses+from datetime import UTC, datetime+from typing import Any++from posthog.test.base import BaseTest+from unittest.mock import patch++from posthog.hogql import ast++from posthog.models import EventProperty++from products.experiments.backend.hogql_queries.exposure_query_logic import (+ DEFAULT_EXPOSURE_EVENT,+ EXPERIMENT_EXPOSURE_EVENT,+ EXPERIMENT_EXPOSURE_EVENT_CUTOFF,+ EXPERIMENT_EXPOSURE_EVENT_FLAG,+)+from products.experiments.backend.models.experiment import Experiment+from products.experiments.backend.replay_linkage import (+ IN_SESSION_EXPOSURE_ACTIVATION_REASON,+ IN_SESSION_EXPOSURE_UNMATCHABLE_REASON,+ resolve_in_session_exposure_semantics,+)+from products.experiments.backend.session_exposure import resolve_session_exposure+from products.feature_flags.backend.models.feature_flag import FeatureFlag+++def _string_constants(node: object) -> set[str]:+ # Every string literal in a HogQL expression tree, so a test can assert which key a condition+ # matches on without depending on the tree's shape.+ found: set[str] = set()++ def walk(current: object) -> None:+ if isinstance(current, ast.Constant):+ if isinstance(current.value, str):+ found.add(current.value)+ return+ if dataclasses.is_dataclass(current) and not isinstance(current, type):+ for field in dataclasses.fields(current):+ walk(getattr(current, field.name))+ elif isinstance(current, list | tuple):+ for item in current:+ walk(item)++ walk(node)+ return found+++class TestSessionExposureTombstonedFlag(BaseTest):+ ORIGINAL_KEY = "checkout-cta"++ def _tombstoned_experiment(self) -> Experiment:+ # A flag cleaned up after its experiment stopped: soft-deleted, and its key renamed to free+ # the original. The experiment keeps serving its recordings tab, and historical exposure+ # events still carry the original key.+ flag = FeatureFlag.objects.create(+ team=self.team,+ key=self.ORIGINAL_KEY,+ name=self.ORIGINAL_KEY,+ created_by=self.user,+ filters={+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 50},+ {"key": "test", "rollout_percentage": 50},+ ]+ }+ },+ )+ experiment = Experiment.objects.create(+ team=self.team,+ name="Checkout CTA copy",+ feature_flag=flag,+ created_by=self.user,+ # Before EXPERIMENT_EXPOSURE_EVENT_CUTOFF, so the default resolves to $feature_flag_called.+ start_date=datetime(2026, 1, 1, tzinfo=UTC),+ exposure_criteria={},+ )+ flag.deleted = True+ flag.key = flag.tombstoned_key()+ flag.save()+ return experiment++ def test_condition_matches_on_the_original_key_not_the_tombstone(self) -> None:+ experiment = self._tombstoned_experiment()+ # The default exposure event is session-linked here, so the condition filters on+ # $feature_flag rather than the stamped fallback.+ EventProperty.objects.get_or_create(+ team=self.team, project_id=self.team.project_id, event=DEFAULT_EXPOSURE_EVENT, property="$session_id"+ )++ exposure = resolve_session_exposure(self.team, experiment, event_names=frozenset())+ assert exposure.used_fallback is False++ constants = _string_constants(exposure.condition(["control", "test"]))+ assert self.ORIGINAL_KEY in constants+ assert not any(":deleted:" in value for value in constants)++ def test_stamped_fallback_uses_the_original_key_not_the_tombstone(self) -> None:+ experiment = self._tombstoned_experiment()+ # No $session_id trace for the default event, so it falls back to the stamped+ # $feature/<key> property, which must name the original key, not the renamed one.+ exposure = resolve_session_exposure(self.team, experiment, event_names=frozenset())++ assert exposure.used_fallback is True+ assert exposure.variant_property == f"$feature/{self.ORIGINAL_KEY}"+ assert ":deleted:" not in exposure.variant_property+++# The seam the recordings query's in_session refusal and the tab's scope control both read, so+# they can't drift on whether the scope is available or on the fallback caveat.+class TestResolveInSessionExposureSemantics(BaseTest):+ def _experiment(self, exposure_criteria: dict | None = None, start_date: datetime | None = None) -> Experiment:+ flag = FeatureFlag.objects.create(+ team=self.team,+ key="checkout-cta",+ name="checkout-cta",+ created_by=self.user,+ filters={+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 50},+ {"key": "test", "rollout_percentage": 50},+ ]+ }+ },+ )+ return Experiment.objects.create(+ team=self.team,+ name="Checkout CTA copy",+ feature_flag=flag,+ created_by=self.user,+ # The default is before EXPERIMENT_EXPOSURE_EVENT_CUTOFF, so the exposure event+ # resolves to $feature_flag_called.+ start_date=start_date or datetime(2026, 1, 1, tzinfo=UTC),+ exposure_criteria=exposure_criteria or {},+ )++ def test_available_without_fallback_when_the_exposure_event_is_session_linked(self) -> None:+ experiment = self._experiment()+ EventProperty.objects.get_or_create(+ team=self.team, project_id=self.team.project_id, event=DEFAULT_EXPOSURE_EVENT, property="$session_id"+ )++ semantics = resolve_in_session_exposure_semantics(self.team, experiment)++ assert semantics.unavailable_reason is None+ assert semantics.session_exposure is not None+ assert semantics.uses_stamped_fallback is False++ def test_available_but_flags_the_stamped_fallback_for_a_server_side_default_event(self) -> None:+ # No EventProperty row marks the default event as ever session-linked, so evidence is the+ # stamped flag property. The scope still answers, but the copy must say the flag was active,+ # not that the exposure was captured, so the caveat has to reach the tab.+ experiment = self._experiment()++ semantics = resolve_in_session_exposure_semantics(self.team, experiment)++ assert semantics.unavailable_reason is None+ assert semantics.uses_stamped_fallback is True++ def test_condition_matches_the_rollout_default_event_at_the_cutoff(self) -> None:+ # The in-session narrowing reads the exposure event off this seam. If the seam kept the+ # legacy default, exposures arriving as $experiment_exposure would leave every rollout+ # experiment's in-session list empty.+ experiment = self._experiment(start_date=EXPERIMENT_EXPOSURE_EVENT_CUTOFF)+ EventProperty.objects.get_or_create(+ team=self.team, project_id=self.team.project_id, event=EXPERIMENT_EXPOSURE_EVENT, property="$session_id"+ )++ # Only answer for the rollout flag; a blanket True would flip unrelated rollouts on too.+ def rollout_only(flag_key: str, *args: Any, **kwargs: Any) -> bool:+ return flag_key == EXPERIMENT_EXPOSURE_EVENT_FLAG++ with patch("posthoganalytics.feature_enabled", side_effect=rollout_only):+ semantics = resolve_in_session_exposure_semantics(self.team, experiment)++ assert semantics.session_exposure is not None+ assert semantics.uses_stamped_fallback is False+ assert EXPERIMENT_EXPOSURE_EVENT in _string_constants(semantics.session_exposure.condition(["control"]))++ def test_unavailable_for_activation_criteria(self) -> None:+ experiment = self._experiment(+ exposure_criteria={+ "activation_config": {+ "kind": "ExperimentEventExposureConfig",+ "event": "task_completed",+ "properties": [],+ }+ }+ )++ semantics = resolve_in_session_exposure_semantics(self.team, experiment)++ assert semantics.unavailable_reason == IN_SESSION_EXPOSURE_ACTIVATION_REASON+ assert semantics.session_exposure is None++ def test_unavailable_for_a_never_session_linked_custom_event(self) -> None:+ experiment = self._experiment(+ exposure_criteria={+ "exposure_config": {+ "kind": "ExperimentEventExposureConfig",+ "event": "backend_exposure",+ "properties": [],+ }+ }+ )++ semantics = resolve_in_session_exposure_semantics(self.team, experiment)++ assert semantics.unavailable_reason == IN_SESSION_EXPOSURE_UNMATCHABLE_REASON+ assert semantics.session_exposure is Nonediff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 24f34171e1a3..5a2672b472db 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -2029,6 +2029,21 @@ export interface ExperimentFlagCleanupTaskApi {can_view_task: boolean}+/**+ * How the recordings tab's in-session exposure scope reads on this experiment.+ */+export interface ExperimentInSessionExposureApi {+ /** Whether the in-session exposure scope can answer for this experiment. Mirrors the recordings query, which refuses `experiment_exposure.in_session` exactly when this is false. */+ available: boolean+ /**+ * Why the in-session scope can't answer for this experiment, worded for display next to the disabled option. Null when available.+ * @nullable+ */+ unavailable_reason: string | null+ /** True when in-session evidence is the stamped `$feature/<flag_key>` property, which means the flag was active in the session, rather than the exposure event itself being captured there. Copy must not claim the exposure was captured in the session when this is set. */+ uses_stamped_fallback: boolean+}+/*** * `manual` - Manual* * `agent_mcp` - Agent (MCP)diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.tsindex d96320181bdb..ade28684540c 100644--- a/products/experiments/frontend/generated/api.ts+++ b/products/experiments/frontend/generated/api.ts@@ -19,6 +19,7 @@ import type {ExperimentFlagCleanupTaskApi,ExperimentHoldoutApi,ExperimentHoldoutsListParams,+ ExperimentInSessionExposureApi,ExperimentMetricsRecalculationApi,ExperimentSavedMetricApi,ExperimentSavedMetricsListParams,@@ -664,6 +665,29 @@ export const experimentsFreezeExposureCreate = async (})}+export const getExperimentsInSessionExposureRetrieveUrl = (projectId: string, id: number) => {+ return `/api/projects/${projectId}/experiments/${id}/in_session_exposure/`+}++/**+ * How the recordings tab's in-session exposure scope reads on this experiment.+ *+ * Resolved through the same seam as the recordings query's `in_session` refusal, so the+ * scope control disables exactly what a query would be refused for, and the copy can say+ * when sessions are matched on the stamped flag property rather than on the exposure event.+ * Postgres reads only, so it can serve the tab's mount path.+ */+export const experimentsInSessionExposureRetrieve = async (+ projectId: string,+ id: number,+ options?: RequestInit+): Promise<ExperimentInSessionExposureApi> => {+ return apiMutator<ExperimentInSessionExposureApi>(getExperimentsInSessionExposureRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}+export const getExperimentsLaunchCreateUrl = (projectId: string, id: number) => {return `/api/projects/${projectId}/experiments/${id}/launch/`}diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yamlindex 1b1b17184479..18116d6720a2 100644--- a/products/experiments/mcp/tools.yaml+++ b/products/experiments/mcp/tools.yaml@@ -1408,6 +1408,9 @@ tools:experiments-flag-cleanup-target-retrieve:operation: experiments_flag_cleanup_target_retrieveenabled: false+ experiments-in-session-exposure-retrieve:+ operation: experiments_in_session_exposure_retrieve+ enabled: falseexperiments-recalculate-timeseries:operation: experiments_recalculate_timeseries_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 904982e73e3c..1619fd13cb4c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -34763,6 +34763,21 @@ export namespace Schemas {can_view_task: boolean;}+ /**+ * How the recordings tab's in-session exposure scope reads on this experiment.+ */+ export interface ExperimentInSessionExposure {+ /** Whether the in-session exposure scope can answer for this experiment. Mirrors the recordings query, which refuses `experiment_exposure.in_session` exactly when this is false. */+ available: boolean;+ /**+ * Why the in-session scope can't answer for this experiment, worded for display next to the disabled option. Null when available.+ * @nullable+ */+ unavailable_reason: string | null;+ /** True when in-session evidence is the stamped `$feature/<flag_key>` property, which means the flag was active in the session, rather than the exposure event itself being captured there. Copy must not claim the exposure was captured in the session when this is set. */+ uses_stamped_fallback: boolean;+ }+/*** * `manual` - Manual* * `agent_mcp` - Agent (MCP)@@ -44613,6 +44628,8 @@ export namespace Schemas {export interface RecordingsQueryExperimentExposureFilter {/** Experiment whose exposed persons' sessions to show. Must belong to the environment the query runs in. */experiment_id: number;+ /** Only sessions carrying in-session exposure evidence: an event matching the experiment's exposure criteria inside the session (with the stamped `$feature/<flag_key>` property standing in when the exposure event was never captured with a session id). Defaults to all exposed persons' sessions from first exposure onward. */+ in_session?: boolean | null;/** Narrow to persons exposed to this variant. Defaults to all of the experiment's variants. */variant?: string | null;}