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.

fix(experiments): hide "view recordings" button for non-session-linkable events in recordings (#71639)

Marcel Poelkerd29cad6fea7d
diff --git a/frontend/src/scenes/experiments/MetricsView/new/ResultDetails.tsx b/frontend/src/scenes/experiments/MetricsView/new/ResultDetails.tsx
index 2cc05ac4bd92..2ddc46b83501 100644
--- a/frontend/src/scenes/experiments/MetricsView/new/ResultDetails.tsx
+++ b/frontend/src/scenes/experiments/MetricsView/new/ResultDetails.tsx
@@ -11,7 +11,7 @@ import { humanFriendlyNumber } from 'lib/utils/numbers'
import { FunnelChart } from 'scenes/experiments/charts/funnel/FunnelChart'
import { experimentLogic } from 'scenes/experiments/experimentLogic'
import { VariantTag } from 'scenes/experiments/ExperimentView/VariantTag'
-import { getViewRecordingFilters } from 'scenes/experiments/utils'
+import { applySessionLinkability, getViewRecordingFilters } from 'scenes/experiments/utils'
import {
CachedNewExperimentQueryResponse,
@@ -41,6 +41,7 @@ import {
isBayesianResult,
isFrequentistResult,
} from '../shared/utils'
+import { viewRecordingsLinkabilityLogic } from './viewRecordingsLinkabilityLogic'
/**
* Convert new experiment results directly to DataDrivenFunnel format
@@ -175,6 +176,7 @@ export function ResultDetails({
metric: ExperimentMetric
}): JSX.Element {
const { featureFlags } = useValues(experimentLogic)
+ const { unlinkableEventNames, linkabilityLoaded } = useValues(viewRecordingsLinkabilityLogic({ experiment }))
const baselineKey = result.baseline?.key
@@ -254,13 +256,22 @@ export function ResultDetails({
const variantKey = item.key
const filters = getViewRecordingFilters(experiment, metric, variantKey)
+ // While the seenTogether check is in flight, keep today's behavior (fail open).
+ const {
+ filters: safeFilters,
+ droppedMetricEventCount,
+ exposureUnlinkable,
+ } = linkabilityLoaded
+ ? applySessionLinkability(filters, unlinkableEventNames)
+ : { filters, droppedMetricEventCount: 0, exposureUnlinkable: false }
+
const filterGroup: Partial<RecordingUniversalFilters> = {
filter_group: {
type: FilterLogicalOperator.And,
values: [
{
type: FilterLogicalOperator.And,
- values: filters,
+ values: safeFilters,
},
],
},
@@ -274,10 +285,20 @@ export function ResultDetails({
filters={filterGroup}
size="xsmall"
type="secondary"
- tooltip="Watch recordings of people who were exposed to this variant."
- disabled={filters.length === 0}
+ tooltip={
+ droppedMetricEventCount > 0
+ ? `Watch recordings of people who were exposed to this variant. Excluded ${droppedMetricEventCount} server-side ${
+ droppedMetricEventCount === 1 ? 'event' : 'events'
+ } captured without a session ID, which can't match recordings.`
+ : 'Watch recordings of people who were exposed to this variant.'
+ }
+ disabled={safeFilters.length === 0}
disabledReason={
- filters.length === 0 ? 'Unable to identify recordings for this metric' : undefined
+ exposureUnlinkable
+ ? "This experiment's exposure event is captured server-side without a session ID, so recordings can't be matched."
+ : filters.length === 0
+ ? 'Unable to identify recordings for this metric'
+ : undefined
}
data-attr="experiment-metrics-view-recordings"
onClick={() => {
diff --git a/frontend/src/scenes/experiments/MetricsView/new/viewRecordingsLinkabilityLogic.test.ts b/frontend/src/scenes/experiments/MetricsView/new/viewRecordingsLinkabilityLogic.test.ts
new file mode 100644
index 000000000000..4097d3edf333
--- /dev/null
+++ b/frontend/src/scenes/experiments/MetricsView/new/viewRecordingsLinkabilityLogic.test.ts
@@ -0,0 +1,69 @@
+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 { AccessControlLevel, Experiment } from '~/types'
+
+import { viewRecordingsLinkabilityLogic } from './viewRecordingsLinkabilityLogic'
+
+const experimentBase = {
+ id: 1,
+ name: 'test experiment',
+ feature_flag_key: 'my-flag',
+ exposure_criteria: undefined,
+ filters: {},
+ metrics: [],
+ metrics_secondary: [],
+ primary_metrics_ordered_uuids: null,
+ secondary_metrics_ordered_uuids: null,
+ saved_metrics_ids: [],
+ saved_metrics: [],
+ parameters: {},
+ secondary_metrics: [],
+ created_at: null,
+ created_by: null,
+ updated_at: null,
+ user_access_level: AccessControlLevel.Editor,
+} satisfies Experiment
+
+describe('viewRecordingsLinkabilityLogic', () => {
+ let logic: ReturnType<typeof viewRecordingsLinkabilityLogic.build>
+ let seenTogetherSpy: jest.SpyInstance
+
+ beforeEach(() => {
+ initKeaTests()
+ seenTogetherSpy = jest.spyOn(api.propertyDefinitions, 'seenTogether')
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ jest.restoreAllMocks()
+ })
+
+ it('checks $session_id linkability on mount and flags only events explicitly seen without it', async () => {
+ seenTogetherSpy.mockResolvedValue({ purchase: false })
+ logic = viewRecordingsLinkabilityLogic({
+ experiment: {
+ ...experimentBase,
+ metrics: [
+ {
+ kind: NodeKind.ExperimentMetric,
+ metric_type: ExperimentMetricType.MEAN,
+ source: { kind: NodeKind.EventsNode, event: 'purchase', name: 'purchase' },
+ },
+ ],
+ } satisfies Experiment,
+ })
+ logic.mount()
+
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ linkabilityLoaded: true })
+ expect(seenTogetherSpy).toHaveBeenCalledWith({
+ eventNames: ['$feature_flag_called', 'purchase'],
+ propertyDefinitionName: '$session_id',
+ })
+ // $feature_flag_called is absent from the response: absent keys stay linkable
+ expect(logic.values.unlinkableEventNames).toEqual(new Set(['purchase']))
+ })
+})
diff --git a/frontend/src/scenes/experiments/MetricsView/new/viewRecordingsLinkabilityLogic.ts b/frontend/src/scenes/experiments/MetricsView/new/viewRecordingsLinkabilityLogic.ts
new file mode 100644
index 000000000000..2344157b97fb
--- /dev/null
+++ b/frontend/src/scenes/experiments/MetricsView/new/viewRecordingsLinkabilityLogic.ts
@@ -0,0 +1,116 @@
+import { MakeLogicType, afterMount, kea, key, path, props, propsChanged, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import api from 'lib/api'
+import { objectsEqual } from 'lib/utils/objects'
+
+import { Experiment } from '~/types'
+
+import type { ExperimentIdType } from '../../../../types'
+import { getSessionLinkabilityEventNames } from '../../utils'
+
+export interface ViewRecordingsLinkabilityLogicProps {
+ experiment: Experiment
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface viewRecordingsLinkabilityLogicValues {
+ linkabilityLoaded: boolean
+ seenTogetherMap: Record<string, boolean> | null
+ seenTogetherMapLoading: boolean
+ unlinkableEventNames: Set<string>
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface viewRecordingsLinkabilityLogicActions {
+ loadSeenTogether: () => any
+ loadSeenTogetherFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSeenTogetherSuccess: (
+ seenTogetherMap: Record<string, boolean>,
+ payload?: any
+ ) => {
+ seenTogetherMap: Record<string, boolean>
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface viewRecordingsLinkabilityLogicMeta {
+ key: ExperimentIdType
+ __keaTypeGenInternalSelectorTypes: {
+ linkabilityLoaded: (seenTogetherMap: Record<string, boolean> | null) => boolean
+ unlinkableEventNames: (seenTogetherMap: Record<string, boolean> | null) => Set<string>
+ }
+}
+
+export type viewRecordingsLinkabilityLogicType = MakeLogicType<
+ viewRecordingsLinkabilityLogicValues,
+ viewRecordingsLinkabilityLogicActions,
+ ViewRecordingsLinkabilityLogicProps,
+ viewRecordingsLinkabilityLogicMeta
+>
+
+/**
+ * Checks, once per experiment page, which of the experiment's events have ever been seen with
+ * `$session_id` — events captured server-side never carry one, so a recordings filter on them
+ * can only match zero sessions. Keyed on the experiment id so every "View recordings" button
+ * (inline result details and the details modal) shares a single lookup.
+ */
+export const viewRecordingsLinkabilityLogic = kea<viewRecordingsLinkabilityLogicType>([
+ props({} as ViewRecordingsLinkabilityLogicProps),
+ key((props) => props.experiment.id ?? 'new'),
+ path((key) => ['scenes', 'experiments', 'MetricsView', 'new', 'viewRecordingsLinkabilityLogic', key]),
+ loaders(({ props }) => ({
+ seenTogetherMap: [
+ null as Record<string, boolean> | null,
+ {
+ loadSeenTogether: async (): Promise<Record<string, boolean>> => {
+ const eventNames = getSessionLinkabilityEventNames(props.experiment)
+ if (eventNames.length === 0) {
+ return {}
+ }
+ return await api.propertyDefinitions.seenTogether({
+ eventNames,
+ propertyDefinitionName: '$session_id',
+ })
+ },
+ },
+ ],
+ })),
+ selectors({
+ /** False while the check is in flight or if it failed — callers fail open to today's behavior. */
+ linkabilityLoaded: [
+ (s) => [s.seenTogetherMap],
+ (seenTogetherMap: Record<string, boolean> | null): boolean => seenTogetherMap !== null,
+ ],
+ /** Only an explicit `false` marks an event unlinkable; absent keys stay linkable (fail open). */
+ unlinkableEventNames: [
+ (s) => [s.seenTogetherMap],
+ (seenTogetherMap: Record<string, boolean> | null): Set<string> =>
+ new Set(
+ Object.entries(seenTogetherMap ?? {})
+ .filter(([, seen]) => seen === false)
+ .map(([eventName]) => eventName)
+ ),
+ ],
+ }),
+ afterMount(({ actions }) => {
+ actions.loadSeenTogether()
+ }),
+ propsChanged(({ actions, props }, oldProps) => {
+ if (
+ !objectsEqual(
+ getSessionLinkabilityEventNames(props.experiment),
+ getSessionLinkabilityEventNames(oldProps.experiment)
+ )
+ ) {
+ actions.loadSeenTogether()
+ }
+ }),
+])
diff --git a/frontend/src/scenes/experiments/utils.test.ts b/frontend/src/scenes/experiments/utils.test.ts
index d3828f917a5c..f483f1b9c9cf 100644
--- a/frontend/src/scenes/experiments/utils.test.ts
+++ b/frontend/src/scenes/experiments/utils.test.ts
@@ -24,17 +24,20 @@ import {
FeatureFlagType,
PropertyFilterType,
PropertyOperator,
+ UniversalFiltersGroupValue,
} from '~/types'
import { filterToMetricConfig } from './metricQueryUtils'
import { getNiceTickValues } from './MetricsView/shared/utils'
import {
+ applySessionLinkability,
exposureConfigToFilter,
featureFlagEligibleForExperiment,
filterToExposureConfig,
getBaselineVariantKey,
getEventCountQuery,
getOrderedMetricsWithResults,
+ getSessionLinkabilityEventNames,
getViewRecordingFilters,
getViewRecordingFiltersLegacy,
isEvenlyDistributed,
@@ -362,6 +365,158 @@ describe('getViewRecordingFilters', () => {
})
})
+describe('getSessionLinkabilityEventNames', () => {
+ const experimentBase = {
+ id: 1,
+ name: 'test experiment',
+ feature_flag_key: 'my-flag',
+ exposure_criteria: undefined,
+ filters: {},
+ metrics: [],
+ metrics_secondary: [],
+ primary_metrics_ordered_uuids: null,
+ secondary_metrics_ordered_uuids: null,
+ saved_metrics_ids: [],
+ saved_metrics: [],
+ parameters: {},
+ secondary_metrics: [],
+ created_at: null,
+ created_by: null,
+ updated_at: null,
+ user_access_level: AccessControlLevel.Editor,
+ }
+
+ it('collects the default exposure event and every plain-event metric step, deduped, across primary, secondary and shared metrics', () => {
+ const experiment = {
+ ...experimentBase,
+ metrics: [
+ {
+ kind: NodeKind.ExperimentMetric,
+ metric_type: ExperimentMetricType.FUNNEL,
+ series: [
+ { kind: NodeKind.EventsNode, event: 'step1', name: 'step1' },
+ { kind: NodeKind.ActionsNode, id: 123, name: 'action1' },
+ // "all events" step: no event name, matches recordings unconditionally, so not checked
+ { kind: NodeKind.EventsNode, event: null },
+ ],
+ },
+ ],
+ metrics_secondary: [
+ {
+ kind: NodeKind.ExperimentMetric,
+ metric_type: ExperimentMetricType.RATIO,
+ numerator: { kind: NodeKind.EventsNode, event: 'purchase', name: 'purchase' },
+ denominator: { kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' },
+ },
+ ],
+ saved_metrics: [
+ {
+ metadata: { type: 'primary' },
+ query: {
+ kind: NodeKind.ExperimentMetric,
+ metric_type: ExperimentMetricType.MEAN,
+ source: { kind: NodeKind.EventsNode, event: 'purchase', name: 'purchase' },
+ },
+ },
+ ],
+ } satisfies Experiment
+
+ expect(getSessionLinkabilityEventNames(experiment)).toEqual([
+ '$feature_flag_called',
+ 'step1',
+ 'purchase',
+ '$pageview',
+ ])
+ })
+
+ it('includes a custom exposure event but not a custom exposure action', () => {
+ const withEventExposure = {
+ ...experimentBase,
+ exposure_criteria: {
+ exposure_config: {
+ kind: NodeKind.ExperimentEventExposureConfig,
+ event: 'exposure_event',
+ properties: [],
+ },
+ },
+ } satisfies Experiment
+ expect(getSessionLinkabilityEventNames(withEventExposure)).toEqual(['exposure_event'])
+
+ const withActionExposure = {
+ ...experimentBase,
+ exposure_criteria: {
+ exposure_config: { kind: NodeKind.ActionsNode, id: 123, name: 'action1' },
+ },
+ } satisfies Experiment
+ expect(getSessionLinkabilityEventNames(withActionExposure)).toEqual([])
+ })
+})
+
+describe('applySessionLinkability', () => {
+ const exposureFilter: UniversalFiltersGroupValue = {
+ id: '$feature_flag_called',
+ name: '$feature_flag_called',
+ type: 'events',
+ properties: [],
+ }
+ const purchaseEventFilter: UniversalFiltersGroupValue = {
+ id: 'purchase',
+ name: 'purchase',
+ type: 'events',
+ properties: [],
+ }
+ const checkoutEventFilter: UniversalFiltersGroupValue = {
+ id: 'checkout',
+ name: 'checkout',
+ type: 'events',
+ properties: [],
+ }
+ const purchaseActionFilter: UniversalFiltersGroupValue = { id: 123, name: 'purchase', type: 'actions' }
+
+ it.each([
+ {
+ case: 'keeps everything when nothing is unlinkable',
+ filters: [exposureFilter, purchaseEventFilter],
+ unlinkable: new Set<string>(),
+ expected: {
+ filters: [exposureFilter, purchaseEventFilter],
+ droppedMetricEventCount: 0,
+ exposureUnlinkable: false,
+ },
+ },
+ {
+ case: 'drops unlinkable metric event steps but keeps the rest',
+ filters: [exposureFilter, purchaseEventFilter, checkoutEventFilter],
+ unlinkable: new Set(['purchase']),
+ expected: {
+ filters: [exposureFilter, checkoutEventFilter],
+ droppedMetricEventCount: 1,
+ exposureUnlinkable: false,
+ },
+ },
+ {
+ case: 'lets action steps pass through unchecked even when their name matches',
+ filters: [exposureFilter, purchaseActionFilter],
+ unlinkable: new Set(['purchase']),
+ expected: {
+ filters: [exposureFilter, purchaseActionFilter],
+ droppedMetricEventCount: 0,
+ exposureUnlinkable: false,
+ },
+ },
+ {
+ case: 'empties the filters when the exposure event itself is unlinkable',
+ filters: [exposureFilter, purchaseEventFilter],
+ unlinkable: new Set(['$feature_flag_called']),
+ expected: { filters: [], droppedMetricEventCount: 0, exposureUnlinkable: true },
+ },
+ ])('$case', ({ filters, unlinkable, expected }) => {
+ const input = [...filters]
+ expect(applySessionLinkability(filters, unlinkable)).toEqual(expected)
+ expect(filters).toEqual(input) // does not mutate its input
+ })
+})
+
describe('getViewRecordingFiltersLegacy', () => {
const featureFlagKey = 'jan-16-running'
diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.ts
index 9d8b83e3c76a..03010f383f81 100644
--- a/frontend/src/scenes/experiments/utils.ts
+++ b/frontend/src/scenes/experiments/utils.ts
@@ -322,6 +322,83 @@ export function getViewRecordingFilters(
return filters
}
+/**
+ * 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
+ * metrics, mirroring how `getViewRecordingFilters` enumerates them. Action and data warehouse
+ * steps pass through unchecked (same as the replay playlist's own check), as do "all events"
+ * steps, which have no event name.
+ */
+export function getSessionLinkabilityEventNames(experiment: Experiment): string[] {
+ const eventNames = new Set<string>()
+
+ const exposureConfig = experiment.exposure_criteria?.exposure_config
+ if (exposureConfig && !(isEventExposureConfig(exposureConfig) && exposureConfig.event === EXPOSURE_DEFAULT_EVENT)) {
+ if (isEventExposureConfig(exposureConfig) && exposureConfig.event) {
+ eventNames.add(exposureConfig.event)
+ }
+ } else {
+ eventNames.add(EXPOSURE_DEFAULT_EVENT)
+ }
+
+ const metrics = [
+ ...(experiment.metrics || []),
+ ...(experiment.metrics_secondary || []),
+ ...(experiment.saved_metrics || []).map((savedMetric: { query?: ExperimentMetric }) => savedMetric?.query),
+ ].filter((metric): metric is ExperimentMetric => metric?.kind === NodeKind.ExperimentMetric)
+
+ for (const metric of metrics) {
+ const sources: (ExperimentMetricSource | ExperimentFunnelMetricStep)[] = isExperimentMeanMetric(metric)
+ ? [metric.source]
+ : isExperimentFunnelMetric(metric)
+ ? metric.series
+ : isExperimentRatioMetric(metric)
+ ? [metric.numerator, metric.denominator]
+ : []
+ for (const source of sources) {
+ if (source.kind === NodeKind.EventsNode && source.event) {
+ eventNames.add(source.event)
+ }
+ }
+ }
+
+ return Array.from(eventNames)
+}
+
+/**
+ * Post-filters `getViewRecordingFilters` output. Recordings are matched through events carrying
+ * a `$session_id`, so an event filter the project has never seen with that property (e.g. one
+ * captured server-side) would zero out the whole AND-combined recordings query. The exposure
+ * filter is always first; when it is itself unlinkable there are no recordings to show at all.
+ */
+export function applySessionLinkability(
+ filters: UniversalFiltersGroupValue[],
+ 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)
+
+ if (filters.length === 0) {
+ return { filters: [], droppedMetricEventCount: 0, exposureUnlinkable: false }
+ }
+
+ const [exposureFilter, ...metricFilters] = filters
+ if (isUnlinkable(exposureFilter)) {
+ return { filters: [], droppedMetricEventCount: 0, exposureUnlinkable: true }
+ }
+
+ const keptMetricFilters = metricFilters.filter((filter) => !isUnlinkable(filter))
+ return {
+ filters: [exposureFilter, ...keptMetricFilters],
+ droppedMetricEventCount: metricFilters.length - keptMetricFilters.length,
+ exposureUnlinkable: false,
+ }
+}
+
export function getViewRecordingFiltersLegacy(
metric: ExperimentMetric | ExperimentTrendsQuery | ExperimentFunnelsQuery,
featureFlagKey: string,