: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): server-side session buckets + advanced recording filters (#74955)
Marcel Poelker226cc5d13b05
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsxindex cdbe1f0f5557..5ba3d67a67b6 100644--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx@@ -16,13 +16,20 @@ import {import { LemonButton } from 'lib/lemon-ui/LemonButton'import { Tooltip } from 'lib/lemon-ui/Tooltip'+import { pluralize } from 'lib/utils/strings'import { SessionRecordingsPlaylist } from 'scenes/session-recordings/playlist/SessionRecordingsPlaylist'import { Experiment } from '~/types'import { isLaunched } from '../experimentStatus'+import { NOT_A_FUNNEL_REASON } from '../utils'import { EXPOSURE_FALLBACK_NOTICE, EXPOSURE_UNLINKABLE_REASON } from '../viewRecordingsLinkabilityLogic'-import { ExperimentReplayMetricOption, experimentReplayTabLogic } from './experimentReplayTabLogic'+import {+ ExperimentReplayMetricFilterMode,+ ExperimentReplayMetricOption,+ ExperimentSessionBucket,+ experimentReplayTabLogic,+} from './experimentReplayTabLogic'import { VariantTag } from './VariantTag'// LemonSegmentedButton values must be strings; the logic stores null for "All". '$' is not an@@ -30,6 +37,127 @@ import { VariantTag } from './VariantTag'// variant — a variant literally named "all" just renders as its own option after the built-in "All".const ALL_VARIANTS = '$all'+// 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> = {+ fired_all: 'fired events from every selected metric',+ fired_any: 'fired events from at least one selected metric',+ no_metric_activity: 'fired no events from the selected metrics',+ funnel_dropoff: "started the funnel but didn't finish it",+}++/**+ * What the trigger says, so the current mode is readable without opening the menu.+ *+ * The count is always of *metrics* — that's what the checkboxes select. A metric can count+ * several events (a ratio counts two, a funnel one per step), so counting events here would+ * disagree with the number of boxes ticked. The mode verb carries the events half: what a+ * session fires is a metric's events, never the metric itself.+ */+function metricFilterTriggerLabel(+ mode: ExperimentReplayMetricFilterMode,+ selectedUuids: string[],+ options: ExperimentReplayMetricOption[]+): string {+ if (mode === 'funnel_dropoff') {+ const selected = options.find((option) => option.uuid === selectedUuids[0])+ return selected ? `Didn't finish funnel: ${selected.name}` : "Didn't finish funnel"+ }+ if (selectedUuids.length === 0) {+ // Never fall back to the neutral label for a non-default mode: the mode is on, and the+ // caption below is what explains why it isn't narrowing anything yet.+ return mode === 'fired_all' ? 'Metric events' : mode === 'fired_any' ? 'Fired any' : 'No metric events'+ }+ const metrics = pluralize(selectedUuids.length, 'metric')+ if (selectedUuids.length === 1) {+ // "all of" and "any of" one metric are the same question, and both quantifiers read as+ // noise next to a count of one.+ return mode === 'no_metric_activity' ? `Didn't fire ${metrics}` : `Fired ${metrics}`+ }+ if (mode === 'fired_any') {+ return `Fired any of ${metrics}`+ }+ if (mode === 'no_metric_activity') {+ return `Fired none of ${metrics}`+ }+ return `Fired all ${metrics}`+}++/** Why a picked mode isn't narrowing the list — it needs a selection it doesn't have yet. */+function unappliedModeReason(mode: ExperimentReplayMetricFilterMode): string {+ return mode === 'funnel_dropoff'+ ? 'Pick a funnel metric with at least two steps that can be matched to recordings. Showing every exposed recording until then.'+ : 'Pick at least one metric. Showing every exposed recording until then.'+}++/**+ * States what the server-computed set does and doesn't cover. Every clause is load-bearing: the+ * list is capped, the scan window is clamped, and "in this session" is the honest unit — the+ * experiment analysis counts per person over the whole run window.+ */+function bucketCaption(bucket: ExperimentSessionBucket): string {+ const { session_ids, truncated, considered_metrics, excluded_metrics, filter_test_accounts } = bucket.response+ if (session_ids.length === 0) {+ return 'No recordings matched this filter.'+ }+ const sessions = truncated+ ? `Showing the ${session_ids.length} most recent recordings that`+ : `Showing ${pluralize(session_ids.length, 'recording')} that`+ const what =+ bucket.request.bucket === 'no_metric_activity'+ ? `fired no events from ${pluralize(considered_metrics.length, 'metric')} in this session`+ : bucket.request.bucket === 'fired_any' && considered_metrics.length === 1+ ? // One metric needs no quantifier, and naming it beats "at least one selected metric".+ `fired events from ${considered_metrics[0].metric_name} in this session`+ : `${MODE_SUMMARIES[bucket.request.bucket as ExperimentReplayMetricFilterMode]}, in this session`+ const caveats = [+ filter_test_accounts ? 'test accounts excluded' : null,+ excluded_metrics.length > 0+ ? `${pluralize(excluded_metrics.length, 'metric')} left out: ${excluded_metrics+ .map((metric) => metric.metric_name)+ .join(', ')}`+ : null,+ ].filter(Boolean)+ return `${sessions} ${what}.${caveats.length > 0 ? ` ${caveats.join('. ')}.` : ''}`+}++/** A metric row: its name, plus the events a session actually has to have fired to match it. */+function MetricOptionLabel({ option }: { option: ExperimentReplayMetricOption }): JSX.Element {+ return (+ <span className="flex min-w-0 items-baseline gap-2">+ <span className="truncate">{option.name}</span>+ {option.eventNames.length > 0 && (+ <span className="shrink-0 text-xs text-muted">{option.eventNames.join(', ')}</span>+ )}+ </span>+ )+}++const METRIC_FILTER_MODE_OPTIONS: { value: ExperimentReplayMetricFilterMode; label: string; tooltip: string }[] = [+ {+ value: 'fired_all',+ label: 'Fired all',+ tooltip: 'Sessions that fired events for every selected metric.',+ },+ {+ value: 'fired_any',+ label: 'Fired any',+ tooltip: 'Sessions that fired events for at least one of the selected metrics.',+ },+ {+ value: 'no_metric_activity',+ label: 'Fired none',+ tooltip:+ 'Sessions that fired no events for any of the selected metrics. Select nothing to use every metric that can be matched.',+ },+ {+ value: 'funnel_dropoff',+ label: "Didn't finish funnel",+ tooltip:+ "Sessions that reached a funnel metric's first step but not its last one during the recording. The same person may have finished it in a later session.",+ },+]+export function ExperimentReplayTab({ experiment }: { experiment: Experiment }): JSX.Element {const logic = experimentReplayTabLogic({ experiment })const {@@ -40,8 +168,21 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):usingExposureFallback,effectiveMetricUuids,metricOptions,+ metricFilterMode,+ sessionBucket,+ sessionBucketLoading,+ sessionBucketError,+ sessionBucketRequest,} = useValues(logic)- const { setSelectedVariantKey, setMetricSelected, recordingsLoaded, recordingOpened } = useActions(logic)+ const {+ setSelectedVariantKey,+ setMetricSelected,+ setMetricFilterMode,+ loadSessionBucket,+ playlistFiltersChanged,+ recordingsLoaded,+ recordingOpened,+ } = useActions(logic)if (!isLaunched(experiment)) {return <LemonBanner type="info">Launch the experiment to see recordings of participants.</LemonBanner>@@ -51,18 +192,23 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):return <LemonBanner type="warning">{EXPOSURE_UNLINKABLE_REASON}</LemonBanner>}- // Selectable metrics render as checkboxes. Unlinkable ones move to labelled sections that- // explain once, via a section tooltip, why they can't be matched — instead of repeating the- // same reason on every row. One section per distinct reason, since metrics can be unmatchable- // for different reasons (server-side events, a retention window, data-warehouse-only sources).- const linkableMetricOptions = metricOptions.filter((option) => !option.unlinkable)- const unlinkableOptionsByReason = new Map<string, ExperimentReplayMetricOption[]>()+ // Selectable metrics render as checkboxes. The rest move to labelled sections that explain+ // once, via a section tooltip, why they can't be matched — instead of repeating the same+ // reason on every row. One section per distinct reason, since metrics can be unmatchable for+ // different reasons (server-side events, a retention window, data-warehouse-only sources, or+ // simply not being a funnel while the drop-off mode is on).+ const linkableMetricOptions = metricOptions.filter(+ (option) => !option.unlinkable && (metricFilterMode !== 'funnel_dropoff' || option.dropoffReason === null)+ )+ const unselectableOptionsByReason = new Map<string, ExperimentReplayMetricOption[]>()for (const option of metricOptions) {- if (option.unlinkable && option.unlinkableReason) {- unlinkableOptionsByReason.set(option.unlinkableReason, [- ...(unlinkableOptionsByReason.get(option.unlinkableReason) ?? []),- option,- ])+ const reason = option.unlinkable+ ? option.unlinkableReason+ : metricFilterMode === 'funnel_dropoff'+ ? option.dropoffReason+ : null+ if (reason) {+ unselectableOptionsByReason.set(reason, [...(unselectableOptionsByReason.get(reason) ?? []), option])}}@@ -91,16 +237,24 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):size="small"type="secondary"sideIcon={<IconChevronDown />}- tooltip="Only show sessions that fired events for every selected metric. Whether a session fired a metric's events can differ from what the experiment analysis counts."+ tooltip="Narrow the list by what fired in each session. Whether a session fired a metric's events can differ from what the experiment analysis counts."data-attr="experiment-recordings-metric-filter"/>}>- {effectiveMetricUuids.length > 0- ? `Metric events (${effectiveMetricUuids.length})`- : 'Metric events'}+ {metricFilterTriggerLabel(metricFilterMode, effectiveMetricUuids, metricOptions)}</DropdownMenuTrigger><DropdownMenuContent align="start" className="min-w-fit max-w-100">+ <div className="p-1">+ <LemonSegmentedButton+ size="xsmall"+ fullWidth+ value={metricFilterMode}+ onChange={(value) => setMetricFilterMode(value)}+ options={METRIC_FILTER_MODE_OPTIONS}+ />+ </div>+ <DropdownMenuSeparator />{linkableMetricOptions.map((option) => (<DropdownMenuCheckboxItemkey={option.uuid}@@ -109,10 +263,10 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):closeOnClick={false}data-attr="experiment-recordings-metric-option">- {option.name}+ <MetricOptionLabel option={option} /></DropdownMenuCheckboxItem>))}- {[...unlinkableOptionsByReason.entries()].map(([reason, options], index) => (+ {[...unselectableOptionsByReason.entries()].map(([reason, options], index) => (// Fragment, not a wrapper element: the separator, label, and items// must stay direct children of the menu for keyboard nav and ARIA.<Fragment key={reason}>@@ -121,7 +275,9 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):live inside a DropdownMenuGroup or it throws at render. */}<DropdownMenuGroup><DropdownMenuLabel inset className="flex items-center gap-1">- Can't match to recordings+ {reason === NOT_A_FUNNEL_REASON+ ? 'Needs two funnel steps'+ : "Can't match to recordings"}<Tooltip title={reason}><IconInfo className="size-3 shrink-0" /></Tooltip>@@ -135,7 +291,7 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):disableddata-attr="experiment-recordings-metric-option">- {option.name}+ <MetricOptionLabel option={option} /></DropdownMenuItem>))}</DropdownMenuGroup>@@ -145,11 +301,32 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):</DropdownMenu>)}</div>+ {/* The default mode also uses the endpoint for a single multi-source metric, so the+ caption follows the request, not the mode. */}+ {(sessionBucketRequest || metricFilterMode !== 'fired_all') && (+ <div className="mb-2 flex items-center gap-2 text-xs text-secondary">+ {!sessionBucketRequest ? (+ <span>{unappliedModeReason(metricFilterMode)}</span>+ ) : sessionBucketError !== null ? (+ <>+ <span>Couldn't work out which sessions match this filter: {sessionBucketError}</span>+ <LemonButton size="xsmall" type="secondary" onClick={() => loadSessionBucket()}>+ Try again+ </LemonButton>+ </>+ ) : sessionBucketLoading || !sessionBucket ? (+ <span>Finding matching sessions…</span>+ ) : (+ <span data-attr="experiment-recordings-bucket-caption">{bucketCaption(sessionBucket)}</span>+ )}+ </div>+ )}<div className="SessionRecordingPlaylistHeightWrapper"><SessionRecordingsPlaylistlogicKey={`experiment-${experiment.id}`}filters={recordingsFilters}updateSearchParams={false}+ onFiltersChange={(filters) => playlistFiltersChanged(filters)}onRecordingsLoaded={(recordings) => recordingsLoaded(recordings.map((recording) => recording.id))}onRecordingSelected={(recordingId) => recordingOpened(recordingId)}/>diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.tsindex 622b61115237..dd3a701a2b64 100644--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts@@ -15,9 +15,16 @@ import {SessionRecordingSidebarTab,} from '~/types'-import { experimentsSessionContextsCreate } from 'products/experiments/frontend/generated/api'+import {+ experimentsSessionBucketsCreate,+ experimentsSessionContextsCreate,+} from 'products/experiments/frontend/generated/api'-import { getViewRecordingFiltersForVariant } from '../utils'+import {+ FUNNEL_DATA_WAREHOUSE_BOUNDARY_REASON,+ FUNNEL_SERVER_SIDE_BOUNDARY_REASON,+ getViewRecordingFiltersForVariant,+} from '../utils'import { RETENTION_UNLINKABLE_REASON } from '../viewRecordingsLinkabilityLogic'import { experimentReplayTabLogic } from './experimentReplayTabLogic'@@ -27,8 +34,19 @@ jest.mock('lib/utils/product-intents', () => ({jest.mock('products/experiments/frontend/generated/api', () => ({experimentsSessionContextsCreate: jest.fn().mockResolvedValue({ results: [] }),+ experimentsSessionBucketsCreate: jest.fn(),}))+const BUCKET_RESPONSE = {+ session_ids: ['bucket-1', 'bucket-2'],+ truncated: false,+ considered_metrics: [{ metric_uuid: 'metric-purchase', metric_name: 'Purchase' }],+ excluded_metrics: [],+ date_from: '2026-01-01T00:00:00Z',+ date_to: '2026-02-01T00:00:00Z',+ filter_test_accounts: true,+}+const PURCHASE_METRIC = {kind: NodeKind.ExperimentMetric,metric_type: ExperimentMetricType.MEAN,@@ -84,6 +102,8 @@ describe('experimentReplayTabLogic', () => {localStorage.clear()initKeaTests();(experimentsSessionContextsCreate as jest.Mock).mockClear()+ ;(experimentsSessionBucketsCreate as jest.Mock).mockClear()+ ;(experimentsSessionBucketsCreate as jest.Mock).mockResolvedValue(BUCKET_RESPONSE)seenTogetherSpy = jest.spyOn(api.propertyDefinitions, 'seenTogether')seenTogetherSpy.mockResolvedValue(ALL_LINKABLE)logic = experimentReplayTabLogic({ experiment: EXPERIMENT })@@ -344,33 +364,47 @@ describe('experimentReplayTabLogic', () => {unlinkable: false,})partiallyLinkable.actions.setMetricSelected('metric-funnel', true)- expect(partiallyLinkable.values.recordingsFilters.filter_group.values).toEqual([- {- type: FilterLogicalOperator.And,- values: [- ...getViewRecordingFiltersForVariant(EXPERIMENT, undefined),- { id: 'client_step', name: 'client_step', type: 'events', properties: [] },- ],- },- ])+ await expectLogic(partiallyLinkable).toFinishAllListeners()+ // A multi-source metric resolves server-side, where the unmatchable step is simply one+ // OR arm that never matches a session — so it drops out without narrowing anything.+ expect(experimentsSessionBucketsCreate).toHaveBeenLastCalledWith(expect.any(String), 45, {+ bucket: 'fired_any',+ metric_uuids: ['metric-funnel'],+ variant: null,+ })+ expect(partiallyLinkable.values.recordingsFilters.session_ids).toEqual(['bucket-1', 'bucket-2'])partiallyLinkable.unmount()})- it('filters a multi-source metric on its primary event only, not every source', async () => {- // Both funnel steps are session-linkable here. The recordings query flattens to a single- // AND operand, so ANDing every step would demand a session fire *all* of them; we filter on- // the entry step (series[0]) instead.+ it('resolves one multi-source metric server-side, and one single-source metric client-side', async () => {await expectLogic(logic).toFinishAllListeners()- logic.actions.setMetricSelected('metric-funnel', true)++ // A single event is expressible as a filter: exact, uncapped, no request.+ logic.actions.setMetricSelected('metric-purchase', true)+ await expectLogic(logic).toFinishAllListeners()+ expect(experimentsSessionBucketsCreate).not.toHaveBeenCalled()+ expect(logic.values.recordingsFilters.session_ids).toBeUndefined()expect(logic.values.recordingsFilters.filter_group.values).toEqual([{type: FilterLogicalOperator.And,values: [...getViewRecordingFiltersForVariant(EXPERIMENT, undefined),- { id: 'server_side_step', name: 'server_side_step', type: 'events', properties: [] },+ { id: 'purchase', name: 'purchase', type: 'events', properties: [] },],},])++ // Several events are not: a recordings query carries one operator for its whole tree, so+ // the filter could only match the metric's first event and would silently miss the rest.+ logic.actions.setMetricSelected('metric-purchase', false)+ logic.actions.setMetricSelected('metric-funnel', true)+ await expectLogic(logic).toFinishAllListeners()+ expect(experimentsSessionBucketsCreate).toHaveBeenLastCalledWith(expect.any(String), 42, {+ bucket: 'fired_any',+ metric_uuids: ['metric-funnel'],+ variant: null,+ })+ expect(logic.values.recordingsFilters.session_ids).toEqual(['bucket-1', 'bucket-2'])})it('skips metrics without a uuid — the persisted selection needs a stable identity', async () => {@@ -514,6 +548,168 @@ describe('experimentReplayTabLogic', () => {])withSaved.unmount()})+ it('hands the list to the bucket endpoint for filters the recordings query cannot express', async () => {+ await expectLogic(logic, () => {+ logic.actions.setSelectedVariantKey('test')+ logic.actions.setMetricSelected('metric-purchase', true)+ logic.actions.setMetricSelected('metric-funnel', true)+ logic.actions.setMetricFilterMode('fired_any')+ }).toFinishAllListeners()++ expect(experimentsSessionBucketsCreate).toHaveBeenLastCalledWith(expect.any(String), 42, {+ bucket: 'fired_any',+ metric_uuids: ['metric-purchase', 'metric-funnel'],+ variant: 'test',+ })+ const { recordingsFilters } = logic.values+ expect(recordingsFilters.session_ids).toEqual(['bucket-1', 'bucket-2'])+ // The returned set already encodes the metric condition; ANDing the event filters back in+ // would narrow it a second time.+ expect(recordingsFilters.filter_group.values).toEqual([+ {+ type: FilterLogicalOperator.And,+ values: getViewRecordingFiltersForVariant(EXPERIMENT, 'test'),+ },+ ])+ })++ it('follows the playlist\'s own "Show all" back to the unbucketed list', async () => {+ await expectLogic(logic, () => {+ logic.actions.setMetricFilterMode('no_metric_activity')+ }).toFinishAllListeners()+ expect(logic.values.recordingsFilters.session_ids).toEqual(['bucket-1', 'bucket-2'])++ // The shared playlist clears session_ids itself; without following it the tab would push+ // the same ids straight back and the control would look broken.+ await expectLogic(logic, () => {+ logic.actions.playlistFiltersChanged({ ...logic.values.recordingsFilters, session_ids: undefined })+ }).toMatchValues({ metricFilterMode: 'fired_all' })+ expect(logic.values.recordingsFilters.session_ids).toBeUndefined()+ })++ it('takes one funnel metric for drop-off and leaves the rest unselectable', async () => {+ await expectLogic(logic, () => {+ logic.actions.setMetricSelected('metric-purchase', true)+ logic.actions.setMetricSelected('metric-funnel', true)+ logic.actions.setMetricFilterMode('funnel_dropoff')+ }).toFinishAllListeners()++ // A mean metric has no steps to drop off between, and only one funnel can be compared.+ expect(logic.values.effectiveMetricUuids).toEqual(['metric-funnel'])+ expect(experimentsSessionBucketsCreate).toHaveBeenLastCalledWith(expect.any(String), 42, {+ bucket: 'funnel_dropoff',+ metric_uuids: ['metric-funnel'],+ variant: null,+ })+ })++ it.each([+ [+ 'server-side',+ [+ { kind: NodeKind.EventsNode, event: 'client_step' },+ { kind: NodeKind.EventsNode, event: 'server_side_step' },+ ],+ FUNNEL_SERVER_SIDE_BOUNDARY_REASON,+ ],+ [+ 'data warehouse',+ [+ { kind: NodeKind.EventsNode, event: 'client_step' },+ { kind: NodeKind.EventsNode, event: 'purchase' },+ { kind: NodeKind.ExperimentDataWarehouseNode, table_name: 'stripe_charges' },+ ],+ FUNNEL_DATA_WAREHOUSE_BOUNDARY_REASON,+ ],+ ])('refuses drop-off when the funnel finishes on a %s step', async (_name, series, expectedReason) => {+ seenTogetherSpy.mockResolvedValue({ ...ALL_LINKABLE, server_side_step: false })+ const unmatchableFinish = experimentReplayTabLogic({+ experiment: {+ ...EXPERIMENT,+ id: 50,+ metrics_secondary: [{ ...FUNNEL_METRIC, series }],+ } as unknown as Experiment,+ })+ unmatchableFinish.mount()++ await expectLogic(unmatchableFinish, () => {+ unmatchableFinish.actions.setMetricSelected('metric-funnel', true)+ unmatchableFinish.actions.setMetricFilterMode('funnel_dropoff')+ }).toFinishAllListeners()++ // Both steps between the boundaries stay matchable, so the metric is selectable in every+ // other mode. Drop-off is the one that reads the last step, and a completion no recording+ // can show would return everyone who entered as not having finished.+ expect(unmatchableFinish.values.metricOptions.find((option) => option.uuid === 'metric-funnel')).toMatchObject({+ unlinkable: false,+ dropoffReason: expectedReason,+ })+ expect(unmatchableFinish.values.effectiveMetricUuids).toEqual([])+ // Nothing is asked of the endpoint, which would refuse this funnel anyway.+ expect(unmatchableFinish.values.sessionBucketRequest).toBeNull()+ expect(unmatchableFinish.values.recordingsFilters.session_ids).toBeUndefined()+ unmatchableFinish.unmount()+ })++ it('keeps the list empty when the bucket fails, rather than widening it silently', async () => {+ ;(experimentsSessionBucketsCreate as jest.Mock).mockRejectedValue(new Error('boom'))++ await expectLogic(logic, () => {+ logic.actions.setMetricSelected('metric-purchase', true)+ logic.actions.setMetricSelected('metric-funnel', true)+ logic.actions.setMetricFilterMode('fired_any')+ }).toFinishAllListeners()++ // Falling back to no session_ids would show every exposed session under a label that+ // promises a narrower set. The message is kept, not just a flag: a rejected request+ // usually says what to fix.+ expect(logic.values.sessionBucketError).toBe('boom')+ expect(logic.values.recordingsFilters.session_ids).toEqual([])+ })++ it('keeps a picked mode that has nothing to filter on yet', async () => {+ // The tab pushes no session_ids until an eligible metric is picked, and the playlist echoes+ // that back through onFiltersChange. Reading it as the user clearing the bucket bounced the+ // mode straight back to "Fired all" the moment it was picked.+ const oneStepFunnel = experimentReplayTabLogic({+ experiment: {+ ...EXPERIMENT,+ id: 47,+ metrics_secondary: [{ ...FUNNEL_METRIC, series: [FUNNEL_METRIC.series[0]] }],+ } as unknown as Experiment,+ })+ oneStepFunnel.mount()++ await expectLogic(oneStepFunnel, () => {+ oneStepFunnel.actions.setMetricFilterMode('funnel_dropoff')+ }).toFinishAllListeners()+ oneStepFunnel.actions.playlistFiltersChanged(oneStepFunnel.values.recordingsFilters)++ expect(oneStepFunnel.values.metricFilterMode).toBe('funnel_dropoff')+ // No funnel with two matchable steps, so nothing is asked of the endpoint either.+ expect(oneStepFunnel.values.sessionBucketRequest).toBeNull()+ expect(experimentsSessionBucketsCreate).not.toHaveBeenCalled()+ oneStepFunnel.unmount()+ })+ it("lists metrics in the experiment page's order, and never hides one missing from it", async () => {+ // The ordering arrays are the metrics page's display order. Sorting on them keeps the two+ // surfaces in step; filtering on them would silently drop a metric whose uuid never made+ // it into the array (older experiments, or a row written outside the API).+ const ordered = experimentReplayTabLogic({+ experiment: {+ ...EXPERIMENT,+ id: 48,+ metrics: [PURCHASE_METRIC, FUNNEL_METRIC],+ metrics_secondary: [],+ primary_metrics_ordered_uuids: ['metric-funnel'],+ } as unknown as Experiment,+ })+ ordered.mount()+ await expectLogic(ordered).toFinishAllListeners()++ expect(ordered.values.metricOptions.map((option) => option.uuid)).toEqual(['metric-funnel', 'metric-purchase'])+ ordered.unmount()+ })it('lands the player sidebar on Overview, and hands it back when the tab goes away', () => {// Held mounted across the unmount below, standing in for a player that outlives this tab —diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.tsindex 0e415f8efada..55887058d8da 100644--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts@@ -12,6 +12,7 @@ import {reducers,selectors,} from 'kea'+import { loaders } from 'kea-loaders'import { FEATURE_FLAGS } from 'lib/constants'import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'@@ -35,7 +36,14 @@ import {UniversalFiltersGroupValue,} from '~/types'-import { experimentsSessionContextsCreate } from 'products/experiments/frontend/generated/api'+import {+ experimentsSessionBucketsCreate,+ experimentsSessionContextsCreate,+} from 'products/experiments/frontend/generated/api'+import type {+ ExperimentSessionBucketResponseApi,+ ExperimentSessionBucketEnumApi,+} from 'products/experiments/frontend/generated/api.schemas'import type { ExperimentIdType } from '../../../types'import type { ExperimentSavedMetric } from '../experimentLogic'@@ -44,6 +52,7 @@ import {applySessionLinkability,getExperimentVariants,getExposureFallbackFilter,+ getFunnelDropoffReason,getMetricSessionFilters,getViewRecordingFiltersForVariant,isUnlinkableEventFilter,@@ -67,11 +76,69 @@ export interface ExperimentReplayMetricOption {unlinkable: boolean/** Why the metric can't narrow the playlist, shown alongside it. Null when it can. */unlinkableReason: string | null+ /** Why drop-off can't be asked of this metric, shown alongside it. Null when it can. */+ dropoffReason: string | null+ /** The events the metric counts, deduped — a metric's name rarely says which they are. */+ eventNames: string[]+}++/**+ * How the selected metrics narrow the list.+ *+ * `fired_all` composes event filters client-side and is uncapped. The other three are server+ * computed: the recordings query carries one operator for its whole filter tree, so an OR, an+ * absence, and a drop-off can only come back as an explicit session-id list — which the endpoint+ * bounds, so those modes show a capped, most-recent-first slice.+ */+export type ExperimentReplayMetricFilterMode = 'fired_all' | 'fired_any' | 'no_metric_activity' | 'funnel_dropoff'++/** What the tab asks the bucket endpoint for, and the spec a loaded response belongs to. */+export interface ExperimentSessionBucketRequest {+ bucket: ExperimentSessionBucketEnumApi+ metric_uuids: string[]+ variant: string | null+}++export interface ExperimentSessionBucket {+ request: ExperimentSessionBucketRequest+ response: ExperimentSessionBucketResponseApi}// Mirrors the backend's MAX_SESSION_CONTEXT_BATCH — ids beyond it would 400 the whole batch.const SESSION_CONTEXT_PREFETCH_LIMIT = 20+/**+ * Sort metrics the way the experiment's metrics page lists them. The ordering arrays are that+ * page's display order, and every metric uuid is meant to be in one of them — but only sorting+ * on them, never filtering, so a metric missing from the arrays still shows up (last) rather+ * than vanishing from the filter with no trace.+ */+function metricDisplayOrder(experiment: Experiment): (a: { uuid: string }, b: { uuid: string }) => number {+ const order = [+ ...(experiment.primary_metrics_ordered_uuids || []),+ ...(experiment.secondary_metrics_ordered_uuids || []),+ ]+ const rank = (uuid: string): number => {+ const index = order.indexOf(uuid)+ // Not MAX_SAFE_INTEGER arithmetic on both sides — equal ranks must subtract to 0 so the+ // sort stays stable and unlisted metrics keep their existing relative order.+ return index === -1 ? order.length : index+ }+ return (a, b) => rank(a.uuid) - rank(b.uuid)+}++/**+ * The distinct events a metric counts. A metric's name is free text ("Rageclicks per user"), so+ * on its own it doesn't say what a session has to have fired to match.+ */+function metricSourceEventNames(metric: ExperimentMetric): string[] {+ const names = getMetricSessionFilters(metric)+ // Only entity filters name an event; a nested filter group (which the type allows) doesn't.+ .flatMap((filter) => ('id' in filter ? [String(filter.name ?? filter.id ?? '')] : []))+ .filter(Boolean)+ return [...new Set(names)]+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface experimentReplayTabLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogic@@ -79,14 +146,20 @@ export interface experimentReplayTabLogicValues {linkabilityLoaded: boolean // viewRecordingsLinkabilityLogicseenTogetherMapLoading: boolean // viewRecordingsLinkabilityLogicunlinkableEventNames: Set<string> // viewRecordingsLinkabilityLogic+ bucketSessionIds: string[] | undefinedeffectiveMetricUuids: string[]effectiveVariantKey: string | nullexposureUnlinkable: booleanloadedSessionIds: string[]+ metricFilterMode: ExperimentReplayMetricFilterModemetricOptions: ExperimentReplayMetricOption[]recordingsFilters: RecordingUniversalFiltersselectedMetricUuids: string[]selectedVariantKey: string | null+ sessionBucket: ExperimentSessionBucket | null+ sessionBucketError: string | null+ sessionBucketLoading: boolean+ sessionBucketRequest: ExperimentSessionBucketRequest | nullusingExposureFallback: booleanvariantKeys: string[]}@@ -96,6 +169,30 @@ export interface experimentReplayTabLogicActions {setDefaultTab: (tab: SessionRecordingSidebarTab) => {tab: SessionRecordingSidebarTab} // playerSidebarLogic+ loadSessionBucket: (_?: unknown) => unknown+ loadSessionBucketFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSessionBucketSuccess: (+ sessionBucket: {+ request: ExperimentSessionBucketRequest+ response: ExperimentSessionBucketResponseApi+ } | null,+ payload?: unknown+ ) => {+ sessionBucket: {+ request: ExperimentSessionBucketRequest+ response: ExperimentSessionBucketResponseApi+ } | null+ payload?: unknown+ }+ playlistFiltersChanged: (filters: RecordingUniversalFilters) => {+ filters: RecordingUniversalFilters+ }prefetchSessionContexts: (sessionIds: string[]) => {sessionIds: string[]}@@ -105,6 +202,9 @@ export interface experimentReplayTabLogicActions {recordingsLoaded: (sessionIds: string[]) => {sessionIds: string[]}+ setMetricFilterMode: (mode: ExperimentReplayMetricFilterMode) => {+ mode: ExperimentReplayMetricFilterMode+ }setMetricSelected: (metricUuid: string,selected: boolean@@ -130,13 +230,30 @@ export interface experimentReplayTabLogicMeta {unlinkableEventNames: Set<string>,arg: any) => ExperimentReplayMetricOption[]- effectiveMetricUuids: (selectedMetricUuids: string[], metricOptions: ExperimentReplayMetricOption[]) => string[]+ effectiveMetricUuids: (+ selectedMetricUuids: string[],+ metricOptions: ExperimentReplayMetricOption[],+ metricFilterMode: ExperimentReplayMetricFilterMode+ ) => string[]+ sessionBucketRequest: (+ metricFilterMode: ExperimentReplayMetricFilterMode,+ effectiveMetricUuids: string[],+ effectiveVariantKey: string | null,+ exposureUnlinkable: boolean,+ metricOptions: ExperimentReplayMetricOption[]+ ) => ExperimentSessionBucketRequest | null+ bucketSessionIds: (+ sessionBucketRequest: ExperimentSessionBucketRequest | null,+ sessionBucket: ExperimentSessionBucket | null,+ sessionBucketError: string | null+ ) => string[] | undefinedrecordingsFilters: (effectiveVariantKey: string | null,effectiveMetricUuids: string[],metricOptions: ExperimentReplayMetricOption[],unlinkableEventNames: Set<string>,seenTogetherMapLoading: boolean,+ bucketSessionIds: string[] | undefined,arg: any) => RecordingUniversalFilters}@@ -174,10 +291,34 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([actions({setSelectedVariantKey: (variantKey: string | null) => ({ variantKey }),setMetricSelected: (metricUuid: string, selected: boolean) => ({ metricUuid, selected }),+ setMetricFilterMode: (mode: ExperimentReplayMetricFilterMode) => ({ mode }),+ playlistFiltersChanged: (filters: RecordingUniversalFilters) => ({ filters }),recordingsLoaded: (sessionIds: string[]) => ({ sessionIds }),recordingOpened: (sessionId: string) => ({ sessionId }),prefetchSessionContexts: (sessionIds: string[]) => ({ sessionIds }),}),+ loaders(({ values, props }) => ({+ sessionBucket: [+ null as ExperimentSessionBucket | null,+ {+ loadSessionBucket: async (_: unknown = null, breakpoint) => {+ const request = values.sessionBucketRequest+ if (!request) {+ return null+ }+ // Debounce the checkbox churn of picking several metrics in a row.+ await breakpoint(300)+ const response = await experimentsSessionBucketsCreate(+ String(values.currentProjectId),+ Number(props.experiment.id),+ request+ )+ breakpoint()+ return { request, response }+ },+ },+ ],+ })),reducers({// null = "All" (every exposed session, regardless of variant). Persisted (keyed per// experiment via the logic path) so the facet stays in step with the playlist across tab@@ -203,6 +344,15 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([: state.filter((uuid) => uuid !== metricUuid),},],+ // Persisted with the facets it composes with. 'fired_all' keeps the client-side event+ // filters; the other modes hand the list over to the bucket endpoint.+ metricFilterMode: [+ 'fired_all' as ExperimentReplayMetricFilterMode,+ { persist: true },+ {+ setMetricFilterMode: (_, { mode }) => mode,+ },+ ],// The playlist's most recently loaded page, kept so opening a recording can re-warm// the rest of the page's contexts.loadedSessionIds: [@@ -211,6 +361,18 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([recordingsLoaded: (_, { sessionIds }) => sessionIds,},],+ // A failed bucket must not silently fall back to the unbucketed list: the label would+ // then describe a population the list isn't showing. The message is kept because a+ // rejected request is usually actionable ("takes exactly one funnel metric") — a generic+ // failure line hides that from the user and the cause from us.+ sessionBucketError: [+ null as string | null,+ {+ loadSessionBucket: () => null,+ loadSessionBucketSuccess: () => null,+ loadSessionBucketFailure: (_, { error, errorObject }) => errorObject?.detail || error || 'unknown',+ },+ ],}),selectors({variantKeys: [@@ -282,6 +444,11 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([uuid: metric.uuid,name: metric.name || getDefaultMetricTitle(metric),filters: getMetricSessionFilters(metric),+ dropoffReason: getFunnelDropoffReason(+ metric,+ linkabilityLoaded ? unlinkableEventNames : new Set<string>()+ ),+ eventNames: metricSourceEventNames(metric),noFilterReason: isExperimentRetentionMetric(metric)? RETENTION_UNLINKABLE_REASON: DATA_WAREHOUSE_UNLINKABLE_REASON,@@ -296,6 +463,7 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([seenUuids.add(option.uuid)return true})+ .sort(metricDisplayOrder(experiment)).map(({ noFilterReason, ...option }) => {const unlinkableReason =option.filters.length === 0@@ -311,12 +479,96 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([},],effectiveMetricUuids: [- (s) => [s.selectedMetricUuids, s.metricOptions],- (selectedMetricUuids: string[], metricOptions: ExperimentReplayMetricOption[]): string[] =>- selectedMetricUuids.filter((uuid) => {+ (s) => [s.selectedMetricUuids, s.metricOptions, s.metricFilterMode],+ (+ selectedMetricUuids: string[],+ metricOptions: ExperimentReplayMetricOption[],+ metricFilterMode: ExperimentReplayMetricFilterMode+ ): string[] => {+ const selectable = selectedMetricUuids.filter((uuid) => {const option = metricOptions.find((candidate) => candidate.uuid === uuid)- return !!option && !option.unlinkable- }),+ if (!option || option.unlinkable) {+ return false+ }+ return metricFilterMode !== 'funnel_dropoff' || option.dropoffReason === null+ })+ // Selections persist across mode switches, so a mode that takes exactly one metric+ // keeps the most recently picked rather than rejecting the whole selection.+ return metricFilterMode === 'funnel_dropoff' ? selectable.slice(-1) : selectable+ },+ ],+ /**+ * Null whenever the client-side event filters express the question exactly, so the list+ * keeps its uncapped path: no metric selected, and any "fired all" of several metrics+ * (ANDing filters is the one thing a recordings query can do).+ *+ * One selected metric is the interesting case. "Fired all of it" and "fired any of it"+ * are the same question, so both take the same path — the client filter when the metric+ * counts a single event (exact and uncapped), the endpoint when it counts several. A+ * recordings query can't OR within a metric, so on a ratio or funnel the client filter+ * silently matches the primary event only.+ */+ sessionBucketRequest: [+ (s) => [+ s.metricFilterMode,+ s.effectiveMetricUuids,+ s.effectiveVariantKey,+ s.exposureUnlinkable,+ s.metricOptions,+ ],+ (+ metricFilterMode: ExperimentReplayMetricFilterMode,+ effectiveMetricUuids: string[],+ effectiveVariantKey: string | null,+ exposureUnlinkable: boolean,+ metricOptions: ExperimentReplayMetricOption[]+ ): ExperimentSessionBucketRequest | null => {+ if (exposureUnlinkable) {+ return null+ }+ const request = (bucket: ExperimentSessionBucketEnumApi): ExperimentSessionBucketRequest => ({+ bucket,+ metric_uuids: effectiveMetricUuids,+ variant: effectiveVariantKey,+ })+ if (metricFilterMode === 'funnel_dropoff') {+ return effectiveMetricUuids.length === 1 ? request('funnel_dropoff') : null+ }+ if (metricFilterMode === 'no_metric_activity') {+ // Absence without a selection legitimately means every matchable metric.+ return request('no_metric_activity')+ }+ if (effectiveMetricUuids.length === 0) {+ // "Fired any of nothing" has no answer.+ return null+ }+ if (effectiveMetricUuids.length > 1) {+ return metricFilterMode === 'fired_any' ? request('fired_any') : null+ }+ const only = metricOptions.find((option) => option.uuid === effectiveMetricUuids[0])+ return (only?.eventNames.length ?? 0) > 1 ? request('fired_any') : null+ },+ ],+ // Undefined = no bucket, so the playlist keeps its own (uncapped) population. An empty+ // list is a real answer: nothing matched, or the request is still in flight — never a+ // silent widening to the unbucketed list.+ bucketSessionIds: [+ (s) => [s.sessionBucketRequest, s.sessionBucket, s.sessionBucketError],+ (+ sessionBucketRequest: ExperimentSessionBucketRequest | null,+ sessionBucket: ExperimentSessionBucket | null,+ sessionBucketError: string | null+ ): string[] | undefined => {+ if (!sessionBucketRequest) {+ return undefined+ }+ if (sessionBucketError !== null || !sessionBucket) {+ return []+ }+ // The last loaded set is kept while a new one loads, so changing a facet doesn't+ // blank the list — it is replaced once the new answer arrives.+ return sessionBucket.response.session_ids+ },],recordingsFilters: [(s) => [@@ -325,6 +577,7 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([s.metricOptions,s.unlinkableEventNames,s.seenTogetherMapLoading,+ s.bucketSessionIds,(_, props) => props.experiment,],(@@ -333,6 +586,7 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([metricOptions: ExperimentReplayMetricOption[],unlinkableEventNames: Set<string>,seenTogetherMapLoading: boolean,+ bucketSessionIds: string[] | undefined,experiment: Experiment): RecordingUniversalFilters => {// A recordings query carries a single AND/OR operand across the whole flattened@@ -350,23 +604,26 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([// *fails*, loading ends with an empty unlinkable set and the filters apply — the// fail-open posture every linkability consumer shares.const seenFilters = new Set<string>()- const metricFilters = seenTogetherMapLoading- ? []- : effectiveMetricUuids- .map((uuid) => {- const linkable = (- metricOptions.find((option) => option.uuid === uuid)?.filters ?? []- ).filter((filter) => !isUnlinkableEventFilter(filter, unlinkableEventNames))- return linkable[0]- })- .filter((filter): filter is UniversalFiltersGroupValue => {- // Two metrics can share a primary event; the duplicate filter adds nothing.- if (!filter || seenFilters.has(JSON.stringify(filter))) {- return false- }- seenFilters.add(JSON.stringify(filter))- return true- })+ const metricFilters =+ seenTogetherMapLoading || bucketSessionIds !== undefined+ ? // A bucket already encodes the metric condition in the session set it+ // returns, so also ANDing the event filters would narrow it a second time.+ []+ : effectiveMetricUuids+ .map((uuid) => {+ const linkable = (+ metricOptions.find((option) => option.uuid === uuid)?.filters ?? []+ ).filter((filter) => !isUnlinkableEventFilter(filter, unlinkableEventNames))+ return linkable[0]+ })+ .filter((filter): filter is UniversalFiltersGroupValue => {+ // Two metrics can share a primary event; the duplicate filter adds nothing.+ if (!filter || seenFilters.has(JSON.stringify(filter))) {+ return false+ }+ seenFilters.add(JSON.stringify(filter))+ return true+ })// When the default exposure event can't match sessions, the fallback filter on// `$feature/<flag_key>` takes its place (see `getExposureFallbackFilter`). While// the check is in flight the unlinkable set is empty, so the exposure filter@@ -378,6 +635,10 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([).filtersreturn {...DEFAULT_RECORDING_FILTERS,+ // The exposure filter stays in place alongside the bucket: the returned ids are+ // a subset of the exposed sessions, so this only keeps the list's definition+ // visible in the filter UI.+ session_ids: bucketSessionIds,date_from: experiment.start_date ?? DEFAULT_RECORDING_FILTERS.date_from,date_to: experiment.end_date ?? null,filter_test_accounts: experiment.exposure_criteria?.filterTestAccounts ?? false,@@ -395,6 +656,36 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([],}),listeners(({ values, actions, cache }) => ({+ // Every facet the bucket is keyed on re-asks for it. Listening to the actions rather than+ // subscribing to the spec keeps this off the redux subscription path.+ setMetricFilterMode: () => {+ actions.loadSessionBucket()+ },+ setMetricSelected: () => {+ if (values.sessionBucketRequest) {+ actions.loadSessionBucket()+ }+ },+ setSelectedVariantKey: () => {+ if (values.sessionBucketRequest) {+ actions.loadSessionBucket()+ }+ },+ // 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+ // ids of its own: a mode with nothing to filter on yet (no eligible metric selected)+ // pushes no session_ids either, and reading that back as a clear would bounce the mode+ // to 'fired_all' the moment it was picked.+ playlistFiltersChanged: ({ filters }) => {+ if (+ values.metricFilterMode !== 'fired_all' &&+ filters.session_ids === undefined &&+ values.bucketSessionIds !== undefined+ ) {+ actions.setMetricFilterMode('fired_all')+ }+ },// Prefetch experiment context for the freshly loaded page of recordings, so opening// any of them renders the player's experiments box straight from the server-side// cache. A session's context is independent of the list filters (it's per@@ -439,9 +730,14 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([}},})),- afterMount(({ actions }) => {+ afterMount(({ values, actions }) => {actions.setDefaultTab(SessionRecordingSidebarTab.OVERVIEW)+ // The mode persists, so a tab reopened in a bucket needs its session set again.+ if (values.sessionBucketRequest) {+ actions.loadSessionBucket()+ }+// Opening the tab is a session-replay cross-sell from experiments.void addProductIntentForCrossSell({from: ProductKey.EXPERIMENTS,diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.tsindex 46182dd4b337..e38b18119d0f 100644--- a/frontend/src/scenes/experiments/utils.ts+++ b/frontend/src/scenes/experiments/utils.ts@@ -411,6 +411,40 @@ export function getMetricSessionFilters(metric: ExperimentMetric): UniversalFilt.filter((filter): filter is UniversalFiltersGroupValue => filter !== null)}+export const NOT_A_FUNNEL_REASON =+ 'This filter compares a funnel’s first and last step, so it needs a funnel metric with at least two steps that can be matched to recordings.'++export const FUNNEL_SERVER_SIDE_BOUNDARY_REASON =+ "This filter compares a funnel's first and last step. One of them is captured server-side without a session ID, so recordings can't be matched."++export const FUNNEL_DATA_WAREHOUSE_BOUNDARY_REASON =+ "This filter compares a funnel's first and last step. One of them is measured in the data warehouse, which has no session events to match recordings on."++/**+ * Why drop-off can't be asked of this metric, or null when it can. It compares the funnel's first+ * step against its last, so both of those have to be matchable — which the whole-metric+ * linkability check can't stand in for, since a funnel stays matchable on the steps between them.+ * Mirrors the `session_buckets` endpoint, which refuses the same shapes rather than counting a+ * completion no recording can show as zero in every session.+ */+export function getFunnelDropoffReason(metric: ExperimentMetric, unlinkableEventNames: Set<string>): string | null {+ if (!isExperimentFunnelMetric(metric) || getMetricSessionFilters(metric).length < 2) {+ return NOT_A_FUNNEL_REASON+ }+ const boundaries = [metric.series[0], metric.series[metric.series.length - 1]]+ if (boundaries.some((step) => step.kind === NodeKind.ExperimentDataWarehouseNode)) {+ return FUNNEL_DATA_WAREHOUSE_BOUNDARY_REASON+ }+ if (+ boundaries.some(+ (step) => step.kind === NodeKind.EventsNode && step.event && unlinkableEventNames.has(step.event)+ )+ ) {+ return FUNNEL_SERVER_SIDE_BOUNDARY_REASON+ }+ return null+}+/*** Whether a recordings event filter can only match zero sessions: the project has never seen the* event with a `$session_id` (e.g. it is captured server-side). Action and data warehouse filtersdiff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex ae753fa31d77..b5d8c7e7ad24 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -533,6 +533,20 @@ class SessionContextsSustainedRateThrottle(_TeamBucketRateThrottle):rate = "600/hour"+# The experiment session-bucket endpoint scans every session in an experiment's recent run+# window rather than a known id list, so one call is heavier than a session-context batch. Same+# project-wide bucketing and same session-authenticated caller as those, at a lower rate: the UI+# fires at most one per filter change (debounced), and repeats hit the server-side cache.+class SessionBucketsBurstRateThrottle(_TeamBucketRateThrottle):+ scope = "session_buckets_burst"+ rate = "20/minute"+++class SessionBucketsSustainedRateThrottle(_TeamBucketRateThrottle):+ scope = "session_buckets_sustained"+ rate = "200/hour"++class _AIThrottleBase(UserRateThrottle):action_name: strdiff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 1b7562fdf634..00edcfcec79b 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -641,6 +641,8 @@ SPECTACULAR_SETTINGS = {"TargetTypeEnum": "products.exports.backend.models.subscription.Subscription.SubscriptionTarget",# --- Inline value lists (type-hint enums, no x-spec-enum-id) ---"PropertyGroupOperator": ["AND", "OR"],+ # `bucket` is a generic field name; name the experiment recordings bucket set explicitly.+ "ExperimentSessionBucketEnum": ["fired_any", "no_metric_activity", "funnel_dropoff"],# Account.slack_summary_cadence and AccountChannelSummary.cadence share the same# daily/weekly/monthly choice set; pin one name for both."SlackSummaryCadenceEnum": ["daily", "weekly", "monthly"],diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex d5482bdab06e..9efdcb5a661c 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -107,7 +107,6 @@ from products.notifications.backend.facade.api import (from products.tasks.backend.facade import api as tasks_facadefrom ee.clickhouse.views.experiment_saved_metrics import ExperimentToSavedMetricSerializer-from ee.hogai.context.experiment.format import ExperimentTimeseriesFormatterlogger = structlog.get_logger(__name__)@@ -3903,6 +3902,10 @@ class ExperimentService:"recalculation_status": active_recalculation.status if active_recalculation else None,"recalculation_created_at": active_recalculation.created_at.isoformat() if active_recalculation else None,}+ from ee.hogai.context.experiment.format import (+ ExperimentTimeseriesFormatter, # noqa: PLC0415 — keeps the heavy ee.hogai/langgraph chain off the import path+ )+response["formatted_results"] = ExperimentTimeseriesFormatter(response).format()return responsediff --git a/products/experiments/backend/metric_events.py b/products/experiments/backend/metric_events.pyindex 290614b084d5..30aeedc64bef 100644--- a/products/experiments/backend/metric_events.py+++ b/products/experiments/backend/metric_events.py@@ -172,7 +172,7 @@ class MetricScanResult:dropped_metric_uuids: set[str]-def _node_signature(node: MetricSourceNode | ExperimentDataWarehouseNode) -> str:+def node_signature(node: MetricSourceNode | ExperimentDataWarehouseNode) -> str:"""A stable identity for a source node. Two nodes with the same signature match the same eventsand share one aggregate in the scan, so they can only ever render identical hits."""return node.model_dump_json(exclude_none=True)@@ -199,7 +199,7 @@ def _metric_sources(sources: list[tuple[MetricSourceRole, MetricSourceNode | ExperimentDataWarehouseNode]] = [(MetricSourceRole.RETENTION_START, metric.start_event)]- if _node_signature(metric.completion_event) != _node_signature(metric.start_event):+ if node_signature(metric.completion_event) != node_signature(metric.start_event):sources.append((MetricSourceRole.RETENTION_COMPLETION, metric.completion_event))return sources@@ -270,7 +270,7 @@ def resolve_metric_events(experiment: Experiment) -> list[MetricEventSource]:return metric_sources-def _node_condition(node: MetricSourceNode, team: Team) -> ast.Expr:+def build_source_condition(node: MetricSourceNode, team: Team) -> ast.Expr:"""Match expression for one source node, built on `event_or_action_to_filter` — the samematcher the experiment analysis uses, so what counts as "this metric's event" cannotdiverge between the analysis and this surface. `fixedProperties` are ANDed on top: the@@ -341,7 +341,7 @@ def scan_sessions_for_metric_events(skipped_breakdown_sources = 0def node_key(source: MetricSource) -> str:- return _node_signature(source.node)+ return node_signature(source.node)def metric_group_key(metric_source: MetricEventSource) -> tuple[str, ...]:# Distinct nodes only, so a ratio measuring the same event on both sides is one aggregate.@@ -366,7 +366,7 @@ def scan_sessions_for_metric_events(seen_uuids.add(metric_source.metric_uuid)accepted.append(metric_source)for source in metric_source.sources:- conditions_by_node.setdefault(node_key(source), _node_condition(source.node, team))+ conditions_by_node.setdefault(node_key(source), build_source_condition(source.node, team))# Every metric's own totals group is registered first and uncapped — it is bounded by# MAX_SCANNED_METRICS, so it never competes for the ceiling. Only the per-source breakdown isdiff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 9a4e8fa35b4e..629a6b619371 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -43,6 +43,7 @@ from products.experiments.backend.models.experiment import (experiment_has_legacy_metrics,)from products.experiments.backend.running_time_calculator import METRIC_TYPE_CHOICES+from products.experiments.backend.session_buckets import MAX_BUCKET_SCAN_DAYS, MAX_SESSION_BUCKET_LIMIT, SessionBucketfrom products.experiments.backend.session_context import MAX_SESSION_CONTEXT_BATCHfrom products.feature_flags.backend.api.feature_flag import MinimalFeatureFlagSerializerfrom products.feature_flags.backend.models.feature_flag import FeatureFlag, experiment_eligibility_error@@ -1686,3 +1687,129 @@ class ExperimentSessionContextsResponseSerializer(serializers.Serializer):"single-session endpoint."),)+++class ExperimentSessionBucketRequestSerializer(serializers.Serializer):+ """Request body for the session-bucket endpoint."""++ bucket = serializers.ChoiceField(+ choices=[bucket.value for bucket in SessionBucket],+ help_text=(+ "Which question the returned session set answers. 'fired_any': the session fired at least one event "+ "of any listed metric (an OR the recordings query itself can't express). 'no_metric_activity': the "+ "session fired none of them. 'funnel_dropoff': the session fired the funnel metric's first step and "+ "never reached its last one. All three are session-scoped and goal-free: they say what happened in "+ "the session, not whether it helped or hurt the metric."+ ),+ )+ metric_uuids = serializers.ListField(+ child=serializers.CharField(allow_blank=False, help_text="UUID of one of the experiment's metrics."),+ required=False,+ default=list,+ help_text=(+ "Metrics the bucket is computed over. Exactly one funnel metric for 'funnel_dropoff'. Omit for the "+ "other buckets to use every metric of the experiment that can be matched to recordings."+ ),+ )+ variant = serializers.CharField(+ required=False,+ allow_null=True,+ default=None,+ help_text=(+ "Restrict to sessions that saw this variant. Omit for every variant. A session that saw more than "+ "one variant matches each variant it saw."+ ),+ )+ limit = serializers.IntegerField(+ required=False,+ default=MAX_SESSION_BUCKET_LIMIT,+ min_value=1,+ max_value=MAX_SESSION_BUCKET_LIMIT,+ help_text=(+ f"Maximum session IDs to return, at most {MAX_SESSION_BUCKET_LIMIT}. The most recently active "+ "matching sessions win."+ ),+ )++ def validate(self, attrs: dict) -> dict:+ if attrs["bucket"] == SessionBucket.FUNNEL_DROPOFF and len(attrs.get("metric_uuids") or []) != 1:+ raise serializers.ValidationError(+ {"metric_uuids": ["The drop-off bucket takes exactly one funnel metric."]}+ )+ return attrs+++class ExperimentSessionBucketMetricSerializer(serializers.Serializer):+ """One metric the bucket was computed over."""++ metric_uuid = serializers.CharField(help_text="UUID of the experiment metric.")+ metric_name = serializers.CharField(+ help_text="Display name of the metric, or an event-derived title (matching the experiment UI) when unnamed."+ )+++class ExperimentSessionBucketExcludedMetricSerializer(serializers.Serializer):+ """One requested metric the bucket could not be computed over."""++ metric_uuid = serializers.CharField(help_text="UUID of the experiment metric.")+ metric_name = serializers.CharField(help_text="Display name of the metric.")+ reason = serializers.CharField(+ help_text=(+ "Why the metric can't be matched to recordings: a data-warehouse-only source, a retention window, "+ "or events only ever captured server-side."+ )+ )+++class ExperimentSessionBucketResponseSerializer(serializers.Serializer):+ """Session recordings of an experiment matching a bucket."""++ session_ids = serializers.ListField(+ child=serializers.CharField(),+ help_text=(+ "IDs of matching sessions that have a recording, most recently active first. Feed these to a "+ "recordings query as session_ids; they are a subset of the experiment's exposed sessions, so the "+ "exposure filter can stay in place alongside them."+ ),+ )+ truncated = serializers.BooleanField(+ help_text="True when more sessions matched than the limit returned. Older matches were dropped first."+ )+ considered_metrics = ExperimentSessionBucketMetricSerializer(+ many=True,+ help_text=(+ "The metrics the bucket was actually computed over. Load-bearing for 'no_metric_activity': "+ "'fired nothing' only means something next to the list of metrics it was evaluated against."+ ),+ )+ excluded_metrics = ExperimentSessionBucketExcludedMetricSerializer(+ many=True,+ help_text=(+ "Requested metrics left out of the bucket because they can never match a recording, with the reason. "+ "They are reported rather than silently producing an empty result."+ ),+ )+ date_from = serializers.DateTimeField(+ help_text=(+ f"Start of the window scanned: the experiment's run window, clamped to its most recent "+ f"{MAX_BUCKET_SCAN_DAYS} days. Matches outside it are not returned."+ )+ )+ date_to = serializers.DateTimeField(+ help_text="End of the window scanned: the experiment's end date, or now while it runs."+ )+ filter_test_accounts = serializers.BooleanField(+ help_text=(+ "Whether the project's test-account filters were applied, following the experiment's exposure "+ "criteria, the same rule the experiment's recordings list uses."+ )+ )+ used_exposure_fallback = serializers.BooleanField(+ help_text=(+ "True when the exposed population was matched on the stamped $feature/<flag key> event property "+ "instead of the exposure event, because the default exposure event has only ever been captured "+ "server-side and can never match a session. The sessions then mean 'the flag was active in this "+ "session', not 'the exposure moment was captured'. The variant comes from the flag's value on each "+ "event, so a returning user can appear under a variant they were re-bucketed into later."+ )+ )diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex ffb833a1dcdc..5cb855ae48af 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -38,6 +38,8 @@ from posthog.permissions import is_service_authfrom posthog.rate_limit import (ClickHouseBurstRateThrottle,ClickHouseSustainedRateThrottle,+ SessionBucketsBurstRateThrottle,+ SessionBucketsSustainedRateThrottle,SessionContextsBurstRateThrottle,SessionContextsSustainedRateThrottle,)@@ -72,6 +74,8 @@ from products.experiments.backend.presentation.serializers import (ExperimentFlagCleanupTaskSerializer,ExperimentMetricsRecalculationSerializer,ExperimentSerializer,+ ExperimentSessionBucketRequestSerializer,+ ExperimentSessionBucketResponseSerializer,ExperimentSessionContextResponseSerializer,ExperimentSessionContextsRequestSerializer,ExperimentSessionContextsResponseSerializer,@@ -98,6 +102,12 @@ from products.experiments.backend.running_time_calculator import (calculate_variance,calculate_variance_from_stats,)+from products.experiments.backend.session_buckets import (+ SessionBucket,+ SessionBucketUnavailable,+ finalize_session_bucket,+ get_experiment_session_bucket,+)from products.experiments.backend.session_context import get_session_experiment_context, get_session_experiment_contextsfrom products.experiments.backend.temporal.models import (ExperimentMetricsRecalculationWorkflowInputs as MetricsRecalcInputs,@@ -1403,6 +1413,64 @@ class EnterpriseExperimentsViewSet()return Response(serializer.data)+ @validated_request(+ request_serializer=ExperimentSessionBucketRequestSerializer,+ responses={200: OpenApiResponse(response=ExperimentSessionBucketResponseSerializer)},+ )+ @action(+ methods=["POST"],+ detail=True,+ url_path="session_buckets",+ required_scopes=["experiment:read", "session_recording:read"],+ # Heavier than the session-context batch (it scans the run window rather than a known id+ # list) and called by the session-authenticated web app, which the ClickHouse* pair+ # doesn't cover.+ throttle_classes=[SessionBucketsBurstRateThrottle, SessionBucketsSustainedRateThrottle],+ )+ def session_buckets(self, request: ValidatedRequest, **kwargs: Any) -> Response:+ """Session recordings of this experiment matching a bucket.++ Answers the questions a recordings query can't express on its own — "fired any of these+ metrics", "fired none of them", "entered the funnel but never completed it in this+ session" — by returning a bounded, most-recent-first list of session IDs to pass back as+ a recordings query's session_ids. POST because the metric list doesn't fit a query+ string; the endpoint only reads.++ Session-scoped and goal-free: the set describes what happened in each session, while the+ experiment analysis counts per person over the whole run window. A session can be in the+ drop-off bucket while the same person converts in a later one.+ """+ experiment: Experiment = self.get_object()++ if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):+ raise PermissionDenied("Reading experiment session buckets requires session replay access.")++ try:+ scan = get_experiment_session_bucket(+ team=self.team,+ # user threads through to the HogQL query: metric sources and exposure criteria+ # can filter on arbitrary properties, which must respect the viewer's+ # property-level access control.+ user=cast(User, request.user),+ experiment=experiment,+ bucket=SessionBucket(request.validated_data["bucket"]),+ metric_uuids=request.validated_data["metric_uuids"],+ variant=request.validated_data["variant"],+ limit=request.validated_data["limit"],+ )+ except SessionBucketUnavailable as error:+ raise ValidationError(str(error))++ # Applied to the computed set rather than inside the scan: the bucket is cached per+ # viewer, so filtering on read honors a revocation that lands while an entry is warm. The+ # cut to `limit` follows it, so a denied recording never spends a returned slot and+ # `truncated` describes what this viewer may see.+ result = finalize_session_bucket(+ scan,+ _accessible_session_ids(request, self.user_access_control, self.team, scan.candidate_session_ids),+ )+ return Response(ExperimentSessionBucketResponseSerializer(result).data)+def _serialize_recalculation(recalc: ExperimentMetricsRecalculation, active_run: dict | None = None) -> dict:results = get_run_results(recalc)diff --git a/products/experiments/backend/session_buckets.py b/products/experiments/backend/session_buckets.pynew file mode 100644index 000000000000..6507d58d8da4--- /dev/null+++ b/products/experiments/backend/session_buckets.py@@ -0,0 +1,660 @@+"""Compute a bounded session-id list for one experiment's recordings tab.++A recordings query carries a single AND/OR operator across its whole filter tree, so the tab+can only ask "fired every one of these metrics". Three questions it cannot express client-side+are answered here instead — "fired any of these", "fired none of them", and "entered the funnel+but never completed it in this session" — by computing the matching session ids server-side and+feeding them to the playlist as `RecordingsQuery.session_ids`.++Buckets are goal-free: they say what happened in the session, never whether it helped or hurt a+metric. The analysis counts per person over the whole run window, while a recording is one+session of one person, so copy built on this must stay session-scoped ("in this session") and+must never claim the analysis counted or discounted anyone.++The population is the same session-scoped exposure evidence the tab's own list is built from —+an event matching the experiment's exposure criteria, carrying one of the flag's defined+variants. Not the exposure query's `exposure_session_id`, which is the person's *first*+exposure session only: the playlist ANDs these ids with its own exposure filter, so ids it+would reject are wasted slots out of the cap, and the later sessions `exposure_session_id`+omits are exactly where drop-off and conversion happen. `exposure_session_id` is the right+source for a future person-scoped bucket, not for a session-scoped one.++Whether an event can match sessions at all is decided here, from the same `EventProperty` fact+the taxonomy `seen_together` endpoint serves the tab: an event never ingested with a+`$session_id` (backend-fired exposure, server-side metrics) can only ever match zero sessions.+For the default exposure event the population falls back to the stamped `$feature/<flag_key>`+property — the same fallback the tab's list uses — flagged in the response as+`used_exposure_fallback`. Custom criteria get no such stand-in: they assert that something+specific happened, which the stamped property doesn't imply, so a custom exposure event that+can't be matched is refused with a reason rather than answered over a wider population.+Metrics whose every source is such an event are excluded with a reason instead of silently+matching nothing, which for `no_metric_activity` would otherwise inflate the bucket to the whole+exposed population. Drop-off narrows that rule to the two steps it reads: a funnel stays+matchable overall while its first or last step can't be seen in a recording, and counting an+unobservable completion as zero would return everyone who entered.+"""++import json+import hashlib+import logging+from dataclasses import dataclass+from datetime import datetime, timedelta+from enum import StrEnum+from typing import Optional++from django.db import models+from django.db.models.functions import Coalesce+from django.utils import timezone++from posthog.schema import EventsNode++from posthog.hogql import ast+from posthog.hogql.database.database import Database+from posthog.hogql.modifiers import create_default_modifiers_for_team+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.models import EventProperty+from posthog.models.team.team import Team+from posthog.models.user import User+from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents+from posthog.utils import get_safe_cache, safe_cache_set++from products.access_control.backend.property_access_control import get_restricted_properties_for_team+from products.experiments.backend.hogql_queries.exposure_query_logic import (+ DEFAULT_EXPOSURE_EVENT,+ build_exposure_event_conditions,+ get_exposure_event_and_property,+ get_test_accounts_filter,+ normalize_to_exposure_criteria,+)+from products.experiments.backend.metric_events import (+ MetricEventSource,+ MetricSource,+ MetricSourceRole,+ SharedHogQLDatabase,+ build_source_condition,+ node_signature,+ resolve_metric_events,+)+from products.experiments.backend.models.experiment import Experiment++logger = logging.getLogger(__name__)++# Ceiling on returned session ids. The recordings list is fetched over GET, so the ids ride in a+# query string: ~45 encoded characters each puts 100 ids at ~4.5 KB, with headroom under the 8 KB+# request-line limits proxies commonly enforce. Doubling it would not.+MAX_SESSION_BUCKET_LIMIT = 100+# The scan reads every session in the window, not a known id list, so the window is what bounds+# it. Recency-ordered output capped at 100 means older sessions could not surface anyway, which+# makes this clamp close to free in practice — but it must be stated wherever the bucket is.+MAX_BUCKET_SCAN_DAYS = 30+# Rows fetched before filtering to sessions that actually have a recording, so the cap isn't+# spent on sessions sampled out of replay.+RECORDING_LOOKUP_FACTOR = 3+# Ceilings on how wide one scan can get. An experiment's metric count and a funnel's step count+# are user-configurable with no server-side cap, so without these a single request can compile a+# query hundreds of conditions wide over the whole window. The numbers mirror MAX_SCANNED_METRICS+# and MAX_AGGREGATE_GROUPS in the metric-events scan. Over the ceiling the request is refused+# rather than quietly computed over a subset: a bucket answered over fewer metrics than asked for+# is a different question, and for `no_metric_activity` a dropped metric inflates the result.+MAX_BUCKET_METRICS = 50+MAX_BUCKET_SOURCES = 200+# Per (team, viewer, experiment, bucket spec). Shorter than the session-context cache: that+# caches an immutable-ish fact about one recording, this caches a list that should visibly grow+# as an experiment runs. Keyed by viewer for the same reason — the metric set is read through+# the viewer's access control.+SESSION_BUCKET_CACHE_TTL = 5 * 60++RETENTION_EXCLUSION_REASON = (+ "Retention metrics measure a return visit, which happens in a later session than the one that starts it. "+ "No single recording can show both, so these metrics are left out of the filter."+)+DATA_WAREHOUSE_EXCLUSION_REASON = (+ "This metric is measured entirely in the data warehouse, which has no session events to match recordings on."+)+SERVER_SIDE_EXCLUSION_REASON = (+ "This metric's events have only ever been captured server-side, where there is no session to record, "+ "so they can never be matched to a recording."+)+CUSTOM_EXPOSURE_UNLINKABLE_REASON = (+ "This experiment's exposure event has only ever been captured server-side, where there is no session to "+ "record, so no session can match it."+)+# Drop-off reads two of a funnel's steps, so its own boundary check is narrower than the+# whole-metric one above: a funnel stays matchable on the steps between them.+FUNNEL_SERVER_SIDE_BOUNDARY_REASON = (+ "Drop-off reads this funnel's first and last step. One of them has only ever been captured server-side, "+ "where there is no session to record, so it can never be matched to a recording."+)+FUNNEL_DATA_WAREHOUSE_BOUNDARY_REASON = (+ "Drop-off reads this funnel's first and last step. One of them is measured in the data warehouse, "+ "which has no session events to match recordings on."+)+++class SessionBucket(StrEnum):+ """Which question the returned session set answers."""++ FIRED_ANY = "fired_any"+ NO_METRIC_ACTIVITY = "no_metric_activity"+ FUNNEL_DROPOFF = "funnel_dropoff"+++class SessionBucketUnavailable(Exception):+ """The requested bucket can't be computed for this experiment — a caller error, not a+ failure. Raised instead of returning an empty session list, so an unmatchable metric never+ reads as "no sessions matched"."""+++@dataclass(frozen=True)+class BucketMetric:+ metric_uuid: str+ metric_name: str+++@dataclass(frozen=True)+class ExcludedBucketMetric:+ metric_uuid: str+ metric_name: str+ reason: str+++@dataclass(frozen=True)+class SessionBucketScan:+ """What the scan found, and what gets cached: every recorded match, most recent first, not yet+ cut to `limit`.++ The cut waits for the viewer's per-recording access filter, which runs on read so a revocation+ lands even on a warm entry. Cutting first would let a denied recording spend a returned slot,+ and would let `truncated` carry the one bit that a recording the viewer can't see matched.+ """++ candidate_session_ids: list[str]+ # The scan filled its over-fetch batch, so more matches may exist beyond the ones it saw.+ scan_hit_cap: bool+ limit: int+ considered_metrics: list[BucketMetric]+ excluded_metrics: list[ExcludedBucketMetric]+ date_from: datetime+ date_to: datetime+ filter_test_accounts: bool+ used_exposure_fallback: bool+++@dataclass(frozen=True)+class SessionBucketResult:+ """One viewer's answer: the sessions they may see, cut to the limit."""++ session_ids: list[str]+ truncated: bool+ considered_metrics: list[BucketMetric]+ excluded_metrics: list[ExcludedBucketMetric]+ date_from: datetime+ date_to: datetime+ filter_test_accounts: bool+ used_exposure_fallback: bool+++def finalize_session_bucket(scan: SessionBucketScan, accessible_session_ids: list[str]) -> SessionBucketResult:+ """Cut the sessions this viewer may see to the limit, and say whether anything was left out."""+ return SessionBucketResult(+ session_ids=accessible_session_ids[: scan.limit],+ truncated=len(accessible_session_ids) > scan.limit or scan.scan_hit_cap,+ considered_metrics=scan.considered_metrics,+ excluded_metrics=scan.excluded_metrics,+ date_from=scan.date_from,+ date_to=scan.date_to,+ filter_test_accounts=scan.filter_test_accounts,+ used_exposure_fallback=scan.used_exposure_fallback,+ )+++def get_experiment_session_bucket(+ team: Team,+ user: User,+ experiment: Experiment,+ *,+ bucket: SessionBucket,+ metric_uuids: list[str],+ variant: Optional[str],+ limit: int,+) -> SessionBucketScan:+ """Session ids of this experiment's exposed sessions matching `bucket`, most recent first.++ The caller filters the result through the viewer's per-recording access control and passes it+ to `finalize_session_bucket`, which cuts it to `limit`.++ `user` is the viewer: metric sources and exposure criteria can filter on arbitrary event+ properties, so the query must run under that user's property-level access control, as the+ experiment query runners do.++ Raises SessionBucketUnavailable when the request can't produce a meaningful set — an+ experiment that never launched, a variant the flag doesn't define, a metric that can't be+ matched to recordings at all.+ """+ # The scan is experiments' own — exposure criteria and metric definitions over the events+ # table — so it bills to experiments, following the convention of tagging the product whose+ # logic and cost a query is rather than the surface it renders on. Without this it runs+ # untagged: no cost attribution in production, and a hard error in local dev. The replay+ # recording-existence lookup that follows tags itself, as replay's own query.+ tag_queries(product=Product.EXPERIMENTS, feature=Feature.QUERY, team_id=team.pk)++ if experiment.start_date is None:+ raise SessionBucketUnavailable("This experiment hasn't launched, so it has no exposed sessions yet.")++ variant_keys = {variant_definition["key"] for variant_definition in experiment.feature_flag.variants or []}+ if not variant_keys:+ raise SessionBucketUnavailable("This experiment's feature flag defines no variants.")+ if variant is not None and variant not in variant_keys:+ raise SessionBucketUnavailable(f"'{variant}' is not a variant of this experiment.")++ window_end = experiment.end_date or timezone.now()+ window_start = max(experiment.start_date, window_end - timedelta(days=MAX_BUCKET_SCAN_DAYS))+ criteria = normalize_to_exposure_criteria(experiment.exposure_criteria)+ filter_test_accounts = bool(criteria.filterTestAccounts) if criteria else False+ limit = min(limit, MAX_SESSION_BUCKET_LIMIT)++ requested = _resolve_requested_metrics(experiment, metric_uuids)+ exposure_event, _ = get_exposure_event_and_property(experiment.feature_flag.key, experiment.exposure_criteria)++ # One EventProperty read covers both linkability decisions — whether the exposure event can+ # match sessions at all, and which metrics can. The verdict must be the endpoint's own:+ # callers other than the tab (the API, MCP tools) have no reason to know the lookup exists,+ # and an empty bucket that's really an unlinkable event would read as "no sessions did this".+ # An action-based exposure has no single event name to look up, so it fails open, the same+ # posture action metric sources get.+ # Collected per source, not per metric: `_source_event_names` is all-or-nothing, so a funnel+ # with an action step among its named ones would contribute none of its event names and the+ # boundary check below would pass on a name the lookup never asked about.+ lookup_names: set[str] = {exposure_event} if exposure_event is not None else set()+ for metric in requested:+ lookup_names |= _concrete_event_names(metric)+ never_linked = _never_session_linked_events(team, lookup_names)+ use_exposure_fallback = exposure_event == DEFAULT_EXPOSURE_EVENT and exposure_event in never_linked+ if exposure_event in never_linked and not use_exposure_fallback:+ # Only the default event has a stand-in. Custom criteria assert that something specific+ # happened, which the stamped flag property doesn't imply, so falling back would answer+ # over "the flag was active in this session" — a wider population than the criteria name.+ raise SessionBucketUnavailable(CUSTOM_EXPOSURE_UNLINKABLE_REASON)++ considered, excluded = _partition_metrics(requested, bucket, never_linked)++ cache_key = _cache_key(team, user, experiment, bucket, considered, variant, window_start, window_end, limit)+ cached = get_safe_cache(cache_key)+ if cached is not None:+ return cached++ candidate_session_ids, scan_hit_cap = _query_bucket_sessions(+ team,+ user,+ experiment,+ bucket=bucket,+ considered=considered,+ variant_keys=[variant] if variant is not None else sorted(variant_keys),+ window_start=window_start,+ window_end=window_end,+ limit=limit,+ use_exposure_fallback=use_exposure_fallback,+ )+ result = SessionBucketScan(+ candidate_session_ids=candidate_session_ids,+ scan_hit_cap=scan_hit_cap,+ limit=limit,+ considered_metrics=[+ BucketMetric(metric_uuid=metric.metric_uuid, metric_name=metric.metric_name) for metric in considered+ ],+ excluded_metrics=excluded,+ date_from=window_start,+ date_to=window_end,+ filter_test_accounts=filter_test_accounts,+ used_exposure_fallback=use_exposure_fallback,+ )+ safe_cache_set(cache_key, result, timeout=SESSION_BUCKET_CACHE_TTL)+ return result+++def _cache_key(+ team: Team,+ user: User,+ experiment: Experiment,+ bucket: SessionBucket,+ considered: list[MetricEventSource],+ variant: Optional[str],+ window_start: datetime,+ window_end: datetime,+ limit: int,+) -> str:+ # The version segment must be bumped whenever SessionBucketScan changes shape: entries are+ # pickled, so a deploy would otherwise restore instances missing the new fields.+ spec = json.dumps(+ [+ bucket.value,+ sorted(metric.metric_uuid for metric in considered),+ variant,+ # The scan window moves with wall-clock time on a running experiment; rounding to the+ # minute keeps a burst of requests on one entry without pinning a stale window.+ window_start.replace(second=0, microsecond=0).isoformat(),+ window_end.replace(second=0, microsecond=0).isoformat(),+ # Part of the key even though the cut happens on read: the scan over-fetches a+ # multiple of the limit, so a larger one looks further than a cached smaller one did.+ limit,+ # Property restrictions are compiled into the SQL, so unlike recording access they+ # can't be re-filtered on read; a restriction change has to miss the cache instead.+ sorted(get_restricted_properties_for_team(user=user, team=team)),+ ]+ )+ digest = hashlib.sha256(spec.encode()).hexdigest()[:16]+ return f"experiment_session_bucket_v3_{team.pk}_{user.pk}_{experiment.pk}_{digest}"+++def _resolve_requested_metrics(experiment: Experiment, metric_uuids: list[str]) -> list[MetricEventSource]:+ resolved = resolve_metric_events(experiment)+ by_uuid = {metric.metric_uuid: metric for metric in resolved}++ unknown = [metric_uuid for metric_uuid in metric_uuids if metric_uuid not in by_uuid]+ if unknown:+ raise SessionBucketUnavailable(f"Unknown metric(s) for this experiment: {', '.join(sorted(unknown))}.")++ return [by_uuid[metric_uuid] for metric_uuid in dict.fromkeys(metric_uuids)] if metric_uuids else resolved+++def _partition_metrics(+ requested: list[MetricEventSource], bucket: SessionBucket, never_linked: set[str]+) -> tuple[list[MetricEventSource], list[ExcludedBucketMetric]]:+ """Split the requested metrics into the ones the bucket is computed over and the ones that+ can't be matched to a recording at all, with the reason.++ Reporting the excluded ones back matters most for `no_metric_activity`: "fired nothing" is+ only meaningful next to the list of metrics it was evaluated against — a metric whose events+ never carry a session id would count as "fired nothing" in every session, inflating the+ bucket to the whole exposed population.+ """+ considered: list[MetricEventSource] = []+ excluded: list[ExcludedBucketMetric] = []+ for metric in requested:+ reason = _exclusion_reason(metric, never_linked)+ if reason is None:+ considered.append(metric)+ else:+ excluded.append(+ ExcludedBucketMetric(metric_uuid=metric.metric_uuid, metric_name=metric.metric_name, reason=reason)+ )++ if not considered:+ raise SessionBucketUnavailable(+ "None of these metrics can be matched to recordings, so no session set would be meaningful."+ )+ if len(considered) > MAX_BUCKET_METRICS:+ raise SessionBucketUnavailable(+ f"This bucket would be computed over {len(considered)} metrics, more than the {MAX_BUCKET_METRICS} "+ "one scan can cover. Ask for fewer metrics."+ )+ source_count = sum(len(metric.sources) for metric in considered)+ if source_count > MAX_BUCKET_SOURCES:+ raise SessionBucketUnavailable(+ f"These metrics count {source_count} events between them, more than the {MAX_BUCKET_SOURCES} "+ "one scan can cover. Ask for fewer metrics."+ )+ if bucket == SessionBucket.FUNNEL_DROPOFF:+ if len(considered) != 1:+ raise SessionBucketUnavailable("The drop-off bucket takes exactly one funnel metric.")+ boundary_reason = _funnel_boundary_reason(considered[0], never_linked)+ if boundary_reason is not None:+ # Raised rather than excluded: drop-off takes one metric, so excluding it would leave+ # the generic "none of these can be matched" message and lose the reason.+ raise SessionBucketUnavailable(boundary_reason)+ return considered, excluded+++def _exclusion_reason(metric: MetricEventSource, never_linked: set[str]) -> Optional[str]:+ if not metric.session_linkable:+ return DATA_WAREHOUSE_EXCLUSION_REASON+ if any(+ source.role in (MetricSourceRole.RETENTION_START, MetricSourceRole.RETENTION_COMPLETION)+ for source in metric.sources+ ):+ # A retention metric's return visit is a later session by construction, so no single+ # recording can show the metric happening. Its start event alone would answer a different+ # question than the metric asks.+ return RETENTION_EXCLUSION_REASON+ source_events = _source_event_names(metric)+ if source_events is not None and source_events <= never_linked:+ return SERVER_SIDE_EXCLUSION_REASON+ return None+++def _concrete_event_names(metric: MetricEventSource) -> set[str]:+ """Every named event this metric counts, skipping the sources that have no single name.++ What the linkability lookup reads. Deliberately not `_source_event_names`: that one answers a+ question about the metric as a whole and gives up entirely on an action source, which would+ leave a funnel's named boundary steps unchecked.+ """+ return {source.node.event for source in metric.sources if isinstance(source.node, EventsNode) and source.node.event}+++def _source_event_names(metric: MetricEventSource) -> Optional[set[str]]:+ """The concrete event names a metric counts, or None when any source is an action or an+ all-events node. Those can match client-captured events, so their linkability can't be+ decided from event names and the metric must stay considered."""+ names: set[str] = set()+ for source in metric.sources:+ if not isinstance(source.node, EventsNode) or not source.node.event:+ return None+ names.add(source.node.event)+ return names+++def _never_session_linked_events(team: Team, event_names: set[str]) -> set[str]:+ """Event names never ingested with a `$session_id` property — only ever captured+ server-side, so no recordings filter on them can match. The same `EventProperty` fact the+ taxonomy `seen_together` endpoint serves the tab, read directly so the verdict doesn't+ depend on the caller knowing to check."""+ if not event_names:+ return set()+ seen = (+ EventProperty.objects.alias(+ effective_project_id=Coalesce("project_id", "team_id", output_field=models.BigIntegerField())+ )+ .filter(effective_project_id=team.project_id, event__in=sorted(event_names), property="$session_id")+ .values_list("event", flat=True)+ .distinct()+ )+ return event_names - set(seen)+++def _metric_condition(metric: MetricEventSource, team: Team) -> ast.Expr:+ """Match expression for "any of this metric's events" — the OR over its sources, built on the+ same matcher the analysis uses, so what counts as this metric's event can't diverge."""+ conditions = [build_source_condition(source.node, team) for source in metric.sources]+ return ast.Or(exprs=conditions) if len(conditions) > 1 else conditions[0]+++def _funnel_boundary_steps(metric: MetricEventSource) -> tuple[MetricSource, MetricSource]:+ """The two steps drop-off is computed from: the funnel's entry and its completion."""+ steps = [source for source in metric.sources if source.role == MetricSourceRole.STEP]+ if len(steps) < 2:+ raise SessionBucketUnavailable(+ "Drop-off needs a funnel with at least two steps that can be matched to recordings."+ )+ return steps[0], steps[-1]+++def _funnel_boundary_reason(metric: MetricEventSource, never_linked: set[str]) -> Optional[str]:+ """Why drop-off can't be asked of this funnel, or None when it can.++ The whole-metric check in `_exclusion_reason` is too coarse here. It clears a funnel as long+ as one of its steps can be matched, while drop-off rests on two specific ones — so a funnel+ whose completion is a server-side charge passes there and then counts that completion as+ zero in every session, returning everyone who entered as not having finished.+ """+ entry, completion = _funnel_boundary_steps(metric)+ # Data-warehouse steps are dropped from `sources` while the survivors keep their real+ # position, so a gap at either end means the boundary read landed on an inner step.+ if entry.index != 0 or completion.index != completion.total - 1:+ return FUNNEL_DATA_WAREHOUSE_BOUNDARY_REASON+ boundary_events = {+ step.node.event for step in (entry, completion) if isinstance(step.node, EventsNode) and step.node.event+ }+ if boundary_events & never_linked:+ return FUNNEL_SERVER_SIDE_BOUNDARY_REASON+ return None+++def _funnel_step_conditions(metric: MetricEventSource, team: Team) -> tuple[ast.Expr, ast.Expr, int]:+ """The funnel's entry condition, its completion condition, and how many times the completion+ event must fire to count as completed.++ A funnel can list one event as several steps (the "N-th occurrence" shape), where entry and+ completion are the same condition and only the occurrence count tells them apart — the same+ positional reading the per-source hits use.+ """+ steps = [source for source in metric.sources if source.role == MetricSourceRole.STEP]+ entry_step, completion_step = _funnel_boundary_steps(metric)+ completion_signature = node_signature(completion_step.node)+ completion_occurrences = sum(1 for step in steps if node_signature(step.node) == completion_signature)+ return (+ build_source_condition(entry_step.node, team),+ build_source_condition(completion_step.node, team),+ completion_occurrences,+ )+++def _query_bucket_sessions(+ team: Team,+ user: User,+ experiment: Experiment,+ *,+ bucket: SessionBucket,+ considered: list[MetricEventSource],+ variant_keys: list[str],+ window_start: datetime,+ window_end: datetime,+ limit: int,+ use_exposure_fallback: bool,+) -> tuple[list[str], bool]:+ flag_key = experiment.feature_flag.key+ _event, variant_property = get_exposure_event_and_property(flag_key, experiment.exposure_criteria)+ if use_exposure_fallback:+ variant_property = f"$feature/{flag_key}"++ def exposure_condition() -> ast.Expr:+ # The exposure criteria resolved through the shared helpers — the single seam that keeps+ # this surface in sync with the analysis and with the player's session context. Rebuilt+ # per use site: the HogQL resolver annotates ast nodes in place, so one instance can't+ # appear in both the WHERE and the HAVING.+ variant_condition = ast.CompareOperation(+ op=ast.CompareOperationOp.In,+ left=ast.Call(name="toString", args=[ast.Field(chain=["properties", variant_property])]),+ right=ast.Constant(value=variant_keys),+ )+ if use_exposure_fallback:+ # The default exposure event has only ever been captured server-side, so it can't+ # match any session. posthog-js stamps `$feature/<flag_key>` on every client event+ # captured after flags load, so the stamped property stands in — the same fallback+ # the tab's own list uses. It means "the flag was active in this session", not "the+ # enrollment moment was captured": no event-name condition, and the variant is the+ # flag's value on each event rather than the exposure response.+ return variant_condition+ conditions = [+ *build_exposure_event_conditions(experiment.exposure_criteria, team, flag_key),+ variant_condition,+ ]+ return ast.And(exprs=conditions) if len(conditions) > 1 else conditions[0]++ def metric_conditions() -> list[ast.Expr]:+ return [_metric_condition(metric, team) for metric in considered]++ def any_metric_condition() -> ast.Expr:+ conditions = metric_conditions()+ return ast.Or(exprs=conditions) if len(conditions) > 1 else conditions[0]++ def count_if(condition: ast.Expr) -> ast.Expr:+ return ast.Call(name="countIf", args=[condition])++ if bucket == SessionBucket.FIRED_ANY:+ bucket_predicate: ast.Expr = ast.CompareOperation(+ op=ast.CompareOperationOp.Gt, left=count_if(any_metric_condition()), right=ast.Constant(value=0)+ )+ elif bucket == SessionBucket.NO_METRIC_ACTIVITY:+ bucket_predicate = ast.CompareOperation(+ op=ast.CompareOperationOp.Eq, left=count_if(any_metric_condition()), right=ast.Constant(value=0)+ )+ else:+ entry, completion, completion_occurrences = _funnel_step_conditions(considered[0], team)+ # Count-based on purpose: the filter promises "fired the last step's event", not funnel ordering.+ bucket_predicate = ast.And(+ exprs=[+ ast.CompareOperation(op=ast.CompareOperationOp.Gt, left=count_if(entry), right=ast.Constant(value=0)),+ ast.CompareOperation(+ op=ast.CompareOperationOp.Lt,+ left=count_if(completion),+ right=ast.Constant(value=completion_occurrences),+ ),+ ]+ )++ # The WHERE keeps the OR of every condition the query can match on, so ClickHouse still prunes+ # by event name on the events table's primary key — without it this reads the team's whole+ # window. Sessions are then classified in the HAVING over the same conditions.+ where_conditions: list[ast.Expr] = [+ ast.CompareOperation(+ op=ast.CompareOperationOp.GtEq,+ left=ast.Field(chain=["timestamp"]),+ right=ast.Constant(value=window_start),+ ),+ ast.CompareOperation(+ op=ast.CompareOperationOp.LtEq, left=ast.Field(chain=["timestamp"]), right=ast.Constant(value=window_end)+ ),+ ast.CompareOperation(+ op=ast.CompareOperationOp.NotEq, left=ast.Field(chain=["$session_id"]), right=ast.Constant(value="")+ ),+ ast.Or(exprs=[exposure_condition(), *metric_conditions()]),+ *get_test_accounts_filter(team, experiment.exposure_criteria),+ ]++ # Over-fetched, because ids without a recording are dropped below and would otherwise eat the+ # cap on projects that sample replay.+ fetch_limit = limit * RECORDING_LOOKUP_FACTOR+ query = ast.SelectQuery(+ select=[+ ast.Alias(alias="session_id", expr=ast.Field(chain=["$session_id"])),+ ast.Alias(alias="last_seen", expr=ast.Call(name="max", args=[ast.Field(chain=["timestamp"])])),+ ],+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),+ where=ast.And(exprs=where_conditions),+ group_by=[ast.Field(chain=["session_id"])],+ having=ast.And(+ exprs=[+ ast.CompareOperation(+ op=ast.CompareOperationOp.Gt,+ left=count_if(exposure_condition()),+ right=ast.Constant(value=0),+ ),+ bucket_predicate,+ ]+ ),+ order_by=[ast.OrderExpr(expr=ast.Field(chain=["last_seen"]), order="DESC")],+ limit=ast.Constant(value=fetch_limit),+ )++ # One query, so there is no union to hide an implicit per-branch limit — but the limit is+ # still set explicitly, since an unset one would silently become HogQL's LIMIT 100.+ modifiers = create_default_modifiers_for_team(team)+ shared_hogql = SharedHogQLDatabase(+ # Postgres foreign-key lazy joins are the most expensive part of building the virtual+ # database and this query only reads events.+ database=Database.create_for(team=team, user=user, modifiers=modifiers, build_postgres_foreign_keys=False),+ modifiers=modifiers,+ )+ response = execute_hogql_query(+ query, team=team, user=user, context=shared_hogql.fresh_context(team, user), modifiers=shared_hogql.modifiers+ )++ candidate_ids = [str(row[0]) for row in response.results or []]+ exists_by_id = SessionReplayEvents().batch_exists(candidate_ids, team)+ # Not cut to `limit` here: the caller drops the recordings this viewer can't open first, and+ # the cut has to come after that.+ recorded_ids = [session_id for session_id in candidate_ids if exists_by_id.get(session_id)]+ return recorded_ids, len(candidate_ids) >= fetch_limitdiff --git a/products/experiments/backend/session_context.py b/products/experiments/backend/session_context.pyindex 8dd8d3bc50b4..d67e1fb25b3a 100644--- a/products/experiments/backend/session_context.py+++ b/products/experiments/backend/session_context.py@@ -28,7 +28,6 @@ from functools import partialfrom typing import Optionalfrom django.conf import settings-from django.core.cache import cachefrom django.db.models import Q, QuerySetimport pydantic@@ -42,10 +41,11 @@ from posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.query import execute_hogql_query+from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.session_recordings.queries.session_replay_events import SessionReplayEvents, uuidv7_session_lower_bound-from posthog.utils import get_safe_cache+from posthog.utils import get_safe_cache, safe_cache_setfrom products.cohorts.backend.models.cohort import Cohort@@ -198,7 +198,7 @@ def get_session_experiment_context(items = computed[session_id]# A capped single session is still cached: with one session there is no batch union, so a# recompute would drop the same metrics again and caching the capped result loses nothing.- cache.set(cache_key, items, timeout=SESSION_CONTEXT_CACHE_TTL)+ safe_cache_set(cache_key, items, timeout=SESSION_CONTEXT_CACHE_TTL)return items@@ -262,7 +262,7 @@ def get_session_experiment_contexts(# single-session endpoint computes; it is returned best-effort and left for# on-demand recompute instead.if session_id not in capped_session_ids:- cache.set(_cache_key(team, user, session_id), items, timeout=SESSION_CONTEXT_CACHE_TTL)+ safe_cache_set(_cache_key(team, user, session_id), items, timeout=SESSION_CONTEXT_CACHE_TTL)results.update(computed)return {session_id: results[session_id] for session_id in unique_ids if session_id in results}@@ -405,6 +405,13 @@ def _compute_session_experiment_contexts(# built for; no scan may pass its own modifiers. Postgres foreign-key lazy joins are# skipped — the single most expensive build step, and these queries only ever read the# events table.+ # Tagged here, not at the entry points: the recording-metadata lookup above is replay's own+ # query and tags itself as such, so an earlier tag would be overwritten and these scans would+ # bill to replay. The scans are experiments' own — exposure criteria and metric definitions+ # over the events table — and follow the convention of tagging the product whose logic and+ # cost they are, not the surface they render on.+ tag_queries(product=Product.EXPERIMENTS, feature=Feature.QUERY, team_id=team.pk)+hogql_modifiers = create_default_modifiers_for_team(team)shared_hogql = SharedHogQLDatabase(database=Database.create_for(diff --git a/products/experiments/backend/test/test_metric_events.py b/products/experiments/backend/test/test_metric_events.pyindex 11689d1d7fdf..24893e278584 100644--- a/products/experiments/backend/test/test_metric_events.py+++ b/products/experiments/backend/test/test_metric_events.py@@ -294,7 +294,7 @@ class TestScanSessionForMetricEvents(ClickhouseTestMixin, MetricEventsTestMixin)@parameterized.expand(["properties", "fixedProperties"])def test_honors_source_node_property_filters(self, properties_field: str) -> None:# `properties` flows through the shared `event_or_action_to_filter`; `fixedProperties`- # are ANDed on top by `_node_condition` — both must narrow the match.+ # are ANDed on top by `build_source_condition` — both must narrow the match.filtered = _metric("mean",name="Premium purchases",diff --git a/products/experiments/backend/test/test_session_buckets_api.py b/products/experiments/backend/test/test_session_buckets_api.pynew file mode 100644index 000000000000..cdbb5e246efb--- /dev/null+++ b/products/experiments/backend/test/test_session_buckets_api.py@@ -0,0 +1,799 @@+from datetime import UTC, datetime, timedelta+from typing import Any, Optional++from freezegun import freeze_time+from posthog.test.base import ClickhouseTestMixin, _create_event, flush_persons_and_events+from unittest.mock import patch++from django.core.cache import cache++from parameterized import parameterized+from rest_framework import status++import posthog.hogql.query as hogql_query_module++from posthog.clickhouse.query_tagging import Product, get_query_tags+from posthog.constants import AvailableFeature+from posthog.models import EventProperty, Team, User+from posthog.models.utils import uuid7+from posthog.session_recordings.models.session_recording import SessionRecording+from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary++from products.actions.backend.models.action import Action+from products.experiments.backend.models.experiment import Experiment+from products.experiments.backend.session_buckets import MAX_BUCKET_METRICS, MAX_BUCKET_SCAN_DAYS, MAX_BUCKET_SOURCES+from products.feature_flags.backend.models.feature_flag import FeatureFlag++from ee.api.test.base import APILicensedTest+from ee.models.rbac.access_control import AccessControl++NOW = datetime(2026, 1, 10, 12, 0, 0, tzinfo=UTC)+EXPERIMENT_START = datetime(2025, 12, 20, tzinfo=UTC)++PURCHASE_METRIC = {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "11111111-1111-1111-1111-111111111111",+ "name": "Purchases",+ "source": {"kind": "EventsNode", "event": "purchase"},+}+SIGNUP_METRIC = {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "22222222-2222-2222-2222-222222222222",+ "name": "Signups",+ "source": {"kind": "EventsNode", "event": "signup"},+}+CHECKOUT_FUNNEL_METRIC = {+ "kind": "ExperimentMetric",+ "metric_type": "funnel",+ "uuid": "33333333-3333-3333-3333-333333333333",+ "name": "Checkout funnel",+ "series": [{"kind": "EventsNode", "event": "cart viewed"}, {"kind": "EventsNode", "event": "purchase"}],+}+REPEATED_STEP_FUNNEL_METRIC = {+ "kind": "ExperimentMetric",+ "metric_type": "funnel",+ "uuid": "44444444-4444-4444-4444-444444444444",+ "name": "Second upload",+ "series": [{"kind": "EventsNode", "event": "uploaded file"}, {"kind": "EventsNode", "event": "uploaded file"}],+}+RETENTION_METRIC = {+ "kind": "ExperimentMetric",+ "metric_type": "retention",+ "uuid": "55555555-5555-5555-5555-555555555555",+ "name": "Weekly return",+ "start_event": {"kind": "EventsNode", "event": "signed up"},+ "completion_event": {"kind": "EventsNode", "event": "$pageview"},+ "retention_window_start": 1,+ "retention_window_end": 7,+ "retention_window_unit": "day",+ "start_handling": "first_seen",+}+DATA_WAREHOUSE_METRIC = {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "66666666-6666-6666-6666-666666666666",+ "name": "Stripe revenue",+ "source": {+ "kind": "ExperimentDataWarehouseNode",+ "table_name": "stripe_charges",+ "timestamp_field": "created_at",+ "data_warehouse_join_key": "customer_id",+ "events_join_key": "distinct_id",+ },+}+# No session in `_session` ever fires this event, so it never gets an EventProperty row linking+# it to `$session_id` — the shape of an event only ever captured from a backend SDK.+SERVER_SIDE_METRIC = {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "77777777-7777-7777-7777-777777777777",+ "name": "Server charges",+ "source": {"kind": "EventsNode", "event": "server charge"},+}+DATA_WAREHOUSE_STEP = {+ "kind": "ExperimentDataWarehouseNode",+ "table_name": "stripe_charges",+ "timestamp_field": "created_at",+ "data_warehouse_join_key": "customer_id",+ "events_join_key": "distinct_id",+}+++def _funnel(uuid: str, name: str, series: list[dict[str, Any]]) -> dict[str, Any]:+ return {"kind": "ExperimentMetric", "metric_type": "funnel", "uuid": uuid, "name": name, "series": series}+++CART = {"kind": "EventsNode", "event": "cart viewed"}+PURCHASE = {"kind": "EventsNode", "event": "purchase"}+SERVER_CHARGE = {"kind": "EventsNode", "event": "server charge"}+++@freeze_time(NOW)+class TestExperimentSessionBuckets(ClickhouseTestMixin, APILicensedTest):+ def setUp(self) -> None:+ super().setUp()+ cache.clear()++ def _create_experiment(+ self,+ metrics: Optional[list[dict[str, Any]]] = None,+ key: str = "checkout-cta",+ start_date: datetime = EXPERIMENT_START,+ exposure_criteria: Optional[dict[str, Any]] = None,+ team: Optional[Team] = None,+ created_by: Optional[User] = None,+ ) -> Experiment:+ team = team or self.team+ flag = FeatureFlag.objects.create(+ team=team,+ key=key,+ name=key,+ created_by=self.user,+ filters={+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 50},+ {"key": "test", "rollout_percentage": 50},+ ]+ }+ },+ )+ return Experiment.objects.create(+ team=team,+ name="Checkout CTA copy",+ feature_flag=flag,+ created_by=created_by or self.user,+ start_date=start_date,+ exposure_criteria=exposure_criteria or {},+ metrics=metrics or [],+ )++ def _session(+ self,+ *,+ variant: Optional[str] = "test",+ events: Optional[list[tuple[str, datetime]]] = None,+ at: datetime = datetime(2026, 1, 9, 10, 0, 0, tzinfo=UTC),+ with_recording: bool = True,+ flag_key: str = "checkout-cta",+ distinct_id: str = "user1",+ properties: Optional[dict[str, Any]] = None,+ ) -> str:+ """One session: a recording, an exposure event for `variant` (unless None), and events.++ `properties` is stamped on every event of the session, exposure included.+ """+ session_id = str(uuid7(unix_ms_time=int(at.timestamp() * 1000)))+ shared_properties = {"$session_id": session_id, **(properties or {})}+ if with_recording:+ produce_replay_summary(+ team_id=self.team.pk,+ session_id=session_id,+ distinct_id=distinct_id,+ first_timestamp=at,+ last_timestamp=at + timedelta(minutes=30),+ )+ if variant is not None:+ _create_event(+ team=self.team,+ event="$feature_flag_called",+ distinct_id=distinct_id,+ timestamp=at,+ properties={+ **shared_properties,+ "$feature_flag": flag_key,+ "$feature_flag_response": variant,+ },+ )+ for event, timestamp in events or []:+ _create_event(+ team=self.team,+ event=event,+ distinct_id=distinct_id,+ timestamp=timestamp,+ properties=shared_properties,+ )+ # Ingestion records every (event, property) pair in Postgres, and the endpoint reads+ # those rows to decide whether an event can be matched to sessions at all — so events+ # captured with a $session_id here must leave the same trace they would in production.+ ingested = {event for event, _ in events or []}+ if variant is not None:+ ingested.add("$feature_flag_called")+ for event_name in ingested:+ EventProperty.objects.get_or_create(+ team=self.team, project_id=self.team.project_id, event=event_name, property="$session_id"+ )+ return session_id++ def _post_bucket(self, experiment: Experiment, **body: Any) -> Any:+ return self.client.post(+ f"/api/projects/{self.team.id}/experiments/{experiment.id}/session_buckets/",+ body,+ format="json",+ )++ def test_fired_any_is_an_or_across_metrics(self) -> None:+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC, SIGNUP_METRIC])+ purchased = self._session(events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])+ signed_up = self._session(events=[("signup", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])+ neither = self._session()+ flush_persons_and_events()++ response = self._post_bucket(+ experiment,+ bucket="fired_any",+ metric_uuids=[PURCHASE_METRIC["uuid"], SIGNUP_METRIC["uuid"]],+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ data = response.json()+ # The client-side path ANDs its filters, so a session firing only one of the two metrics+ # would be excluded there — this is the capability the endpoint exists for.+ assert set(data["session_ids"]) == {purchased, signed_up}+ assert neither not in data["session_ids"]+ assert data["truncated"] is False+ assert {metric["metric_uuid"] for metric in data["considered_metrics"]} == {+ PURCHASE_METRIC["uuid"],+ SIGNUP_METRIC["uuid"],+ }+ assert data["excluded_metrics"] == []+ assert data["used_exposure_fallback"] is False++ def test_no_metric_activity_returns_exposed_sessions_without_any_considered_metric(self) -> None:+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC, SIGNUP_METRIC])+ quiet = self._session()+ self._session(events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])+ self._session(events=[("signup", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])+ flush_persons_and_events()++ response = self._post_bucket(experiment, bucket="no_metric_activity")++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["session_ids"] == [quiet]++ def test_metric_events_without_exposure_stay_out_of_every_bucket(self) -> None:+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])+ unexposed = self._session(variant=None, events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])+ flush_persons_and_events()++ fired = self._post_bucket(experiment, bucket="fired_any", metric_uuids=[PURCHASE_METRIC["uuid"]])+ quiet = self._post_bucket(experiment, bucket="no_metric_activity")++ # Metric-only sessions don't surface anywhere in the experiment today; a bucket must not+ # be the place they start appearing.+ assert unexposed not in fired.json()["session_ids"]+ assert unexposed not in quiet.json()["session_ids"]++ @parameterized.expand(+ [+ # Distinct entry and completion events: entering is one event, completing is the other.+ ("distinct_steps", CHECKOUT_FUNNEL_METRIC, "cart viewed", "purchase"),+ # One event repeated as two steps ("the second upload"): entry and completion match the+ # same event, so only the occurrence count tells them apart.+ ("repeated_step", REPEATED_STEP_FUNNEL_METRIC, "uploaded file", "uploaded file"),+ ]+ )+ def test_funnel_dropoff_returns_entered_but_not_completed(+ self, _name: str, metric: dict[str, Any], entry_event: str, completion_event: str+ ) -> None:+ experiment = self._create_experiment(metrics=[metric])+ dropped_off = self._session(events=[(entry_event, datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])+ completed = self._session(+ events=[+ (entry_event, datetime(2026, 1, 9, 10, 5, tzinfo=UTC)),+ (completion_event, datetime(2026, 1, 9, 10, 7, tzinfo=UTC)),+ ]+ )+ never_entered = self._session()+ flush_persons_and_events()++ response = self._post_bucket(experiment, bucket="funnel_dropoff", metric_uuids=[metric["uuid"]])++ assert response.status_code == status.HTTP_200_OK, response.json()+ session_ids = response.json()["session_ids"]+ assert session_ids == [dropped_off]+ assert completed not in session_ids+ assert never_entered not in session_ids++ @parameterized.expand(+ [+ # The completion side: without the check every session that entered comes back as+ # "didn't finish", including the ones whose purchase really did happen.+ (+ "server_side_completion",+ _funnel("a1111111-1111-1111-1111-111111111111", "Checkout", [CART, SERVER_CHARGE]),+ "captured server-side",+ ),+ # The entry side fails the other way, to a silently empty bucket.+ (+ "server_side_entry",+ _funnel("a2222222-2222-2222-2222-222222222222", "Charge then buy", [SERVER_CHARGE, PURCHASE]),+ "captured server-side",+ ),+ # A data-warehouse step is dropped from the metric's sources, so the positional read+ # would silently promote an inner step to the funnel's boundary.+ (+ "data_warehouse_entry",+ _funnel("a3333333-3333-3333-3333-333333333333", "Charge first", [DATA_WAREHOUSE_STEP, CART, PURCHASE]),+ "data warehouse",+ ),+ (+ "data_warehouse_completion",+ _funnel("a4444444-4444-4444-4444-444444444444", "Charge last", [CART, PURCHASE, DATA_WAREHOUSE_STEP]),+ "data warehouse",+ ),+ ]+ )+ def test_funnel_dropoff_refuses_when_a_boundary_step_cannot_be_matched(+ self, _name: str, metric: dict[str, Any], expected_reason: str+ ) -> None:+ experiment = self._create_experiment(metrics=[metric])+ self._session(+ events=[+ ("cart viewed", datetime(2026, 1, 9, 10, 5, tzinfo=UTC)),+ ("purchase", datetime(2026, 1, 9, 10, 7, tzinfo=UTC)),+ ]+ )+ flush_persons_and_events()++ response = self._post_bucket(experiment, bucket="funnel_dropoff", metric_uuids=[metric["uuid"]])++ # Drop-off is the count of the funnel's first step against its last one. When either can't+ # appear in a recording the predicate answers a question nobody asked, and every exposed+ # session lands in (or out of) the bucket with nothing on screen saying why.+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert expected_reason in response.json()["detail"]++ def test_funnel_dropoff_boundary_check_survives_an_action_step(self) -> None:+ action = Action.objects.create(team=self.team, name="Viewed cart", steps_json=[{"event": "cart viewed"}])+ metric = _funnel(+ "a7777777-7777-7777-7777-777777777777",+ "Checkout via action",+ [CART, {"kind": "ActionsNode", "id": action.pk}, SERVER_CHARGE],+ )+ experiment = self._create_experiment(metrics=[metric])+ self._session(events=[("cart viewed", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])+ flush_persons_and_events()++ response = self._post_bucket(experiment, bucket="funnel_dropoff", metric_uuids=[metric["uuid"]])++ # An action among the steps makes the metric's event names unresolvable as a whole, but the+ # boundary steps are still concrete events. Looking names up per metric rather than per+ # source would leave the completion event out of the linkability read, and the boundary+ # check would pass on a name it never asked about.+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert "captured server-side" in response.json()["detail"]++ def test_funnel_dropoff_allows_an_unmatchable_step_between_the_boundaries(self) -> None:+ metric = _funnel("a5555555-5555-5555-5555-555555555555", "Checkout", [CART, SERVER_CHARGE, PURCHASE])+ experiment = self._create_experiment(metrics=[metric])+ dropped_off = self._session(events=[("cart viewed", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])+ completed = self._session(+ events=[+ ("cart viewed", datetime(2026, 1, 9, 10, 5, tzinfo=UTC)),+ ("purchase", datetime(2026, 1, 9, 10, 7, tzinfo=UTC)),+ ]+ )+ flush_persons_and_events()++ response = self._post_bucket(experiment, bucket="funnel_dropoff", metric_uuids=[metric["uuid"]])++ # Only the two boundary steps are read, so a server-side step between them costs nothing.+ # Refusing here would take drop-off away from funnels it answers correctly.+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["session_ids"] == [dropped_off]+ assert completed not in response.json()["session_ids"]++ @parameterized.expand(+ [+ ("retention", RETENTION_METRIC, "Retention metrics measure a return visit"),+ ("data_warehouse", DATA_WAREHOUSE_METRIC, "measured entirely in the data warehouse"),+ ("server_side", SERVER_SIDE_METRIC, "only ever been captured server-side"),+ ]+ )+ def test_unmatchable_metrics_are_reported_rather_than_returning_nothing(+ self, _name: str, metric: dict[str, Any], expected_reason: str+ ) -> None:+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC, metric])+ purchased = self._session(events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])+ flush_persons_and_events()++ response = self._post_bucket(+ experiment, bucket="fired_any", metric_uuids=[PURCHASE_METRIC["uuid"], metric["uuid"]]+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ data = response.json()+ assert data["session_ids"] == [purchased]+ assert [excluded["metric_uuid"] for excluded in data["excluded_metrics"]] == [metric["uuid"]]+ assert expected_reason in data["excluded_metrics"][0]["reason"]+ assert [considered["metric_uuid"] for considered in data["considered_metrics"]] == [PURCHASE_METRIC["uuid"]]++ # Asked for on its own it can only ever match zero sessions, so the endpoint refuses+ # instead of returning an empty list that reads as "no sessions did this".+ only_unmatchable = self._post_bucket(experiment, bucket="fired_any", metric_uuids=[metric["uuid"]])+ assert only_unmatchable.status_code == status.HTTP_400_BAD_REQUEST++ def test_no_metric_activity_never_evaluates_absence_against_a_server_side_metric(self) -> None:+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC, SERVER_SIDE_METRIC])+ quiet = self._session()+ purchased = self._session(events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])+ flush_persons_and_events()++ response = self._post_bucket(experiment, bucket="no_metric_activity")++ # A server-side metric's events never carry a session id, so counted naively it "fired+ # nothing" in every session — absence must be computed over the linkable metrics only,+ # with the server-side one reported out.+ data = response.json()+ assert data["session_ids"] == [quiet]+ assert purchased not in data["session_ids"]+ assert [excluded["metric_uuid"] for excluded in data["excluded_metrics"]] == [SERVER_SIDE_METRIC["uuid"]]++ # With no linkable metric left, every exposed session would trivially qualify — refuse+ # rather than confidently returning the whole population as "fired nothing".+ only_server_side = self._post_bucket(+ experiment, bucket="no_metric_activity", metric_uuids=[SERVER_SIDE_METRIC["uuid"]]+ )+ assert only_server_side.status_code == status.HTTP_400_BAD_REQUEST++ def test_backend_fired_exposure_falls_back_to_the_stamped_flag_property(self) -> None:+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])+ # No session ever fires $feature_flag_called, so the default exposure event has no+ # EventProperty row — the shape of exposure evaluated in a backend SDK. Client events+ # still carry the stamped flag property.+ purchased = self._session(+ variant=None,+ events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))],+ properties={"$feature/checkout-cta": "test"},+ )+ quiet = self._session(+ variant=None,+ events=[("$pageview", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))],+ properties={"$feature/checkout-cta": "test"},+ )+ flush_persons_and_events()++ fired = self._post_bucket(experiment, bucket="fired_any", metric_uuids=[PURCHASE_METRIC["uuid"]])+ inactive = self._post_bucket(experiment, bucket="no_metric_activity")++ # Without the fallback the population is empty and every bucket returns nothing — on+ # exactly the experiments where the tab's list falls back and shows sessions.+ assert fired.status_code == status.HTTP_200_OK, fired.json()+ assert fired.json()["session_ids"] == [purchased]+ assert fired.json()["used_exposure_fallback"] is True+ assert inactive.json()["session_ids"] == [quiet]++ def test_server_side_custom_exposure_is_refused_rather_than_silently_empty(self) -> None:+ experiment = self._create_experiment(+ metrics=[PURCHASE_METRIC],+ exposure_criteria={+ "exposure_config": {+ "kind": "ExperimentEventExposureConfig",+ "event": "server exposure",+ "properties": [],+ }+ },+ )+ purchased = self._session(+ variant=None,+ events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))],+ properties={"$feature/checkout-cta": "test"},+ )+ flush_persons_and_events()++ response = self._post_bucket(experiment, bucket="fired_any", metric_uuids=[PURCHASE_METRIC["uuid"]])++ # An exposure event no session can carry matches nothing, and an empty list reads as "no+ # session did this" instead of "this experiment can't be answered from recordings".+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert "captured server-side" in response.json()["detail"]+ # The stamped flag property is on that session, so a fallback would have returned it.+ # Custom criteria carry semantics a flag-value filter can't stand in for: the population+ # must not widen to "the flag was active".+ assert purchased not in str(response.json())++ @parameterized.expand([("custom_event",), ("action",)])+ def test_session_linkable_custom_exposure_defines_the_population(self, exposure_kind: str) -> None:+ if exposure_kind == "action":+ action = Action.objects.create(team=self.team, name="Checkout", steps_json=[{"event": "checkout started"}])+ exposure_config: dict[str, Any] = {"kind": "ActionsNode", "id": action.pk}+ else:+ exposure_config = {+ "kind": "ExperimentEventExposureConfig",+ "event": "checkout started",+ "properties": [],+ }+ experiment = self._create_experiment(+ metrics=[PURCHASE_METRIC], exposure_criteria={"exposure_config": exposure_config}+ )+ exposed = self._session(+ variant=None,+ events=[+ ("checkout started", datetime(2026, 1, 9, 10, 4, tzinfo=UTC)),+ ("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC)),+ ],+ properties={"$feature/checkout-cta": "test"},+ )+ flush_persons_and_events()++ response = self._post_bucket(experiment, bucket="fired_any", metric_uuids=[PURCHASE_METRIC["uuid"]])++ # The refusal above must stay narrow. A custom event that sessions do carry is the normal+ # case, and an action has no single event name to look up at all, so it fails open.+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["session_ids"] == [exposed]+ assert response.json()["used_exposure_fallback"] is False++ def test_action_metrics_are_not_excluded_by_the_linkability_check(self) -> None:+ action = Action.objects.create(team=self.team, name="Purchased", steps_json=[{"event": "purchase"}])+ action_metric = {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "88888888-8888-8888-8888-888888888888",+ "name": "Purchased (action)",+ "source": {"kind": "ActionsNode", "id": action.pk},+ }+ experiment = self._create_experiment(metrics=[action_metric])+ purchased = self._session(events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])+ flush_persons_and_events()++ response = self._post_bucket(experiment, bucket="fired_any", metric_uuids=[action_metric["uuid"]])++ # An action has no single event name to look up, so linkability can't be decided for it —+ # it must fail open into the considered set, not read as "never seen with a session".+ data = response.json()+ assert response.status_code == status.HTTP_200_OK, data+ assert data["session_ids"] == [purchased]+ assert [metric["metric_uuid"] for metric in data["considered_metrics"]] == [action_metric["uuid"]]+ assert data["excluded_metrics"] == []++ def test_variant_facet_includes_multi_variant_sessions_under_each_arm(self) -> None:+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])+ test_only = self._session(variant="test", events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])+ control_only = self._session(variant="control", events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])+ both = self._session(variant="test", events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])+ _create_event(+ team=self.team,+ event="$feature_flag_called",+ distinct_id="user1",+ timestamp=datetime(2026, 1, 9, 10, 6, tzinfo=UTC),+ properties={+ "$session_id": both,+ "$feature_flag": "checkout-cta",+ "$feature_flag_response": "control",+ },+ )+ flush_persons_and_events()++ by_variant = {+ variant: set(+ self._post_bucket(+ experiment, bucket="fired_any", metric_uuids=[PURCHASE_METRIC["uuid"]], variant=variant+ ).json()["session_ids"]+ )+ for variant in ("test", "control")+ }++ # A session that saw both arms is the multi-exposure bias signal, not an error — it stays+ # visible under each variant it saw rather than being dropped from both.+ assert by_variant["test"] == {test_only, both}+ assert by_variant["control"] == {control_only, both}++ def test_sessions_without_a_recording_are_left_out(self) -> None:+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])+ recorded = self._session(events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])+ unrecorded = self._session(events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))], with_recording=False)+ flush_persons_and_events()++ response = self._post_bucket(experiment, bucket="fired_any", metric_uuids=[PURCHASE_METRIC["uuid"]])++ # The cap is small, so ids the playlist can never render must not consume it.+ assert response.json()["session_ids"] == [recorded]+ assert unrecorded not in response.json()["session_ids"]++ def test_returns_most_recent_first_and_flags_truncation(self) -> None:+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])+ older = self._session(+ at=datetime(2026, 1, 7, 10, 0, tzinfo=UTC),+ events=[("purchase", datetime(2026, 1, 7, 10, 5, tzinfo=UTC))],+ )+ newer = self._session(+ at=datetime(2026, 1, 9, 10, 0, tzinfo=UTC),+ events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))],+ )+ flush_persons_and_events()++ response = self._post_bucket(experiment, bucket="fired_any", metric_uuids=[PURCHASE_METRIC["uuid"]], limit=1)++ data = response.json()+ assert data["session_ids"] == [newer]+ assert older not in data["session_ids"]+ assert data["truncated"] is True++ def test_scan_window_is_clamped_to_the_recent_run_window(self) -> None:+ experiment = self._create_experiment(+ metrics=[PURCHASE_METRIC], start_date=NOW - timedelta(days=MAX_BUCKET_SCAN_DAYS + 30)+ )+ too_old = self._session(+ at=NOW - timedelta(days=MAX_BUCKET_SCAN_DAYS + 5),+ events=[("purchase", NOW - timedelta(days=MAX_BUCKET_SCAN_DAYS + 5) + timedelta(minutes=5))],+ )+ recent = self._session(events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])+ flush_persons_and_events()++ response = self._post_bucket(experiment, bucket="fired_any", metric_uuids=[PURCHASE_METRIC["uuid"]])++ data = response.json()+ assert data["session_ids"] == [recent]+ assert too_old not in data["session_ids"]+ # The response says what it scanned, so the surface can state the omission rather than+ # implying the bucket is empty beyond the clamp.+ assert data["date_from"] == (NOW - timedelta(days=MAX_BUCKET_SCAN_DAYS)).isoformat().replace("+00:00", "Z")++ def test_test_account_filtering_follows_the_exposure_criteria(self) -> None:+ self.team.test_account_filters = [{"key": "$host", "value": "localhost", "operator": "is_not", "type": "event"}]+ self.team.save()+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC], exposure_criteria={"filterTestAccounts": True})+ internal = self._session(+ distinct_id="internal",+ events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))],+ properties={"$host": "localhost"},+ )+ real = self._session(+ distinct_id="customer",+ events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))],+ properties={"$host": "app.example.com"},+ )+ flush_persons_and_events()++ response = self._post_bucket(experiment, bucket="fired_any", metric_uuids=[PURCHASE_METRIC["uuid"]])++ data = response.json()+ assert data["filter_test_accounts"] is True+ assert real in data["session_ids"]+ assert internal not in data["session_ids"]++ def test_not_launched_experiment_is_rejected(self) -> None:+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])+ experiment.start_date = None+ experiment.save()++ response = self._post_bucket(experiment, bucket="no_metric_activity")++ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_tags_its_clickhouse_queries_as_experiments(self) -> None:+ # Untagged queries lose their cost attribution in production, and the first scan runs+ # before anything else in the request has tagged — so this can't ride on another+ # product's tags the way the session-context endpoint does. Local dev raises on an+ # untagged query, but TEST mode doesn't, so the tag needs asserting here.+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])+ self._session(events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])+ flush_persons_and_events()++ # Captured at the ClickHouse boundary rather than read afterwards: the replay+ # recording-existence lookup tags itself last, and tags don't outlive the request.+ tagged_products = []+ original = hogql_query_module.sync_execute++ def _capturing_sync_execute(*args: Any, **kwargs: Any) -> Any:+ tagged_products.append(get_query_tags().product)+ return original(*args, **kwargs)++ with patch.object(hogql_query_module, "sync_execute", side_effect=_capturing_sync_execute):+ assert self._post_bucket(experiment, bucket="fired_any").status_code == status.HTTP_200_OK++ # The scan is ours; the recording-existence lookup that follows is replay's own helper+ # and tags itself. Neither may run untagged.+ assert tagged_products[0] == Product.EXPERIMENTS+ assert None not in tagged_products++ def test_recordings_blocked_by_object_level_access_are_left_out(self) -> None:+ features = self.organization.available_product_features or []+ features.append({"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL})+ self.organization.available_product_features = features+ self.organization.save()+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])+ blocked_session = self._session(events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])+ visible_session = self._session(+ distinct_id="user2", events=[("purchase", datetime(2026, 1, 9, 10, 6, tzinfo=UTC))]+ )+ flush_persons_and_events()+ blocked = SessionRecording.objects.create(team=self.team, session_id=blocked_session)+ AccessControl.objects.create(+ team=self.team, resource="session_recording", resource_id=str(blocked.id), access_level="none"+ )++ response = self._post_bucket(experiment, bucket="fired_any", metric_uuids=[PURCHASE_METRIC["uuid"]])++ # Replay-product access is not access to every recording in it. Returning the id of a+ # recording the viewer is denied would leak which sessions the experiment touched.+ data = response.json()+ assert visible_session in data["session_ids"]+ assert blocked_session not in data["session_ids"]++ def test_denied_recordings_neither_consume_a_slot_nor_show_up_in_truncation(self) -> None:+ features = self.organization.available_product_features or []+ features.append({"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL})+ self.organization.available_product_features = features+ self.organization.save()+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC])+ older_visible = self._session(+ at=datetime(2026, 1, 9, 9, 0, tzinfo=UTC), events=[("purchase", datetime(2026, 1, 9, 9, 5, tzinfo=UTC))]+ )+ newer_blocked = self._session(+ at=datetime(2026, 1, 9, 10, 0, tzinfo=UTC),+ distinct_id="user2",+ events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))],+ )+ flush_persons_and_events()+ blocked = SessionRecording.objects.create(team=self.team, session_id=newer_blocked)+ AccessControl.objects.create(+ team=self.team, resource="session_recording", resource_id=str(blocked.id), access_level="none"+ )++ response = self._post_bucket(experiment, bucket="fired_any", metric_uuids=[PURCHASE_METRIC["uuid"]], limit=1)++ # The denied recording is the most recent match, so cutting to the limit before the access+ # filter would spend the only slot on it and hand back nothing. And `truncated` would then+ # be the one bit that says a recording the viewer can't see matched this bucket.+ data = response.json()+ assert data["session_ids"] == [older_visible]+ assert newer_blocked not in data["session_ids"]+ assert data["truncated"] is False++ @parameterized.expand(+ [+ (+ "metric_count",+ [+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": f"{index:08d}-0000-0000-0000-000000000000",+ "name": f"Metric {index}",+ "source": PURCHASE,+ }+ for index in range(MAX_BUCKET_METRICS + 1)+ ],+ f"more than the {MAX_BUCKET_METRICS}",+ ),+ (+ "source_count",+ [+ _funnel(+ "a6666666-6666-6666-6666-666666666666",+ "Very long funnel",+ [PURCHASE for _ in range(MAX_BUCKET_SOURCES + 1)],+ )+ ],+ f"more than the {MAX_BUCKET_SOURCES}",+ ),+ ]+ )+ def test_refuses_a_metric_set_too_wide_to_scan(+ self, _name: str, metrics: list[dict[str, Any]], expected_reason: str+ ) -> None:+ experiment = self._create_experiment(metrics=metrics)+ # The metrics have to be matchable, or the linkability check refuses them first.+ EventProperty.objects.get_or_create(+ team=self.team, project_id=self.team.project_id, event="purchase", property="$session_id"+ )++ response = self._post_bucket(experiment, bucket="fired_any")++ # Metric and funnel-step counts are user-configurable with no server-side cap, so without+ # a ceiling one request can compile an arbitrarily wide query over the whole 30-day window.+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert expected_reason in response.json()["detail"]++ def test_team_isolation(self) -> None:+ other_team = Team.objects.create(organization=self.organization, name="other team")+ experiment = self._create_experiment(metrics=[PURCHASE_METRIC], key="other-team-flag", team=other_team)++ response = self._post_bucket(experiment, bucket="no_metric_activity")++ assert response.status_code == status.HTTP_404_NOT_FOUNDdiff --git a/products/experiments/backend/test/test_session_buckets_serializer.py b/products/experiments/backend/test/test_session_buckets_serializer.pynew file mode 100644index 000000000000..6c76904b9027--- /dev/null+++ b/products/experiments/backend/test/test_session_buckets_serializer.py@@ -0,0 +1,23 @@+from typing import Any++from posthog.test.base import SimpleTestCase++from parameterized import parameterized++from products.experiments.backend.presentation.serializers import ExperimentSessionBucketRequestSerializer+++class TestExperimentSessionBucketRequestValidation(SimpleTestCase):+ @parameterized.expand(+ [+ ("unknown_bucket", {"bucket": "helped"}, "bucket"),+ ("dropoff_without_metric", {"bucket": "funnel_dropoff"}, "metric_uuids"),+ ("dropoff_with_two_metrics", {"bucket": "funnel_dropoff", "metric_uuids": ["a", "b"]}, "metric_uuids"),+ ("limit_over_cap", {"bucket": "fired_any", "limit": 500}, "limit"),+ ]+ )+ def test_rejects_invalid_requests(self, _name: str, payload: dict[str, Any], expected_field: str) -> None:+ serializer = ExperimentSessionBucketRequestSerializer(data=payload)++ assert not serializer.is_valid()+ assert expected_field in serializer.errorsdiff --git a/products/experiments/backend/test/test_session_context_api.py b/products/experiments/backend/test/test_session_context_api.pyindex 49efb4e49250..993c0a4b2511 100644--- a/products/experiments/backend/test/test_session_context_api.py+++ b/products/experiments/backend/test/test_session_context_api.py@@ -10,9 +10,11 @@ from django.test import SimpleTestCasefrom rest_framework import status+import posthog.hogql.query as hogql_query_modulefrom posthog.hogql.database.database import Databasefrom posthog.hogql.database.models import Table, TableNode+from posthog.clickhouse.query_tagging import Product, get_query_tagsfrom posthog.constants import AvailableFeaturefrom posthog.models import PropertyDefinition, Team, Userfrom posthog.models.personal_api_key import PersonalAPIKey@@ -174,6 +176,31 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):assert response.status_code == status.HTTP_200_OKassert response.json() == {"session_id": SESSION_ID, "results": []}+ def test_tags_its_scans_as_experiments(self) -> None:+ # The scans are experiments' own logic and cost, rendered in the replay player. They used+ # to inherit product=replay from the recording-metadata lookup that runs first, so the+ # tag has to be applied after it — and local dev hard-errors on a query with no tag at+ # all, which TEST mode doesn't reproduce.+ self._create_recording()+ self._create_experiment()+ self._create_session_event(+ properties={"$feature_flag": "checkout-cta", "$feature_flag_response": "test"},+ )+ flush_persons_and_events()++ tagged_products = []+ original = hogql_query_module.sync_execute++ def _capturing_sync_execute(*args: Any, **kwargs: Any) -> Any:+ tagged_products.append(get_query_tags().product)+ return original(*args, **kwargs)++ with patch.object(hogql_query_module, "sync_execute", side_effect=_capturing_sync_execute):+ assert self._get_session_context().status_code == status.HTTP_200_OK++ assert tagged_products+ assert set(tagged_products) == {Product.EXPERIMENTS}+def test_resolves_variant_from_flag_called_event(self) -> None:self._create_recording()experiment = self._create_experiment()diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex f99e6708c91e..a1368ae118d5 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -2109,6 +2109,89 @@ export interface ExperimentMetricsRecalculationApi {estimated_rows_total?: number | null}+/**+ * * `fired_any` - fired_any+ * * `no_metric_activity` - no_metric_activity+ * * `funnel_dropoff` - funnel_dropoff+ */+export type ExperimentSessionBucketEnumApi =+ (typeof ExperimentSessionBucketEnumApi)[keyof typeof ExperimentSessionBucketEnumApi]++export const ExperimentSessionBucketEnumApi = {+ FiredAny: 'fired_any',+ NoMetricActivity: 'no_metric_activity',+ FunnelDropoff: 'funnel_dropoff',+} as const++/**+ * Request body for the session-bucket endpoint.+ */+export interface ExperimentSessionBucketRequestApi {+ /** Which question the returned session set answers. 'fired_any': the session fired at least one event of any listed metric (an OR the recordings query itself can't express). 'no_metric_activity': the session fired none of them. 'funnel_dropoff': the session fired the funnel metric's first step and never reached its last one. All three are session-scoped and goal-free: they say what happened in the session, not whether it helped or hurt the metric.+ *+ * * `fired_any` - fired_any+ * * `no_metric_activity` - no_metric_activity+ * * `funnel_dropoff` - funnel_dropoff */+ bucket: ExperimentSessionBucketEnumApi+ /** Metrics the bucket is computed over. Exactly one funnel metric for 'funnel_dropoff'. Omit for the other buckets to use every metric of the experiment that can be matched to recordings. */+ metric_uuids?: string[]+ /**+ * Restrict to sessions that saw this variant. Omit for every variant. A session that saw more than one variant matches each variant it saw.+ * @nullable+ */+ variant?: string | null+ /**+ * Maximum session IDs to return, at most 100. The most recently active matching sessions win.+ * @minimum 1+ * @maximum 100+ */+ limit?: number+}++/**+ * One metric the bucket was computed over.+ */+export interface ExperimentSessionBucketMetricApi {+ /** UUID of the experiment metric. */+ metric_uuid: string+ /** Display name of the metric, or an event-derived title (matching the experiment UI) when unnamed. */+ metric_name: string+}++/**+ * One requested metric the bucket could not be computed over.+ */+export interface ExperimentSessionBucketExcludedMetricApi {+ /** UUID of the experiment metric. */+ metric_uuid: string+ /** Display name of the metric. */+ metric_name: string+ /** Why the metric can't be matched to recordings: a data-warehouse-only source, a retention window, or events only ever captured server-side. */+ reason: string+}++/**+ * Session recordings of an experiment matching a bucket.+ */+export interface ExperimentSessionBucketResponseApi {+ /** IDs of matching sessions that have a recording, most recently active first. Feed these to a recordings query as session_ids; they are a subset of the experiment's exposed sessions, so the exposure filter can stay in place alongside them. */+ session_ids: string[]+ /** True when more sessions matched than the limit returned. Older matches were dropped first. */+ truncated: boolean+ /** The metrics the bucket was actually computed over. Load-bearing for 'no_metric_activity': 'fired nothing' only means something next to the list of metrics it was evaluated against. */+ considered_metrics: ExperimentSessionBucketMetricApi[]+ /** Requested metrics left out of the bucket because they can never match a recording, with the reason. They are reported rather than silently producing an empty result. */+ excluded_metrics: ExperimentSessionBucketExcludedMetricApi[]+ /** Start of the window scanned: the experiment's run window, clamped to its most recent 30 days. Matches outside it are not returned. */+ date_from: string+ /** End of the window scanned: the experiment's end date, or now while it runs. */+ date_to: string+ /** Whether the project's test-account filters were applied, following the experiment's exposure criteria, the same rule the experiment's recordings list uses. */+ filter_test_accounts: boolean+ /** True when the exposed population was matched on the stamped $feature/<flag key> event property instead of the exposure event, because the default exposure event has only ever been captured server-side and can never match a session. The sessions then mean 'the flag was active in this session', not 'the exposure moment was captured'. The variant comes from the flag's value on each event, so a returning user can appear under a variant they were re-bucketed into later. */+ used_exposure_fallback: boolean+}+export interface ShipVariantApi {/** The conclusion of the experiment.*diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.tsindex 2bda112fb713..1fa25d279b19 100644--- a/products/experiments/frontend/generated/api.ts+++ b/products/experiments/frontend/generated/api.ts@@ -22,6 +22,8 @@ import type {ExperimentMetricsRecalculationApi,ExperimentSavedMetricApi,ExperimentSavedMetricsListParams,+ ExperimentSessionBucketRequestApi,+ ExperimentSessionBucketResponseApi,ExperimentSessionContextResponseApi,ExperimentSessionContextsRequestApi,ExperimentSessionContextsResponseApi,@@ -865,6 +867,37 @@ export const experimentsResumeCreate = async (})}+export const getExperimentsSessionBucketsCreateUrl = (projectId: string, id: number) => {+ return `/api/projects/${projectId}/experiments/${id}/session_buckets/`+}++/**+ * Session recordings of this experiment matching a bucket.+ *+ * Answers the questions a recordings query can't express on its own — "fired any of these+ * metrics", "fired none of them", "entered the funnel but never completed it in this+ * session" — by returning a bounded, most-recent-first list of session IDs to pass back as+ * a recordings query's session_ids. POST because the metric list doesn't fit a query+ * string; the endpoint only reads.+ *+ * Session-scoped and goal-free: the set describes what happened in each session, while the+ * experiment analysis counts per person over the whole run window. A session can be in the+ * drop-off bucket while the same person converts in a later one.+ */+export const experimentsSessionBucketsCreate = async (+ projectId: string,+ id: number,+ experimentSessionBucketRequestApi: ExperimentSessionBucketRequestApi,+ options?: RequestInit+): Promise<ExperimentSessionBucketResponseApi> => {+ return apiMutator<ExperimentSessionBucketResponseApi>(getExperimentsSessionBucketsCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(experimentSessionBucketRequestApi),+ })+}+export const getExperimentsShipVariantCreateUrl = (projectId: string, id: number) => {return `/api/projects/${projectId}/experiments/${id}/ship_variant/`}diff --git a/products/experiments/frontend/generated/api.zod.ts b/products/experiments/frontend/generated/api.zod.tsindex 92753d9f218d..25250d66e710 100644--- a/products/experiments/frontend/generated/api.zod.ts+++ b/products/experiments/frontend/generated/api.zod.ts@@ -1055,6 +1055,53 @@ export const ExperimentsRecalculateTimeseriesCreateBody = /* @__PURE__ */ zod.record(zod.string(), zod.unknown()).describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')+/**+ * Session recordings of this experiment matching a bucket.+ *+ * Answers the questions a recordings query can't express on its own — "fired any of these+ * metrics", "fired none of them", "entered the funnel but never completed it in this+ * session" — by returning a bounded, most-recent-first list of session IDs to pass back as+ * a recordings query's session_ids. POST because the metric list doesn't fit a query+ * string; the endpoint only reads.+ *+ * Session-scoped and goal-free: the set describes what happened in each session, while the+ * experiment analysis counts per person over the whole run window. A session can be in the+ * drop-off bucket while the same person converts in a later one.+ */+export const experimentsSessionBucketsCreateBodyLimitDefault = 100+export const experimentsSessionBucketsCreateBodyLimitMax = 100++export const ExperimentsSessionBucketsCreateBody = /* @__PURE__ */ zod+ .object({+ bucket: zod+ .enum(['fired_any', 'no_metric_activity', 'funnel_dropoff'])+ .describe(+ '\* `fired_any` - fired_any\n\* `no_metric_activity` - no_metric_activity\n\* `funnel_dropoff` - funnel_dropoff'+ )+ .describe(+ "Which question the returned session set answers. 'fired_any': the session fired at least one event of any listed metric (an OR the recordings query itself can't express). 'no_metric_activity': the session fired none of them. 'funnel_dropoff': the session fired the funnel metric's first step and never reached its last one. All three are session-scoped and goal-free: they say what happened in the session, not whether it helped or hurt the metric.\n\n\* `fired_any` - fired_any\n\* `no_metric_activity` - no_metric_activity\n\* `funnel_dropoff` - funnel_dropoff"+ ),+ metric_uuids: zod+ .array(zod.string().describe("UUID of one of the experiment's metrics."))+ .optional()+ .describe(+ "Metrics the bucket is computed over. Exactly one funnel metric for 'funnel_dropoff'. Omit for the other buckets to use every metric of the experiment that can be matched to recordings."+ ),+ variant: zod+ .string()+ .nullish()+ .describe(+ 'Restrict to sessions that saw this variant. Omit for every variant. A session that saw more than one variant matches each variant it saw.'+ ),+ limit: zod+ .number()+ .min(1)+ .max(experimentsSessionBucketsCreateBodyLimitMax)+ .default(experimentsSessionBucketsCreateBodyLimitDefault)+ .describe('Maximum session IDs to return, at most 100. The most recently active matching sessions win.'),+ })+ .describe('Request body for the session-bucket endpoint.')+/*** Ship a variant and (optionally) end the experiment.*diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yamlindex b4c190708343..6fb558c1c4eb 100644--- a/products/experiments/mcp/tools.yaml+++ b/products/experiments/mcp/tools.yaml@@ -1266,6 +1266,9 @@ tools:experiments-recalculate-timeseries:operation: experiments_recalculate_timeseries_createenabled: false+ experiments-session-buckets-create:+ operation: experiments_session_buckets_create+ enabled: falseexperiments-session-context-retrieve:operation: experiments_session_context_retrieveenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a1a3410a1952..6ea4fb0f602c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -28562,6 +28562,89 @@ export namespace Schemas {readonly user_access_level: string | null;}+ /**+ * * `fired_any` - fired_any+ * * `no_metric_activity` - no_metric_activity+ * * `funnel_dropoff` - funnel_dropoff+ */+ export type ExperimentSessionBucketEnum = typeof ExperimentSessionBucketEnum[keyof typeof ExperimentSessionBucketEnum];+++ export const ExperimentSessionBucketEnum = {+ FiredAny: 'fired_any',+ NoMetricActivity: 'no_metric_activity',+ FunnelDropoff: 'funnel_dropoff',+ } as const;++ /**+ * One requested metric the bucket could not be computed over.+ */+ export interface ExperimentSessionBucketExcludedMetric {+ /** UUID of the experiment metric. */+ metric_uuid: string;+ /** Display name of the metric. */+ metric_name: string;+ /** Why the metric can't be matched to recordings: a data-warehouse-only source, a retention window, or events only ever captured server-side. */+ reason: string;+ }++ /**+ * One metric the bucket was computed over.+ */+ export interface ExperimentSessionBucketMetric {+ /** UUID of the experiment metric. */+ metric_uuid: string;+ /** Display name of the metric, or an event-derived title (matching the experiment UI) when unnamed. */+ metric_name: string;+ }++ /**+ * Request body for the session-bucket endpoint.+ */+ export interface ExperimentSessionBucketRequest {+ /** Which question the returned session set answers. 'fired_any': the session fired at least one event of any listed metric (an OR the recordings query itself can't express). 'no_metric_activity': the session fired none of them. 'funnel_dropoff': the session fired the funnel metric's first step and never reached its last one. All three are session-scoped and goal-free: they say what happened in the session, not whether it helped or hurt the metric.+ *+ * * `fired_any` - fired_any+ * * `no_metric_activity` - no_metric_activity+ * * `funnel_dropoff` - funnel_dropoff */+ bucket: ExperimentSessionBucketEnum;+ /** Metrics the bucket is computed over. Exactly one funnel metric for 'funnel_dropoff'. Omit for the other buckets to use every metric of the experiment that can be matched to recordings. */+ metric_uuids?: string[];+ /**+ * Restrict to sessions that saw this variant. Omit for every variant. A session that saw more than one variant matches each variant it saw.+ * @nullable+ */+ variant?: string | null;+ /**+ * Maximum session IDs to return, at most 100. The most recently active matching sessions win.+ * @minimum 1+ * @maximum 100+ */+ limit?: number;+ }++ /**+ * Session recordings of an experiment matching a bucket.+ */+ export interface ExperimentSessionBucketResponse {+ /** IDs of matching sessions that have a recording, most recently active first. Feed these to a recordings query as session_ids; they are a subset of the experiment's exposed sessions, so the exposure filter can stay in place alongside them. */+ session_ids: string[];+ /** True when more sessions matched than the limit returned. Older matches were dropped first. */+ truncated: boolean;+ /** The metrics the bucket was actually computed over. Load-bearing for 'no_metric_activity': 'fired nothing' only means something next to the list of metrics it was evaluated against. */+ considered_metrics: ExperimentSessionBucketMetric[];+ /** Requested metrics left out of the bucket because they can never match a recording, with the reason. They are reported rather than silently producing an empty result. */+ excluded_metrics: ExperimentSessionBucketExcludedMetric[];+ /** Start of the window scanned: the experiment's run window, clamped to its most recent 30 days. Matches outside it are not returned. */+ date_from: string;+ /** End of the window scanned: the experiment's end date, or now while it runs. */+ date_to: string;+ /** Whether the project's test-account filters were applied, following the experiment's exposure criteria, the same rule the experiment's recordings list uses. */+ filter_test_accounts: boolean;+ /** True when the exposed population was matched on the stamped $feature/<flag key> event property instead of the exposure event, because the default exposure event has only ever been captured server-side and can never match a session. The sessions then mean 'the flag was active in this session', not 'the exposure moment was captured'. The variant comes from the flag's value on each event, so a returning user can appear under a variant they were re-bucketed into later. */+ used_exposure_fallback: boolean;+ }+/*** * `source` - source* * `step` - step