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): say the watch shelf is unavailable for group-aggregated experiments (#101181)

Marcel Poelkerf5f44cd96890
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 73ff49127096..1cccd1065dae 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7748,6 +7748,14 @@ snapshots:
hash: v1.k794b7964.15025ce8da34f316ffe376c966175713e2403f80695ca110c66276f75500d47c.Y3pkvasO7oNBS13HbR38_ATxIB0fpteXe2El28zRV5A
scenes-app-experiments--experiment-watch-shelf-no-session-linked-exposures--light:
hash: v1.k794b7964.9067d1a95cfecf50489d0d61b1771d27bda19540b0bd8459578fb64f514a4308.2ntIYvfmzpopRY9FUsnRw5Hf_f7vauU3eYHZ7qE9mUo
+ scenes-app-experiments--experiment-watch-shelf-refused--dark:
+ hash: v1.k794b7964.7f7599bd3cb11a2ac4dfb32e47594bc3bd5fc508e61a99058a6ae384f134211a.LF_BG5xSx4fCFi2aXsRH3R2yjHK8TyxdQfOHJ88pZ60
+ scenes-app-experiments--experiment-watch-shelf-refused--light:
+ hash: v1.k794b7964.4c5f359551a885f81a011476e11309daf0e10a54742f9c1e8d9dba6014c0fb03.K4ODLqveKp2y0391XhpcGuaV9wbnvT0oyENvvBKLiMw
+ scenes-app-experiments--experiment-watch-shelf-refused-narrow--dark:
+ hash: v1.k794b7964.e0b7711af9b296d5a444ee191c9493ce09daf725d694d16dada2e8b518768e94.MnMz6HWxuPWm1YN-0SsepZhXHD7zp4t9iP55f58HRN8
+ scenes-app-experiments--experiment-watch-shelf-refused-narrow--light:
+ hash: v1.k794b7964.9f4f616b16a12c583bc51f654a507103830304065be754a5fc7a8e56587b614e.XGIizpFvFzDdXlTI0n4TRNdF-NsJLZHsh8IWQhbuTvI
scenes-app-experiments--experiment-watch-shelf-too-early--dark:
hash: v1.k794b7964.3e5f919fc0ee8641df2561640122f1e8579266b1b3c39a1b79702a79023a2cdb.0YEvFMCCv1VnUboUz8fkK1q5w7TDKFH4wzR_3aUo6EU
scenes-app-experiments--experiment-watch-shelf-too-early--light:
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.ts
index f7fa89d6e271..e9723e064bcf 100644
--- a/frontend/src/initKea.ts
+++ b/frontend/src/initKea.ts
@@ -67,6 +67,7 @@ const ERROR_FILTER_ALLOW_LIST = [
'loadReplayComments', // The replay Comments tab renders its own retry state
'loadCoreMemory', // The PostHog AI memory setting renders its own load error banner with a retry
'updateCoreMemory', // maxSettingsLogic's updateCoreMemoryFailure listener shows its own save-failure toast
+ 'loadSessionEventDeltas', // The experiment watch shelf renders the refusal, or the failure with a retry
]
/*
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index 5499f725307b..c50fdeda31fe 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -138,6 +138,10 @@ export interface ExperimentRecordingsTabContext {
in_session_available: boolean | null
in_session_unavailable_reason: string | null
in_session_uses_stamped_fallback: boolean | null
+ /** Whether the "What to watch" toggle was on the tab at all: the denominator for opening it. */
+ behavior_comparison_available: boolean
+ /** Why the toggle was shown disabled, null when it was usable. */
+ behavior_comparison_unavailable_reason: string | null
}
/** The facets the recordings list was narrowed by when a recording was opened from it. */
@@ -247,6 +251,10 @@ export interface ExperimentWatchShelfContext {
sessions_truncated: boolean
/** The project has more event names than one comparison ranks, so some were never considered. */
events_truncated: boolean
+ /** Whether the experiment has stopped enrolling, so waiting cannot fill an empty shelf. */
+ experiment_ended: boolean
+ /** Whole days from the launch to this load, null when the experiment has not launched. */
+ days_since_start: number | null
}
/** The comparison could not be loaded, and how: a request failure or a backend refusal. */
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentBehaviorComparison.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentBehaviorComparison.tsx
index dc0f1e15c8c0..e10bc84ee55a 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentBehaviorComparison.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentBehaviorComparison.tsx
@@ -375,7 +375,8 @@ function HighlightList({
/** The toggle alone, so it can sit in the tab's filter row while the shelves render below it. */
export function ExperimentBehaviorComparisonToggle({ experiment }: { experiment: Experiment }): JSX.Element | null {
const logic = experimentReplayTabLogic({ experiment })
- const { behaviorComparisonAvailable, behaviorComparisonOpen } = useValues(logic)
+ const { behaviorComparisonAvailable, behaviorComparisonOpen, behaviorComparisonUnavailableReason } =
+ useValues(logic)
const { toggleBehaviorComparison } = useActions(logic)
if (!behaviorComparisonAvailable) {
@@ -391,6 +392,13 @@ export function ExperimentBehaviorComparisonToggle({ experiment }: { experiment:
icon={<IconChevronDown className={cn('transition-transform', !behaviorComparisonOpen && '-rotate-90')} />}
onClick={() => toggleBehaviorComparison()}
aria-expanded={behaviorComparisonOpen}
+ // Kept visible rather than hidden, so the tab still says the shelf exists and why this
+ // experiment cannot have it.
+ disabledReason={
+ behaviorComparisonUnavailableReason === 'group_aggregated'
+ ? "Not available for experiments that split by group. What to watch compares people's recordings."
+ : undefined
+ }
tooltip="Groups of recordings worth watching: behavior one variant shows more of, friction, and your metric events happening on screen."
data-attr="experiment-behavior-comparison-toggle"
>
@@ -414,6 +422,7 @@ export function ExperimentBehaviorComparison({
sessionEventDeltas,
sessionEventDeltasLoading,
sessionEventDeltasError,
+ sessionEventDeltasErrorStatus,
selectedWatchCard,
loadedRecordingsById,
} = useValues(logic)
@@ -427,7 +436,12 @@ export function ExperimentBehaviorComparison({
return (
<div className="mb-4">
- {sessionEventDeltasError !== null ? (
+ {/* A 400 is the backend stating that this experiment cannot have a comparison, so it is
+ shown as an answer. Every other failure could pass on a second attempt, so it keeps
+ the retry. */}
+ {sessionEventDeltasError !== null && sessionEventDeltasErrorStatus === 400 ? (
+ <div className="text-xs text-secondary">{sessionEventDeltasError}</div>
+ ) : sessionEventDeltasError !== null ? (
<div className="flex items-center gap-2 text-xs text-secondary">
<span>Couldn't pick recordings to watch: {sessionEventDeltasError}</span>
<LemonButton size="xsmall" type="secondary" onClick={() => loadSessionEventDeltas()}>
diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
index 52f512ad3806..0cfb101bbbf9 100644
--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
@@ -142,6 +142,19 @@ const EXPERIMENT = {
},
} as unknown as Experiment
+// A flag that aggregates by group exposes groups rather than persons, which is what the comparison
+// would have to match against recordings.
+const GROUP_AGGREGATED_EXPERIMENT = {
+ ...EXPERIMENT,
+ id: 53,
+ feature_flag: {
+ ...EXPERIMENT.feature_flag,
+ filters: { ...EXPERIMENT.feature_flag?.filters, aggregation_group_type_index: 0 },
+ },
+} as unknown as Experiment
+
+const REFUSAL_DETAIL = "This experiment aggregates by group, so its exposures can't be matched to persons' recordings."
+
const ALL_LINKABLE = {
$feature_flag_called: true,
purchase: true,
@@ -714,6 +727,9 @@ describe('experimentReplayTabLogic', () => {
in_session_available: true,
in_session_unavailable_reason: null,
in_session_uses_stamped_fallback: true,
+ // The default test flags leave the shelf off, so this view never saw the toggle.
+ behavior_comparison_available: false,
+ behavior_comparison_unavailable_reason: null,
})
// The check is shared with the metrics tab and reloads when the experiment's metrics change,
@@ -1383,6 +1399,70 @@ describe('experimentReplayTabLogic', () => {
expect(logic.values.sessionEventDeltas).toEqual(DELTA_RESPONSE)
})
+ it('asks for no comparison when the experiment aggregates by group, and reports why', async () => {
+ // The backend answers a group-aggregated experiment with the same 400 every time, so each
+ // open would spend a heavy request on a refusal the tab can name in advance. The tab view
+ // carries that reason, which is how a disabled toggle is told apart from one nobody opened.
+ const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)
+ const tabViews = (): any[] =>
+ captureSpy.mock.calls.filter(
+ ([event, properties]) =>
+ event === 'experiment recordings tab viewed' && (properties as any)?.experiment_id === 53
+ )
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.EXPERIMENT_BEHAVIOR_COMPARISON]: true })
+ const grouped = experimentReplayTabLogic({ experiment: GROUP_AGGREGATED_EXPERIMENT })
+ grouped.mount()
+
+ await expectLogic(grouped, () => {
+ grouped.actions.toggleBehaviorComparison()
+ }).toFinishAllListeners()
+
+ expect(grouped.values.behaviorComparisonUnavailableReason).toBe('group_aggregated')
+ expect(experimentsSessionEventDeltasCreate).not.toHaveBeenCalled()
+ expect(tabViews()).toHaveLength(1)
+ expect(tabViews()[0][1]).toMatchObject({
+ behavior_comparison_available: true,
+ behavior_comparison_unavailable_reason: 'group_aggregated',
+ })
+ grouped.unmount()
+ })
+
+ it.each([
+ {
+ failure: 'a refusal the backend states on purpose',
+ rejection: Object.assign(new Error('Request failed'), { status: 400, detail: REFUSAL_DETAIL }),
+ status: 400,
+ message: REFUSAL_DETAIL,
+ callsAfterReopen: 1,
+ },
+ {
+ failure: 'a request that may pass on a second attempt',
+ rejection: new Error('Failed to fetch'),
+ status: null,
+ message: 'Failed to fetch',
+ callsAfterReopen: 2,
+ },
+ ])('keeps the status beside the message for $failure', async ({ rejection, status, message, callsAfterReopen }) => {
+ // The status is what splits the two states the shelf renders, and what decides whether
+ // reopening asks again. A refusal leaves no deltas behind, so without the status the
+ // reopen path sends the same request and gets the same refusal back.
+ ;(experimentsSessionEventDeltasCreate as jest.Mock).mockRejectedValue(rejection)
+
+ await expectLogic(logic, () => {
+ logic.actions.toggleBehaviorComparison()
+ }).toFinishAllListeners()
+
+ expect(logic.values.sessionEventDeltasError).toBe(message)
+ expect(logic.values.sessionEventDeltasErrorStatus).toBe(status)
+
+ await expectLogic(logic, () => {
+ logic.actions.toggleBehaviorComparison()
+ logic.actions.toggleBehaviorComparison()
+ }).toFinishAllListeners()
+
+ expect(experimentsSessionEventDeltasCreate).toHaveBeenCalledTimes(callsAfterReopen)
+ })
+
it('reports the population the comparison covered, not just what it found', async () => {
// An empty reason on its own cannot be read: 'no_separation' over sixty people and over
// twelve thousand ask for different answers. So the report carries the denominator, the
@@ -1409,6 +1489,10 @@ describe('experimentReplayTabLogic', () => {
compared_enrollment_hours: 744,
sessions_truncated: false,
events_truncated: false,
+ experiment_ended: true,
+ // Read off the fixture rather than hardcoded, so the assertion still states the same
+ // distance as real time moves past the run window.
+ days_since_start: dayjs().diff(dayjs(EXPERIMENT.start_date), 'day'),
})
})
diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
index 53934990247a..97e4b90fe881 100644
--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
@@ -59,6 +59,7 @@ import {
UniversalFiltersGroupValue,
} from '~/types'
+import { hasEnded } from 'products/experiments/frontend/experimentStatus'
import {
experimentsInSessionExposureRetrieve,
experimentsSessionBucketsCreate,
@@ -156,6 +157,13 @@ export interface ExperimentSessionBucket {
*/
export type ExperimentReplayRecording = Pick<SessionRecordingType, 'id' | 'recording_duration' | 'person'>
+/**
+ * Why the behavior comparison cannot run for this experiment, known before any request is sent.
+ * `group_aggregated` is the backend's refusal: the comparison matches exposures to persons'
+ * recordings, and a flag that aggregates by group exposes groups instead of persons.
+ */
+export type ExperimentBehaviorComparisonUnavailableReason = 'group_aggregated'
+
/** The link an empty "what to watch" state offers, as reported to telemetry. */
export type ExperimentWatchEmptyAction = 'exposure_docs' | 'replay_settings'
@@ -298,6 +306,7 @@ export interface experimentReplayTabLogicValues {
appliedDurationFilterCount: number
behaviorComparisonAvailable: boolean
behaviorComparisonOpen: boolean
+ behaviorComparisonUnavailableReason: ExperimentBehaviorComparisonUnavailableReason | null
bucketSessionIds: string[] | undefined
durationFilterActive: boolean
durationFilterCustomized: boolean
@@ -332,6 +341,7 @@ export interface experimentReplayTabLogicValues {
sessionBucketRequest: ExperimentSessionBucketRequest | null
sessionEventDeltas: ExperimentSessionEventDeltaResponseApi | null
sessionEventDeltasError: string | null
+ sessionEventDeltasErrorStatus: number | null
sessionEventDeltasLoading: boolean
tabViewContext: ExperimentRecordingsTabContext
variantKeys: string[]
@@ -582,6 +592,7 @@ export interface experimentReplayTabLogicMeta {
loadedRecordingsById: (loadedRecordings: ExperimentReplayRecording[]) => Map<string, ExperimentReplayRecording>
variantKeys: (arg: any) => string[]
behaviorComparisonAvailable: (featureFlags: FeatureFlagsSet) => boolean
+ behaviorComparisonUnavailableReason: (arg: any) => ExperimentBehaviorComparisonUnavailableReason | null
effectiveVariantKey: (selectedVariantKey: string | null, variantKeys: string[]) => string | null
exposureInSessionUnavailableReason: (inSessionExposure: ExperimentInSessionExposureApi | null) => string | null
effectiveExposureScope: (
@@ -648,7 +659,9 @@ export interface experimentReplayTabLogicMeta {
variantKeys: string[],
metricOptions: ExperimentReplayMetricOption[],
effectiveExposureScope: ExperimentReplayExposureScope,
- inSessionExposure: ExperimentInSessionExposureApi | null
+ inSessionExposure: ExperimentInSessionExposureApi | null,
+ behaviorComparisonAvailable: boolean,
+ behaviorComparisonUnavailableReason: 'group_aggregated' | null
) => ExperimentRecordingsTabContext
metricOptions: (
linkabilityLoaded: boolean,
@@ -854,6 +867,11 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
),
sessions_truncated: response.sessions_truncated,
events_truncated: response.events_truncated,
+ // An empty shelf on a young experiment is a different answer from the same
+ // shelf on one that has stopped enrolling, so the age of the run is read
+ // next to `empty_reason` rather than inferred from the event's timestamp.
+ experiment_ended: hasEnded(props.experiment),
+ days_since_start: daysSince(props.experiment.start_date),
})
return response
},
@@ -1017,6 +1035,17 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
loadSessionEventDeltasFailure: (_, { error, errorObject }) => errorObject?.detail || error || 'unknown',
},
],
+ // Kept beside the message because the two are read together: the backend states a refusal
+ // as a 400, which no retry can change, while every other failure is worth retrying.
+ sessionEventDeltasErrorStatus: [
+ null as number | null,
+ {
+ loadSessionEventDeltas: () => null,
+ loadSessionEventDeltasSuccess: () => null,
+ loadSessionEventDeltasFailure: (_, { errorObject }) =>
+ typeof errorObject?.status === 'number' ? errorObject.status : null,
+ },
+ ],
// The card whose recordings the playlist is showing, kept apart from the metric
// selection: its session set comes from the shelf rather than from the experiment's
// metrics.
@@ -1053,6 +1082,13 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
(s) => [s.featureFlags],
(featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.EXPERIMENT_BEHAVIOR_COMPARISON],
],
+ // Read off the feature flag's filters rather than the experiment's, because the flag's
+ // aggregation is what the backend checks before it refuses the comparison.
+ behaviorComparisonUnavailableReason: [
+ () => [(_, props) => props.experiment],
+ (experiment: Experiment): ExperimentBehaviorComparisonUnavailableReason | null =>
+ experiment.feature_flag?.filters?.aggregation_group_type_index != null ? 'group_aggregated' : null,
+ ],
effectiveVariantKey: [
(s) => [s.selectedVariantKey, s.variantKeys],
(selectedVariantKey: string | null, variantKeys: string[]): string | null =>
@@ -1310,12 +1346,21 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
// The `experiment recordings tab viewed` payload, in a selector so the settled-checks
// report and the beforeUnmount flush send the same shape.
tabViewContext: [
- (s) => [s.variantKeys, s.metricOptions, s.effectiveExposureScope, s.inSessionExposure],
+ (s) => [
+ s.variantKeys,
+ s.metricOptions,
+ s.effectiveExposureScope,
+ s.inSessionExposure,
+ s.behaviorComparisonAvailable,
+ s.behaviorComparisonUnavailableReason,
+ ],
(
variantKeys: string[],
metricOptions: ExperimentReplayMetricOption[],
effectiveExposureScope: ExperimentReplayExposureScope,
- inSessionExposure: ExperimentInSessionExposureApi | null
+ inSessionExposure: ExperimentInSessionExposureApi | null,
+ behaviorComparisonAvailable: boolean,
+ behaviorComparisonUnavailableReason: ExperimentBehaviorComparisonUnavailableReason | null
): ExperimentRecordingsTabContext => ({
variant_count: variantKeys.length,
metric_count: metricOptions.length,
@@ -1326,6 +1371,8 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
in_session_available: inSessionExposure?.available ?? null,
in_session_unavailable_reason: inSessionExposure?.unavailable_reason ?? null,
in_session_uses_stamped_fallback: inSessionExposure?.uses_stamped_fallback ?? null,
+ behavior_comparison_available: behaviorComparisonAvailable,
+ behavior_comparison_unavailable_reason: behaviorComparisonUnavailableReason,
}),
],
// Every uuid-carrying metric: inline primary + secondary, then saved/shared metrics (their
@@ -1637,7 +1684,19 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
// finish rather than firing a duplicate; the server-side cache covers a deliberate reload.
toggleBehaviorComparison: () => {
actions.reportExperimentBehaviorComparisonToggled(props.experiment.id, values.behaviorComparisonOpen)
- if (values.behaviorComparisonOpen && !values.sessionEventDeltas && !values.sessionEventDeltasLoading) {
+ // The backend refuses a comparison this experiment cannot have, so asking for it only
+ // costs a request and returns the same refusal every time.
+ if (values.behaviorComparisonUnavailableReason !== null) {
+ return
+ }
+ // A 400 is a refusal for a reason the client cannot foresee, and it leaves no deltas
+ // behind, so reopening the shelf would otherwise send the same doomed request again.
+ if (
+ values.behaviorComparisonOpen &&
+ !values.sessionEventDeltas &&
+ !values.sessionEventDeltasLoading &&
+ values.sessionEventDeltasErrorStatus !== 400
+ ) {
actions.loadSessionEventDeltas()
}
},
diff --git a/frontend/src/scenes/experiments/stories/ExperimentWatchShelfEmpty.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWatchShelfEmpty.stories.tsx
index 366e0e716ef1..28055c75ebda 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentWatchShelfEmpty.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentWatchShelfEmpty.stories.tsx
@@ -122,3 +122,17 @@ export const ExperimentWatchShelfNoSessionLinkedExposures: Story = shelfStory(
ExperimentWatchEmptyReasonEnumApi.NoSessionLinkedExposures,
[0, 0, 0]
)
+
+// A 400 is the backend refusing a comparison this experiment cannot have, so the shelf states it
+// and offers no retry. Shot at two widths because the line sits under the filter row, where a long
+// refusal is what runs out of room first.
+const REFUSAL_DETAIL = 'This experiment has only one variant, so there is nothing to compare it against.'
+
+const refusedStory = (width: number): Story => ({
+ parameters: { testOptions: { viewport: { width, height: 1000 } } },
+ decorators: [mswDecorator({ post: { [DELTAS_PATH]: [400, { detail: REFUSAL_DETAIL }] } })],
+ play: openTheShelf,
+})
+
+export const ExperimentWatchShelfRefused: Story = refusedStory(1300)
+export const ExperimentWatchShelfRefusedNarrow: Story = refusedStory(800)