Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(experiments): show which metric source fired in replay (#73491)

Marcel Poelker26ebf574a90b
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
index 9fb5d31c8f6d..1527ddf1f323 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
@@ -1,4 +1,5 @@
import { useActions, useValues } from 'kea'
+import { Fragment } from 'react'
import { IconChevronDown, IconInfo } from '@posthog/icons'
import { LemonBanner, LemonSegmentedButton } from '@posthog/lemon-ui'
@@ -20,8 +21,8 @@ import { SessionRecordingsPlaylist } from 'scenes/session-recordings/playlist/Se
import { Experiment } from '~/types'
import { isLaunched } from '../experimentStatus'
-import { EXPOSURE_UNLINKABLE_REASON, METRIC_UNLINKABLE_REASON } from '../viewRecordingsLinkabilityLogic'
-import { experimentReplayTabLogic } from './experimentReplayTabLogic'
+import { EXPOSURE_UNLINKABLE_REASON } from '../viewRecordingsLinkabilityLogic'
+import { ExperimentReplayMetricOption, experimentReplayTabLogic } from './experimentReplayTabLogic'
import { VariantTag } from './VariantTag'
// LemonSegmentedButton values must be strings; the logic stores null for "All". '$' is not an
@@ -49,11 +50,20 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):
return <LemonBanner type="warning">{EXPOSURE_UNLINKABLE_REASON}</LemonBanner>
}
- // Selectable metrics render as checkboxes. Unlinkable ones move to a labelled section that
- // explains once, via a section tooltip, why they can't be matched — instead of repeating the
- // same reason on every row.
+ // Selectable metrics render as checkboxes. Unlinkable ones move to labelled sections that
+ // explain once, via a section tooltip, why they can't be matched — instead of repeating the
+ // same reason on every row. One section per distinct reason, since metrics can be unmatchable
+ // for different reasons (server-side events, a retention window, data-warehouse-only sources).
const linkableMetricOptions = metricOptions.filter((option) => !option.unlinkable)
- const unlinkableMetricOptions = metricOptions.filter((option) => option.unlinkable)
+ const unlinkableOptionsByReason = new Map<string, ExperimentReplayMetricOption[]>()
+ for (const option of metricOptions) {
+ if (option.unlinkable && option.unlinkableReason) {
+ unlinkableOptionsByReason.set(option.unlinkableReason, [
+ ...(unlinkableOptionsByReason.get(option.unlinkableReason) ?? []),
+ option,
+ ])
+ }
+ }
return (
<div data-attr="experiment-recordings-tab">
@@ -96,21 +106,23 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):
{option.name}
</DropdownMenuCheckboxItem>
))}
- {unlinkableMetricOptions.length > 0 && (
- <>
- {linkableMetricOptions.length > 0 && <DropdownMenuSeparator />}
+ {[...unlinkableOptionsByReason.entries()].map(([reason, options], index) => (
+ // Fragment, not a wrapper element: the separator, label, and items
+ // must stay direct children of the menu for keyboard nav and ARIA.
+ <Fragment key={reason}>
+ {(linkableMetricOptions.length > 0 || index > 0) && <DropdownMenuSeparator />}
{/* Quill's DropdownMenuLabel renders a Base UI GroupLabel, which must
live inside a DropdownMenuGroup or it throws at render. */}
<DropdownMenuGroup>
<DropdownMenuLabel inset className="flex items-center gap-1">
Can't match to recordings
- <Tooltip title={METRIC_UNLINKABLE_REASON}>
+ <Tooltip title={reason}>
<IconInfo className="size-3 shrink-0" />
</Tooltip>
</DropdownMenuLabel>
- {unlinkableMetricOptions.map((option) => (
+ {options.map((option) => (
// Informational only — not selectable. The section label above
- // carries the single shared explanation.
+ // carries the explanation shared by this section's metrics.
<DropdownMenuItem
key={option.uuid}
inset
@@ -121,8 +133,8 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):
</DropdownMenuItem>
))}
</DropdownMenuGroup>
- </>
- )}
+ </Fragment>
+ ))}
</DropdownMenuContent>
</DropdownMenu>
)}
diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
index 8cf0c0b4bb77..1030b4efb77e 100644
--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
@@ -7,6 +7,7 @@ import { initKeaTests } from '~/test/init'
import { Experiment, FilterLogicalOperator } from '~/types'
import { getViewRecordingFiltersForVariant } from '../utils'
+import { RETENTION_UNLINKABLE_REASON } from '../viewRecordingsLinkabilityLogic'
import { experimentReplayTabLogic } from './experimentReplayTabLogic'
jest.mock('lib/utils/product-intents', () => ({
@@ -221,6 +222,46 @@ describe('experimentReplayTabLogic', () => {
])
})
+ it('lists a retention metric as unmatchable instead of dropping it silently', async () => {
+ // A retention metric yields no session filter (its return visit lands in a later session).
+ // Dropping it from the list reads as the metric having been forgotten, so it stays listed
+ // with a reason — and must never reach the query, which would only narrow to nothing.
+ const withRetention = experimentReplayTabLogic({
+ experiment: {
+ ...EXPERIMENT,
+ id: 46,
+ metrics_secondary: [
+ ...(EXPERIMENT.metrics_secondary ?? []),
+ {
+ kind: NodeKind.ExperimentMetric,
+ metric_type: ExperimentMetricType.RETENTION,
+ uuid: 'metric-retention',
+ name: '7-day retention',
+ start_event: { kind: NodeKind.EventsNode, event: '$pageview' },
+ completion_event: { kind: NodeKind.EventsNode, event: '$pageview' },
+ },
+ ],
+ } as unknown as Experiment,
+ })
+ withRetention.mount()
+ await expectLogic(withRetention).toFinishAllListeners()
+
+ expect(withRetention.values.metricOptions.find((option) => option.uuid === 'metric-retention')).toMatchObject({
+ name: '7-day retention',
+ unlinkable: true,
+ unlinkableReason: RETENTION_UNLINKABLE_REASON,
+ })
+ withRetention.actions.setMetricSelected('metric-retention', true)
+ expect(withRetention.values.effectiveMetricUuids).toEqual([])
+ expect(withRetention.values.recordingsFilters.filter_group.values).toEqual([
+ {
+ type: FilterLogicalOperator.And,
+ values: getViewRecordingFiltersForVariant(EXPERIMENT, undefined),
+ },
+ ])
+ withRetention.unmount()
+ })
+
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 })
diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
index 3358822218df..e6b9b314c481 100644
--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
@@ -3,7 +3,13 @@ import { MakeLogicType, actions, afterMount, connect, kea, key, path, props, red
import { addProductIntentForCrossSell } from 'lib/utils/product-intents'
import { DEFAULT_RECORDING_FILTERS } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'
-import { ExperimentMetric, NodeKind, ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
+import {
+ ExperimentMetric,
+ NodeKind,
+ ProductIntentContext,
+ ProductKey,
+ isExperimentRetentionMetric,
+} from '~/queries/schema/schema-general'
import { Experiment, FilterLogicalOperator, RecordingUniversalFilters, UniversalFiltersGroupValue } from '~/types'
import type { ExperimentIdType } from '../../../types'
@@ -16,7 +22,12 @@ import {
getViewRecordingFiltersForVariant,
isUnlinkableEventFilter,
} from '../utils'
-import { viewRecordingsLinkabilityLogic } from '../viewRecordingsLinkabilityLogic'
+import {
+ DATA_WAREHOUSE_UNLINKABLE_REASON,
+ METRIC_UNLINKABLE_REASON,
+ RETENTION_UNLINKABLE_REASON,
+ viewRecordingsLinkabilityLogic,
+} from '../viewRecordingsLinkabilityLogic'
export interface ExperimentReplayTabLogicProps {
experiment: Experiment
@@ -28,6 +39,8 @@ export interface ExperimentReplayMetricOption {
name: string
filters: UniversalFiltersGroupValue[]
unlinkable: boolean
+ /** Why the metric can't narrow the playlist, shown alongside it. Null when it can. */
+ unlinkableReason: string | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -155,15 +168,17 @@ 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.
+ // Every uuid-carrying metric: inline primary + secondary, then saved/shared metrics (their
+ // definition lives in `saved_metrics[].query`) — the same set the backend
+ // `resolve_metric_events` scans, deduped by uuid so a shared metric linked more than once
+ // 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 when every one
+ // of its sources is a never-session-linked event, or when it yields no session filter at
+ // all (a retention metric, or one measured only in the data warehouse) — either way its
+ // filter could only match zero sessions. Those stay listed with their reason rather than
+ // vanishing, which reads as the metric having been forgotten. Fails open while the check
+ // loads.
metricOptions: [
(s) => [s.linkabilityLoaded, s.unlinkableEventNames, (_, props) => props.experiment],
(
@@ -185,23 +200,32 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
uuid: metric.uuid,
name: metric.name || getDefaultMetricTitle(metric),
filters: getMetricSessionFilters(metric),
+ noFilterReason: isExperimentRetentionMetric(metric)
+ ? RETENTION_UNLINKABLE_REASON
+ : DATA_WAREHOUSE_UNLINKABLE_REASON,
},
]
: []
)
.filter((option) => {
- if (option.filters.length === 0 || seenUuids.has(option.uuid)) {
+ if (seenUuids.has(option.uuid)) {
return false
}
seenUuids.add(option.uuid)
return true
})
- .map((option) => ({
- ...option,
- unlinkable:
- linkabilityLoaded &&
- option.filters.every((filter) => isUnlinkableEventFilter(filter, unlinkableEventNames)),
- }))
+ .map(({ noFilterReason, ...option }) => {
+ const unlinkableReason =
+ option.filters.length === 0
+ ? noFilterReason
+ : linkabilityLoaded &&
+ option.filters.every((filter) =>
+ isUnlinkableEventFilter(filter, unlinkableEventNames)
+ )
+ ? METRIC_UNLINKABLE_REASON
+ : null
+ return { ...option, unlinkable: unlinkableReason !== null, unlinkableReason }
+ })
},
],
effectiveMetricUuids: [
diff --git a/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts b/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts
index bad4edef9e1c..ee903e20a1b3 100644
--- a/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts
+++ b/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts
@@ -19,6 +19,12 @@ export const EXPOSURE_UNLINKABLE_REASON =
export const METRIC_UNLINKABLE_REASON =
"This metric's events are captured server-side without a session ID, so recordings can't be matched."
+export const RETENTION_UNLINKABLE_REASON =
+ 'Retention metrics measure a return visit, which happens in a later session than the one that starts it. No single recording can show both, so these metrics are left out of the filter.'
+
+export const DATA_WAREHOUSE_UNLINKABLE_REASON =
+ 'This metric is measured entirely in the data warehouse, which has no session events to match recordings on.'
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface viewRecordingsLinkabilityLogicValues {
linkabilityLoaded: boolean
diff --git a/frontend/src/scenes/session-recordings/__mocks__/experiment_session_context.ts b/frontend/src/scenes/session-recordings/__mocks__/experiment_session_context.ts
index 48b899ab180c..1dc969a90828 100644
--- a/frontend/src/scenes/session-recordings/__mocks__/experiment_session_context.ts
+++ b/frontend/src/scenes/session-recordings/__mocks__/experiment_session_context.ts
@@ -38,6 +38,23 @@ export const experimentSessionContextResponse: ExperimentSessionContextResponseA
'2023-05-01T14:46:31.000000Z',
'2023-05-01T14:46:44.000000Z',
],
+ // A mean metric's single source: no role qualifier, so it renders as the flat
+ // metric name plus its seek chips.
+ sources: [
+ {
+ source_role: 'source',
+ source_name: 'purchase completed',
+ source_index: 0,
+ source_total: 1,
+ event_count: 3,
+ first_timestamp: '2023-05-01T14:46:26.000000Z',
+ timestamps: [
+ '2023-05-01T14:46:26.000000Z',
+ '2023-05-01T14:46:31.000000Z',
+ '2023-05-01T14:46:44.000000Z',
+ ],
+ },
+ ],
},
{
metric_uuid: 'metric-2',
@@ -46,6 +63,57 @@ export const experimentSessionContextResponse: ExperimentSessionContextResponseA
// 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'],
+ sources: [
+ {
+ source_role: 'source',
+ source_name: 'checkout started',
+ source_index: 0,
+ source_total: 1,
+ event_count: 1,
+ first_timestamp: '2023-05-01T15:20:00.000000Z',
+ timestamps: ['2023-05-01T15:20:00.000000Z'],
+ },
+ ],
+ },
+ {
+ metric_uuid: 'metric-3',
+ metric_name: 'Signup funnel',
+ event_count: 2,
+ first_timestamp: '2023-05-01T14:46:25.000000Z',
+ timestamps: ['2023-05-01T14:46:25.000000Z', '2023-05-01T14:46:29.000000Z'],
+ // Only the middle step fired — the breakdown is what stops this reading as
+ // "completed the funnel".
+ sources: [
+ {
+ source_role: 'step',
+ source_name: 'activated',
+ source_index: 1,
+ source_total: 3,
+ event_count: 2,
+ first_timestamp: '2023-05-01T14:46:25.000000Z',
+ timestamps: ['2023-05-01T14:46:25.000000Z', '2023-05-01T14:46:29.000000Z'],
+ },
+ ],
+ },
+ {
+ metric_uuid: 'metric-4',
+ metric_name: '7-day retention',
+ event_count: 1,
+ first_timestamp: '2023-05-01T14:46:27.000000Z',
+ timestamps: ['2023-05-01T14:46:27.000000Z'],
+ // $pageview on both the start and return side: the return source would just
+ // duplicate the start's identical events, so only the start is contributed here.
+ sources: [
+ {
+ source_role: 'retention_start',
+ source_name: '$pageview',
+ source_index: 0,
+ source_total: 1,
+ event_count: 1,
+ first_timestamp: '2023-05-01T14:46:27.000000Z',
+ timestamps: ['2023-05-01T14:46:27.000000Z'],
+ },
+ ],
},
],
}),
diff --git a/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.tsx b/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.tsx
index e906da4e205f..67e257315343 100644
--- a/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.tsx
+++ b/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
import { useEffect, useRef } from 'react'
-import { IconCollapse, IconExpand, IconExternal, IconMinus, IconWarning } from '@posthog/icons'
+import { IconCollapse, IconExpand, IconExternal, IconInfo, IconMinus, IconWarning } from '@posthog/icons'
import { dayjs } from 'lib/dayjs'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
@@ -17,9 +17,11 @@ import { urls } from 'scenes/urls'
import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
-import type {
- ExperimentSessionContextItemApi,
- ExperimentSessionMetricHitApi,
+import {
+ type ExperimentSessionContextItemApi,
+ type ExperimentSessionMetricHitApi,
+ type ExperimentSessionMetricSourceHitApi,
+ SourceRoleEnumApi,
} from 'products/experiments/frontend/generated/api.schemas'
import {
@@ -82,27 +84,58 @@ function MetricEventChips({
)
}
-function MetricHitRow({
- hit,
+// What each source is to its metric. A metric's own name says nothing about which side of it fired,
+// and for most metric types that distinction is the difference between "they converted" and "they
+// took the first step" — so it's spelled out rather than left to the reader.
+function sourceLabel(source: ExperimentSessionMetricSourceHitApi): string | null {
+ switch (source.source_role) {
+ case SourceRoleEnumApi.Step:
+ return source.source_total > 1
+ ? `Step ${source.source_index + 1} of ${source.source_total}`
+ : // A one-step funnel is just its event; the step number would be noise.
+ null
+ case SourceRoleEnumApi.Numerator:
+ return 'Numerator'
+ case SourceRoleEnumApi.Denominator:
+ return 'Denominator'
+ case SourceRoleEnumApi.RetentionStart:
+ return 'Start event'
+ case SourceRoleEnumApi.RetentionCompletion:
+ return 'Return event'
+ default:
+ return null
+ }
+}
+
+const SESSION_SCOPE_CAVEAT =
+ "What this session saw, and the metric events that fired in it. These are events a metric counts, not its result: whether they count for this person depends on their exposure and the metric's window, which the experiment analysis decides across all their sessions."
+
+function MetricSourceRow({
+ source,
recordingStartMs,
isWithinRecording,
onSeek,
}: {
- hit: ExperimentSessionMetricHitApi
+ source: ExperimentSessionMetricSourceHitApi
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
+ const seekPoints = source.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 }))
+ const label = sourceLabel(source)
return (
- <div className="flex flex-col gap-y-0.5 min-w-0 pl-3 text-xs">
- <span className="truncate">{hit.metric_name}</span>
+ <div className="flex flex-col gap-y-0.5 min-w-0">
+ {label ? (
+ <span className="pl-3 truncate text-muted">
+ {label} · {source.source_name}
+ </span>
+ ) : null}
{seekPoints.length === 0 ? (
<span className="pl-3 text-muted">Fired outside the recording</span>
) : (
@@ -112,6 +145,52 @@ function MetricHitRow({
)
}
+function MetricHitRow({
+ hit,
+ recordingStartMs,
+ isWithinRecording,
+ onSeek,
+}: {
+ hit: ExperimentSessionMetricHitApi
+ recordingStartMs: number | null
+ isWithinRecording: (timestampMs: number | null) => timestampMs is number
+ onSeek: (timestampMs: number) => void
+}): JSX.Element {
+ // Metrics past the scan's aggregate ceiling carry no breakdown; their own totals are then the
+ // only thing to show, unqualified — which is exactly what the 'source' role renders.
+ const sources: ExperimentSessionMetricSourceHitApi[] =
+ hit.sources.length > 0
+ ? hit.sources
+ : [
+ {
+ source_role: SourceRoleEnumApi.Source,
+ source_name: hit.metric_name,
+ source_index: 0,
+ source_total: 1,
+ event_count: hit.event_count,
+ first_timestamp: hit.first_timestamp,
+ timestamps: hit.timestamps,
+ },
+ ]
+
+ return (
+ // Indented to start under the exposure-time column, so the block reads as belonging to the
+ // experiment row above it rather than as another top-level row.
+ <div className="flex flex-col gap-y-0.5 min-w-0 pl-8 text-xs">
+ <span className="truncate">{hit.metric_name}</span>
+ {sources.map((source) => (
+ <MetricSourceRow
+ key={`${source.source_role}-${source.source_index}`}
+ source={source}
+ recordingStartMs={recordingStartMs}
+ isWithinRecording={isWithinRecording}
+ onSeek={onSeek}
+ />
+ ))}
+ </div>
+ )
+}
+
function OpenExperimentButton({ item }: { item: ExperimentSessionContextItemApi }): JSX.Element {
return (
<LemonButton
@@ -381,7 +460,15 @@ export function PlayerSidebarExperimentsSection(): JSX.Element | null {
className="rounded border bg-surface-primary px-2 py-1 flex flex-col gap-y-1"
data-attr="replay-experiment-context-overview"
>
- <h4 className="font-semibold text-xs mb-0">Experiments</h4>
+ <h4 className="font-semibold text-xs mb-0 flex items-center gap-1">
+ Experiments
+ {/* One icon for the whole section: the caveat applies to every row and every metric
+ under it, so repeating it per metric name would fire a tooltip on almost any
+ hover in here. */}
+ <Tooltip title={SESSION_SCOPE_CAVEAT}>
+ <IconInfo className="size-3 shrink-0 text-secondary" />
+ </Tooltip>
+ </h4>
{pinnedItem ? (
<div className="flex flex-col gap-y-0.5" data-attr="replay-experiment-context-current">
diff --git a/products/experiments/backend/metric_events.py b/products/experiments/backend/metric_events.py
index 4a1c57de3b9f..aad9fd03248f 100644
--- a/products/experiments/backend/metric_events.py
+++ b/products/experiments/backend/metric_events.py
@@ -14,6 +14,8 @@ import logging
from copy import deepcopy
from dataclasses import dataclass
from datetime import datetime
+from enum import StrEnum
+from typing import Optional
import pydantic
@@ -53,10 +55,40 @@ MAX_METRIC_EVENT_TIMESTAMPS = 50
# arbitrarily wide query or emit an unbounded hit list; 50 mirrors MAX_CANDIDATE_EXPERIMENTS
# in session_context.
MAX_SCANNED_METRICS = 50
+# Ceiling on aggregate groups (each costs three conditional aggregates in the scan). Only the
+# per-source breakdown is capped here — every accepted metric's own totals group is registered
+# unconditionally (bounded by MAX_SCANNED_METRICS), so a metric over the ceiling loses its
+# per-source split but never its total. Funnel step counts are user-configurable, so without
+# this a fleet of long funnels could compile a query thousands of aggregates wide.
+MAX_AGGREGATE_GROUPS = 200
MetricSourceNode = EventsNode | ActionsNode
+class MetricSourceRole(StrEnum):
+ """What one source node means to its metric, so a hit can say which side of the metric fired."""
+
+ SOURCE = "source"
+ STEP = "step"
+ NUMERATOR = "numerator"
+ DENOMINATOR = "denominator"
+ RETENTION_START = "retention_start"
+ RETENTION_COMPLETION = "retention_completion"
+
+
+@dataclass(frozen=True)
+class MetricSource:
+ """One event/action source of a metric, with its position in the metric's definition."""
+
+ role: MetricSourceRole
+ name: str
+ # Position among *all* the metric's sources, data-warehouse ones included, so a funnel step
+ # keeps its real step number even when an earlier step has no session events.
+ index: int
+ total: int
+ node: MetricSourceNode
+
+
@dataclass(frozen=True)
class SharedHogQLDatabase:
"""A HogQL virtual database built once per request and shared across that request's
@@ -93,8 +125,21 @@ class MetricEventSource:
# 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, ...]
+ # The parsed event/action sources, kept for their per-node property filters.
+ sources: tuple[MetricSource, ...]
+
+
+@dataclass(frozen=True)
+class MetricSourceHit:
+ """One source of a metric with at least one matching event in a session."""
+
+ role: MetricSourceRole
+ name: str
+ index: int
+ total: int
+ event_count: int
+ first_timestamp: datetime
+ timestamps: tuple[datetime, ...]
@dataclass(frozen=True)
@@ -108,16 +153,43 @@ class MetricHit:
# 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, ...]
+ # Which of the metric's sources fired, so a hit reads as "step 2 of 3" or "the start event of
+ # a retention metric" rather than an unqualified "this metric happened". Sources with no
+ # matching event are omitted, as is the whole breakdown when the metric is over the
+ # aggregate-group ceiling.
+ sources: tuple[MetricSourceHit, ...]
+
+def _node_signature(node: MetricSourceNode | ExperimentDataWarehouseNode) -> str:
+ """A stable identity for a source node. Two nodes with the same signature match the same events
+ and share one aggregate in the scan, so they can only ever render identical hits."""
+ return node.model_dump_json(exclude_none=True)
-def _metric_source_nodes(metric: ExperimentMetric) -> list[MetricSourceNode | ExperimentDataWarehouseNode]:
+
+def _metric_sources(
+ metric: ExperimentMetric,
+) -> list[tuple[MetricSourceRole, MetricSourceNode | ExperimentDataWarehouseNode]]:
if isinstance(metric, ExperimentMeanMetric):
- return [metric.source]
+ return [(MetricSourceRole.SOURCE, metric.source)]
if isinstance(metric, ExperimentFunnelMetric):
- return list(metric.series)
+ return [(MetricSourceRole.STEP, step) for step in metric.series]
if isinstance(metric, ExperimentRatioMetric):
- return [metric.numerator, metric.denominator]
- return [metric.start_event, metric.completion_event]
+ return [
+ (MetricSourceRole.NUMERATOR, metric.numerator),
+ (MetricSourceRole.DENOMINATOR, metric.denominator),
+ ]
+ # The completion is the retention metric's "return visit" event. The scan can only say the event
+ # fired in this session, not that it fired in the window the analysis requires — so when start
+ # and completion are the identical node, a completion source would render a hit byte-identical to
+ # the start's: a duplicate chip implying a return the scan can't distinguish from the entry. A
+ # distinct completion event (or the same event narrowed by different properties) is a separate
+ # signal worth showing, whichever window it opens in.
+ sources: list[tuple[MetricSourceRole, MetricSourceNode | ExperimentDataWarehouseNode]] = [
+ (MetricSourceRole.RETENTION_START, metric.start_event)
+ ]
+ if _node_signature(metric.completion_event) != _node_signature(metric.start_event):
+ sources.append((MetricSourceRole.RETENTION_COMPLETION, metric.completion_event))
+ return sources
def _source_title(node: MetricSourceNode | ExperimentDataWarehouseNode) -> str | None:
@@ -154,24 +226,36 @@ def resolve_metric_events(experiment: Experiment) -> list[MetricEventSource]:
`metric_type` unknown to `build_metric`) are skipped, not fatal — one bad metric must
never fail the whole surface.
"""
- sources: list[MetricEventSource] = []
+ metric_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))
+ all_sources = _metric_sources(metric)
+ sources = tuple(
+ MetricSource(
+ role=role,
+ # `_source_title` returns None only for an all-events node (no name, no event).
+ name=_source_title(node) or "All events",
+ index=index,
+ total=len(all_sources),
+ node=node,
+ )
+ for index, (role, node) in enumerate(all_sources)
+ if isinstance(node, EventsNode | ActionsNode)
+ )
metric_uuid = str(metric_dict["uuid"])
- sources.append(
+ metric_sources.append(
MetricEventSource(
metric_uuid=metric_uuid,
metric_name=metric.name or _default_metric_title(metric),
- session_linkable=bool(nodes),
- nodes=nodes,
+ session_linkable=bool(sources),
+ sources=sources,
)
)
- return sources
+ return metric_sources
def _node_condition(node: MetricSourceNode, team: Team) -> ast.Expr:
@@ -212,6 +296,11 @@ def scan_session_for_metric_events(
metric-carrying experiments. Keeping the OR of every metric condition in WHERE preserves
the event-name primary-key pruning the per-metric branches had.
+ Each metric is aggregated twice over: once across all its sources (its own totals, an OR so
+ an event matching two sources still counts once) and once per source (the breakdown that
+ says *which* side of the metric fired). Groups are keyed by their source nodes, so a metric
+ with a single source needs one group, and metrics sharing a source share its aggregates.
+
Metrics with no hits are omitted. Duplicate metric uuids (a saved metric shared by several
experiments) and metrics with identical source nodes (several experiments measuring the
same event) are aggregated once, and at most MAX_SCANNED_METRICS metrics are accepted per
@@ -225,29 +314,54 @@ def scan_session_for_metric_events(
a large warehouse schema, so callers that already hold one should pass it in, along with
the modifiers it was built with.
"""
- names_by_uuid: dict[str, str] = {}
- # Metric uuids grouped by identical source nodes: identical sources compile to identical
- # row conditions, so they share one aggregate set instead of re-counting the same events.
- uuids_by_source: dict[tuple[str, ...], list[str]] = {}
- conditions_by_source: dict[tuple[str, ...], ast.Expr] = {}
+ accepted: list[MetricEventSource] = []
+ seen_uuids: set[str] = set()
+ # One row condition per distinct source node, so two metrics measuring the same event compile
+ # (and count) it once.
+ conditions_by_node: dict[str, ast.Expr] = {}
+ # Aggregate groups, keyed by the sorted distinct source nodes they cover: one per metric (all
+ # its sources) plus one per individual source. A single-source metric's two keys coincide.
+ group_indexes: dict[tuple[str, ...], int] = {}
skipped_over_cap = 0
- for source in metric_sources:
- if not source.session_linkable or source.metric_uuid in names_by_uuid:
+ skipped_breakdown_sources = 0
+
+ def node_key(source: MetricSource) -> str:
+ return _node_signature(source.node)
+
+ def metric_group_key(metric_source: MetricEventSource) -> tuple[str, ...]:
+ # Distinct nodes only, so a ratio measuring the same event on both sides is one aggregate.
+ return tuple(sorted({node_key(source) for source in metric_source.sources}))
+
+ def register_group(key: tuple[str, ...], *, capped: bool) -> bool:
+ """Give the group an aggregate slot. Returns False only when a capped group was dropped
+ at the aggregate ceiling."""
+ if key in group_indexes:
+ return True
+ if capped and len(group_indexes) >= MAX_AGGREGATE_GROUPS:
+ return False
+ group_indexes[key] = len(group_indexes)
+ return True
+
+ for metric_source in metric_sources:
+ if not metric_source.session_linkable or metric_source.metric_uuid in seen_uuids:
continue
- if len(names_by_uuid) >= MAX_SCANNED_METRICS:
+ if len(seen_uuids) >= MAX_SCANNED_METRICS:
skipped_over_cap += 1
continue
- source_key = tuple(sorted(node.model_dump_json(exclude_none=True) for node in source.nodes))
- if source_key in uuids_by_source:
- names_by_uuid[source.metric_uuid] = source.metric_name
- uuids_by_source[source_key].append(source.metric_uuid)
- continue
- conditions = [_node_condition(node, team) for node in source.nodes]
- if not conditions:
- continue
- names_by_uuid[source.metric_uuid] = source.metric_name
- uuids_by_source[source_key] = [source.metric_uuid]
- conditions_by_source[source_key] = ast.Or(exprs=conditions) if len(conditions) > 1 else conditions[0]
+ seen_uuids.add(metric_source.metric_uuid)
+ accepted.append(metric_source)
+ for source in metric_source.sources:
+ conditions_by_node.setdefault(node_key(source), _node_condition(source.node, team))
+
+ # Every metric's own totals group is registered first and uncapped — it is bounded by
+ # MAX_SCANNED_METRICS, so it never competes for the ceiling. Only the per-source breakdown is
+ # capped, so a metric over the ceiling loses its per-source split but never its totals.
+ for metric_source in accepted:
+ register_group(metric_group_key(metric_source), capped=False)
+ for metric_source in accepted:
+ for source in metric_source.sources:
+ if not register_group((node_key(source),), capped=True):
+ skipped_breakdown_sources += 1
if skipped_over_cap:
logger.warning(
@@ -256,21 +370,30 @@ def scan_session_for_metric_events(
MAX_SCANNED_METRICS,
skipped_over_cap,
)
+ if skipped_breakdown_sources:
+ logger.warning(
+ "Metric scan for session %s capped at %s aggregate groups; per-source breakdown dropped for %s source(s)",
+ session_id,
+ MAX_AGGREGATE_GROUPS,
+ skipped_breakdown_sources,
+ )
- if not uuids_by_source:
+ if not group_indexes:
return []
# Condition asts are deep-copied per use site (three aggregates + the WHERE): the HogQL
# resolver annotates nodes in place, so sharing one instance across positions is unsafe.
- source_keys = list(uuids_by_source)
+ def group_condition(key: tuple[str, ...]) -> ast.Expr:
+ conditions = [deepcopy(conditions_by_node[node]) for node in key]
+ return ast.Or(exprs=conditions) if len(conditions) > 1 else conditions[0]
+
select: list[ast.Expr] = []
- for index, source_key in enumerate(source_keys):
- condition = conditions_by_source[source_key]
- select.append(ast.Alias(alias=f"count_{index}", expr=ast.Call(name="countIf", args=[deepcopy(condition)])))
+ for key, index in group_indexes.items():
+ select.append(ast.Alias(alias=f"count_{index}", expr=ast.Call(name="countIf", args=[group_condition(key)])))
select.append(
ast.Alias(
alias=f"first_{index}",
- expr=ast.Call(name="minIf", args=[ast.Field(chain=["timestamp"]), deepcopy(condition)]),
+ expr=ast.Call(name="minIf", args=[ast.Field(chain=["timestamp"]), group_condition(key)]),
)
)
select.append(
@@ -284,7 +407,7 @@ def scan_session_for_metric_events(
args=[
ast.Call(
name="groupArrayIf",
- args=[ast.Field(chain=["timestamp"]), deepcopy(condition)],
+ args=[ast.Field(chain=["timestamp"]), group_condition(key)],
)
],
),
@@ -295,7 +418,7 @@ def scan_session_for_metric_events(
)
)
- any_metric_condition = [deepcopy(conditions_by_source[source_key]) for source_key in source_keys]
+ any_metric_condition = [deepcopy(condition) for condition in conditions_by_node.values()]
query = ast.SelectQuery(
select=select,
select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
@@ -333,20 +456,47 @@ def scan_session_for_metric_events(
row = response.results[0] if response.results else None
if row is None:
return []
- hits: list[MetricHit] = []
- for index, source_key in enumerate(source_keys):
- event_count, first_timestamp, timestamps = row[index * 3], row[index * 3 + 1], row[index * 3 + 2]
+
+ def read_group(key: tuple[str, ...]) -> Optional[tuple[int, datetime, tuple[datetime, ...]]]:
+ index = group_indexes.get(key)
+ if index is None:
+ return None
+ event_count = row[index * 3]
if not event_count:
+ return None
+ return int(event_count), row[index * 3 + 1], tuple(row[index * 3 + 2])
+
+ hits: list[MetricHit] = []
+ for metric_source in accepted:
+ totals = read_group(metric_group_key(metric_source))
+ if totals is None:
continue
- for metric_uuid in uuids_by_source[source_key]:
- hits.append(
- MetricHit(
- metric_uuid=metric_uuid,
- metric_name=names_by_uuid[metric_uuid],
- event_count=int(event_count),
- first_timestamp=first_timestamp,
- timestamps=tuple(timestamps),
+ event_count, first_timestamp, timestamps = totals
+ source_hits: list[MetricSourceHit] = []
+ for source in metric_source.sources:
+ source_totals = read_group((node_key(source),))
+ if source_totals is None:
+ continue
+ source_hits.append(
+ MetricSourceHit(
+ role=source.role,
+ name=source.name,
+ index=source.index,
+ total=source.total,
+ event_count=source_totals[0],
+ first_timestamp=source_totals[1],
+ timestamps=source_totals[2],
)
)
+ hits.append(
+ MetricHit(
+ metric_uuid=metric_source.metric_uuid,
+ metric_name=metric_source.metric_name,
+ event_count=event_count,
+ first_timestamp=first_timestamp,
+ timestamps=timestamps,
+ sources=tuple(source_hits),
+ )
+ )
hits.sort(key=lambda hit: hit.first_timestamp)
return hits
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index c3c478d37d5e..70e8a5a599ab 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -34,6 +34,7 @@ from products.experiments.backend.facade.contracts import CreateExperimentInput
from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint
from products.experiments.backend.hogql_queries.utils import get_experiment_stats_method
from products.experiments.backend.llm_metric_templates import TEMPLATE_NAMES
+from products.experiments.backend.metric_events import MetricSourceRole
from products.experiments.backend.metric_utils import refresh_action_names_in_metric
from products.experiments.backend.models.experiment import (
Experiment,
@@ -1477,6 +1478,43 @@ class RunningTimeCalculationResultSerializer(serializers.Serializer):
)
+class ExperimentSessionMetricSourceHitSerializer(serializers.Serializer):
+ """One event/action source of a metric with at least one matching event in a session recording."""
+
+ source_role = serializers.ChoiceField(
+ source="role",
+ choices=[role.value for role in MetricSourceRole],
+ help_text=(
+ "What this source means to its metric: 'source' (a mean metric's single event), 'step' (a funnel "
+ "step, numbered by source_index), 'numerator'/'denominator' (a ratio metric's two sides), or "
+ "'retention_start'/'retention_completion' (a retention metric's start event and return visit). "
+ "A hit on one source is not a hit on the metric as the analysis counts it."
+ ),
+ )
+ source_name = serializers.CharField(source="name", help_text="Display name of the source event or action.")
+ source_index = serializers.IntegerField(
+ source="index",
+ help_text=(
+ "0-based position of this source among all the metric's sources, data-warehouse ones included — so a "
+ "funnel step keeps its real step number even when an earlier step has no session events."
+ ),
+ )
+ source_total = serializers.IntegerField(
+ source="total", help_text="Total number of sources the metric is defined over."
+ )
+ event_count = serializers.IntegerField(help_text="Number of events in the session matching this source.")
+ first_timestamp = serializers.DateTimeField(
+ help_text="Timestamp of the first event in the session matching this source."
+ )
+ timestamps = serializers.ListField(
+ child=serializers.DateTimeField(),
+ help_text=(
+ "Ascending timestamps of this source'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 ExperimentSessionMetricHitSerializer(serializers.Serializer):
"""One experiment metric with at least one matching event in a session recording."""
@@ -1499,6 +1537,16 @@ class ExperimentSessionMetricHitSerializer(serializers.Serializer):
"event_count is the true total, so this list may be shorter — treat these as seek points, not a count."
),
)
+ sources = ExperimentSessionMetricSourceHitSerializer(
+ many=True,
+ help_text=(
+ "Which of the metric's sources fired, so a hit reads as 'step 2 of 3' or 'the start event of a "
+ "retention metric' rather than an unqualified 'this metric happened'. Sources with no matching event "
+ "are omitted, as is the whole breakdown for metrics beyond the scan's aggregate ceiling. A retention "
+ "metric whose start and completion are the same event contributes only the start source: the "
+ "completion would match the identical events and render a duplicate."
+ ),
+ )
class ExperimentSessionContextItemSerializer(serializers.Serializer):
diff --git a/products/experiments/backend/session_context.py b/products/experiments/backend/session_context.py
index 0774d697627b..6a95b7408eaa 100644
--- a/products/experiments/backend/session_context.py
+++ b/products/experiments/backend/session_context.py
@@ -124,7 +124,9 @@ def get_session_experiment_context(
a recording doesn't re-run the ClickHouse scans. "Recording not found" is not cached: the
recording may simply still be ingesting.
"""
- cache_key = f"experiment_session_context_{team.pk}_{user.pk}_{session_id}"
+ # The version segment must be bumped whenever the cached dataclasses change shape: entries are
+ # pickled, so a deploy would otherwise restore instances missing the new fields.
+ cache_key = f"experiment_session_context_v2_{team.pk}_{user.pk}_{session_id}"
cached = get_safe_cache(cache_key)
if cached is not None:
return cached
diff --git a/products/experiments/backend/test/test_metric_events.py b/products/experiments/backend/test/test_metric_events.py
index b672d69add09..3f47a17f3f45 100644
--- a/products/experiments/backend/test/test_metric_events.py
+++ b/products/experiments/backend/test/test_metric_events.py
@@ -12,7 +12,12 @@ 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.metric_events import (
+ MetricHit,
+ MetricSourceRole,
+ 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
@@ -47,14 +52,19 @@ def _metric(metric_type: str, name: Optional[str] = "Metric", **type_fields: Any
}
-def _retention_metric(start_event: dict[str, Any], completion_event: dict[str, Any]) -> dict[str, Any]:
+def _retention_metric(
+ start_event: dict[str, Any],
+ completion_event: dict[str, Any],
+ retention_window_start: int = 0,
+ retention_window_unit: str = "day",
+) -> dict[str, Any]:
return _metric(
"retention",
start_event=start_event,
completion_event=completion_event,
- retention_window_start=0,
+ retention_window_start=retention_window_start,
retention_window_end=7,
- retention_window_unit="day",
+ retention_window_unit=retention_window_unit,
start_handling="first_seen",
)
@@ -91,11 +101,30 @@ class TestResolveMetricEvents(MetricEventsTestMixin):
_metric("ratio", numerator=_events_node("purchase"), denominator=_events_node("$pageview")),
("purchase", "$pageview"),
),
+ # A distinct return event is its own source, kept whichever window it opens in — the
+ # day-later window is analysis-side detail this session scan doesn't model, and the
+ # return can still fire in a session that straddles the boundary.
(
- "retention",
- _retention_metric(_events_node("signed up"), _events_node("uploaded file")),
+ "retention_distinct_completion_event",
+ _retention_metric(_events_node("signed up"), _events_node("uploaded file"), retention_window_start=1),
("signed up", "uploaded file"),
),
+ # Same event on both sides: the completion would match the identical events and render a
+ # duplicate of the start chip, so only the start source is kept.
+ (
+ "retention_same_event_dedupes_completion",
+ _retention_metric(_events_node("$pageview"), _events_node("$pageview")),
+ ("$pageview",),
+ ),
+ # Same event narrowed by different properties is a genuinely separate signal — both kept.
+ (
+ "retention_same_event_different_properties",
+ _retention_metric(
+ _events_node("$pageview", [{"key": "$pathname", "value": "/in", "type": "event"}]),
+ _events_node("$pageview", [{"key": "$pathname", "value": "/out", "type": "event"}]),
+ ),
+ ("$pageview", "$pageview"),
+ ),
]
)
def test_resolves_event_sources_per_metric_type(
@@ -107,8 +136,10 @@ class TestResolveMetricEvents(MetricEventsTestMixin):
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 (
+ tuple(source.node.event for source in sources[0].sources if isinstance(source.node, EventsNode))
+ == expected_events
+ )
assert sources[0].session_linkable is True
@parameterized.expand(
@@ -151,8 +182,8 @@ class TestResolveMetricEvents(MetricEventsTestMixin):
sources = resolve_metric_events(experiment)
assert len(sources) == 1
- assert len(sources[0].nodes) == 1
- node = sources[0].nodes[0]
+ assert len(sources[0].sources) == 1
+ node = sources[0].sources[0].node
assert isinstance(node, ActionsNode)
assert int(node.id) == action.pk
assert sources[0].session_linkable is True
@@ -168,10 +199,13 @@ class TestResolveMetricEvents(MetricEventsTestMixin):
dw_only, mixed = resolve_metric_events(experiment)
assert dw_only.session_linkable is False
- assert dw_only.nodes == ()
+ assert dw_only.sources == ()
assert mixed.session_linkable is True
- assert len(mixed.nodes) == 1
- assert [node.event for node in mixed.nodes if isinstance(node, EventsNode)] == ["purchase"]
+ assert len(mixed.sources) == 1
+ # The surviving numerator keeps its position in the metric, so a breakdown can still say
+ # which side of the ratio it is even though the denominator has no session events.
+ assert mixed.sources[0].role == MetricSourceRole.NUMERATOR
+ assert (mixed.sources[0].index, mixed.sources[0].total) == (0, 2)
def test_includes_secondary_and_saved_metrics(self) -> None:
primary = _metric("mean", source=_events_node("purchase"))
@@ -323,6 +357,93 @@ class TestScanSessionForMetricEvents(ClickhouseTestMixin, MetricEventsTestMixin)
assert sorted(hit.metric_uuid for hit in hits) == sorted([first["uuid"], second["uuid"]])
assert all(hit.event_count == 1 for hit in hits)
+ def test_hit_reports_which_sources_fired(self) -> None:
+ # A funnel hit must say which step fired: without the breakdown, a session that only fired
+ # the last step reads as "reached this metric", which is what the analysis would deny.
+ funnel = _metric(
+ "funnel",
+ name="Signup funnel",
+ series=[_events_node("signed up"), _events_node("activated"), _events_node("upgraded")],
+ )
+ self._create_session_event("upgraded", "s1")
+ flush_persons_and_events()
+
+ hits = self._scan([funnel], "s1")
+
+ assert len(hits) == 1
+ assert [(source.role, source.name, source.index, source.total) for source in hits[0].sources] == [
+ (MetricSourceRole.STEP, "upgraded", 2, 3)
+ ]
+
+ def test_retention_distinct_completion_in_session_reports_its_source(self) -> None:
+ # A distinct return event that fires in the session must surface as a completion source,
+ # even for a window that opens a day later — the analysis counts such a return when the
+ # session straddles the boundary, and dropping it before the scan hid it from the sidebar.
+ retention = _retention_metric(
+ _events_node("signed up"), _events_node("uploaded file"), retention_window_start=1
+ )
+ self._create_session_event("signed up", "s1")
+ self._create_session_event("uploaded file", "s1")
+ flush_persons_and_events()
+
+ hits = self._scan([retention], "s1")
+
+ assert len(hits) == 1
+ assert [(source.role, source.name) for source in hits[0].sources] == [
+ (MetricSourceRole.RETENTION_START, "signed up"),
+ (MetricSourceRole.RETENTION_COMPLETION, "uploaded file"),
+ ]
+
+ def test_metric_total_counts_an_event_matching_two_sources_once(self) -> None:
+ # A ratio measuring the same event on both sides (and retention metrics, which routinely
+ # reuse one event) must not double count: the metric's own total is the OR across its
+ # sources, while each source still reports its own count.
+ ratio = _metric(
+ "ratio",
+ name="Purchases per purchase",
+ numerator=_events_node("purchase"),
+ denominator=_events_node("purchase"),
+ )
+ self._create_session_event("purchase", "s1")
+ flush_persons_and_events()
+
+ hits = self._scan([ratio], "s1")
+
+ assert hits[0].event_count == 1
+ assert [(source.role, source.event_count) for source in hits[0].sources] == [
+ (MetricSourceRole.NUMERATOR, 1),
+ (MetricSourceRole.DENOMINATOR, 1),
+ ]
+
+ def test_metric_over_the_aggregate_cap_keeps_its_total_without_the_breakdown(self) -> None:
+ # Funnel step counts are user-configurable, so the aggregate ceiling can bite. Degrading
+ # must cost the per-source breakdown, never the hit itself.
+ funnel = _metric("funnel", name="Signup funnel", series=[_events_node("signed up"), _events_node("activated")])
+ self._create_session_event("signed up", "s1")
+ flush_persons_and_events()
+
+ with patch("products.experiments.backend.metric_events.MAX_AGGREGATE_GROUPS", 1):
+ hits = self._scan([funnel], "s1")
+
+ assert len(hits) == 1
+ assert hits[0].event_count == 1
+ assert hits[0].sources == ()
+
+ def test_aggregate_cap_never_drops_a_metric_below_its_own_totals(self) -> None:
+ # With more metrics than the ceiling, the cap must still only trim per-source breakdowns —
+ # every metric that fired keeps its totals. Guards against the ceiling swallowing whole
+ # metrics once the metric count (not just the step count) exceeds it.
+ metrics = [_metric("mean", name=event, source=_events_node(event)) for event in ("a", "b", "c")]
+ for event in ("a", "b", "c"):
+ self._create_session_event(event, "s1")
+ flush_persons_and_events()
+
+ with patch("products.experiments.backend.metric_events.MAX_AGGREGATE_GROUPS", 1):
+ hits = self._scan(metrics, "s1")
+
+ assert sorted(hit.metric_name for hit in hits) == ["a", "b", "c"]
+ assert all(hit.event_count == 1 for hit in hits)
+
def test_scan_caps_number_of_scanned_metrics(self) -> None:
# Metric counts are user-configurable with no server-side cap; without the metric cap a
# metric-heavy experiment would compile an arbitrarily wide scan per player open. The
diff --git a/products/experiments/backend/test/test_session_context_api.py b/products/experiments/backend/test/test_session_context_api.py
index 9a8fa74eb8eb..6a209d3af6d6 100644
--- a/products/experiments/backend/test/test_session_context_api.py
+++ b/products/experiments/backend/test/test_session_context_api.py
@@ -754,6 +754,17 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):
"event_count": 1,
"first_timestamp": "2026-01-01T10:09:00Z",
"timestamps": ["2026-01-01T10:09:00Z"],
+ "sources": [
+ {
+ "source_role": "source",
+ "source_name": "purchase",
+ "source_index": 0,
+ "source_total": 1,
+ "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
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index c72697283508..8ae4fc85924c 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -2228,6 +2228,52 @@ export interface CreateFromPromptInputApi {
description?: string
}
+/**
+ * * `source` - source
+ * * `step` - step
+ * * `numerator` - numerator
+ * * `denominator` - denominator
+ * * `retention_start` - retention_start
+ * * `retention_completion` - retention_completion
+ */
+export type SourceRoleEnumApi = (typeof SourceRoleEnumApi)[keyof typeof SourceRoleEnumApi]
+
+export const SourceRoleEnumApi = {
+ Source: 'source',
+ Step: 'step',
+ Numerator: 'numerator',
+ Denominator: 'denominator',
+ RetentionStart: 'retention_start',
+ RetentionCompletion: 'retention_completion',
+} as const
+
+/**
+ * One event/action source of a metric with at least one matching event in a session recording.
+ */
+export interface ExperimentSessionMetricSourceHitApi {
+ /** What this source means to its metric: 'source' (a mean metric's single event), 'step' (a funnel step, numbered by source_index), 'numerator'/'denominator' (a ratio metric's two sides), or 'retention_start'/'retention_completion' (a retention metric's start event and return visit). A hit on one source is not a hit on the metric as the analysis counts it.
+ *
+ * * `source` - source
+ * * `step` - step
+ * * `numerator` - numerator
+ * * `denominator` - denominator
+ * * `retention_start` - retention_start
+ * * `retention_completion` - retention_completion */
+ source_role: SourceRoleEnumApi
+ /** Display name of the source event or action. */
+ source_name: string
+ /** 0-based position of this source among all the metric's sources, data-warehouse ones included — so a funnel step keeps its real step number even when an earlier step has no session events. */
+ source_index: number
+ /** Total number of sources the metric is defined over. */
+ source_total: number
+ /** Number of events in the session matching this source. */
+ event_count: number
+ /** Timestamp of the first event in the session matching this source. */
+ first_timestamp: string
+ /** Ascending timestamps of this source'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 metric with at least one matching event in a session recording.
*/
@@ -2242,6 +2288,8 @@ export interface ExperimentSessionMetricHitApi {
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[]
+ /** Which of the metric's sources fired, so a hit reads as 'step 2 of 3' or 'the start event of a retention metric' rather than an unqualified 'this metric happened'. Sources with no matching event are omitted, as is the whole breakdown for metrics beyond the scan's aggregate ceiling. A retention metric whose start and completion are the same event contributes only the start source: the completion would match the identical events and render a duplicate. */
+ sources: ExperimentSessionMetricSourceHitApi[]
}
/**
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index dcf185f2ff16..5803cb97c46a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -27069,6 +27069,53 @@ export namespace Schemas {
readonly user_access_level: string | null;
}
+ /**
+ * * `source` - source
+ * * `step` - step
+ * * `numerator` - numerator
+ * * `denominator` - denominator
+ * * `retention_start` - retention_start
+ * * `retention_completion` - retention_completion
+ */
+ export type SourceRoleEnum = typeof SourceRoleEnum[keyof typeof SourceRoleEnum];
+
+
+ export const SourceRoleEnum = {
+ Source: 'source',
+ Step: 'step',
+ Numerator: 'numerator',
+ Denominator: 'denominator',
+ RetentionStart: 'retention_start',
+ RetentionCompletion: 'retention_completion',
+ } as const;
+
+ /**
+ * One event/action source of a metric with at least one matching event in a session recording.
+ */
+ export interface ExperimentSessionMetricSourceHit {
+ /** What this source means to its metric: 'source' (a mean metric's single event), 'step' (a funnel step, numbered by source_index), 'numerator'/'denominator' (a ratio metric's two sides), or 'retention_start'/'retention_completion' (a retention metric's start event and return visit). A hit on one source is not a hit on the metric as the analysis counts it.
+ *
+ * * `source` - source
+ * * `step` - step
+ * * `numerator` - numerator
+ * * `denominator` - denominator
+ * * `retention_start` - retention_start
+ * * `retention_completion` - retention_completion */
+ source_role: SourceRoleEnum;
+ /** Display name of the source event or action. */
+ source_name: string;
+ /** 0-based position of this source among all the metric's sources, data-warehouse ones included — so a funnel step keeps its real step number even when an earlier step has no session events. */
+ source_index: number;
+ /** Total number of sources the metric is defined over. */
+ source_total: number;
+ /** Number of events in the session matching this source. */
+ event_count: number;
+ /** Timestamp of the first event in the session matching this source. */
+ first_timestamp: string;
+ /** Ascending timestamps of this source'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 metric with at least one matching event in a session recording.
*/
@@ -27083,6 +27130,8 @@ export namespace Schemas {
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[];
+ /** Which of the metric's sources fired, so a hit reads as 'step 2 of 3' or 'the start event of a retention metric' rather than an unqualified 'this metric happened'. Sources with no matching event are omitted, as is the whole breakdown for metrics beyond the scan's aggregate ceiling. A retention metric whose start and completion are the same event contributes only the start source: the completion would match the identical events and render a duplicate. */
+ sources: ExperimentSessionMetricSourceHit[];
}
/**