: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(toolbar): surface real failure mode in experiments loader (#62325)
posthog[bot]a1ff14a84fda
diff --git a/frontend/src/toolbar/experiments/experimentsLogic.test.ts b/frontend/src/toolbar/experiments/experimentsLogic.test.tsnew file mode 100644index 000000000000..1dfc0fcc011c--- /dev/null+++ b/frontend/src/toolbar/experiments/experimentsLogic.test.ts@@ -0,0 +1,100 @@+import { expectLogic } from 'kea-test-utils'++jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({+ lemonToast: { success: jest.fn(), error: jest.fn() },+}))++import { initKeaTests } from '~/test/init'+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'++import { experimentsLogic } from './experimentsLogic'++const web_experiments = [{ id: 1, name: 'Test Experiment 1', variants: {} }]++function mockFetch(response: Partial<Response> & { json?: () => Promise<unknown> }): void {+ global.fetch = jest.fn(() => Promise.resolve(response as Response))+}++describe('experimentsLogic', () => {+ let logic: ReturnType<typeof experimentsLogic.build>+ const savedFetch = global.fetch++ afterAll(() => {+ global.fetch = savedFetch+ })++ function mountLogic({ withToken = true }: { withToken?: boolean } = {}): void {+ initKeaTests()+ toolbarConfigLogic+ .build({ apiURL: 'http://localhost', ...(withToken ? { accessToken: 'test-token' } : {}) })+ .mount()+ logic = experimentsLogic()+ logic.mount()+ }++ it('loads experiments on a successful response', async () => {+ mockFetch({ ok: true, status: 200, json: () => Promise.resolve({ results: web_experiments }) })+ mountLogic()++ await expectLogic(logic, () => {+ logic.actions.getExperiments()+ })+ .toDispatchActions(['getExperiments', 'getExperimentsSuccess'])+ .toMatchValues({ allExperiments: web_experiments })+ })++ it('returns an empty list when unauthenticated (stubbed 401)', async () => {+ // No access token → toolbarFetch short-circuits to a stubbed 401, never hitting fetch.+ mountLogic({ withToken: false })++ await expectLogic(logic, () => {+ logic.actions.getExperiments()+ })+ .toDispatchActions(['getExperiments', 'getExperimentsSuccess'])+ .toMatchValues({ allExperiments: [] })+ })++ it('soft-fails to an empty list on a 5xx server error', async () => {+ mockFetch({ ok: false, status: 503, json: () => Promise.reject(new Error('unused')) })+ mountLogic()++ await expectLogic(logic, () => {+ logic.actions.getExperiments()+ })+ .toDispatchActions(['getExperiments', 'getExperimentsSuccess'])+ .toMatchValues({ allExperiments: [] })+ })++ it.each([+ [+ 'a non-2xx response',+ { ok: false, status: 404, json: () => Promise.resolve({}) },+ ['HTTP 404', '/api/projects/@current/web_experiments/'],+ ],+ [+ 'the body is not valid JSON',+ { ok: true, status: 200, json: () => Promise.reject(new Error('Unexpected token')) },+ ['not valid JSON'],+ ],+ [+ 'results is not an array',+ { ok: true, status: 200, json: () => Promise.resolve({ results: { unexpected: true } }) },+ ['expected an array', 'got object'],+ ],+ ] as [string, Partial<Response> & { json?: () => Promise<unknown> }, string[]][])(+ 'throws a descriptive error when %s',+ async (_name, fetchResponse, expectedSubstrings) => {+ mockFetch(fetchResponse)+ mountLogic()++ await expectLogic(logic, () => {+ logic.actions.getExperiments()+ }).toDispatchActions([+ 'getExperiments',+ (action) =>+ action.type === logic.actionTypes.getExperimentsFailure &&+ expectedSubstrings.every((s) => action.payload.error.includes(s)),+ ])+ }+ )+})diff --git a/frontend/src/toolbar/experiments/experimentsLogic.ts b/frontend/src/toolbar/experiments/experimentsLogic.tsindex 75b6d8955050..ca584b46df3b 100644--- a/frontend/src/toolbar/experiments/experimentsLogic.ts+++ b/frontend/src/toolbar/experiments/experimentsLogic.ts@@ -5,10 +5,22 @@ import { createFuse } from 'lib/utils/fuseSearch'import { permanentlyMount } from 'lib/utils/kea-logic-builders'import { toolbarConfigLogic, toolbarFetch } from '~/toolbar/toolbarConfigLogic'+import { toolbarLogger } from '~/toolbar/toolbarLogger'import { WebExperiment } from '~/toolbar/types'import type { experimentsLogicType } from './experimentsLogicType'+/** Short, PII-free description of an unexpected value's shape for error messages. */+function describeShape(value: unknown): string {+ if (value === null) {+ return 'null'+ }+ if (Array.isArray(value)) {+ return 'array'+ }+ return typeof value+}+export const experimentsLogic = kea<experimentsLogicType>([path(['toolbar', 'experiments', 'experimentsLogic']),actions({@@ -20,21 +32,53 @@ export const experimentsLogic = kea<experimentsLogicType>([{// oxlint-disable-next-line @typescript-eslint/no-unused-varsgetExperiments: async (_ = null, breakpoint: () => void) => {- const response = await toolbarFetch('/api/projects/@current/web_experiments/')- const results = await response.json()+ const url = '/api/projects/@current/web_experiments/'+ const response = await toolbarFetch(url)if (response.status === 403) {toolbarConfigLogic.actions.authenticate()return []}+ // toolbarFetch returns a stubbed 401 when there's no access token yet —+ // the toolbar simply isn't authenticated, so show an empty list, not an error.+ if (response.status === 401) {+ return []+ }+breakpoint()- if (!Array.isArray(results?.results)) {- throw new Error('Error loading experiments!')+ // Transient server errors aren't actionable for the user — soft-fail to an+ // empty list and let them retry rather than surfacing a scary error panel.+ if (response.status >= 500) {+ toolbarLogger.warn('experiments', 'Server error loading experiments, returning empty list', {+ status: response.status,+ url,+ })+ return []+ }++ if (!response.ok) {+ throw new Error(`Failed to load experiments: HTTP ${response.status} from ${url}`)+ }++ let results: unknown+ try {+ results = await response.json()+ } catch {+ throw new Error(`Failed to load experiments: response from ${url} was not valid JSON`)+ }++ const resultsList = (results as { results?: unknown } | null)?.results+ if (!Array.isArray(resultsList)) {+ throw new Error(+ `Failed to load experiments: expected an array at "results" from ${url}, got ${describeShape(+ resultsList+ )}`+ )}- return results.results+ return resultsList as WebExperiment[]},updateExperiment: ({ experiment }: { experiment: WebExperiment }) => {return values.allExperiments.filter((r) => r.id !== experiment.id).concat([experiment])