:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(experiments): Add metrics and events to experiments player (filters, player markers, inspect items) (#72240)
Marcel Poelkere9b59a75b01f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex cc76c8fd0ef9..50e249c02ce1 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4967,9 +4967,9 @@ snapshots:replay-overview-tab--wide-overview-tab--light:hash: v1.k794b7964.deb71477c91ae3fb89eaa9c6c9a45e665db4fa8363df4de30b3737c655930825.n5T9fmKBWN7qXDwbX9sYPEtdRgVYiaUgrJfvtail2tgreplay-overview-tab-experiments--default--dark:- hash: v1.k794b7964.33a861df26de2c58bb3f682709f548f3c18e4055068e53210d6bf0eed290f3b9.n3yoSXnVRzJVlrCCoLNytIv7UTIIaJA1fb-ApkS6_rE+ hash: v1.k794b7964.84ba0a1ff57ca5b14b54715912350609faee2d5c65f9ea6c5ade055b33ddcc81.D2N4NQPNCpcUXsQkvrjeq_XDQ8L98D6paPPsajdYWgQreplay-overview-tab-experiments--default--light:- hash: v1.k794b7964.d9bf55d955df06da692463ec7d1526a899103567f37d68e807c2c3b94c575e78.dRJfZZ5apQCOXa20PcujmkCflmN-X733GYazCRK2PRg+ hash: v1.k794b7964.4d37d89ed1aeb7e8d0d037a9c468e2f36986abb9b6b07d712bab94dfbaf35148.pGSFsm8IUjIcH3ffC3Iw0NRrCJcbWB2L2eBAvjxxPFsreplay-overview-tab-experiments--empty--dark:hash: v1.k794b7964.13e51a486b40a1455fde0075af333e3dff21f25491d06cc59ab10c24200eb1d2.Fn0OHVeRm39HLB3-xcZUZavR375CxuNraJZdmfxTS-Ureplay-overview-tab-experiments--empty--light:diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsxindex f3f5c0eebe95..1b1d20d50362 100644--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx@@ -1,13 +1,16 @@import { useActions, useValues } from 'kea'+import { IconChevronDown } from '@posthog/icons'import { LemonBanner, LemonSegmentedButton } from '@posthog/lemon-ui'+import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuTrigger } from '@posthog/quill'+import { LemonButton } from 'lib/lemon-ui/LemonButton'import { SessionRecordingsPlaylist } from 'scenes/session-recordings/playlist/SessionRecordingsPlaylist'import { Experiment } from '~/types'import { isLaunched } from '../experimentStatus'-import { EXPOSURE_UNLINKABLE_REASON } from '../viewRecordingsLinkabilityLogic'+import { EXPOSURE_UNLINKABLE_REASON, METRIC_UNLINKABLE_REASON } from '../viewRecordingsLinkabilityLogic'import { experimentReplayTabLogic } from './experimentReplayTabLogic'import { VariantTag } from './VariantTag'@@ -18,8 +21,15 @@ const ALL_VARIANTS = '$all'export function ExperimentReplayTab({ experiment }: { experiment: Experiment }): JSX.Element {const logic = experimentReplayTabLogic({ experiment })- const { effectiveVariantKey, variantKeys, recordingsFilters, exposureUnlinkable } = useValues(logic)- const { setSelectedVariantKey } = useActions(logic)+ const {+ effectiveVariantKey,+ variantKeys,+ recordingsFilters,+ exposureUnlinkable,+ effectiveMetricUuids,+ metricOptions,+ } = useValues(logic)+ const { setSelectedVariantKey, setMetricSelected } = useActions(logic)if (!isLaunched(experiment)) {return <LemonBanner type="info">Launch the experiment to see recordings of participants.</LemonBanner>@@ -31,7 +41,7 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):return (<div data-attr="experiment-recordings-tab">- <div className="mb-2">+ <div className="mb-2 flex flex-wrap gap-2"><LemonSegmentedButtonsize="small"value={effectiveVariantKey ?? ALL_VARIANTS}@@ -41,6 +51,50 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):...variantKeys.map((key) => ({ value: key, label: <VariantTag variantKey={key} /> })),]}/>+ {metricOptions.length > 0 && (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <LemonButton+ 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."+ data-attr="experiment-recordings-metric-filter"+ />+ }+ >+ {effectiveMetricUuids.length > 0+ ? `Metric events (${effectiveMetricUuids.length})`+ : 'Metric events'}+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="min-w-fit max-w-100">+ {metricOptions.map((option) => (+ <DropdownMenuCheckboxItem+ key={option.uuid}+ checked={effectiveMetricUuids.includes(option.uuid)}+ onCheckedChange={(checked: boolean) => setMetricSelected(option.uuid, checked)}+ closeOnClick={false}+ disabled={option.unlinkable}+ data-attr="experiment-recordings-metric-option"+ >+ {option.unlinkable ? (+ // Disabled items get pointer-events: none, so a tooltip can't+ // explain them — the reason renders inline instead.+ <span className="flex flex-col items-start text-left">+ <span>{option.name}</span>+ <span className="text-muted whitespace-normal">+ {METRIC_UNLINKABLE_REASON}+ </span>+ </span>+ ) : (+ option.name+ )}+ </DropdownMenuCheckboxItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ )}</div><div className="SessionRecordingPlaylistHeightWrapper"><SessionRecordingsPlaylistdiff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.tsindex d2039a1b111c..8cf0c0b4bb77 100644--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts@@ -2,6 +2,7 @@ import { expectLogic } from 'kea-test-utils'import api from 'lib/api'+import { ExperimentMetricType, NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import { Experiment, FilterLogicalOperator } from '~/types'@@ -12,12 +13,33 @@ jest.mock('lib/utils/product-intents', () => ({addProductIntentForCrossSell: jest.fn().mockResolvedValue(null),}))+const PURCHASE_METRIC = {+ kind: NodeKind.ExperimentMetric,+ metric_type: ExperimentMetricType.MEAN,+ uuid: 'metric-purchase',+ name: 'Purchase',+ source: { kind: NodeKind.EventsNode, event: 'purchase' },+}++const FUNNEL_METRIC = {+ kind: NodeKind.ExperimentMetric,+ metric_type: ExperimentMetricType.FUNNEL,+ uuid: 'metric-funnel',+ name: 'Checkout funnel',+ series: [+ { kind: NodeKind.EventsNode, event: 'server_side_step' },+ { kind: NodeKind.EventsNode, event: 'client_step' },+ ],+}+const EXPERIMENT = {id: 42,feature_flag_key: 'my-flag',start_date: '2026-01-01T00:00:00Z',end_date: '2026-02-01T00:00:00Z',exposure_criteria: { filterTestAccounts: true },+ metrics: [PURCHASE_METRIC],+ metrics_secondary: [FUNNEL_METRIC],feature_flag: {filters: {multivariate: {@@ -30,6 +52,13 @@ const EXPERIMENT = {},} as unknown as Experiment+const ALL_LINKABLE = {+ $feature_flag_called: true,+ purchase: true,+ server_side_step: true,+ client_step: true,+}+describe('experimentReplayTabLogic', () => {let logic: ReturnType<typeof experimentReplayTabLogic.build>let seenTogetherSpy: jest.SpyInstance@@ -39,7 +68,7 @@ describe('experimentReplayTabLogic', () => {localStorage.clear()initKeaTests()seenTogetherSpy = jest.spyOn(api.propertyDefinitions, 'seenTogether')- seenTogetherSpy.mockResolvedValue({ $feature_flag_called: true })+ seenTogetherSpy.mockResolvedValue(ALL_LINKABLE)logic = experimentReplayTabLogic({ experiment: EXPERIMENT })logic.mount()})@@ -148,4 +177,203 @@ describe('experimentReplayTabLogic', () => {it('keeps the list when the exposure event is session-linkable', async () => {await expectLogic(logic).toFinishAllListeners().toMatchValues({ exposureUnlinkable: false })})++ it('ANDs each selected metric filter onto the exposure filter, and ignores unknown metric uuids', async () => {+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.metricOptions.map((option) => option.uuid)).toEqual(['metric-purchase', 'metric-funnel'])++ logic.actions.setMetricSelected('metric-purchase', true)+ expect(logic.values.effectiveMetricUuids).toEqual(['metric-purchase'])+ expect(logic.values.recordingsFilters.filter_group.values).toEqual([+ {+ type: FilterLogicalOperator.And,+ values: [+ ...getViewRecordingFiltersForVariant(EXPERIMENT, undefined),+ { id: 'purchase', name: 'purchase', type: 'events', properties: [] },+ ],+ },+ ])++ // A second selection narrows further: both metrics' primary events AND together.+ logic.actions.setMetricSelected('metric-funnel', true)+ expect(logic.values.effectiveMetricUuids).toEqual(['metric-purchase', 'metric-funnel'])+ expect(logic.values.recordingsFilters.filter_group.values).toEqual([+ {+ type: FilterLogicalOperator.And,+ values: [+ ...getViewRecordingFiltersForVariant(EXPERIMENT, undefined),+ { id: 'purchase', name: 'purchase', type: 'events', properties: [] },+ { id: 'server_side_step', name: 'server_side_step', type: 'events', properties: [] },+ ],+ },+ ])++ logic.actions.setMetricSelected('metric-purchase', false)+ logic.actions.setMetricSelected('metric-funnel', false)+ // A persisted uuid whose metric has since been removed must not leak into the query.+ logic.actions.setMetricSelected('ghost', true)+ expect(logic.values.effectiveMetricUuids).toEqual([])+ expect(logic.values.recordingsFilters.filter_group.values).toEqual([+ {+ type: FilterLogicalOperator.And,+ values: getViewRecordingFiltersForVariant(EXPERIMENT, undefined),+ },+ ])+ })++ it('disables a fully server-side metric and never ANDs it into the query', async () => {+ seenTogetherSpy.mockResolvedValue({ ...ALL_LINKABLE, purchase: false })+ const serverSideMetric = experimentReplayTabLogic({ experiment: { ...EXPERIMENT, id: 44 } as Experiment })+ serverSideMetric.mount()+ await expectLogic(serverSideMetric).toFinishAllListeners()++ expect(serverSideMetric.values.metricOptions.find((option) => option.uuid === 'metric-purchase')).toMatchObject(+ { unlinkable: true }+ )+ serverSideMetric.actions.setMetricSelected('metric-purchase', true)+ expect(serverSideMetric.values.effectiveMetricUuids).toEqual([])+ // The unlinkable event would zero the whole AND-combined query — it must never appear.+ expect(serverSideMetric.values.recordingsFilters.filter_group.values).toEqual([+ {+ type: FilterLogicalOperator.And,+ values: getViewRecordingFiltersForVariant(EXPERIMENT, undefined),+ },+ ])+ serverSideMetric.unmount()+ })++ it('keeps a partially linkable metric selectable but drops its unlinkable step from the query', async () => {+ seenTogetherSpy.mockResolvedValue({ ...ALL_LINKABLE, server_side_step: false })+ const partiallyLinkable = experimentReplayTabLogic({ experiment: { ...EXPERIMENT, id: 45 } as Experiment })+ partiallyLinkable.mount()+ await expectLogic(partiallyLinkable).toFinishAllListeners()++ expect(partiallyLinkable.values.metricOptions.find((option) => option.uuid === 'metric-funnel')).toMatchObject({+ 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: [] },+ ],+ },+ ])+ 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.+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.setMetricSelected('metric-funnel', true)+ 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: [] },+ ],+ },+ ])+ })++ it('skips metrics without a uuid — the persisted selection needs a stable identity', async () => {+ // A positional stand-in id would re-attach a persisted selection to a *different* metric+ // once the metric list is edited, silently filtering the playlist on the wrong event.+ const withoutUuid = experimentReplayTabLogic({+ experiment: {+ ...EXPERIMENT,+ id: 47,+ metrics: [{ ...PURCHASE_METRIC, uuid: undefined }],+ metrics_secondary: [],+ } as unknown as Experiment,+ })+ withoutUuid.mount()+ await expectLogic(withoutUuid).toFinishAllListeners()++ expect(withoutUuid.values.metricOptions).toEqual([])+ withoutUuid.unmount()+ })++ it('holds metric filters out of the query until the linkability check lands', async () => {+ // Applying a persisted selection before linkability is known can fire an exposure+metric+ // query that can only be empty (server-side-only metric), flashing a false empty state.+ let resolveSeenTogether!: (map: Record<string, boolean>) => void+ seenTogetherSpy.mockReturnValue(new Promise((resolve) => (resolveSeenTogether = resolve)))+ const pending = experimentReplayTabLogic({ experiment: { ...EXPERIMENT, id: 48 } as Experiment })+ pending.mount()+ pending.actions.setMetricSelected('metric-purchase', true)++ expect(pending.values.recordingsFilters.filter_group.values).toEqual([+ {+ type: FilterLogicalOperator.And,+ values: getViewRecordingFiltersForVariant(EXPERIMENT, undefined),+ },+ ])++ resolveSeenTogether(ALL_LINKABLE)+ await expectLogic(pending).toFinishAllListeners()+ expect(pending.values.recordingsFilters.filter_group.values).toEqual([+ {+ type: FilterLogicalOperator.And,+ values: [+ ...getViewRecordingFiltersForVariant(EXPERIMENT, undefined),+ { id: 'purchase', name: 'purchase', type: 'events', properties: [] },+ ],+ },+ ])+ pending.unmount()+ })++ it('applies metric filters when the linkability check fails — fail open, not permanently gated', async () => {+ seenTogetherSpy.mockRejectedValue(new Error('network error'))+ const failed = experimentReplayTabLogic({ experiment: { ...EXPERIMENT, id: 49 } as Experiment })+ failed.mount()+ failed.actions.setMetricSelected('metric-purchase', true)+ await expectLogic(failed).toFinishAllListeners()++ expect(failed.values.recordingsFilters.filter_group.values).toEqual([+ {+ type: FilterLogicalOperator.And,+ values: [+ ...getViewRecordingFiltersForVariant(EXPERIMENT, undefined),+ { id: 'purchase', name: 'purchase', type: 'events', properties: [] },+ ],+ },+ ])+ failed.unmount()+ })++ it('offers saved/shared metrics in the facet, deduped by uuid', async () => {+ const savedMetric = {+ query: {+ kind: NodeKind.ExperimentMetric,+ metric_type: ExperimentMetricType.MEAN,+ uuid: 'metric-saved',+ name: 'Signups',+ source: { kind: NodeKind.EventsNode, event: 'signup' },+ },+ }+ const withSaved = experimentReplayTabLogic({+ experiment: {+ ...EXPERIMENT,+ id: 46,+ // Same saved metric linked twice (e.g. primary + secondary) must yield one chip.+ saved_metrics: [savedMetric, savedMetric],+ } as unknown as Experiment,+ })+ withSaved.mount()+ await expectLogic(withSaved).toFinishAllListeners()++ expect(withSaved.values.metricOptions.map((option) => option.uuid)).toEqual([+ 'metric-purchase',+ 'metric-funnel',+ 'metric-saved',+ ])+ withSaved.unmount()+ })})diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.tsindex 4765e3b65ac9..3358822218df 100644--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts@@ -3,30 +3,57 @@ import { MakeLogicType, actions, afterMount, connect, kea, key, path, props, redimport { addProductIntentForCrossSell } from 'lib/utils/product-intents'import { DEFAULT_RECORDING_FILTERS } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'-import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'-import { Experiment, FilterLogicalOperator, RecordingUniversalFilters } from '~/types'+import { ExperimentMetric, NodeKind, ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'+import { Experiment, FilterLogicalOperator, RecordingUniversalFilters, UniversalFiltersGroupValue } from '~/types'import type { ExperimentIdType } from '../../../types'-import { applySessionLinkability, getExperimentVariants, getViewRecordingFiltersForVariant } from '../utils'+import type { ExperimentSavedMetric } from '../experimentLogic'+import { getDefaultMetricTitle } from '../MetricsView/shared/utils'+import {+ applySessionLinkability,+ getExperimentVariants,+ getMetricSessionFilters,+ getViewRecordingFiltersForVariant,+ isUnlinkableEventFilter,+} from '../utils'import { viewRecordingsLinkabilityLogic } from '../viewRecordingsLinkabilityLogic'export interface ExperimentReplayTabLogicProps {experiment: Experiment}+/** One experiment metric offered in the recordings tab's "Metric events" dropdown. */+export interface ExperimentReplayMetricOption {+ uuid: string+ name: string+ filters: UniversalFiltersGroupValue[]+ unlinkable: boolean+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface experimentReplayTabLogicValues {linkabilityLoaded: boolean // viewRecordingsLinkabilityLogic+ seenTogetherMapLoading: boolean // viewRecordingsLinkabilityLogicunlinkableEventNames: Set<string> // viewRecordingsLinkabilityLogic+ effectiveMetricUuids: string[]effectiveVariantKey: string | nullexposureUnlinkable: boolean+ metricOptions: ExperimentReplayMetricOption[]recordingsFilters: RecordingUniversalFilters+ selectedMetricUuids: string[]selectedVariantKey: string | nullvariantKeys: string[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface experimentReplayTabLogicActions {+ setMetricSelected: (+ metricUuid: string,+ selected: boolean+ ) => {+ metricUuid: string+ selected: boolean+ }setSelectedVariantKey: (variantKey: string | null) => {variantKey: string | null}@@ -39,7 +66,20 @@ export interface experimentReplayTabLogicMeta {variantKeys: (arg: any) => string[]exposureUnlinkable: (linkabilityLoaded: boolean, unlinkableEventNames: Set<string>, arg: any) => booleaneffectiveVariantKey: (selectedVariantKey: string | null, variantKeys: string[]) => string | null- recordingsFilters: (effectiveVariantKey: string | null, arg: any) => RecordingUniversalFilters+ metricOptions: (+ linkabilityLoaded: boolean,+ unlinkableEventNames: Set<string>,+ arg: any+ ) => ExperimentReplayMetricOption[]+ effectiveMetricUuids: (selectedMetricUuids: string[], metricOptions: ExperimentReplayMetricOption[]) => string[]+ recordingsFilters: (+ effectiveVariantKey: string | null,+ effectiveMetricUuids: string[],+ metricOptions: ExperimentReplayMetricOption[],+ unlinkableEventNames: Set<string>,+ seenTogetherMapLoading: boolean,+ arg: any+ ) => RecordingUniversalFilters}}@@ -52,7 +92,7 @@ export type experimentReplayTabLogicType = MakeLogicType</*** Backs the experiment "Recordings" tab: sessions exposed to the experiment over its run window,- * narrowed by the variant facet.+ * narrowed by the variant facet and the metric facet ("replays that reached this metric").*/export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([props({} as ExperimentReplayTabLogicProps),@@ -62,11 +102,12 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([// Same key as the metric buttons' lookup, so the two surfaces share one `seen_together` request.values: [viewRecordingsLinkabilityLogic({ experiment: props.experiment }),- ['unlinkableEventNames', 'linkabilityLoaded'],+ ['unlinkableEventNames', 'linkabilityLoaded', 'seenTogetherMapLoading'],],})),actions({setSelectedVariantKey: (variantKey: string | null) => ({ variantKey }),+ setMetricSelected: (metricUuid: string, selected: boolean) => ({ metricUuid, selected }),}),reducers({// null = "All" (every exposed session, regardless of variant). Persisted (keyed per@@ -79,6 +120,20 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([setSelectedVariantKey: (_, { variantKey }) => variantKey,},],+ // Empty = no metric filter. Every selected metric narrows the playlist further (AND) —+ // OR across metrics is inexpressible, since the recordings query carries a single+ // operator shared with the exposure filter. Persisted for the same reason as the+ // variant facet.+ selectedMetricUuids: [+ [] as string[],+ { persist: true },+ {+ setMetricSelected: (state: string[], { metricUuid, selected }) =>+ selected+ ? [...state.filter((uuid) => uuid !== metricUuid), metricUuid]+ : state.filter((uuid) => uuid !== metricUuid),+ },+ ],}),selectors({variantKeys: [@@ -100,23 +155,131 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([(selectedVariantKey: string | null, variantKeys: string[]): string | null =>selectedVariantKey !== null && variantKeys.includes(selectedVariantKey) ? selectedVariantKey : null,],+ // Every uuid-carrying metric with at least one event/action source: inline primary ++ // secondary, then saved/shared metrics (their definition lives in `saved_metrics[].query`)+ // — the same set the backend `resolve_metric_events` scans, deduped by uuid so a shared+ // metric linked more than once shows one option. Metrics without a uuid are skipped, as+ // the backend does: the selection persists across remounts, and any positional stand-in+ // id could re-attach it to a different metric after the metric list is edited. A metric+ // is unlinkable only when every one of its sources is a never-session-linked event — with+ // no linkable source at all, its filter could only match zero sessions. Fails open while+ // the check loads.+ metricOptions: [+ (s) => [s.linkabilityLoaded, s.unlinkableEventNames, (_, props) => props.experiment],+ (+ linkabilityLoaded: boolean,+ unlinkableEventNames: Set<string>,+ experiment: Experiment+ ): ExperimentReplayMetricOption[] => {+ const inlineMetrics = [...(experiment.metrics || []), ...(experiment.metrics_secondary || [])]+ const savedMetrics = ((experiment.saved_metrics || []) as ExperimentSavedMetric[]).map(+ (saved) => saved.query+ )+ const seenUuids = new Set<string>()+ return [...inlineMetrics, ...savedMetrics]+ .filter((metric): metric is ExperimentMetric => metric?.kind === NodeKind.ExperimentMetric)+ .flatMap((metric) =>+ metric.uuid+ ? [+ {+ uuid: metric.uuid,+ name: metric.name || getDefaultMetricTitle(metric),+ filters: getMetricSessionFilters(metric),+ },+ ]+ : []+ )+ .filter((option) => {+ if (option.filters.length === 0 || seenUuids.has(option.uuid)) {+ return false+ }+ seenUuids.add(option.uuid)+ return true+ })+ .map((option) => ({+ ...option,+ unlinkable:+ linkabilityLoaded &&+ option.filters.every((filter) => isUnlinkableEventFilter(filter, unlinkableEventNames)),+ }))+ },+ ],+ effectiveMetricUuids: [+ (s) => [s.selectedMetricUuids, s.metricOptions],+ (selectedMetricUuids: string[], metricOptions: ExperimentReplayMetricOption[]): string[] =>+ selectedMetricUuids.filter((uuid) => {+ const option = metricOptions.find((candidate) => candidate.uuid === uuid)+ return !!option && !option.unlinkable+ }),+ ],recordingsFilters: [- (s) => [s.effectiveVariantKey, (_, props) => props.experiment],- (effectiveVariantKey: string | null, experiment: Experiment): RecordingUniversalFilters => ({- ...DEFAULT_RECORDING_FILTERS,- date_from: experiment.start_date ?? DEFAULT_RECORDING_FILTERS.date_from,- date_to: experiment.end_date ?? null,- filter_test_accounts: experiment.exposure_criteria?.filterTestAccounts ?? false,- filter_group: {- type: FilterLogicalOperator.And,- values: [- {- type: FilterLogicalOperator.And,- values: getViewRecordingFiltersForVariant(experiment, effectiveVariantKey ?? undefined),- },- ],- },- }),+ (s) => [+ s.effectiveVariantKey,+ s.effectiveMetricUuids,+ s.metricOptions,+ s.unlinkableEventNames,+ s.seenTogetherMapLoading,+ (_, props) => props.experiment,+ ],+ (+ effectiveVariantKey: string | null,+ effectiveMetricUuids: string[],+ metricOptions: ExperimentReplayMetricOption[],+ unlinkableEventNames: Set<string>,+ seenTogetherMapLoading: boolean,+ experiment: Experiment+ ): RecordingUniversalFilters => {+ // A recordings query carries a single AND/OR operand across the whole flattened+ // filter tree (see `deriveOperand`), so "exposed to the variant AND (any of the+ // metric's events)" can't be expressed — an OR anywhere flips the exposure filter to+ // OR too. Each selected metric matches on its primary event (the first+ // session-linkable source: a mean metric's event, a funnel's entry step, a ratio's+ // numerator) rather than ANDing every source, which used to require a session to+ // fire *all* funnel steps. Multiple selected metrics AND together — each narrows.+ //+ // While the linkability check is in flight, metric filters stay out of the query:+ // a persisted selection of a metric that turns out unlinkable would otherwise fire+ // an exposure+metric query that can only be empty, flashing a false "no recordings"+ // state. Exposure-only is the correct superset until the check lands. If the check+ // *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+ })+ return {+ ...DEFAULT_RECORDING_FILTERS,+ date_from: experiment.start_date ?? DEFAULT_RECORDING_FILTERS.date_from,+ date_to: experiment.end_date ?? null,+ filter_test_accounts: experiment.exposure_criteria?.filterTestAccounts ?? false,+ filter_group: {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: FilterLogicalOperator.And,+ values: [+ ...getViewRecordingFiltersForVariant(experiment, effectiveVariantKey ?? undefined),+ ...metricFilters,+ ],+ },+ ],+ },+ }+ },],}),afterMount(() => {diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.tsindex a348e1df8a22..97092e2a8010 100644--- a/frontend/src/scenes/experiments/utils.ts+++ b/frontend/src/scenes/experiments/utils.ts@@ -351,6 +351,44 @@ export function getViewRecordingFilters(return filters}+/**+ * Event/action filters for one metric's sources — the "session reached this metric" part of a+ * recordings query. Data-warehouse sources have no session events and are skipped, so a metric+ * whose every source is a data-warehouse node (or a retention metric, whose steps the recordings+ * surfaces don't enumerate) yields no filters.+ */+export function getMetricSessionFilters(metric: ExperimentMetric): UniversalFiltersGroupValue[] {+ const sources: (ExperimentMetricSource | ExperimentFunnelMetricStep)[] = isExperimentMeanMetric(metric)+ ? [metric.source]+ : isExperimentFunnelMetric(metric)+ ? metric.series+ : isExperimentRatioMetric(metric)+ ? [metric.numerator, metric.denominator]+ : []+ return sources+ .filter((source) => source.kind === NodeKind.EventsNode || source.kind === NodeKind.ActionsNode)+ .map((source) => seriesToFilter(source))+ .filter((filter): filter is UniversalFiltersGroupValue => filter !== 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 filters+ * pass through unchecked, matching the replay playlist's own posture.+ */+export function isUnlinkableEventFilter(+ filter: UniversalFiltersGroupValue,+ unlinkableEventNames: Set<string>+): boolean {+ return (+ 'type' in filter &&+ filter.type === 'events' &&+ 'name' in filter &&+ typeof filter.name === 'string' &&+ unlinkableEventNames.has(filter.name)+ )+}+/*** Event names whose session-linkability must be checked before building "View recordings" links:* the exposure event plus every plain-event metric step across primary, secondary and shared@@ -405,11 +443,7 @@ export function applySessionLinkability(unlinkableEventNames: Set<string>): { filters: UniversalFiltersGroupValue[]; droppedMetricEventCount: number; exposureUnlinkable: boolean } {const isUnlinkable = (filter: UniversalFiltersGroupValue): boolean =>- 'type' in filter &&- filter.type === 'events' &&- 'name' in filter &&- typeof filter.name === 'string' &&- unlinkableEventNames.has(filter.name)+ isUnlinkableEventFilter(filter, unlinkableEventNames)if (filters.length === 0) {return { filters: [], droppedMetricEventCount: 0, exposureUnlinkable: false }diff --git a/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts b/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.tsindex 7daa43f7ee46..bad4edef9e1c 100644--- a/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts+++ b/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts@@ -16,6 +16,9 @@ export interface ViewRecordingsLinkabilityLogicProps {export const EXPOSURE_UNLINKABLE_REASON ="This experiment's exposure event is captured server-side without a session ID, so recordings can't be matched."+export const METRIC_UNLINKABLE_REASON =+ "This metric's events are captured server-side without a session ID, so recordings can't be matched."+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface viewRecordingsLinkabilityLogicValues {linkabilityLoaded: booleandiff --git a/frontend/src/scenes/session-recordings/__mocks__/experiment_session_context.ts b/frontend/src/scenes/session-recordings/__mocks__/experiment_session_context.tsindex 1a616faa6c29..48b899ab180c 100644--- a/frontend/src/scenes/session-recordings/__mocks__/experiment_session_context.ts+++ b/frontend/src/scenes/session-recordings/__mocks__/experiment_session_context.ts@@ -15,6 +15,7 @@ export const makeExperimentSessionContextItem = (first_exposure_timestamp: '2023-05-01T14:46:24.000000Z',experiment_start_date: '2023-04-01T00:00:00Z',experiment_end_date: null,+ metrics_in_session: [],...overrides,})@@ -23,7 +24,31 @@ export const makeExperimentSessionContextItem = (export const experimentSessionContextResponse: ExperimentSessionContextResponseApi = {session_id: 'experiment-context-session',results: [- makeExperimentSessionContextItem(),+ makeExperimentSessionContextItem({+ metrics_in_session: [+ {+ metric_uuid: 'metric-1',+ metric_name: 'purchase completed',+ event_count: 3,+ // Inside the recording_meta mock's bounds — renders as a seekable jump link.+ first_timestamp: '2023-05-01T14:46:26.000000Z',+ // Three in-bounds occurrences — renders per-event seek chips.+ timestamps: [+ '2023-05-01T14:46:26.000000Z',+ '2023-05-01T14:46:31.000000Z',+ '2023-05-01T14:46:44.000000Z',+ ],+ },+ {+ metric_uuid: 'metric-2',+ metric_name: 'checkout started',+ event_count: 1,+ // Outside the recording bounds (backend ±1h slack) — renders without a jump link.+ first_timestamp: '2023-05-01T15:20:00.000000Z',+ timestamps: ['2023-05-01T15:20:00.000000Z'],+ },+ ],+ }),makeExperimentSessionContextItem({experiment_id: 102,experiment_name: 'Pricing page layout',diff --git a/frontend/src/scenes/session-recordings/player/controller/PlayerSeekbarTicks.tsx b/frontend/src/scenes/session-recordings/player/controller/PlayerSeekbarTicks.tsxindex 6dc44aa72df6..92622efd03e6 100644--- a/frontend/src/scenes/session-recordings/player/controller/PlayerSeekbarTicks.tsx+++ b/frontend/src/scenes/session-recordings/player/controller/PlayerSeekbarTicks.tsx@@ -18,6 +18,7 @@ import {InspectorListItemComment,InspectorListItemEvent,InspectorListItemExperimentVariant,+ InspectorListItemMetricEvent,InspectorListItemNotebookComment,} from 'scenes/session-recordings/player/inspector/playerInspectorLogic'import { isSingleEmoji } from 'scenes/session-recordings/utils'@@ -34,6 +35,10 @@ function isExperimentVariantItem(x: InspectorListItem): x is InspectorListItemExreturn x.type === 'experiment-variant'}+function isMetricEventItem(x: InspectorListItem): x is InspectorListItemMetricEvent {+ return x.type === 'metric-event'+}+function isNotebookComment(x: InspectorListItem): x is InspectorListItemNotebookComment {if (x.type !== 'comment') {return false@@ -68,6 +73,7 @@ function PlayerSeekbarTick({| InspectorListItemNotebookComment| InspectorListItemEvent| InspectorListItemExperimentVariant+ | InspectorListItemMetricEventendTimeMs: numberzIndex: numberonClick: (e: React.MouseEvent) => void@@ -106,6 +112,10 @@ function PlayerSeekbarTick({<>Saw variant "{item.data.variant}" of {item.data.experimentName}</>+ ) : isMetricEventItem(item) ? (+ <>+ Fired a {item.data.metricName} event ({item.data.experimentName})+ </>) : isEventItem(item) ? (<>{item.data.event === '$autocapture' ? (@@ -168,6 +178,7 @@ const MemoisedPlayerSeekbarTicks = memo(| InspectorListItemComment| InspectorListItemNotebookComment| InspectorListItemExperimentVariant+ | InspectorListItemMetricEvent)[]endTimeMs: numberseekToTime: (timeInMilliseconds: number) => void@@ -220,6 +231,7 @@ export function PlayerSeekbarTicks({| InspectorListItemComment| InspectorListItemNotebookComment| InspectorListItemExperimentVariant+ | InspectorListItemMetricEvent)[]endTimeMs: numberseekToTime: (timeInMilliseconds: number) => voiddiff --git a/frontend/src/scenes/session-recordings/player/inspector/components/ItemMetricEvent.tsx b/frontend/src/scenes/session-recordings/player/inspector/components/ItemMetricEvent.tsxnew file mode 100644index 000000000000..f3ed04bf4b24--- /dev/null+++ b/frontend/src/scenes/session-recordings/player/inspector/components/ItemMetricEvent.tsx@@ -0,0 +1,66 @@+import { Link } from 'lib/lemon-ui/Link'+import { addProductIntentForCrossSell } from 'lib/utils/product-intents'+import { InspectorListItemMetricEvent } from 'scenes/session-recordings/player/inspector/playerInspectorLogic'+import { urls } from 'scenes/urls'++import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'++export interface ItemMetricEventProps {+ item: InspectorListItemMetricEvent+}++export function ItemMetricEvent({ item }: ItemMetricEventProps): JSX.Element {+ return (+ <div data-attr="item-metric-event" className="font-light w-full">+ <div className="flex flex-row w-full gap-2 items-center px-2 py-1 text-xs">+ <div className="truncate flex-1 min-w-0 font-medium">Fired a {item.data.metricName} event</div>+ <div className="flex items-center gap-1 shrink-0 text-secondary">+ <span className="truncate max-w-[40ch]" title={item.data.experimentName}>+ {item.data.experimentName}+ </span>+ </div>+ </div>+ </div>+ )+}++export function ItemMetricEventDetail({ item }: ItemMetricEventProps): JSX.Element {+ const { experimentId, experimentName, metricName, eventCount } = item.data++ return (+ <div data-attr="item-metric-event" className="font-light w-full">+ <div className="px-2 py-1 text-xs border-t flex flex-col gap-1">+ <div className="flex items-center justify-between gap-2 min-w-0">+ <span className="text-secondary shrink-0">Experiment</span>+ <Link+ to={urls.experiment(experimentId)}+ target="_blank"+ className="truncate"+ onClick={() => {+ void addProductIntentForCrossSell({+ from: ProductKey.SESSION_REPLAY,+ to: ProductKey.EXPERIMENTS,+ intent_context: ProductIntentContext.SESSION_REPLAY_EXPERIMENT_LINK_CLICKED,+ metadata: { experiment_id: experimentId },+ })+ }}+ >+ {experimentName}+ </Link>+ </div>+ <div className="flex items-center justify-between gap-2 min-w-0">+ <span className="text-secondary shrink-0">Metric</span>+ <span className="truncate">{metricName}</span>+ </div>+ <div className="flex items-center justify-between gap-2 min-w-0">+ <span className="text-secondary shrink-0">Events in this session</span>+ <span className="truncate">{eventCount}</span>+ </div>+ <div className="text-secondary">+ Counts every matching event in this session, which can differ from what the experiment analysis+ counts.+ </div>+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/PlayerInspectorListItem.tsx b/frontend/src/scenes/session-recordings/player/inspector/components/PlayerInspectorListItem.tsxindex 904f82cb4cae..944e8d27a6e8 100644--- a/frontend/src/scenes/session-recordings/player/inspector/components/PlayerInspectorListItem.tsx+++ b/frontend/src/scenes/session-recordings/player/inspector/components/PlayerInspectorListItem.tsx@@ -19,6 +19,7 @@ import {IconLive,IconLogomark,IconRedux,+ IconTarget,IconTerminal,} from '@posthog/icons'import { LemonButton, LemonDivider } from '@posthog/lemon-ui'@@ -38,6 +39,10 @@ import {ItemExperimentVariantDetail,} from 'scenes/session-recordings/player/inspector/components/ItemExperimentVariant'import { ItemInactivity } from 'scenes/session-recordings/player/inspector/components/ItemInactivity'+import {+ ItemMetricEvent,+ ItemMetricEventDetail,+} from 'scenes/session-recordings/player/inspector/components/ItemMetricEvent'import { ItemSessionChange } from 'scenes/session-recordings/player/inspector/components/ItemSessionChange'import { ItemSummary } from 'scenes/session-recordings/player/inspector/components/ItemSummary'@@ -116,6 +121,10 @@ const typeToIconAndDescription: Record<InspectorListItem['type'], IconAndDescripIcon: IconFlask,tooltip: 'The moment the feature flag behind an experiment was evaluated for this session',},+ 'metric-event': {+ Icon: IconTarget,+ tooltip: "The first time this session fired one of an experiment metric's events",+ },}const notExpandable = ['inspector-summary', 'inactivity', 'session-change']@@ -216,6 +225,8 @@ function RowItemTitle({<ItemSessionChange item={item} />) : item.type === 'experiment-variant' ? (<ItemExperimentVariant item={item} />+ ) : item.type === 'metric-event' ? (+ <ItemMetricEvent item={item} />) : null}</div>)@@ -258,6 +269,8 @@ function RowItemDetail({<ItemAnyCommentDetail item={item} />) : item.type === 'experiment-variant' ? (<ItemExperimentVariantDetail item={item} />+ ) : item.type === 'metric-event' ? (+ <ItemMetricEventDetail item={item} />) : null}</div>)diff --git a/frontend/src/scenes/session-recordings/player/inspector/inspectorListFiltering.ts b/frontend/src/scenes/session-recordings/player/inspector/inspectorListFiltering.tsindex 85a51bffb25d..e55811028a30 100644--- a/frontend/src/scenes/session-recordings/player/inspector/inspectorListFiltering.ts+++ b/frontend/src/scenes/session-recordings/player/inspector/inspectorListFiltering.ts@@ -78,6 +78,7 @@ function isContextItem(item: InspectorListItem): boolean {'inactivity','session-change','experiment-variant',+ 'metric-event',].includes(item.type)}diff --git a/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.ts b/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.tsindex 0386250faea6..d03b7ecc516e 100644--- a/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.ts+++ b/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.ts@@ -114,6 +114,7 @@ const _itemTypes = ['app-state','session-change','experiment-variant',+ 'metric-event',] as constexport type InspectorListItemType = (typeof _itemTypes)[number]@@ -220,6 +221,21 @@ export type InspectorListItemExperimentVariant = InspectorListItemBase & {}}+export type InspectorListItemMetricEvent = InspectorListItemBase & {+ type: 'metric-event'+ data: {+ // Synthesized client-side from the experiments session_context endpoint response+ // (metrics_in_session[].first_timestamp) — like the exposure marker, there is no backend+ // event for this item. One marker per metric, at its first occurrence in the session.+ // `id` keeps the same keying contract as event/comment items in the seekbar.+ id: string+ experimentId: number+ experimentName: string+ metricName: string+ eventCount: number+ }+}+export type InspectorListItem =| InspectorListItemEvent| InspectorListItemConsole@@ -235,6 +251,7 @@ export type InspectorListItem =| InspectorListSessionChange| InspectorListItemLog| InspectorListItemExperimentVariant+ | InspectorListItemMetricEventexport interface PlayerInspectorLogicProps extends SessionRecordingPlayerLogicProps {matchingEventsMatchType?: MatchingEventsMatchType@@ -441,6 +458,7 @@ export interface playerInspectorLogicValues {items: InspectorListItem[]matchingEvents: MatchedRecordingEvent[] | nullmatchingEventsLoading: boolean+ metricEventItems: InspectorListItemMetricEvent[]notebookCommentItems: InspectorListItemNotebookComment[]playbackIndicatorIndex: numberplaybackIndicatorIndexStop: number@@ -454,7 +472,12 @@ export interface playerInspectorLogicValues {rawConsoleLogs: RecordingConsoleLogV2[]}runtimeDoctorEvents: InspectorListItemDoctor[]- seekbarItems: (InspectorListItemComment | InspectorListItemEvent | InspectorListItemExperimentVariant)[]+ seekbarItems: (+ | InspectorListItemComment+ | InspectorListItemEvent+ | InspectorListItemExperimentVariant+ | InspectorListItemMetricEvent+ )[]syncScrollPaused: booleanwindowNumberForID: (windowId: number | undefined) => number | '?' | undefined}@@ -523,6 +546,7 @@ export interface playerInspectorLogicActions {| 'inactivity'| 'inspector-summary'| 'logs'+ | 'metric-event'| 'network'| 'offline-status'| 'performance'@@ -541,6 +565,7 @@ export interface playerInspectorLogicActions {| 'inactivity'| 'inspector-summary'| 'logs'+ | 'metric-event'| 'network'| 'offline-status'| 'performance'@@ -628,6 +653,12 @@ export interface playerInspectorLogicMeta {windowNumberForID: (windowId: number | undefined) => number | '?' | undefined,start: Dayjs | null) => InspectorListItemExperimentVariant[]+ metricEventItems: (+ experimentItems: ExperimentSessionContextItemApi[],+ windowIdForTimestamp: (timestamp: number) => number | undefined, // sessionRecordingDataCoordinatorLogic+ windowNumberForID: (windowId: number | undefined) => number | '?' | undefined,+ start: Dayjs | null+ ) => InspectorListItemMetricEvent[]runtimeDoctorEvents: (start: Dayjs | null,doctorDiagnostics: DoctorDiagnostics | null@@ -647,7 +678,8 @@ export interface playerInspectorLogicMeta {sessionPlayerMetaData: SessionRecordingType | null,segments: import('@common/replay-shared/src').RecordingSegment[],runtimeDoctorEvents: InspectorListItemDoctor[],- experimentVariantItems: InspectorListItemExperimentVariant[]+ experimentVariantItems: InspectorListItemExperimentVariant[],+ metricEventItems: InspectorListItemMetricEvent[]) => InspectorListItem[]allItems: (start: Dayjs | null,@@ -705,7 +737,12 @@ export interface playerInspectorLogicMeta {allowMatchingEventsFilter: boolean,trackedWindow: number | null,hasEventsToDisplay: boolean- ) => (InspectorListItemComment | InspectorListItemEvent | InspectorListItemExperimentVariant)[]+ ) => (+ | InspectorListItemComment+ | InspectorListItemEvent+ | InspectorListItemExperimentVariant+ | InspectorListItemMetricEvent+ )[]inspectorDataState: (sessionEventsDataLoading: boolean,sessionPlayerMetaDataLoading: boolean,@@ -1315,6 +1352,46 @@ export const playerInspectorLogic = kea<playerInspectorLogicType>([{ resultEqualityCheck: equal },],+ metricEventItems: [+ (s) => [s.experimentItems, s.windowIdForTimestamp, s.windowNumberForID, s.start],+ (+ experimentItems: import('products/experiments/frontend/generated/api.schemas').ExperimentSessionContextItemApi[],+ windowIdForTimestamp: (timestamp: number) => number | undefined,+ windowNumberForID: (windowId: number | undefined) => number | '?' | undefined,+ start: Dayjs | null+ ): InspectorListItemMetricEvent[] => {+ const items: InspectorListItemMetricEvent[] = []+ for (const item of experimentItems || []) {+ // One marker per metric the session hit, at its first occurrence — the direct+ // mirror of the exposure marker (which marks the first exposure moment).+ for (const hit of item.metrics_in_session || []) {+ const { timestamp, timeInRecording } = timeRelativeToStart(+ { timestamp: hit.first_timestamp },+ start+ )+ items.push({+ type: 'metric-event',+ timestamp,+ timeInRecording,+ search: `metric ${item.experiment_name} ${hit.metric_name}`,+ windowId: windowIdForTimestamp(timestamp.valueOf()),+ windowNumber: windowNumberForID(windowIdForTimestamp(timestamp.valueOf())),+ data: {+ id: `metric-event-${item.experiment_id}-${hit.metric_uuid}`,+ experimentId: item.experiment_id,+ experimentName: item.experiment_name,+ metricName: hit.metric_name,+ eventCount: hit.event_count,+ },+ key: `metric-event-${item.experiment_id}-${hit.metric_uuid}`,+ })+ }+ }+ return items+ },+ { resultEqualityCheck: equal },+ ],+runtimeDoctorEvents: [(s) => [s.start, s.doctorDiagnostics],(start: Dayjs | null, doctorDiagnostics: DoctorDiagnostics | null): InspectorListItemDoctor[] => {@@ -1366,6 +1443,7 @@ export const playerInspectorLogic = kea<playerInspectorLogicType>([s.segments,s.runtimeDoctorEvents,s.experimentVariantItems,+ s.metricEventItems,],(start: Dayjs | null,@@ -1382,7 +1460,8 @@ export const playerInspectorLogic = kea<playerInspectorLogicType>([sessionPlayerMetaData: null | import('~/types').SessionRecordingType,segments: import('~/types').RecordingSegment[],runtimeDoctorEvents: InspectorListItemDoctor[],- experimentVariantItems: InspectorListItemExperimentVariant[]+ experimentVariantItems: InspectorListItemExperimentVariant[],+ metricEventItems: InspectorListItemMetricEvent[]) => {const items: InspectorListItem[] = []@@ -1423,6 +1502,11 @@ export const playerInspectorLogic = kea<playerInspectorLogicType>([items.push(item)}+ // Add experiment metric first-hit markers+ for (const item of metricEventItems) {+ items.push(item)+ }+// now we've calculated everything else,// we always start with a context row// that lets us show a little summary@@ -1757,17 +1841,28 @@ export const playerInspectorLogic = kea<playerInspectorLogicType>([allowMatchingEventsFilter: boolean,trackedWindow: number | null,hasEventsToDisplay: boolean- ): (InspectorListItemEvent | InspectorListItemComment | InspectorListItemExperimentVariant)[] => {- // Pre-filter to only events, comments and experiment variant markers, avoiding the full filterInspectorListItems call+ ): (+ | InspectorListItemEvent+ | InspectorListItemComment+ | InspectorListItemExperimentVariant+ | InspectorListItemMetricEvent+ )[] => {+ // Pre-filter to only events, comments and experiment markers, avoiding the full filterInspectorListItems callconst eventAndCommentItems: (| InspectorListItemEvent| InspectorListItemComment| InspectorListItemExperimentVariant+ | InspectorListItemMetricEvent)[] = []for (const item of allItemsData.items) {- // Only process events, comments and experiment variant markers- if (item.type !== 'events' && item.type !== 'comment' && item.type !== 'experiment-variant') {+ // Only process events, comments and experiment markers+ if (+ item.type !== 'events' &&+ item.type !== 'comment' &&+ item.type !== 'experiment-variant' &&+ item.type !== 'metric-event'+ ) {continue}@@ -1786,6 +1881,7 @@ export const playerInspectorLogic = kea<playerInspectorLogicType>([| InspectorListItemEvent| InspectorListItemComment| InspectorListItemExperimentVariant+ | InspectorListItemMetricEvent// Apply event-specific filtersif (item.type === 'events') {@@ -1819,7 +1915,8 @@ export const playerInspectorLogic = kea<playerInspectorLogicType>([const isPageView = item.type === 'events' && item.data.event === '$pageview'const isComment = item.type === 'comment'const isExperimentVariant = item.type === 'experiment-variant'- return isPrimary || isPageView || isComment || isExperimentVariant+ const isMetricEvent = item.type === 'metric-event'+ return isPrimary || isPageView || isComment || isExperimentVariant || isMetricEvent})// If still too many, sample themdiff --git a/frontend/src/scenes/session-recordings/player/player-meta/sessionRecordingExperimentContextLogic.ts b/frontend/src/scenes/session-recordings/player/player-meta/sessionRecordingExperimentContextLogic.tsindex 9a246dc61508..78dce336e27c 100644--- a/frontend/src/scenes/session-recordings/player/player-meta/sessionRecordingExperimentContextLogic.ts+++ b/frontend/src/scenes/session-recordings/player/player-meta/sessionRecordingExperimentContextLogic.ts@@ -1,4 +1,4 @@-import { MakeLogicType, afterMount, connect, kea, key, path, props, selectors } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, key, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import { subscriptions } from 'kea-subscriptions'@@ -43,6 +43,7 @@ export interface sessionRecordingExperimentContextLogicValues {currentProjectId: number | string // teamLogicenrolledCount: numberenrolledItems: ExperimentSessionContextItemApi[]+ expandedExperimentIds: number[]experimentContext: ExperimentSessionContextResponseApi | nullexperimentContextEnabled: booleanexperimentContextLoading: boolean@@ -70,6 +71,13 @@ export interface sessionRecordingExperimentContextLogicActions {experimentContext: ExperimentSessionContextResponseApi | nullpayload?: any}+ setExperimentExpanded: (+ experimentId: number,+ expanded: boolean+ ) => {+ expanded: boolean+ experimentId: number+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -110,6 +118,22 @@ export const sessionRecordingExperimentContextLogic = kea<sessionRecordingExpericonnect(() => ({values: [featureFlagLogic, ['featureFlags'], teamLogic, ['currentProjectId']],})),+ actions({+ // Whether an experiment's metric events are expanded in the sidebar. Collapsed by default —+ // the row shows only exposure + variant until the viewer opts in, mirroring the inspector.+ setExperimentExpanded: (experimentId: number, expanded: boolean) => ({ experimentId, expanded }),+ }),+ reducers({+ expandedExperimentIds: [+ [] as number[],+ {+ setExperimentExpanded: (+ state: number[],+ { experimentId, expanded }: { experimentId: number; expanded: boolean }+ ) => (expanded ? [...state, experimentId] : state.filter((id) => id !== experimentId)),+ },+ ],+ }),loaders(({ props, values }) => ({experimentContext: [null as ExperimentSessionContextResponseApi | null,diff --git a/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.tsx b/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.tsxindex 4f7798627471..256e3578a92e 100644--- a/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.tsx+++ b/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.tsx@@ -1,6 +1,6 @@import { useActions, useValues } from 'kea'-import { IconExternal, IconWarning } from '@posthog/icons'+import { IconCollapse, IconExpand, IconExternal, IconWarning } from '@posthog/icons'import { dayjs } from 'lib/dayjs'import { LemonButton } from 'lib/lemon-ui/LemonButton'@@ -14,7 +14,10 @@ import { urls } from 'scenes/urls'import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'-import type { ExperimentSessionContextItemApi } from 'products/experiments/frontend/generated/api.schemas'+import type {+ ExperimentSessionContextItemApi,+ ExperimentSessionMetricHitApi,+} from 'products/experiments/frontend/generated/api.schemas'import {isControlVariant,@@ -28,7 +31,12 @@ function variantTooltip(item: ExperimentSessionContextItemApi): string {: `This session saw variant "${item.variant}" of ${item.experiment_name}. The experiment analysis counts exposure per person, which can differ from a single session.`}-function VariantTag({ item }: { item: ExperimentSessionContextItemApi }): JSX.Element {+function VariantTag({ item }: { item: ExperimentSessionContextItemApi }): JSX.Element | null {+ // Metric-only sessions (a future backend addition) carry no variant — render no tag rather+ // than an empty one.+ if (!item.variant && item.variants_seen.length === 0) {+ return null+ }const type: LemonTagType = item.multiple_variants ? 'warning' : isControlVariant(item) ? 'muted' : 'highlight'return (<Tooltip title={variantTooltip(item)}>@@ -39,6 +47,76 @@ function VariantTag({ item }: { item: ExperimentSessionContextItemApi }): JSX.El)}+// Above this many in-bounds occurrences the per-event seek chips collapse behind a toggle so a+// busy metric doesn't flood the sidebar.+const INLINE_METRIC_EVENT_LIMIT = 6++function MetricEventChips({+ seekPoints,+ onSeek,+}: {+ seekPoints: { ms: number; offsetSeconds: number }[]+ onSeek: (timestampMs: number) => void+}): JSX.Element {+ return (+ <div className="flex flex-row flex-wrap gap-1 pl-3">+ {seekPoints.map(({ ms, offsetSeconds }) => (+ <Link+ key={ms}+ className="font-mono tabular-nums"+ title="Jump to this event"+ onClick={() => onSeek(ms)}+ data-attr="replay-experiment-context-jump-to-metric-event"+ >+ {colonDelimitedDuration(offsetSeconds, 2)}+ </Link>+ ))}+ </div>+ )+}++function MetricHitRow({+ hit,+ recordingStartMs,+ isWithinRecording,+ onSeek,+}: {+ hit: ExperimentSessionMetricHitApi+ recordingStartMs: number | null+ isWithinRecording: (timestampMs: number | null) => timestampMs is number+ onSeek: (timestampMs: number) => void+}): JSX.Element {+ // Only in-bounds occurrences are seekable — the backend's ±1h slack can place some outside the+ // playable recording. Each becomes a chip labelled with its offset from the recording start.+ const seekPoints = hit.timestamps+ .map((timestamp) => dayjs(timestamp).valueOf())+ .filter((ms): ms is number => isWithinRecording(ms))+ .map((ms) => ({ ms, offsetSeconds: recordingStartMs != null ? Math.floor((ms - recordingStartMs) / 1000) : 0 }))++ return (+ <div className="flex flex-col gap-y-0.5 min-w-0 pl-3 text-xs">+ <span className="truncate">{hit.metric_name}</span>+ {seekPoints.length === 0 ? (+ <span className="pl-3 text-muted">Fired outside the recording</span>+ ) : seekPoints.length > INLINE_METRIC_EVENT_LIMIT ? (+ <LemonCollapse+ embedded+ size="small"+ panels={[+ {+ key: 'events',+ header: `${seekPoints.length} events`,+ content: <MetricEventChips seekPoints={seekPoints} onSeek={onSeek} />,+ },+ ]}+ />+ ) : (+ <MetricEventChips seekPoints={seekPoints} onSeek={onSeek} />+ )}+ </div>+ )+}+function OpenExperimentButton({ item }: { item: ExperimentSessionContextItemApi }): JSX.Element {return (<LemonButton@@ -84,11 +162,15 @@ function ExperimentContextRow({onSeek,outOfWindow,timeInRecording,+ leading,}: {item: ExperimentSessionContextItemApionSeek?: () => voidoutOfWindow?: booleantimeInRecording?: number | null+ // Leading slot rendered before the timestamp — the metric-events expand toggle, or an empty+ // spacer of the same width so the timestamp and name columns line up across rows.+ leading?: JSX.Element | null}): JSX.Element {let name: JSX.Elementif (onSeek) {@@ -116,6 +198,7 @@ function ExperimentContextRow({// button wrapped in a non-flex span, which would otherwise let its tag hug the text).return (<div className="flex flex-row items-center gap-x-2 min-w-0">+ {leading}{timeInRecording != null ? <ExposureTime timeInRecording={timeInRecording} /> : null}<div className="flex-1 min-w-0 truncate">{name}</div><VariantTag item={item} />@@ -127,9 +210,11 @@ function ExperimentContextRow({export function PlayerSidebarExperimentsSection(): JSX.Element | null {const { logicProps, sessionPlayerData } = useValues(sessionRecordingPlayerLogic)const { seekToTimestamp } = useActions(sessionRecordingPlayerLogic)- const { seenItems, enrolledItems, hasExperimentContext } = useValues(- sessionRecordingExperimentContextLogic({ sessionRecordingId: logicProps.sessionRecordingId })- )+ const experimentContextLogic = sessionRecordingExperimentContextLogic({+ sessionRecordingId: logicProps.sessionRecordingId,+ })+ const { seenItems, enrolledItems, hasExperimentContext, expandedExperimentIds } = useValues(experimentContextLogic)+ const { setExperimentExpanded } = useActions(experimentContextLogic)if (!hasExperimentContext) {return null@@ -140,6 +225,19 @@ export function PlayerSidebarExperimentsSection(): JSX.Element | null {recordingStartMs != null && sessionPlayerData?.durationMs != null? recordingStartMs + sessionPlayerData.durationMs: null+ // The backend can return timestamps from its ±1h slack around the recording; seeking to an+ // out-of-bounds time silently clamps to a boundary, so only offer jumps for moments that fall+ // inside the playable recording.+ const isWithinRecording = (timestampMs: number | null): timestampMs is number =>+ timestampMs != null &&+ recordingStartMs != null &&+ recordingEndMs != null &&+ timestampMs >= recordingStartMs &&+ timestampMs <= recordingEndMs++ // Reserve a leading gutter on every seen row (so timestamps and names align) only when at least+ // one experiment has an expand toggle; with nothing expandable, keep the list flush-left.+ const anySeenExpandable = seenItems.some((seenItem) => seenItem.metrics_in_session.length > 0)return (<div@@ -152,15 +250,7 @@ export function PlayerSidebarExperimentsSection(): JSX.Element | null {const exposedAtMs = item.first_exposure_timestamp? dayjs(item.first_exposure_timestamp).valueOf(): null- // The backend can return an exposure timestamp from its ±1h slack around the- // recording; seeking to an out-of-bounds time silently clamps to a boundary, so only- // offer the jump when the moment falls inside the playable recording.- const canSeek =- exposedAtMs != null &&- recordingStartMs != null &&- recordingEndMs != null &&- exposedAtMs >= recordingStartMs &&- exposedAtMs <= recordingEndMs+ const canSeek = isWithinRecording(exposedAtMs)// Distinguish "seen but outside the window" (worth a tooltip) from "bounds not known// yet" (transient, no tooltip) so we never explain a non-jump we can't actually vouch for.const outOfWindow =@@ -168,16 +258,51 @@ export function PlayerSidebarExperimentsSection(): JSX.Element | null {recordingStartMs != null &&recordingEndMs != null &&(exposedAtMs < recordingStartMs || exposedAtMs > recordingEndMs)+ const hasMetrics = item.metrics_in_session.length > 0+ const isExpanded = expandedExperimentIds.includes(item.experiment_id)return (- <ExperimentContextRow- key={item.experiment_id}- item={item}- onSeek={canSeek && exposedAtMs != null ? () => seekToTimestamp(exposedAtMs) : undefined}- outOfWindow={outOfWindow}- timeInRecording={- exposedAtMs != null && recordingStartMs != null ? exposedAtMs - recordingStartMs : null- }- />+ <div key={item.experiment_id} className="flex flex-col gap-y-0.5 min-w-0">+ <ExperimentContextRow+ item={item}+ onSeek={canSeek && exposedAtMs != null ? () => seekToTimestamp(exposedAtMs) : undefined}+ outOfWindow={outOfWindow}+ timeInRecording={+ exposedAtMs != null && recordingStartMs != null ? exposedAtMs - recordingStartMs : null+ }+ leading={+ anySeenExpandable ? (+ <div className="shrink-0 flex w-[1.625rem] justify-center">+ {hasMetrics ? (+ <LemonButton+ size="xsmall"+ icon={isExpanded ? <IconCollapse /> : <IconExpand />}+ onClick={() => setExperimentExpanded(item.experiment_id, !isExpanded)}+ tooltip={+ isExpanded+ ? 'Hide metric events'+ : `Show metric events (${item.metrics_in_session.length})`+ }+ data-attr="replay-experiment-context-expand-metrics"+ />+ ) : null}+ </div>+ ) : undefined+ }+ />+ {isExpanded && hasMetrics ? (+ <div className="flex flex-col gap-y-0.5">+ {item.metrics_in_session.map((hit) => (+ <MetricHitRow+ key={hit.metric_uuid}+ hit={hit}+ recordingStartMs={recordingStartMs}+ isWithinRecording={isWithinRecording}+ onSeek={seekToTimestamp}+ />+ ))}+ </div>+ ) : null}+ </div>)})}diff --git a/frontend/src/scenes/session-recordings/sessionRecordingEventUsageLogic.ts b/frontend/src/scenes/session-recordings/sessionRecordingEventUsageLogic.tsindex 22c840ffe4c6..6bf73b90c0d4 100644--- a/frontend/src/scenes/session-recordings/sessionRecordingEventUsageLogic.ts+++ b/frontend/src/scenes/session-recordings/sessionRecordingEventUsageLogic.ts@@ -89,6 +89,7 @@ export interface sessionRecordingEventUsageLogicActions {| 'inactivity'| 'inspector-summary'| 'logs'+ | 'metric-event'| 'network'| 'offline-status'| 'performance'diff --git a/products/experiments/backend/metric_events.py b/products/experiments/backend/metric_events.pynew file mode 100644index 000000000000..442a6a999d17--- /dev/null+++ b/products/experiments/backend/metric_events.py@@ -0,0 +1,251 @@+"""Resolve which events an experiment's metrics count, and scan a session for them.++A session recording can contain the events an experiment's metrics count. This module maps an+experiment's metrics (inline primary + secondary and saved/shared, via the shared+`metric_resolution` enumerator) to their concrete event/action sources, and scans one session+for those events. Data-warehouse sources have no session events, so metrics whose every source+is a data-warehouse node are marked non-linkable and skipped by the scan.++Consumed by the additive `metrics_in_session` fields on the single-session `session_context`+endpoint.+"""++import logging+from dataclasses import dataclass+from datetime import datetime++import pydantic++from posthog.schema import (+ ActionsNode,+ EventsNode,+ ExperimentDataWarehouseNode,+ ExperimentFunnelMetric,+ ExperimentMeanMetric,+ ExperimentRatioMetric,+ ExperimentRetentionMetric,+)++from posthog.hogql import ast+from posthog.hogql.errors import BaseHogQLError+from posthog.hogql.parser import parse_select+from posthog.hogql.property import property_to_expr+from posthog.hogql.query import execute_hogql_query++from posthog.models.team.team import Team+from posthog.models.user import User++from products.cohorts.backend.models.cohort import Cohort+from products.experiments.backend.hogql_queries.base_query_utils import event_or_action_to_filter+from products.experiments.backend.models.experiment import Experiment+from products.experiments.backend.temporal.metric_resolution import ExperimentMetric, build_metric, iter_metric_dicts++logger = logging.getLogger(__name__)++# Per hit we return the first N event timestamps as seek points; event_count carries the true+# total, so a busier metric shows the real count and the UI notes the seek points are capped.+MAX_METRIC_EVENT_TIMESTAMPS = 50+# Ceiling on UNION ALL branches per scan. An experiment's metric count is user-configurable+# with no server-side cap, so overlapping metric-heavy experiments could otherwise compile an+# arbitrarily wide union; 50 mirrors MAX_CANDIDATE_EXPERIMENTS in session_context.+MAX_SCANNED_METRICS = 50++MetricSourceNode = EventsNode | ActionsNode+++@dataclass(frozen=True)+class MetricEventSource:+ """An experiment metric resolved to the concrete event/action sources it counts."""++ metric_uuid: str+ metric_name: str+ # False when the metric has no event/action source at all (purely data-warehouse) — there+ # are no session events to scan for. A metric with one event side and one data-warehouse+ # side is still linkable on the event side.+ session_linkable: bool+ # The parsed event/action source nodes, kept for their per-node property filters.+ nodes: tuple[MetricSourceNode, ...]+++@dataclass(frozen=True)+class MetricHit:+ """A metric with at least one matching event in a session."""++ metric_uuid: str+ metric_name: str+ event_count: int+ first_timestamp: datetime+ # The first MAX_METRIC_EVENT_TIMESTAMPS event timestamps, ascending — seek points for the+ # player. event_count is the true total, so this can be shorter than event_count.+ timestamps: tuple[datetime, ...]+++def _metric_source_nodes(metric: ExperimentMetric) -> list[MetricSourceNode | ExperimentDataWarehouseNode]:+ if isinstance(metric, ExperimentMeanMetric):+ return [metric.source]+ if isinstance(metric, ExperimentFunnelMetric):+ return list(metric.series)+ if isinstance(metric, ExperimentRatioMetric):+ return [metric.numerator, metric.denominator]+ return [metric.start_event, metric.completion_event]+++def _source_title(node: MetricSourceNode | ExperimentDataWarehouseNode) -> str | None:+ """Display name for one metric source node, mirroring the frontend `getDefaultName`."""+ if isinstance(node, EventsNode):+ return node.name or node.event+ if isinstance(node, ActionsNode):+ return node.name or f"Action {node.id}"+ if isinstance(node, ExperimentDataWarehouseNode):+ return node.table_name+++def _default_metric_title(metric: ExperimentMetric) -> str:+ """A title derived from a metric's source events, mirroring the frontend+ `getDefaultMetricTitle` — so an unnamed metric reads the same in the player and the+ recordings tab (a `$pageview` mean metric shows "$pageview", not "Metric a34f9547")."""+ if isinstance(metric, ExperimentMeanMetric):+ return _source_title(metric.source) or "Untitled metric"+ if isinstance(metric, ExperimentFunnelMetric):+ return (_source_title(metric.series[0]) if metric.series else None) or "Untitled funnel"+ if isinstance(metric, ExperimentRatioMetric):+ return (+ f"{_source_title(metric.numerator) or 'Numerator'} / {_source_title(metric.denominator) or 'Denominator'}"+ )+ if isinstance(metric, ExperimentRetentionMetric):+ return f"{_source_title(metric.start_event) or 'Start event'} / {_source_title(metric.completion_event) or 'Completion event'}"+++def resolve_metric_events(experiment: Experiment) -> list[MetricEventSource]:+ """Map every metric of an experiment (inline and saved) to its event/action sources.++ Which events a metric counts is the OR over all of its source nodes; `math_*` aggregation+ settings are irrelevant for containment. Metrics that can't be parsed (e.g. a legacy+ `metric_type` unknown to `build_metric`) are skipped, not fatal — one bad metric must+ never fail the whole surface.+ """+ sources: list[MetricEventSource] = []+ for metric_dict in iter_metric_dicts(experiment):+ try:+ metric = build_metric(metric_dict)+ except (KeyError, pydantic.ValidationError):+ logger.warning("Skipping unparseable metric %s on experiment %s", metric_dict.get("uuid"), experiment.pk)+ continue+ nodes = tuple(node for node in _metric_source_nodes(metric) if isinstance(node, EventsNode | ActionsNode))+ metric_uuid = str(metric_dict["uuid"])+ sources.append(+ MetricEventSource(+ metric_uuid=metric_uuid,+ metric_name=metric.name or _default_metric_title(metric),+ session_linkable=bool(nodes),+ nodes=nodes,+ )+ )+ return sources+++def _node_condition(node: MetricSourceNode, team: Team) -> ast.Expr:+ """Match expression for one source node, built on `event_or_action_to_filter` — the same+ matcher the experiment analysis uses, so what counts as "this metric's event" cannot+ diverge between the analysis and this surface. `fixedProperties` are ANDed on top: the+ shared helper only reads `properties`, and layering the extra filter here keeps the scan+ strictly narrower than (never contradicting) the analysis. Sources this project can't+ resolve (a cohort filter whose cohort doesn't exist here, a filter HogQL can't compile)+ match nothing instead of failing the whole scan; the shared helper already maps a missing+ action to a match-nothing expression."""+ try:+ condition = event_or_action_to_filter(team, node)+ fixed = [property_to_expr(prop, team) for prop in node.fixedProperties or []]+ except (Cohort.DoesNotExist, BaseHogQLError):+ logger.warning("Unresolvable metric source filter for team %s; source matches nothing.", team.pk)+ return ast.Constant(value=False)+ if fixed:+ return ast.And(exprs=[condition, *fixed])+ return condition+++def scan_session_for_metric_events(+ team: Team,+ user: User,+ *,+ metric_sources: list[MetricEventSource],+ session_id: str,+ window_start: datetime,+ window_end: datetime,+) -> list[MetricHit]:+ """The metrics with >=1 matching event in the session, sorted by first occurrence.++ Metrics with no hits are omitted. Duplicate metric uuids (a saved metric shared by several+ experiments) are scanned once, and at most MAX_SCANNED_METRICS metrics are scanned per call+ (the overflow is logged, not an error). `user` threads through to HogQL for property-level+ access control — metric source nodes can carry property filters.+ """+ names_by_uuid: dict[str, str] = {}+ branches: list[ast.SelectQuery] = []+ skipped_over_cap = 0+ for source in metric_sources:+ if not source.session_linkable or source.metric_uuid in names_by_uuid:+ continue+ if len(branches) >= MAX_SCANNED_METRICS:+ skipped_over_cap += 1+ continue+ conditions = [_node_condition(node, team) for node in source.nodes]+ if not conditions:+ continue+ names_by_uuid[source.metric_uuid] = source.metric_name+ branch = parse_select(+ """+ SELECT {metric_uuid} AS metric_uuid,+ count() AS event_count,+ min(timestamp) AS first_timestamp,+ arraySlice(arraySort(groupArray(timestamp)), 1, {max_timestamps}) AS timestamps+ FROM events+ WHERE {metric_conditions}+ AND $session_id = {session_id}+ AND timestamp >= {window_start}+ AND timestamp <= {window_end}+ GROUP BY $session_id+ """,+ placeholders={+ "metric_uuid": ast.Constant(value=source.metric_uuid),+ "metric_conditions": ast.Or(exprs=conditions) if len(conditions) > 1 else conditions[0],+ "session_id": ast.Constant(value=session_id),+ "window_start": ast.Constant(value=window_start),+ "window_end": ast.Constant(value=window_end),+ "max_timestamps": ast.Constant(value=MAX_METRIC_EVENT_TIMESTAMPS),+ },+ )+ assert isinstance(branch, ast.SelectQuery)+ branches.append(branch)++ if skipped_over_cap:+ logger.warning(+ "Metric scan for session %s capped at %s branches; %s metrics not scanned",+ session_id,+ MAX_SCANNED_METRICS,+ skipped_over_cap,+ )++ if not branches:+ return []++ # Each branch groups a single session, so it yields at most one row — the implicit+ # LIMIT 100 HogQL stamps on every union branch can never truncate anything here.+ query = ast.SelectSetQuery.create_from_queries(branches, "UNION ALL")+ response = execute_hogql_query(query, team=team, user=user)++ hits: list[MetricHit] = []+ for metric_uuid, event_count, first_timestamp, timestamps in response.results or []:+ if not event_count:+ continue+ hits.append(+ MetricHit(+ metric_uuid=str(metric_uuid),+ metric_name=names_by_uuid[str(metric_uuid)],+ event_count=int(event_count),+ first_timestamp=first_timestamp,+ timestamps=tuple(timestamps),+ )+ )+ hits.sort(key=lambda hit: hit.first_timestamp)+ return hitsdiff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex ec208fe49a0b..533d3a7fc983 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -1438,6 +1438,30 @@ class RunningTimeCalculationResultSerializer(serializers.Serializer):)+class ExperimentSessionMetricHitSerializer(serializers.Serializer):+ """One experiment metric with at least one matching event in a session recording."""++ metric_uuid = serializers.CharField(+ help_text="UUID of the experiment metric (inline primary/secondary or saved) whose events fired."+ )+ metric_name = serializers.CharField(+ help_text="Display name of the metric, or an event-derived title (matching the experiment UI) when unnamed."+ )+ event_count = serializers.IntegerField(+ help_text="Total number of events in the session matching any of the metric's event/action sources."+ )+ first_timestamp = serializers.DateTimeField(+ help_text="Timestamp of the first event in the session matching the metric."+ )+ timestamps = serializers.ListField(+ child=serializers.DateTimeField(),+ help_text=(+ "Ascending timestamps of the metric's matching events in the session, capped at the first 50. "+ "event_count is the true total, so this list may be shorter — treat these as seek points, not a count."+ ),+ )++class ExperimentSessionContextItemSerializer(serializers.Serializer):"""One experiment whose feature flag a session recording saw."""@@ -1477,6 +1501,13 @@ class ExperimentSessionContextItemSerializer(serializers.Serializer):experiment_end_date = serializers.DateTimeField(allow_null=True, help_text="When the experiment ended. Null while the experiment is still running.")+ metrics_in_session = ExperimentSessionMetricHitSerializer(+ many=True,+ help_text=(+ "This experiment's metrics with at least one matching event in the session, sorted by first "+ "occurrence. Empty when none of the experiment's metric events fired during the session."+ ),+ )class ExperimentSessionContextResponseSerializer(serializers.Serializer):diff --git a/products/experiments/backend/session_context.py b/products/experiments/backend/session_context.pyindex c9735891b3e3..4641940d4ad7 100644--- a/products/experiments/backend/session_context.py+++ b/products/experiments/backend/session_context.py@@ -19,6 +19,7 @@ not applied here — this surface shows the raw session truth). Callers must prewhat the session *saw*, not what the experiment analysis counts."""+import loggingfrom dataclasses import dataclassfrom datetime import datetime, timedeltafrom typing import Optional@@ -44,8 +45,16 @@ from products.experiments.backend.hogql_queries.exposure_query_logic import (get_exposure_event_and_property,normalize_to_exposure_criteria,)+from products.experiments.backend.metric_events import (+ MetricEventSource,+ MetricHit,+ resolve_metric_events,+ scan_session_for_metric_events,+)from products.experiments.backend.models.experiment import Experiment+logger = logging.getLogger(__name__)+# Slack around the recording bounds — flag evaluation can be captured slightly outside the# replay window (clock skew, events flushed before/after snapshots).EVENT_WINDOW_SLACK = timedelta(hours=1)@@ -82,6 +91,8 @@ class ExperimentSessionContextItem:first_exposure_timestamp: Optional[datetime]experiment_start_date: Optional[datetime]experiment_end_date: Optional[datetime]+ # The experiment's metrics with >=1 matching event in the session, sorted by first occurrence.+ metrics_in_session: list[MetricHit]def get_session_experiment_context(@@ -190,7 +201,7 @@ def get_session_experiment_context(stamped = _query_stamped_flag_properties(team, user, session_id, candidate_keys, window_start, window_end)- items: list[ExperimentSessionContextItem] = []+ surfaced: list[tuple[Experiment, str, list[str], Optional[datetime]]] = []for experiment in candidates:flag_key = experiment.feature_flag.key# Only the flag's defined variant keys count, mirroring the `variant IN variants` filter in@@ -216,17 +227,58 @@ def get_session_experiment_context(else:variant = variants_seen[0]+ surfaced.append((experiment, variant, variants_seen, first_exposure_timestamp))++ # Only the experiments that actually surfaced (typically 1–3, not the candidate cap) get+ # their metrics scanned. One scan covers them all — shared saved metrics dedupe by uuid+ # inside the scan — and each experiment claims its own metrics' hits back by uuid.+ # Metric hits are enrichment on top of the exposure context: an unexpected failure here+ # (one experiment's malformed stored metric, say) must degrade to "no metric hits", never+ # take down the exposure context that already resolved above.+ sources_by_experiment: dict[int, list[MetricEventSource]] = {}+ session_hits: dict[str, MetricHit] = {}+ try:+ sources_by_experiment = {experiment.pk: resolve_metric_events(experiment) for experiment, *_ in surfaced}+ all_sources = [source for sources in sources_by_experiment.values() for source in sources]+ if all_sources:+ session_hits = {+ hit.metric_uuid: hit+ for hit in scan_session_for_metric_events(+ team,+ user,+ metric_sources=all_sources,+ session_id=session_id,+ window_start=window_start,+ window_end=window_end,+ )+ }+ except Exception:+ logger.exception("Metric-event scan failed for session %s; returning context without metric hits", session_id)+ sources_by_experiment = {}+ session_hits = {}++ items: list[ExperimentSessionContextItem] = []+ for experiment, variant, variants_seen, first_exposure_timestamp in surfaced:+ metrics_in_session = sorted(+ {+ source.metric_uuid: session_hits[source.metric_uuid]+ for source in sources_by_experiment.get(experiment.pk, [])+ if source.metric_uuid in session_hits+ }.values(),+ key=lambda hit: hit.first_timestamp,+ )items.append(ExperimentSessionContextItem(experiment_id=experiment.pk,experiment_name=experiment.name,- flag_key=flag_key,+ flag_key=experiment.feature_flag.key,variant=variant,variants_seen=variants_seen,multiple_variants=len(variants_seen) > 1,first_exposure_timestamp=first_exposure_timestamp,experiment_start_date=experiment.start_date,experiment_end_date=experiment.end_date,+ metrics_in_session=metrics_in_session,))diff --git a/products/experiments/backend/test/test_metric_events.py b/products/experiments/backend/test/test_metric_events.pynew file mode 100644index 000000000000..f3c1dffce80e--- /dev/null+++ b/products/experiments/backend/test/test_metric_events.py@@ -0,0 +1,324 @@+import uuid+from datetime import UTC, datetime+from typing import Any, Optional++from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events+from unittest.mock import patch++from parameterized import parameterized++from posthog.schema import ActionsNode, EventsNode++from posthog.models import Team++from products.actions.backend.models.action import Action+from products.experiments.backend.metric_events import MetricHit, resolve_metric_events, scan_session_for_metric_events+from products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetric+from products.feature_flags.backend.models.feature_flag import FeatureFlag++WINDOW_START = datetime(2026, 1, 1, 9, 0, 0, tzinfo=UTC)+WINDOW_END = datetime(2026, 1, 1, 11, 0, 0, tzinfo=UTC)+++def _events_node(event: Optional[str], properties: Optional[list[dict[str, Any]]] = None) -> dict[str, Any]:+ node: dict[str, Any] = {"kind": "EventsNode", "event": event}+ if properties is not None:+ node["properties"] = properties+ return node+++def _dw_node() -> dict[str, Any]:+ return {+ "kind": "ExperimentDataWarehouseNode",+ "table_name": "stripe_charges",+ "timestamp_field": "created_at",+ "data_warehouse_join_key": "customer_id",+ "events_join_key": "distinct_id",+ }+++def _metric(metric_type: str, name: Optional[str] = "Metric", **type_fields: Any) -> dict[str, Any]:+ return {+ "kind": "ExperimentMetric",+ "metric_type": metric_type,+ "uuid": str(uuid.uuid4()),+ "name": name,+ **type_fields,+ }+++def _retention_metric(start_event: dict[str, Any], completion_event: dict[str, Any]) -> dict[str, Any]:+ return _metric(+ "retention",+ start_event=start_event,+ completion_event=completion_event,+ retention_window_start=0,+ retention_window_end=7,+ retention_window_unit="day",+ start_handling="first_seen",+ )+++class MetricEventsTestMixin(BaseTest):+ def _experiment(self, metrics: Optional[list[dict[str, Any]]] = None, **kwargs: Any) -> Experiment:+ flag = FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key=f"flag-{uuid.uuid4().hex[:8]}",+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )+ return Experiment.objects.create(+ team=self.team,+ created_by=self.user,+ feature_flag=flag,+ name="exp",+ metrics=metrics or [],+ **kwargs,+ )+++class TestResolveMetricEvents(MetricEventsTestMixin):+ @parameterized.expand(+ [+ ("mean", _metric("mean", source=_events_node("purchase")), ("purchase",)),+ (+ "funnel",+ _metric("funnel", series=[_events_node("added to cart"), _events_node("purchase")]),+ ("added to cart", "purchase"),+ ),+ (+ "ratio",+ _metric("ratio", numerator=_events_node("purchase"), denominator=_events_node("$pageview")),+ ("purchase", "$pageview"),+ ),+ (+ "retention",+ _retention_metric(_events_node("signed up"), _events_node("uploaded file")),+ ("signed up", "uploaded file"),+ ),+ ]+ )+ def test_resolves_event_sources_per_metric_type(+ self, _name: str, metric: dict[str, Any], expected_events: tuple[str, ...]+ ) -> None:+ experiment = self._experiment(metrics=[metric])++ sources = resolve_metric_events(experiment)++ assert len(sources) == 1+ assert sources[0].metric_uuid == metric["uuid"]+ assert len(sources[0].nodes) == len(expected_events)+ assert tuple(node.event for node in sources[0].nodes if isinstance(node, EventsNode)) == expected_events+ assert sources[0].session_linkable is True++ @parameterized.expand(+ [+ ("mean", _metric("mean", name=None, source=_events_node("$pageview")), "$pageview"),+ (+ "funnel",+ _metric("funnel", name=None, series=[_events_node("signed up"), _events_node("activated")]),+ "signed up",+ ),+ (+ "ratio",+ _metric("ratio", name=None, numerator=_events_node("purchase"), denominator=_events_node("$pageview")),+ "purchase / $pageview",+ ),+ (+ "retention",+ _retention_metric(_events_node("signed up"), _events_node("uploaded file")),+ "signed up / uploaded file",+ ),+ ]+ )+ def test_unnamed_metric_defaults_to_event_derived_title(+ self, _name: str, metric: dict[str, Any], expected_title: str+ ) -> None:+ # An unnamed metric must read the same event-derived title the recordings tab shows, not a+ # "Metric <uuid>" placeholder.+ experiment = self._experiment(metrics=[{**metric, "name": None}])++ sources = resolve_metric_events(experiment)++ assert sources[0].metric_name == expected_title++ def test_resolves_action_source(self) -> None:+ action = Action.objects.create(team=self.team, name="Purchased", steps_json=[{"event": "purchase"}])+ experiment = self._experiment(+ metrics=[_metric("mean", source={"kind": "ActionsNode", "id": action.pk})],+ )++ sources = resolve_metric_events(experiment)++ assert len(sources) == 1+ assert len(sources[0].nodes) == 1+ node = sources[0].nodes[0]+ assert isinstance(node, ActionsNode)+ assert int(node.id) == action.pk+ assert sources[0].session_linkable is True++ def test_data_warehouse_only_metric_is_not_session_linkable(self) -> None:+ experiment = self._experiment(+ metrics=[+ _metric("mean", source=_dw_node()),+ _metric("ratio", numerator=_events_node("purchase"), denominator=_dw_node()),+ ]+ )++ dw_only, mixed = resolve_metric_events(experiment)++ assert dw_only.session_linkable is False+ assert dw_only.nodes == ()+ assert mixed.session_linkable is True+ assert len(mixed.nodes) == 1+ assert [node.event for node in mixed.nodes if isinstance(node, EventsNode)] == ["purchase"]++ def test_includes_secondary_and_saved_metrics(self) -> None:+ primary = _metric("mean", source=_events_node("purchase"))+ secondary = _metric("mean", source=_events_node("refund"))+ saved_query = _metric("mean", source=_events_node("upgraded"))+ experiment = self._experiment(metrics=[primary], metrics_secondary=[secondary])+ saved = ExperimentSavedMetric.objects.create(team=self.team, name="saved", query=saved_query)+ ExperimentToSavedMetric.objects.create(experiment=experiment, saved_metric=saved, metadata={})++ sources = resolve_metric_events(experiment)++ assert [source.metric_uuid for source in sources] == [+ primary["uuid"],+ secondary["uuid"],+ saved_query["uuid"],+ ]++ def test_unparseable_metric_is_skipped_not_fatal(self) -> None:+ valid = _metric("mean", source=_events_node("purchase"))+ experiment = self._experiment(+ metrics=[+ {"uuid": str(uuid.uuid4()), "metric_type": "trends"}, # legacy type unknown to build_metric+ {"uuid": str(uuid.uuid4()), "metric_type": "mean", "source": {"kind": "EventsNode", "bogus": 1}},+ valid,+ ]+ )++ sources = resolve_metric_events(experiment)++ assert [source.metric_uuid for source in sources] == [valid["uuid"]]+++class TestScanSessionForMetricEvents(ClickhouseTestMixin, MetricEventsTestMixin):+ def _create_session_event(+ self,+ event: str,+ session_id: str,+ timestamp: str = "2026-01-01T10:05:00Z",+ properties: Optional[dict[str, Any]] = None,+ team: Optional[Team] = None,+ ) -> None:+ _create_event(+ team=team or self.team,+ event=event,+ distinct_id="user1",+ timestamp=timestamp,+ properties={"$session_id": session_id, **(properties or {})},+ )++ def _scan(self, metrics: list[dict[str, Any]], session_id: str) -> list[MetricHit]:+ experiment = self._experiment(metrics=metrics)+ return scan_session_for_metric_events(+ self.team,+ self.user,+ metric_sources=resolve_metric_events(experiment),+ session_id=session_id,+ window_start=WINDOW_START,+ window_end=WINDOW_END,+ )++ def test_reports_hits_only_for_metrics_with_in_window_events(self) -> None:+ # Two metrics force a genuine multi-branch UNION ALL — a single branch collapses to a+ # plain SelectQuery, so only this shape proves the union compiles and that a metric+ # with no matching events yields no hit.+ metric_a = _metric("mean", name="Purchases", source=_events_node("purchase"))+ metric_b = _metric("mean", name="Signups", source=_events_node("signup"))+ self._create_session_event("purchase", "s1", timestamp="2026-01-01T10:05:00Z")+ self._create_session_event("purchase", "s1", timestamp="2026-01-01T10:10:00Z")+ self._create_session_event("purchase", "s1", timestamp="2026-01-01T12:30:00Z") # outside window+ flush_persons_and_events()++ hits = self._scan([metric_a, metric_b], "s1")++ assert len(hits) == 1+ hit = hits[0]+ assert hit.metric_uuid == metric_a["uuid"]+ assert hit.metric_name == "Purchases"+ assert hit.event_count == 2+ assert hit.first_timestamp == datetime(2026, 1, 1, 10, 5, 0, tzinfo=UTC)+ # Every in-window event is returned as an ascending seek point, not just the first.+ assert hit.timestamps == (+ datetime(2026, 1, 1, 10, 5, 0, tzinfo=UTC),+ datetime(2026, 1, 1, 10, 10, 0, tzinfo=UTC),+ )++ @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.+ filtered = _metric(+ "mean",+ name="Premium purchases",+ source={+ "kind": "EventsNode",+ "event": "purchase",+ properties_field: [{"key": "plan", "value": ["premium"], "operator": "exact", "type": "event"}],+ },+ )+ unfiltered = _metric("mean", name="Purchases", source=_events_node("purchase"))+ self._create_session_event("purchase", "s1", properties={"plan": "free"})+ flush_persons_and_events()++ hits = self._scan([filtered, unfiltered], "s1")++ assert [hit.metric_uuid for hit in hits] == [unfiltered["uuid"]]++ def test_all_events_source_matches_any_event(self) -> None:+ all_events = _metric("mean", name="Anything", source=_events_node(None))+ purchases = _metric("mean", name="Purchases", source=_events_node("purchase"))+ self._create_session_event("$pageview", "s1")+ flush_persons_and_events()++ hits = self._scan([all_events, purchases], "s1")++ assert [hit.metric_uuid for hit in hits] == [all_events["uuid"]]++ def test_team_isolation(self) -> None:+ other_team = Team.objects.create(organization=self.organization, name="other team")+ metric_a = _metric("mean", source=_events_node("purchase"))+ metric_b = _metric("mean", source=_events_node("signup"))+ self._create_session_event("purchase", "s1", team=other_team)+ flush_persons_and_events()++ hits = self._scan([metric_a, metric_b], "s1")++ assert hits == []++ def test_missing_action_matches_nothing(self) -> None:+ broken = _metric("mean", name="Broken", source={"kind": "ActionsNode", "id": 999_999})+ purchases = _metric("mean", name="Purchases", source=_events_node("purchase"))+ self._create_session_event("purchase", "s1")+ flush_persons_and_events()++ hits = self._scan([broken, purchases], "s1")++ assert [hit.metric_uuid for hit in hits] == [purchases["uuid"]]++ def test_scan_caps_number_of_scanned_metrics(self) -> None:+ # Metric counts are user-configurable with no server-side cap; without the branch cap a+ # metric-heavy experiment would compile an arbitrarily wide UNION ALL per player open.+ first = _metric("mean", name="Purchases", source=_events_node("purchase"))+ second = _metric("mean", name="Signups", source=_events_node("signup"))+ self._create_session_event("purchase", "s1")+ self._create_session_event("signup", "s1")+ flush_persons_and_events()++ with patch("products.experiments.backend.metric_events.MAX_SCANNED_METRICS", 1):+ hits = self._scan([first, second], "s1")++ assert [hit.metric_uuid for hit in hits] == [first["uuid"]]diff --git a/products/experiments/backend/test/test_session_context_api.py b/products/experiments/backend/test/test_session_context_api.pyindex a6c27ab23b33..21964bb06027 100644--- a/products/experiments/backend/test/test_session_context_api.py+++ b/products/experiments/backend/test/test_session_context_api.py@@ -16,7 +16,7 @@ from posthog.session_recordings.queries.test.session_replay_sql import produce_rfrom products.access_control.backend.facade.api import upsert_property_access_controlfrom products.access_control.backend.facade.contracts import PropertyAccessLevel, UpsertPropertyAccessControlInputfrom products.actions.backend.models.action import Action-from products.experiments.backend.models.experiment import Experiment+from products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetricfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.api.test.base import APILicensedTest@@ -47,6 +47,7 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):end_date: Optional[datetime] = None,created_by: Optional[User] = None,exposure_criteria: Optional[dict[str, Any]] = None,+ metrics: Optional[list[dict[str, Any]]] = None,) -> Experiment:team = team or self.teamflag = FeatureFlag.objects.create(@@ -71,6 +72,7 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):start_date=start_date,end_date=end_date,exposure_criteria=exposure_criteria or {},+ metrics=metrics or [],)def _enable_access_controls(self, feature: str = AvailableFeature.ACCESS_CONTROL) -> None:@@ -601,6 +603,93 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):)assert response.status_code == status.HTTP_200_OK+ def test_metrics_in_session(self) -> None:+ self._create_recording()+ # Two overlapping experiments with a metric each force a genuine multi-branch UNION ALL+ # in the metric scan — a single branch collapses to a plain SelectQuery, so only this+ # shape proves the union compiles end to end through the endpoint.+ metric = {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "11111111-1111-1111-1111-111111111111",+ "name": "Purchases",+ "source": {"kind": "EventsNode", "event": "purchase"},+ }+ other_metric = {+ **metric,+ "uuid": "22222222-2222-2222-2222-222222222222",+ "name": "Pricing clicks",+ "source": {"kind": "EventsNode", "event": "pricing clicked"},+ }+ with_hit = self._create_experiment(metrics=[metric])+ without_hit = self._create_experiment(key="pricing-banner", name="Pricing banner", metrics=[other_metric])+ for key in ("checkout-cta", "pricing-banner"):+ self._create_session_event(properties={"$feature_flag": key, "$feature_flag_response": "test"})+ self._create_session_event(event="purchase", timestamp="2026-01-01T10:09:00Z")+ flush_persons_and_events()++ response = self._get_session_context()++ assert response.status_code == status.HTTP_200_OK+ by_id = {result["experiment_id"]: result for result in response.json()["results"]}+ assert by_id[with_hit.id]["metrics_in_session"] == [+ {+ "metric_uuid": metric["uuid"],+ "metric_name": "Purchases",+ "event_count": 1,+ "first_timestamp": "2026-01-01T10:09:00Z",+ "timestamps": ["2026-01-01T10:09:00Z"],+ }+ ]+ # No metric event fired for the other experiment — the additive fields stay inert and+ # every pre-existing field keeps its value (the no-regression claim for current consumers).+ assert by_id[without_hit.id] == {+ "experiment_id": without_hit.id,+ "experiment_name": "Pricing banner",+ "flag_key": "pricing-banner",+ "variant": "test",+ "variants_seen": ["test"],+ "multiple_variants": False,+ "first_exposure_timestamp": "2026-01-01T10:02:11Z",+ "experiment_start_date": "2025-12-01T00:00:00Z",+ "experiment_end_date": None,+ "metrics_in_session": [],+ }++ def test_metrics_in_session_includes_saved_metric(self) -> None:+ self._create_recording()+ inline_metric = {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "11111111-1111-1111-1111-111111111111",+ "name": "Purchases",+ "source": {"kind": "EventsNode", "event": "purchase"},+ }+ saved_query = {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "33333333-3333-3333-3333-333333333333",+ "name": "Signups",+ "source": {"kind": "EventsNode", "event": "signup"},+ }+ experiment = self._create_experiment(metrics=[inline_metric])+ saved = ExperimentSavedMetric.objects.create(team=self.team, name="Signups", query=saved_query)+ ExperimentToSavedMetric.objects.create(experiment=experiment, saved_metric=saved, metadata={})+ self._create_session_event(properties={"$feature_flag": "checkout-cta", "$feature_flag_response": "test"})+ self._create_session_event(event="signup", timestamp="2026-01-01T10:08:00Z")+ self._create_session_event(event="purchase", timestamp="2026-01-01T10:09:00Z")+ flush_persons_and_events()++ response = self._get_session_context()++ assert response.status_code == status.HTTP_200_OK+ result = next(r for r in response.json()["results"] if r["experiment_id"] == experiment.id)+ # Both the inline and the saved/shared metric surface, sorted by first occurrence.+ assert [(hit["metric_uuid"], hit["metric_name"]) for hit in result["metrics_in_session"]] == [+ (saved_query["uuid"], "Signups"),+ (inline_metric["uuid"], "Purchases"),+ ]+def test_team_isolation(self) -> None:other_team = Team.objects.create(organization=self.organization, name="other team")diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex ea7dfeaa025e..d70c42a7d54b 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -2141,6 +2141,22 @@ export interface CreateFromPromptInputApi {description?: string}+/**+ * One experiment metric with at least one matching event in a session recording.+ */+export interface ExperimentSessionMetricHitApi {+ /** UUID of the experiment metric (inline primary/secondary or saved) whose events fired. */+ metric_uuid: string+ /** Display name of the metric, or an event-derived title (matching the experiment UI) when unnamed. */+ metric_name: string+ /** Total number of events in the session matching any of the metric's event/action sources. */+ event_count: number+ /** Timestamp of the first event in the session matching the metric. */+ first_timestamp: string+ /** Ascending timestamps of the metric's matching events in the session, capped at the first 50. event_count is the true total, so this list may be shorter — treat these as seek points, not a count. */+ timestamps: string[]+}+/*** One experiment whose feature flag a session recording saw.*/@@ -2172,6 +2188,8 @@ export interface ExperimentSessionContextItemApi {* @nullable*/experiment_end_date: string | null+ /** This experiment's metrics with at least one matching event in the session, sorted by first occurrence. Empty when none of the experiment's metric events fired during the session. */+ metrics_in_session: ExperimentSessionMetricHitApi[]}/**diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 90c9eab7c7c3..19843256c0e4 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -27081,6 +27081,22 @@ export namespace Schemas {readonly user_access_level: string | null;}+ /**+ * One experiment metric with at least one matching event in a session recording.+ */+ export interface ExperimentSessionMetricHit {+ /** UUID of the experiment metric (inline primary/secondary or saved) whose events fired. */+ metric_uuid: string;+ /** Display name of the metric, or an event-derived title (matching the experiment UI) when unnamed. */+ metric_name: string;+ /** Total number of events in the session matching any of the metric's event/action sources. */+ event_count: number;+ /** Timestamp of the first event in the session matching the metric. */+ first_timestamp: string;+ /** Ascending timestamps of the metric's matching events in the session, capped at the first 50. event_count is the true total, so this list may be shorter — treat these as seek points, not a count. */+ timestamps: string[];+ }+/*** One experiment whose feature flag a session recording saw.*/@@ -27112,6 +27128,8 @@ export namespace Schemas {* @nullable*/experiment_end_date: string | null;+ /** This experiment's metrics with at least one matching event in the session, sorted by first occurrence. Empty when none of the experiment's metric events fired during the session. */+ metrics_in_session: ExperimentSessionMetricHit[];}/**