:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(experiments): improve UX when there is no recordings list or request fails (#102937)
Marcel Poelker61173ffacb37
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 4ac3380bb200..ee0d117ff9ec 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8028,6 +8028,14 @@ snapshots:hash: v1.k794b7964.530d0f67567386042f51c3c7103cf35569830e1fcca930c98c87f19f0e78a0cb.xCXIqElOyZHwKcW8AMioDp7Ms6i0FyHKZMyu_edJ6ykscenes-app-experiments--experiment-recordings-empty-variant-has-none--light:hash: v1.k794b7964.c34b90d09956ebfa2b8e214e6ff72ee83bd52b4373f095001182130074edf77f.BfVbJEalysyFVC_DscyNMfF0di9x2kD1J4GmWS44__E+ scenes-app-experiments--experiment-recordings-list-load-failed--dark:+ hash: v1.k794b7964.160db94cffc5df74c0b50198156f7567da611f072139b541d878ef4bbc34cf6f.4gsYvKM94BXkxGbQZ4JCnrb_lUymDf3HdmcMFjsoYpE+ scenes-app-experiments--experiment-recordings-list-load-failed--light:+ hash: v1.k794b7964.7cd9e41c5df844cfa078cd60bb62133d09bf71ab33300d7cd837095e13d22172.2fS-hNlDpbADdyPN_mxiiuUfjRn5G_eMT2bWro7vk0A+ scenes-app-experiments--experiment-recordings-unavailable-group-aggregated--dark:+ hash: v1.k794b7964.837c51f66678433c6a635315b422fc5970020f40fb4c92009001ecc8ae5ac3d7.GaQDl39lC-sI9UvUYbKqQA1Ixd8DO_hJJq8X58qikBs+ scenes-app-experiments--experiment-recordings-unavailable-group-aggregated--light:+ hash: v1.k794b7964.78f9fac07a4906034659ee437fabf86c6baa1427e452a00ffc3741be5cb205fd.OlxvYcU1VuvZns4GoNwtJLRXbkF2N08Ismoq6ayedRYscenes-app-experiments--experiment-replay-scanner-backlink--dark:hash: v1.k794b7964.ebc31572406f9a52425ac28a209784b99a852c92116fe1ed90df19fc3d73b899.-MGnNAnX0zGAKvPu8HLxqQph4wxAX97lMphrQZdYQBoscenes-app-experiments--experiment-replay-scanner-backlink--light:diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.tsindex 8e26b7813d2a..5fc84580d57c 100644--- a/frontend/src/lib/utils/eventUsageLogic.ts+++ b/frontend/src/lib/utils/eventUsageLogic.ts@@ -143,6 +143,18 @@ export interface ExperimentRecordingsTabContext {* rather than the scene's union so telemetry doesn't import from the scene.*/metric_unavailable_reason: string | null+ /**+ * The experiment's status as the scene reads it, kept as a string rather than the scene's enum+ * so telemetry doesn't import from the scene. A draft experiment never mounts the list at all,+ * so without this a draft visit cannot be told from a visit whose list failed to arrive.+ */+ experiment_status: string+ /**+ * Why the tab stated the list was unavailable instead of mounting it, null when it mounted the+ * list. One of the tab's `ExperimentRecordingsListUnavailableReason` codes, as a string for the+ * same reason the other codes here are.+ */+ list_unavailable_reason: string | nullvariant_count: numbermetric_count: numberlinkable_metric_count: number@@ -259,6 +271,42 @@ export interface ExperimentRecordingsListRenderedContext extends ExperimentRecorexposure_linkable: boolean | null}+/**+ * A first page of the recordings list the tab asked for and did not get. The backend states its+ * refusals as a 400 carrying a message the tab shows, so `error_detail` is what separates a refusal+ * no retry can change from a transient failure. Carries the same facets as `experiment recordings+ * list rendered`, so a failed visit and a rendered one are comparable facet for facet. A page that+ * scrolling added is not reported here: it fails a list that already has rows.+ */+export interface ExperimentRecordingsListFailedContext extends ExperimentRecordingsFilterContext {+ /** The HTTP status, null when the request failed before it reached a response. */+ status: number | null+ /**+ * The backend's own message, truncated. These messages are fixed strings that name an+ * experiment id or a variant key at most, so they carry no user data.+ */+ error_detail: string+ /** Null when the experiment has not launched. */+ days_since_start: number | null+}++/**+ * A visit that left the tab before its first page of recordings either arrived or failed. The list+ * load waits out a debounce and then a request, so a viewer who clicks through to another tab in a+ * second or two leaves before either outcome, and the playlist drops the load without reporting+ * one. These visits are the largest part of "tab viewed, list never rendered", and this event is+ * what accounts for them. A browser tab closed outright does not unmount React, so those visits+ * still report no outcome at all.+ */+export interface ExperimentRecordingsListAbandonedContext extends ExperimentRecordingsFilterContext {+ /** How long the tab stayed mounted, in milliseconds. */+ ms_on_tab: number+ /** Whether the playlist was still held for the tab's own checks, so no list request went out. */+ held_for_checks: boolean+ /** Whether the metric filter's session set was still loading, which holds the list empty. */+ bucket_loading: boolean+}+/*** What the behavior comparison found, captured each time the shelf loads. The card counts are what* say whether the feature finds anything in the wild: all zeros on most experiments would mean the@@ -1592,6 +1640,20 @@ export interface eventUsageLogicActions {context: ExperimentRecordingsEmptyActionContextexperimentId: ExperimentIdType}+ reportExperimentRecordingsListAbandoned: (+ experimentId: ExperimentIdType,+ context: ExperimentRecordingsListAbandonedContext+ ) => {+ context: ExperimentRecordingsListAbandonedContext+ experimentId: ExperimentIdType+ }+ reportExperimentRecordingsListFailed: (+ experimentId: ExperimentIdType,+ context: ExperimentRecordingsListFailedContext+ ) => {+ context: ExperimentRecordingsListFailedContext+ experimentId: ExperimentIdType+ }reportExperimentRecordingsListRendered: (experimentId: ExperimentIdType,context: ExperimentRecordingsListRenderedContext@@ -3073,6 +3135,14 @@ export const eventUsageLogic = kea<eventUsageLogicType>([experimentId: ExperimentIdType,context: ExperimentRecordingsListRenderedContext) => ({ experimentId, context }),+ reportExperimentRecordingsListFailed: (+ experimentId: ExperimentIdType,+ context: ExperimentRecordingsListFailedContext+ ) => ({ experimentId, context }),+ reportExperimentRecordingsListAbandoned: (+ experimentId: ExperimentIdType,+ context: ExperimentRecordingsListAbandonedContext+ ) => ({ experimentId, context }),reportExperimentRecordingsEmptyActionClicked: (experimentId: ExperimentIdType,context: ExperimentRecordingsEmptyActionContext@@ -4256,6 +4326,18 @@ export const eventUsageLogic = kea<eventUsageLogicType>([...context,})},+ reportExperimentRecordingsListFailed: ({ experimentId, context }) => {+ posthog.capture('experiment recordings list failed', {+ experiment_id: experimentId,+ ...context,+ })+ },+ reportExperimentRecordingsListAbandoned: ({ experimentId, context }) => {+ posthog.capture('experiment recordings list abandoned', {+ experiment_id: experimentId,+ ...context,+ })+ },reportExperimentRecordingsEmptyActionClicked: ({ experimentId, context }) => {posthog.capture('experiment recordings empty state action clicked', {experiment_id: experimentId,diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsxindex e573d70f5a7d..37cc13c3dd33 100644--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx@@ -27,7 +27,6 @@ import { urls } from 'scenes/urls'import { Experiment } from '~/types'-import { isLaunched } from 'products/experiments/frontend/experimentStatus'import { experimentScannerParams } from 'products/replay_vision/frontend/replay_scanners/experimentTargeting'import { scannerTypeLabel } from 'products/replay_vision/frontend/replay_scanners/types'@@ -37,6 +36,7 @@ import { EXPERIMENT_RECORDING_MODE_OPTIONS, METRIC_UNSELECTABLE_COPY } from './eimport { type ExperimentReplayMetricFilterMode, isFunnelMode } from './experimentRecordingsDeepLink'import { ExperimentRecordingsListEmptyState } from './ExperimentRecordingsListEmptyState'import {+ ExperimentRecordingsListUnavailableReason,ExperimentReplayMetricOption,ExperimentSessionBucket,LinkedScanner,@@ -89,6 +89,24 @@ const IN_SESSION_COPY: Record<InSessionEvidenceKind, { tooltip: string; caption:},}+// What the tab says in place of a list the backend would refuse. Each entry carries its own+// `data-attr` so autocapture can count how often each state is reached, and so a story can wait+// for the one it renders.+const LIST_UNAVAILABLE_COPY: Record<ExperimentRecordingsListUnavailableReason, { dataAttr: string; copy: string }> = {+ not_launched: {+ dataAttr: 'experiment-recordings-unavailable-not-launched',+ copy: 'Launch the experiment to see recordings of participants.',+ },+ group_aggregated: {+ dataAttr: 'experiment-recordings-unavailable-group-aggregated',+ copy: "Recordings aren't available for this experiment. It counts groups rather than individual people, so recordings can't be matched to a variant.",+ },+ no_variants: {+ dataAttr: 'experiment-recordings-unavailable-no-variants',+ copy: "Recordings aren't available because this experiment's feature flag has no variants. Add variants to the flag to see recordings of participants.",+ },+}+// A session fires a metric's events, never the metric — the caption spells that out where it// has the room the trigger doesn't.const MODE_SUMMARIES: Record<ExperimentReplayMetricFilterMode, string> = {@@ -273,6 +291,8 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):sessionBucketRequest,linkedScanners,linkedScannersLoading,+ listUnavailableReason,+ listLoadError,} = useValues(logic)const {setSelectedVariantKey,@@ -282,6 +302,8 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):loadSessionBucket,playlistFiltersChanged,recordingsLoaded,+ recordingsLoadFailed,+ retryListLoad,recordingOpened,scannerCrossSellClicked,} = useActions(logic)@@ -305,9 +327,22 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):playlist.actions.setSelectedRecordingId(sessionId)return true}+ // The button that calls this only renders under a failed list, so the playlist below it is+ // mounted. Guarded anyway, because nothing in the type keeps it that way.+ const retryList = (): void => {+ retryListLoad()+ sessionRecordingsPlaylistLogic.findMounted(playlistLogicProps)?.actions.loadSessionRecordings()+ }- if (!isLaunched(experiment)) {- return <LemonBanner type="info">Launch the experiment to see recordings of participants.</LemonBanner>+ // The variant switcher, the scope control and the metric filter all describe a list, so they+ // are meaningless without one. Placed after every hook, as the draft case always was.+ if (listUnavailableReason !== null) {+ const { dataAttr, copy } = LIST_UNAVAILABLE_COPY[listUnavailableReason]+ return (+ <div data-attr={dataAttr}>+ <LemonBanner type="info">{copy}</LemonBanner>+ </div>+ )}// Selectable metrics render as checkboxes. The rest move to labelled sections that explain@@ -480,8 +515,27 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):caption follows the request, not the mode. The dropped-metric caption claims a wholepopulation, so a filter the viewer added in the playlist bar makes it wrong and takesit away. The telemetry nulls the reason on the same condition. */}- <div className="mb-2 flex items-center gap-2 text-xs text-secondary">- {clientSideFilterApplied ? null : droppedMetricReason && !filtersCustomized ? (+ <div className="mb-2 flex flex-wrap items-center gap-2 text-xs text-secondary">+ {/* First, because a list that failed makes every other caption moot: none of them+ describes a population the viewer can see. The retry is offered whatever the+ status, unlike the shelf above, which shows a 400 as a plain answer: the tab+ now states the refusals it can foresee instead of sending the list, so the+ ones that reach here pass once the exposures finish computing. */}+ {listLoadError !== null ? (+ <>+ <span data-attr="experiment-recordings-list-error-caption">+ Couldn't load recordings: {listLoadError.detail}+ </span>+ <LemonButton+ size="xsmall"+ type="secondary"+ onClick={retryList}+ data-attr="experiment-recordings-list-retry"+ >+ Try again+ </LemonButton>+ </>+ ) : clientSideFilterApplied ? null : droppedMetricReason && !filtersCustomized ? (<span data-attr="experiment-recordings-dropped-metric-caption">{METRIC_UNSELECTABLE_COPY[droppedMetricReason].onTab}</span>@@ -524,6 +578,7 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):resetToCallerFiltersonFiltersChange={(filters) => playlistFiltersChanged(filters)}onRecordingsLoaded={(recordings, isFirstPage) => recordingsLoaded(recordings, isFirstPage)}+ onRecordingsLoadFailed={(error, isFirstPage) => recordingsLoadFailed(error, isFirstPage)}onRecordingSelected={(recordingId) => recordingOpened(recordingId)}listEmptyState={<ExperimentRecordingsListEmptyState experiment={experiment} />}/>diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.tsindex 51018c98ba26..29287d3a5228 100644--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts@@ -809,6 +809,10 @@ describe('experimentReplayTabLogic', () => {metric_count: 2,linkable_metric_count: 1,exposure_scope: 'all_exposed',+ // The pair that says this visit had a list to show, so a visit with no list rendered+ // after it is a failure or a bounce rather than an experiment that never had one.+ experiment_status: 'stopped',+ list_unavailable_reason: null,in_session_available: true,in_session_unavailable_reason: null,in_session_uses_stamped_fallback: true,@@ -1063,6 +1067,251 @@ describe('experimentReplayTabLogic', () => {filled.unmount()})+ it.each([+ { verdict: 'not_launched', experimentId: 160, experiment: { start_date: null, end_date: null } },+ { verdict: 'group_aggregated', experimentId: 161, experiment: GROUP_AGGREGATED_EXPERIMENT },+ {+ verdict: 'no_variants',+ experimentId: 162,+ experiment: { feature_flag: { filters: { multivariate: { variants: [] } } } },+ },+ { verdict: null, experimentId: 163, experiment: {} },+ ])('resolves $verdict as the list verdict', async ({ verdict, experimentId, experiment }) => {+ // Every verdict but null is a request `resolve_exposure_linkage` refuses outright. The tab+ // used to mount the list anyway, so a group-aggregated experiment answered every visit+ // with an error toast and the playlist's generic banner.+ const checked = experimentReplayTabLogic({+ experiment: { ...EXPERIMENT, ...experiment, id: experimentId } as Experiment,+ })+ checked.mount()+ await expectLogic(checked).toFinishAllListeners()++ expect(checked.values.listUnavailableReason).toBe(verdict)+ checked.unmount()+ })++ it('reports a failed first page with the backend reason, and clears it on the next list', async () => {+ // The playlist's own banner says "Error while trying to load recordings." for every+ // failure, so without the detail neither the viewer nor a reader of the event can tell a+ // refusal this experiment can never escape from a wait-and-retry.+ const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)+ const failures = (): any[] =>+ captureSpy.mock.calls.filter(+ ([event, properties]) =>+ event === 'experiment recordings list failed' && (properties as any)?.experiment_id === 164+ )+ const failing = experimentReplayTabLogic({+ experiment: { ...EXPERIMENT, id: 164, start_date: daysAgo(4), end_date: null } as Experiment,+ })+ failing.mount()+ await expectLogic(failing).toFinishAllListeners()++ failing.actions.recordingsLoadFailed({ status: 400, detail: REFUSAL_DETAIL }, true)+ await expectLogic(failing).toFinishAllListeners()++ expect(failing.values.listLoadError).toEqual({ status: 400, detail: REFUSAL_DETAIL })+ expect(failures()).toHaveLength(1)+ expect(failures()[0][1]).toMatchObject({+ status: 400,+ error_detail: REFUSAL_DETAIL,+ days_since_start: 4,+ variant: null,+ exposure_scope: 'all_exposed',+ })++ // A later page failing is paging against a list that already has rows on screen.+ failing.actions.recordingsLoadFailed({ status: 500, detail: 'Server error' }, false)+ await expectLogic(failing).toFinishAllListeners()+ expect(failures()).toHaveLength(1)++ failing.actions.recordingsLoaded(loadedPage(['s1']))+ await expectLogic(failing).toFinishAllListeners()+ expect(failing.values.listLoadError).toBeNull()+ failing.unmount()+ })++ it.each([+ { visit: 'that never saw a list', experimentId: 165, experiment: {}, setup: undefined, abandoned: 1 },+ {+ visit: 'whose first page rendered',+ experimentId: 166,+ experiment: {},+ setup: (tab: TabLogic) => tab.actions.recordingsLoaded(loadedPage(['s1'])),+ abandoned: 0,+ },+ {+ visit: 'whose first page failed',+ experimentId: 167,+ experiment: {},+ setup: (tab: TabLogic) => tab.actions.recordingsLoadFailed({ status: 400, detail: REFUSAL_DETAIL }, true),+ abandoned: 0,+ },+ {+ visit: 'that never had a list to load',+ experimentId: 168,+ experiment: { start_date: null, end_date: null },+ setup: undefined,+ abandoned: 0,+ },+ ])(+ 'reports $abandoned abandoned list for a visit $visit',+ async ({ experimentId, experiment, setup, abandoned }) => {+ // The playlist drops a load at its breakpoint on unmount without dispatching success or+ // failure, so a viewer who clicks through to another tab produces a tab view and nothing+ // else. That bounce is most of the tab's unexplained visits, and only this event counts it.+ const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)+ const bounced = experimentReplayTabLogic({+ experiment: { ...EXPERIMENT, id: experimentId, ...experiment } as Experiment,+ })+ bounced.mount()+ await expectLogic(bounced).toFinishAllListeners()+ setup?.(bounced)+ await expectLogic(bounced).toFinishAllListeners()++ bounced.unmount()++ const abandons = captureSpy.mock.calls.filter(+ ([event, properties]) =>+ event === 'experiment recordings list abandoned' &&+ (properties as any)?.experiment_id === experimentId+ )+ expect(abandons).toHaveLength(abandoned)+ if (abandoned > 0) {+ expect(abandons[0][1]).toMatchObject({+ held_for_checks: false,+ bucket_loading: false,+ exposure_scope: 'all_exposed',+ ms_on_tab: expect.any(Number),+ })+ }+ }+ )++ it.each([+ {+ answer: 'a bucket that fails',+ experimentId: 169,+ bucket: null,+ renders: 1,+ },+ {+ answer: 'a bucket that matches nothing',+ experimentId: 170,+ bucket: { ...BUCKET_RESPONSE, session_ids: [] },+ renders: 1,+ },+ {+ answer: 'a bucket that changes the session set',+ experimentId: 171,+ bucket: BUCKET_RESPONSE,+ renders: 1,+ },+ ])(+ 'reports $renders render for an empty first page followed by $answer',+ async ({ experimentId, bucket, renders }) => {+ // An empty first page while the bucket loads is held back, because the bucket's answer+ // reloads the list. When the answer leaves `session_ids` as it found them the playlist+ // compares by value and never reloads, so the held-back page has to be replayed or the+ // visit reports no list at all. When the answer does change them the reload reports the+ // render itself, and replaying as well would count one list twice.+ const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)+ ;(experimentsSessionBucketsCreate as jest.Mock).mockImplementation(() =>+ bucket ? Promise.resolve(bucket) : Promise.reject(new Error('bucket failed'))+ )+ const racing = experimentReplayTabLogic({+ experiment: { ...EXPERIMENT, id: experimentId, start_date: daysAgo(10), end_date: null } as Experiment,+ })+ racing.mount()+ racing.actions.setMetricSelected('metric-purchase', true)+ racing.actions.setMetricFilterMode('no_metric_activity')++ // The bucket load debounces, so this page lands while the answer is still out.+ racing.actions.recordingsLoaded([])+ expect(listsRendered(captureSpy, experimentId)).toHaveLength(0)++ await expectLogic(racing).toFinishAllListeners()++ // The playlist reloads on a changed session set, which is the caller's next first page.+ if (bucket?.session_ids.length) {+ racing.actions.recordingsLoaded(loadedPage(bucket.session_ids))+ await expectLogic(racing).toFinishAllListeners()+ }++ expect(listsRendered(captureSpy, experimentId)).toHaveLength(renders)+ racing.unmount()+ }+ )++ it('drops a held-back empty page once a first page fails, rather than replaying it', async () => {+ // The visit ends on the failure, so the caption and the report both have to describe it.+ // Replayed, the held-back page reported a render for a list that failed and cleared the+ // caption underneath the playlist's own error banner.+ const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)+ let resolveBucket!: (response: unknown) => void+ ;(experimentsSessionBucketsCreate as jest.Mock).mockImplementation(+ () => new Promise((resolve) => (resolveBucket = resolve))+ )+ const failing = experimentReplayTabLogic({+ experiment: { ...EXPERIMENT, id: 174, start_date: daysAgo(10), end_date: null } as Experiment,+ })+ failing.mount()+ failing.actions.setMetricSelected('metric-purchase', true)+ failing.actions.setMetricFilterMode('no_metric_activity')++ // The bucket load debounces, so both of these land while the answer is still out.+ failing.actions.recordingsLoaded([])+ failing.actions.recordingsLoadFailed({ status: 500, detail: 'Server error' }, true)++ while ((experimentsSessionBucketsCreate as jest.Mock).mock.calls.length === 0) {+ await new Promise((resolve) => setTimeout(resolve, 25))+ }+ // An answer that matches the session set the dropped page ran under, which is the case the+ // replay exists for: the playlist compares by value, so it never reloads.+ resolveBucket({ ...BUCKET_RESPONSE, session_ids: [] })+ await expectLogic(failing).toFinishAllListeners()++ expect(listsRendered(captureSpy, 174)).toHaveLength(0)+ expect(failing.values.listLoadError).toEqual({ status: 500, detail: 'Server error' })+ failing.unmount()+ })++ it('asks for no session bucket when it states that no list is available', async () => {+ // The metric filter is one of three paths that reach the bucket without a list on screen:+ // a results-row link, a multi-event metric's default click, and a mode a previous visit+ // persisted. Each one used to spend a ClickHouse scan on a session set nothing can show.+ const grouped = experimentReplayTabLogic({+ experiment: { ...GROUP_AGGREGATED_EXPERIMENT, id: 172 } as Experiment,+ })+ grouped.mount()+ grouped.actions.setMetricSelected('metric-purchase', true)+ grouped.actions.setMetricFilterMode('no_metric_activity')+ await expectLogic(grouped).toFinishAllListeners()++ expect(grouped.values.sessionBucketRequest).toBeNull()+ expect(experimentsSessionBucketsCreate).not.toHaveBeenCalled()+ grouped.unmount()+ })++ it('still reports the group aggregation for a draft experiment', async () => {+ // The list verdict takes the first refusal in the backend's order, so a draft's verdict is+ // `not_launched` whatever its flag does. Read from that verdict, the shelf's own reason+ // would go null on exactly the experiments it describes.+ const draftGrouped = experimentReplayTabLogic({+ experiment: {+ ...GROUP_AGGREGATED_EXPERIMENT,+ id: 173,+ start_date: null,+ end_date: null,+ } as Experiment,+ })+ draftGrouped.mount()+ await expectLogic(draftGrouped).toFinishAllListeners()++ expect(draftGrouped.values.listUnavailableReason).toBe('not_launched')+ expect(draftGrouped.values.behaviorComparisonUnavailableReason).toBe('group_aggregated')+ draftGrouped.unmount()+ })+it('reports the entry point a deep link set, and clears it when the viewer moves a facet', async () => {// The entry point is what separates a list a results row opened from one somebody narrowed// by hand, so an empty rate can be read per entry point. Left set after a manual change, it@@ -1348,9 +1597,9 @@ describe('experimentReplayTabLogic', () => {)failing.actions.loadSessionBucket()await expectLogic(failing).toFinishAllListeners()- failing.actions.recordingsLoaded([])- await expectLogic(failing).toFinishAllListeners()+ // A failed bucket leaves the session set empty, exactly as the dropped page found it, so+ // the playlist never reloads and the answer alone has to produce the report.expect(listsRendered(captureSpy, 113)).toHaveLength(1)expect(listsRendered(captureSpy, 113)[0][1]).toMatchObject({result_count: 0,diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.tsindex 673c098fbd8b..4dc33552a61c 100644--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts@@ -11,7 +11,9 @@ import {props,reducers,selectors,+ sharedListeners,} from 'kea'+import type { BreakPointFunction } from 'kea'import { loaders } from 'kea-loaders'import { router, urlToAction } from 'kea-router'@@ -23,6 +25,8 @@ import {ExperimentRecordingsBucketFailedContext,ExperimentRecordingsBucketLoadedContext,ExperimentRecordingsFilterContext,+ ExperimentRecordingsListAbandonedContext,+ ExperimentRecordingsListFailedContext,ExperimentRecordingsListRenderedContext,ExperimentRecordingsTabContext,ExperimentWatchCardContext,@@ -55,7 +59,7 @@ import {UniversalFiltersGroupValue,} from '~/types'-import { hasEnded } from 'products/experiments/frontend/experimentStatus'+import { getExperimentStatus, hasEnded, isLaunched } from 'products/experiments/frontend/experimentStatus'import {experimentsInSessionExposureRetrieve,experimentsSessionBucketsCreate,@@ -156,6 +160,25 @@ export type ExperimentReplayRecording = Pick<SessionRecordingType, 'id' | 'recor*/export type ExperimentBehaviorComparisonUnavailableReason = 'group_aggregated'+/**+ * Why the tab states that no list is available instead of mounting one. Every code mirrors a+ * refusal `resolve_exposure_linkage` raises before it reads any data, so the tab can say what is+ * wrong rather than mount a list whose only possible answer is a 400 and an error toast.+ */+export type ExperimentRecordingsListUnavailableReason = 'not_launched' | 'group_aggregated' | 'no_variants'++/** What a failed first page of the recordings list came back with, as the tab's caption states it. */+export interface ExperimentRecordingsListError {+ status: number | null+ detail: string+}++/**+ * How much of the backend's message the failure report carries. The messages are short fixed+ * strings, so this only bounds an unexpected one.+ */+const LIST_ERROR_DETAIL_LIMIT = 200+/** The link an empty "what to watch" state offers, as reported to telemetry. */export type ExperimentWatchEmptyAction = 'exposure_docs' | 'replay_settings'@@ -383,12 +406,15 @@ export interface experimentReplayTabLogicValues {exposureScope: ExperimentReplayExposureScopefilterContext: ExperimentRecordingsFilterContextfiltersCustomized: boolean+ groupAggregatedExposure: booleaninSessionExposure: ExperimentInSessionExposureApi | nullinSessionExposureLoading: booleanlinkedScanners: LinkedScanner[]linkedScannersLoading: booleanlistEmptyContext: ExperimentRecordingsListEmptyContextlistEmptyReason: ExperimentReplayListEmptyReason+ listLoadError: ExperimentRecordingsListError | null+ listUnavailableReason: ExperimentRecordingsListUnavailableReason | nullloadedRecordings: ExperimentReplayRecording[]loadedRecordingsById: Map<string, ExperimentReplayRecording>metricFilterMode: ExperimentReplayMetricFilterMode@@ -463,6 +489,20 @@ export interface experimentReplayTabLogicActions {context: import('lib/utils/eventUsageLogic').ExperimentRecordingsEmptyActionContextexperimentId: ExperimentIdType} // eventUsageLogic+ reportExperimentRecordingsListAbandoned: (+ experimentId: ExperimentIdType,+ context: ExperimentRecordingsListAbandonedContext+ ) => {+ context: ExperimentRecordingsListAbandonedContext+ experimentId: ExperimentIdType+ } // eventUsageLogic+ reportExperimentRecordingsListFailed: (+ experimentId: ExperimentIdType,+ context: ExperimentRecordingsListFailedContext+ ) => {+ context: ExperimentRecordingsListFailedContext+ experimentId: ExperimentIdType+ } // eventUsageLogicreportExperimentRecordingsListRendered: (experimentId: ExperimentIdType,context: ExperimentRecordingsListRenderedContext@@ -606,6 +646,13 @@ export interface experimentReplayTabLogicActions {recordingOpened: (sessionId: string) => {sessionId: string}+ recordingsLoadFailed: (+ error: ExperimentRecordingsListError,+ isFirstPage?: boolean+ ) => {+ error: ExperimentRecordingsListError+ isFirstPage: boolean+ }recordingsLoaded: (recordings: ExperimentReplayRecording[],isFirstPage?: boolean@@ -616,6 +663,9 @@ export interface experimentReplayTabLogicActions {reportTabViewed: () => {value: true}+ retryListLoad: () => {+ value: true+ }scannerCrossSellClicked: () => {value: true}@@ -656,11 +706,30 @@ export interface experimentReplayTabLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface experimentReplayTabLogicMeta {key: ExperimentIdType+ sharedListeners: {+ replayDroppedEmptyPage: (+ payload: any,+ breakpoint: BreakPointFunction,+ action: {+ type: string+ payload: any+ },+ previousState: any+ ) => void | Promise<void>+ }__keaTypeGenInternalSelectorTypes: {loadedRecordingsById: (loadedRecordings: ExperimentReplayRecording[]) => Map<string, ExperimentReplayRecording>variantKeys: (arg: any) => string[]behaviorComparisonAvailable: (featureFlags: FeatureFlagsSet) => boolean- behaviorComparisonUnavailableReason: (arg: any) => ExperimentBehaviorComparisonUnavailableReason | null+ groupAggregatedExposure: (arg: any) => boolean+ listUnavailableReason: (+ variantKeys: string[],+ groupAggregatedExposure: boolean,+ arg: any+ ) => ExperimentRecordingsListUnavailableReason | null+ behaviorComparisonUnavailableReason: (+ groupAggregatedExposure: boolean+ ) => ExperimentBehaviorComparisonUnavailableReason | nulleffectiveVariantKey: (selectedVariantKey: string | null, variantKeys: string[]) => string | nullexposureInSessionUnavailableReason: (inSessionExposure: ExperimentInSessionExposureApi | null) => string | nulleffectiveExposureScope: (@@ -735,8 +804,10 @@ export interface experimentReplayTabLogicMeta {inSessionExposure: ExperimentInSessionExposureApi | null,behaviorComparisonAvailable: boolean,behaviorComparisonUnavailableReason: 'group_aggregated' | null,+ listUnavailableReason: ExperimentRecordingsListUnavailableReason | null,entryPoint: 'results_button' | 'results_menu' | null,- droppedMetricReason: 'data_warehouse' | 'no_uuid' | 'retention' | 'server_side_events' | null+ droppedMetricReason: 'data_warehouse' | 'no_uuid' | 'retention' | 'server_side_events' | null,+ arg: any) => ExperimentRecordingsTabContextmetricOptions: (linkabilityLoaded: boolean,@@ -752,7 +823,8 @@ export interface experimentReplayTabLogicMeta {metricFilterMode: 'fired_all' | 'fired_any' | 'funnel_completed' | 'funnel_dropoff' | 'no_metric_activity',effectiveMetricUuids: string[],effectiveVariantKey: string | null,- metricOptions: ExperimentReplayMetricOption[]+ metricOptions: ExperimentReplayMetricOption[],+ listUnavailableReason: ExperimentRecordingsListUnavailableReason | null) => ExperimentSessionBucketRequest | nullbucketSessionIds: (sessionBucketRequest: ExperimentSessionBucketRequest | null,@@ -819,6 +891,8 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>(['reportExperimentRecordingsBucketLoaded','reportExperimentRecordingsBucketFailed','reportExperimentRecordingsListRendered',+ 'reportExperimentRecordingsListFailed',+ 'reportExperimentRecordingsListAbandoned','reportExperimentRecordingOpened','reportExperimentBehaviorComparisonToggled','reportExperimentBehaviorComparisonLoaded',@@ -843,6 +917,11 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([recordings,isFirstPage,}),+ recordingsLoadFailed: (error: ExperimentRecordingsListError, isFirstPage: boolean = true) => ({+ error,+ isFirstPage,+ }),+ retryListLoad: true,recordingOpened: (sessionId: string) => ({ sessionId }),toggleBehaviorComparison: true,selectWatchCard: (card: ExperimentWatchCardApi | null) => ({ card }),@@ -1107,6 +1186,20 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([loadSessionBucketFailure: (_, { error, errorObject }) => errorObject?.detail || error || 'unknown',},],+ // Same discipline as the bucket error, for the same reason: the backend's message names+ // what the viewer can do about it ("still being computed. Try again in a few minutes"),+ // which the playlist's own generic banner cannot. Only a first page sets it, because a+ // later page failing leaves a list that has rows on screen. Cleared on the retry so the+ // caption and its button go away while the reload runs, rather than inviting a second+ // click on a request already in flight.+ listLoadError: [+ null as ExperimentRecordingsListError | null,+ {+ recordingsLoadFailed: (state, { error, isFirstPage }) => (isFirstPage ? error : state),+ recordingsLoaded: () => null,+ retryListLoad: () => null,+ },+ ],// The comparison is the heaviest read on this tab, so it is opened rather than loaded with// the tab. Not persisted: reopening the tab shouldn't silently re-run it.behaviorComparisonOpen: [@@ -1204,12 +1297,57 @@ 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: [+ /**+ * Whether the flag exposes groups rather than people. Read off the feature flag's filters+ * rather than the experiment's, because the flag's aggregation is what the backend checks.+ * Both the list verdict and the shelf's read from here, so the two can never disagree+ * about the fact while still stating it independently.+ */+ groupAggregatedExposure: [() => [(_, props) => props.experiment],- (experiment: Experiment): ExperimentBehaviorComparisonUnavailableReason | null =>- experiment.feature_flag?.filters?.aggregation_group_type_index != null ? 'group_aggregated' : null,+ (experiment: Experiment): boolean => experiment.feature_flag?.filters?.aggregation_group_type_index != null,+ ],+ /**+ * Why a list would be refused, decided before any request goes out, in the order+ * `resolve_exposure_linkage` decides it. The backend drops the experiment's excluded+ * variants before its own variant check, so `no_variants` here is a subset of what the+ * backend refuses; whatever it misses comes back as a failure, which the tab reports and+ * states.+ *+ * A missing flag is deliberately not a code, even though variants are read off the flag and+ * a flagless experiment would fall into `no_variants` here: `Experiment.feature_flag` is a+ * non-null foreign key with `on_delete=RESTRICT`, so a saved experiment always carries a+ * flag and the flag cannot be deleted from under it. The null branches in the serializer+ * and in `resolve_exposure_linkage` guard a state the schema forbids, and a scene still+ * loading holds a blank experiment, which `not_launched` answers for.+ */+ listUnavailableReason: [+ (s) => [s.variantKeys, s.groupAggregatedExposure, (_, props) => props.experiment],+ (+ variantKeys: string[],+ groupAggregatedExposure: boolean,+ experiment: Experiment+ ): ExperimentRecordingsListUnavailableReason | null => {+ if (!isLaunched(experiment)) {+ return 'not_launched'+ }+ if (groupAggregatedExposure) {+ return 'group_aggregated'+ }+ if (variantKeys.length === 0) {+ return 'no_variants'+ }+ return null+ },+ ],+ // Read off the aggregation itself rather than the list verdict, which states only the+ // first refusal the backend would raise: a draft that also aggregates by group has the+ // verdict `not_launched`, and a shelf reason taken from it would go null on exactly the+ // experiments this describes.+ behaviorComparisonUnavailableReason: [+ (s) => [s.groupAggregatedExposure],+ (groupAggregatedExposure: boolean): ExperimentBehaviorComparisonUnavailableReason | null =>+ groupAggregatedExposure ? 'group_aggregated' : null,],effectiveVariantKey: [(s) => [s.selectedVariantKey, s.variantKeys],@@ -1502,8 +1640,10 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([s.inSessionExposure,s.behaviorComparisonAvailable,s.behaviorComparisonUnavailableReason,+ s.listUnavailableReason,s.entryPoint,s.droppedMetricReason,+ (_, props) => props.experiment,],(variantKeys: string[],@@ -1512,11 +1652,17 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([inSessionExposure: ExperimentInSessionExposureApi | null,behaviorComparisonAvailable: boolean,behaviorComparisonUnavailableReason: ExperimentBehaviorComparisonUnavailableReason | null,+ listUnavailableReason: ExperimentRecordingsListUnavailableReason | null,entryPoint: ExperimentRecordingsEntryPoint | null,- droppedMetricReason: ExperimentMetricUnselectableCode | null+ droppedMetricReason: ExperimentMetricUnselectableCode | null,+ experiment: Experiment): ExperimentRecordingsTabContext => ({entry_point: entryPoint,metric_unavailable_reason: droppedMetricReason,+ // These two are what split the visits that never had a list from the ones whose+ // list failed or never arrived.+ experiment_status: getExperimentStatus(experiment),+ list_unavailable_reason: listUnavailableReason,variant_count: variantKeys.length,metric_count: metricOptions.length,linkable_metric_count: metricOptions.filter((option) => !option.unlinkable).length,@@ -1609,13 +1755,27 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([* silently matches the primary event only.*/sessionBucketRequest: [- (s) => [s.metricFilterMode, s.effectiveMetricUuids, s.effectiveVariantKey, s.metricOptions],+ (s) => [+ s.metricFilterMode,+ s.effectiveMetricUuids,+ s.effectiveVariantKey,+ s.metricOptions,+ s.listUnavailableReason,+ ],(metricFilterMode: ExperimentReplayMetricFilterMode,effectiveMetricUuids: string[],effectiveVariantKey: string | null,- metricOptions: ExperimentReplayMetricOption[]+ metricOptions: ExperimentReplayMetricOption[],+ listUnavailableReason: ExperimentRecordingsListUnavailableReason | null): ExperimentSessionBucketRequest | null => {+ // A stated reason takes the place of the list, so a bucket would spend a scan on a+ // session set nothing can show. The mode reaches this without a list on screen+ // three ways: a results-row link, a multi-event metric's default click, and a mode+ // a previous visit persisted.+ if (listUnavailableReason !== null) {+ return null+ }const request = (bucket: ExperimentSessionBucketEnumApi): ExperimentSessionBucketRequest => ({bucket,metric_uuids: effectiveMetricUuids,@@ -1785,7 +1945,25 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([},],}),- listeners(({ values, actions, cache, props }) => ({+ sharedListeners(({ values, actions, cache }) => ({+ /**+ * Replays an empty first page that was held back while the bucket loaded, so the visit+ * still reports what the list showed. Only when the answer left the list's session set+ * exactly as the held-back page ran under: a changed set reloads the playlist, and that+ * load reports its own render. An unchanged set (the bucket matched the same sessions, or+ * it failed and the set stays empty) never reloads the playlist, because the playlist+ * compares its filter props by value.+ */+ replayDroppedEmptyPage: () => {+ if (+ cache.pendingEmptyRenderSessionIds !== undefined &&+ objectsEqual(cache.pendingEmptyRenderSessionIds, values.recordingsFilters.session_ids)+ ) {+ actions.recordingsLoaded([], true)+ }+ },+ })),+ listeners(({ values, actions, cache, props, sharedListeners }) => ({// Every facet the bucket is keyed on re-asks for it. Listening to the actions rather than// subscribing to the spec keeps this off the redux subscription path.setMetricFilterMode: () => {@@ -1913,12 +2091,18 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([if (!isFirstPage) {return}+ // A page the playlist really loaded answers the question `replayDroppedEmptyPage`+ // asks, so a replay after this one would report the same visit twice.+ cache.pendingEmptyRenderSessionIds = undefined// An empty list under an in-flight metric filter is the filter not having answered yet,// which the caption says out loud. Reported, it would count twice: once here and once- // when the answer lands and the list reloads.+ // when the answer lands and the list reloads. The session set the page ran under is+ // kept, because only an answer that changes it produces that reload.if (recordings.length === 0 && values.sessionBucketLoading) {+ cache.pendingEmptyRenderSessionIds = values.recordingsFilters.session_idsreturn}+ cache.listOutcomeReported = trueactions.reportExperimentRecordingsListRendered(props.experiment.id, {...values.filterContext,result_count: recordings.length,@@ -1942,6 +2126,26 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([exposure_linkable: values.exposureLinkable,})},+ recordingsLoadFailed: ({ error, isFirstPage }) => {+ // A later page failing is paging against a list that already has rows, the same+ // reading `recordingsLoaded` takes of a later page that arrives.+ if (!isFirstPage) {+ return+ }+ // The visit now ends on this failure, so the empty page held back above is no longer+ // the list to report. Replayed after it, that page would report a render for a list+ // that failed and clear the caption while the playlist's own banner stays up.+ cache.pendingEmptyRenderSessionIds = undefined+ cache.listOutcomeReported = true+ actions.reportExperimentRecordingsListFailed(props.experiment.id, {+ ...values.filterContext,+ status: error.status,+ error_detail: error.detail.slice(0, LIST_ERROR_DETAIL_LIMIT),+ days_since_start: daysSince(props.experiment.start_date),+ })+ },+ loadSessionBucketSuccess: sharedListeners.replayDroppedEmptyPage,+ loadSessionBucketFailure: sharedListeners.replayDroppedEmptyPage,// Re-warm the rest of the page whenever the user moves to another recording: the// server-side cache entries expire on a TTL that starts at prefetch time, so a page// prefetched once goes cold under a user who watches one recording for a while. The@@ -2066,7 +2270,10 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>(['/experiments/:id/:formMode': ({ id }, searchParams) => applyFromUrl(id, searchParams),}}),- afterMount(({ values, actions }) => {+ afterMount(({ values, actions, cache }) => {+ // How long a visit that never saw a list lasted, which is what separates clicking through+ // the tabs from waiting on a list that never came.+ cache.mountedAt = performance.now()actions.setDefaultTab(SessionRecordingSidebarTab.OVERVIEW)// Resolve whether the in-session scope can answer before the viewer picks it, so the option// is disabled (not left to fail as a query error) when it can't, and the caption knows@@ -2104,6 +2311,19 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([cache.reportedTabView = trueactions.reportExperimentRecordingsTabViewed(props.experiment.id, values.tabViewContext)}+ // A visit that ends before the first page arrives or fails is the largest part of the+ // "tab viewed, no list" gap: the playlist waits out a debounce and then a request, and it+ // drops the load at a breakpoint on unmount without dispatching either outcome. Sent+ // through the connected action for the same reason the flush above is. An experiment whose+ // list was never going to load is left out, because the tab view already says so.+ if (!cache.listOutcomeReported && values.listUnavailableReason === null) {+ actions.reportExperimentRecordingsListAbandoned(props.experiment.id, {+ ...values.filterContext,+ ms_on_tab: Math.round(performance.now() - cache.mountedAt),+ held_for_checks: values.playlistHeldForChecks,+ bucket_loading: values.sessionBucketLoading,+ })+ }// The sidebar singleton normally unmounts alongside this logic and resets itself; this// covers the case where another player keeps it mounted, so the experiment default// doesn't leak to it.diff --git a/frontend/src/scenes/experiments/stories/ExperimentRecordingsListEmpty.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentRecordingsListEmpty.stories.tsxindex bb35d5a1bfbd..76e4c86b3834 100644--- a/frontend/src/scenes/experiments/stories/ExperimentRecordingsListEmpty.stories.tsx+++ b/frontend/src/scenes/experiments/stories/ExperimentRecordingsListEmpty.stories.tsx@@ -195,6 +195,56 @@ export const ExperimentRecordingsDroppedMetricNarrow: Story = {},}+/**+ * A flag that aggregates by group exposes groups rather than people, and the backend refuses to+ * match those exposures to recordings. The tab states that instead of mounting a list, so none of+ * the facet controls render either: every one of them describes a list.+ */+export const ExperimentRecordingsUnavailableGroupAggregated: Story = {+ parameters: {+ testOptions: { waitForSelector: '[data-attr="experiment-recordings-unavailable-group-aggregated"]' },+ },+ decorators: [+ mswDecorator({+ get: {+ [EXPERIMENT_PATH]: {+ ...EXPERIMENT_WITH_FUNNEL_METRIC,+ feature_flag: {+ ...EXPERIMENT_WITH_FUNNEL_METRIC.feature_flag,+ filters: {+ ...EXPERIMENT_WITH_FUNNEL_METRIC.feature_flag.filters,+ aggregation_group_type_index: 0,+ },+ },+ },+ },+ }),+ ],+}++/**+ * A list load the backend refused for a reason that passes on its own. The caption carries the+ * backend's own message and a retry, where the playlist's banner below it can only say that+ * something failed.+ */+export const ExperimentRecordingsListLoadFailed: Story = {+ parameters: {+ testOptions: { waitForSelector: '[data-attr="experiment-recordings-list-error-caption"]' },+ },+ decorators: [+ mswDecorator({+ get: {+ '/api/environments/:team_id/session_recordings': [+ 400,+ {+ detail: 'Exposed users for this experiment are still being computed. Try again in a few minutes.',+ },+ ],+ },+ }),+ ],+}+/*** The same matched-nothing state, reached by a results-row link rather than by hand. This is the* one place the whole deep link runs end to end: the scene keeps the params through its first URLdiff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.tsindex 2c102a816698..47fd07c72585 100644--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts@@ -2017,6 +2017,162 @@ describe('sessionRecordingsPlaylistLogic', () => {})})+ describe('failed list loads', () => {+ afterEach(() => {+ jest.restoreAllMocks()+ })++ it('clears the error banner once a later load succeeds', async () => {+ // The reducer keyed the clear on an action name that does not exist, so the banner+ // outlived the failure and covered a list that had since loaded.+ const listSpy = jest+ .spyOn(api.recordings, 'list')+ .mockRejectedValueOnce(Object.assign(new Error('Request failed'), { status: 500 }))++ const erroring = sessionRecordingsPlaylistLogic({ logicKey: 'error-then-success' })+ erroring.mount()+ await expectLogic(erroring).toDispatchActions(['loadSessionRecordingsFailure'])+ expect(erroring.values.sessionRecordingsAPIErrored).toBe(true)++ listSpy.mockResolvedValueOnce({ results: [aRecording], has_next: false } as Awaited<+ ReturnType<typeof api.recordings.list>+ >)+ erroring.actions.loadSessionRecordings(undefined, undefined, true)+ await expectLogic(erroring).toDispatchActions(['loadSessionRecordingsSuccess'])++ expect(erroring.values.sessionRecordingsAPIErrored).toBe(false)+ erroring.unmount()+ })++ it('hands the host page the status and the detail, with whether it was the first page', async () => {+ // An embedding page shows the reason and offers a retry off this callback, so it needs+ // the backend's own message. The status is what tells a refusal from a transient error.+ const onRecordingsLoadFailed = jest.fn()+ jest.spyOn(api.recordings, 'list').mockRejectedValue(+ Object.assign(new Error('Request failed'), { status: 400, detail: 'Exposures are still computing.' })+ )++ const embedded = sessionRecordingsPlaylistLogic({ logicKey: 'failure-reporting', onRecordingsLoadFailed })+ embedded.mount()+ await expectLogic(embedded).toDispatchActions(['loadSessionRecordingsFailure'])++ expect(onRecordingsLoadFailed.mock.calls).toEqual([+ [{ status: 400, detail: 'Exposures are still computing.' }, true],+ ])+ embedded.unmount()+ })++ it('reports neither outcome for a load a newer one supersedes', async () => {+ // An embedding page counts what each visit ended with. A load the viewer left behind+ // stops at a breakpoint, so reporting it would turn a bounce into an outcome.+ const onRecordingsLoadFailed = jest.fn()+ const onRecordingsLoaded = jest.fn()+ let resolveList: (value: unknown) => void = () => {}+ const pendingList = new Promise((resolve) => {+ resolveList = resolve+ })+ const listSpy = jest+ .spyOn(api.recordings, 'list')+ .mockImplementationOnce(() => pendingList as ReturnType<typeof api.recordings.list>)+ .mockImplementation(+ () =>+ Promise.resolve({ results: [], has_next: false } as unknown) as ReturnType<+ typeof api.recordings.list+ >+ )++ const embedded = sessionRecordingsPlaylistLogic({+ logicKey: 'superseded-reporting',+ onRecordingsLoadFailed,+ onRecordingsLoaded,+ })+ embedded.mount()+ while (listSpy.mock.calls.length === 0) {+ await new Promise((resolve) => setTimeout(resolve, 25))+ }++ embedded.actions.setFilters({ filter_test_accounts: true })+ resolveList({ results: [aRecording], has_next: false })+ await expectLogic(embedded).toFinishAllListeners()++ expect(onRecordingsLoadFailed).not.toHaveBeenCalled()+ // The load that replaced it is the only one that reported, and it reported its own rows.+ expect(onRecordingsLoaded.mock.calls).toEqual([[[], true]])+ embedded.unmount()+ })++ it('reports nothing for a superseded load that fails, and keeps the list it was replaced by', async () => {+ // A rejection reaches the loader before the breakpoint that drops a superseded load,+ // so a request the viewer had already moved on from used to report a failure: the banner+ // went up over rows that had just loaded, and the host page counted an outcome for a+ // list nobody was waiting for. The discarded mount query is the one that times out on+ // a heavy team, so this is the common shape rather than a corner.+ const onRecordingsLoadFailed = jest.fn()+ const onRecordingsLoaded = jest.fn()+ let rejectList: (reason: unknown) => void = () => {}+ const pendingList = new Promise((_, reject) => {+ rejectList = reject+ })+ const listSpy = jest+ .spyOn(api.recordings, 'list')+ .mockImplementationOnce(() => pendingList as ReturnType<typeof api.recordings.list>)+ .mockImplementation(+ () =>+ Promise.resolve({ results: [aRecording], has_next: false } as unknown) as ReturnType<+ typeof api.recordings.list+ >+ )++ const embedded = sessionRecordingsPlaylistLogic({+ logicKey: 'superseded-failure',+ onRecordingsLoadFailed,+ onRecordingsLoaded,+ })+ embedded.mount()+ while (listSpy.mock.calls.length === 0) {+ await new Promise((resolve) => setTimeout(resolve, 25))+ }++ embedded.actions.setFilters({ filter_test_accounts: true })+ rejectList(Object.assign(new Error('Request failed'), { status: 504 }))+ await expectLogic(embedded).toFinishAllListeners()++ expect(onRecordingsLoadFailed).not.toHaveBeenCalled()+ expect(embedded.values.sessionRecordingsAPIErrored).toBe(false)+ expect(onRecordingsLoaded.mock.calls).toEqual([[[aRecording], true]])+ embedded.unmount()+ })++ it('reports one failure when several loads answer from the one request that failed', async () => {+ // Identical loads share a single read, so one rejection came back through every load+ // waiting on it and the host page counted the same failure several times.+ const onRecordingsLoadFailed = jest.fn()+ let rejectList: (reason: unknown) => void = () => {}+ const pendingList = new Promise((_, reject) => {+ rejectList = reject+ })+ const listSpy = jest+ .spyOn(api.recordings, 'list')+ .mockImplementation(() => pendingList as ReturnType<typeof api.recordings.list>)++ const embedded = sessionRecordingsPlaylistLogic({ logicKey: 'shared-failure', onRecordingsLoadFailed })+ embedded.mount()+ while (listSpy.mock.calls.length === 0) {+ await new Promise((resolve) => setTimeout(resolve, 25))+ }++ // Same parameters, so this waits out the request already in flight rather than reading+ // the same rows a second time.+ embedded.actions.loadSessionRecordings()+ rejectList(Object.assign(new Error('Request failed'), { status: 500 }))+ await expectLogic(embedded).toFinishAllListeners()++ expect(listSpy).toHaveBeenCalledTimes(1)+ expect(onRecordingsLoadFailed.mock.calls).toEqual([[{ status: 500, detail: 'Request failed' }, true]])+ embedded.unmount()+ })+ })+describe('superseding or unmounting an in-flight load', () => {afterEach(() => {jest.restoreAllMocks()diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.tsindex d40c016b7f50..7a4e5e81e220 100644--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts@@ -504,6 +504,12 @@ export interface SessionRecordingPlaylistLogicProps {* first rendered from the ones paging appended to it.*/onRecordingsLoaded?: (recordings: SessionRecordingType[], isFirstPage: boolean) => void+ /**+ * Called when a list load fails, with whether it was a first-page load. A load that a newer one+ * supersedes, or that the viewer leaves behind, stops at a breakpoint and is not a failure, so+ * it is not reported here.+ */+ onRecordingsLoadFailed?: (error: { status: number | null; detail: string }, isFirstPage: boolean) => void/*** Called once each time the recording the player shows changes — clicked, played next,* picked via the URL, or the implicit autoplay fallback to the top of the list (on first@@ -1106,6 +1112,10 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic},{loadSessionRecordings: async ({ direction, userModifiedFilters, forceRefetch }, breakpoint) => {+ // kea-loaders builds the failure action from the error alone, so the failure+ // listener cannot see which load it belongs to. Recorded here, where the load+ // that is about to run still carries it.+ cache.loadDirection = direction// Captured before the awaits: `values` reads throw if this logic unmounts// mid-flight, and the fetch report must carry the filters the request was// built from, not whatever they are once the response lands.@@ -1176,7 +1186,15 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogicif (memoizedResponse) {response = memoizedResponse} else if (requestInFlight) {- response = await requestInFlight+ try {+ response = await requestInFlight+ } catch (e) {+ // One rejection comes back through every load waiting on the shared+ // read, so without this each of them reports the same failure. The+ // breakpoint leaves only the newest load to answer for it.+ breakpoint()+ throw e+ }} else {await breakpoint(400) // Debounce for lots of quick filter changes@@ -1197,6 +1215,11 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogicif (cache.listRequest === request) {cache.listRequest = undefined}+ // A failure reaches this catch ahead of the breakpoint below, so a load+ // the viewer left behind used to raise the error banner over the rows+ // that replaced it. Failing at the breakpoint instead drops it, the+ // same as a superseded success.+ breakpoint()throw e}// The response is here, so nothing can wait on this request any more. The@@ -1417,7 +1440,7 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogicfalse,{loadSessionRecordingsFailure: () => true,- loadSessionRecordingSuccess: () => false,+ loadSessionRecordingsSuccess: () => false,setFilters: () => false,setAdvancedFilters: () => false,loadNext: () => false,@@ -1745,6 +1768,21 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogicnotifyRecordingSelected()},+ loadSessionRecordingsFailure: ({ error, errorObject }) => {+ // The status rides alongside the message so a host page can tell a refusal the+ // backend states on purpose from a transport failure. What it offers for either is+ // its own decision, and the two differ: the shelf on the experiment recordings tab+ // shows a 400 as a plain answer, while the list there keeps the retry, because the+ // refusals it can still reach pass once the exposures finish computing.+ props.onRecordingsLoadFailed?.(+ {+ status: typeof errorObject?.status === 'number' ? errorObject.status : null,+ detail: errorObject?.detail || error,+ },+ !cache.loadDirection+ )+ },+loadPinnedRecordingsSuccess: () => {pruneSelectedRecordingsIds()// Pinned recordings sort first, so this load can change which recording the