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(engineering-analytics): show validated environment selections (#95596)

Paul D'Ambra62a4a900b96c
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsHealth.stories.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsHealth.stories.tsx
index d495efe10dcc..41f482cff821 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsHealth.stories.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsHealth.stories.tsx
@@ -57,8 +57,8 @@ function leadTimeSeries(stats: (number[] | null)[]): DoraOverviewApi['merge_to_d
const DORA: DoraOverviewApi = {
deploy_data_available: true,
- environment_scope: 'prod-us',
- selected_environments: ['prod-us'],
+ environment_scope: 'prod-us, prod-eu',
+ selected_environments: ['prod-us', 'prod-eu'],
environments: ['prod-us', 'prod-eu', 'dev'],
has_membership_data: true,
github_teams: ['team-devex', 'team-ingestion', 'team-replay'],
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsHealth.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsHealth.tsx
index 33b9bf822c77..7930ff8c34e4 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsHealth.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsHealth.tsx
@@ -28,7 +28,7 @@ export function EngineeringAnalyticsHealth(): JSX.Element {
dora,
doraLoading,
doraFailed,
- environments,
+ selectedEnvironments,
githubTeam,
granularity,
boxPlotBuckets,
@@ -102,7 +102,7 @@ export function EngineeringAnalyticsHealth(): JSX.Element {
<LemonInputSelect
size="small"
mode="multiple"
- value={environments}
+ value={selectedEnvironments}
onChange={setEnvironments}
options={environmentOptions}
placeholder={`Default environment (${environmentScopeLabel})`}
diff --git a/products/engineering_analytics/frontend/scenes/doraLogic.test.ts b/products/engineering_analytics/frontend/scenes/doraLogic.test.ts
new file mode 100644
index 000000000000..8a6f578bf547
--- /dev/null
+++ b/products/engineering_analytics/frontend/scenes/doraLogic.test.ts
@@ -0,0 +1,299 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { ApiConfig, ApiError } from 'lib/api'
+
+import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import type { DoraOverviewApi } from '../generated/api.schemas'
+import { doraLogic } from './doraLogic'
+import { engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'
+
+const DORA: DoraOverviewApi = {
+ environment_scope: 'prod-us, prod-eu',
+ environments: ['dev', 'prod-us', 'prod-eu'],
+ selected_environments: ['prod-us', 'prod-eu'],
+ github_teams: [],
+ series_granularity: 'day',
+ deploy_data_available: true,
+ has_membership_data: false,
+ deployment_count: 0,
+ deployment_count_prev: 0,
+ deployments_per_day: 0,
+ deployments_per_day_prev: 0,
+ median_merge_to_deploy_seconds: null,
+ median_merge_to_deploy_seconds_prev: null,
+ median_open_to_deploy_seconds: null,
+ median_open_to_deploy_seconds_prev: null,
+ deployed_pr_count: 0,
+ deployed_pr_count_prev: 0,
+ failed_deployment_count: 0,
+ failed_deployment_count_prev: 0,
+ failed_deployment_share: null,
+ failed_deployment_share_prev: null,
+ median_failed_deploy_to_next_success_seconds: null,
+ median_failed_deploy_to_next_success_seconds_prev: null,
+ merged_pr_count: 0,
+ unattributed_merged_pr_share: null,
+ latest_deploy_status_at: null,
+ deployment_frequency_series: [],
+ merge_to_deploy_series: [],
+ open_to_merge_series: [],
+ open_to_deploy_series: [],
+}
+
+describe('doraLogic', () => {
+ let logic: ReturnType<typeof doraLogic.build>
+ let requests: URLSearchParams[]
+ let availableEnvironments: string[]
+ let releaseInvalidRequest: () => void
+ let releaseScopedRequest: () => void
+ let invalidRequest: Promise<void>
+ let scopedRequest: Promise<void>
+
+ beforeEach(() => {
+ requests = []
+ availableEnvironments = [...DORA.environments, 'preview-pr-2']
+ invalidRequest = new Promise((resolve) => {
+ releaseInvalidRequest = resolve
+ })
+ scopedRequest = new Promise((resolve) => {
+ releaseScopedRequest = resolve
+ })
+ useMocks({
+ get: {
+ '/api/projects/:team_id/engineering_analytics/dora/': async ({ request }) => {
+ const params = new URL(request.url).searchParams
+ requests.push(params)
+ const requested = [...new Set(params.getAll('environment').map((name) => name.trim()))]
+ const available = new Set(
+ params.get('repo') === 'example/repo' ? ['staging'] : availableEnvironments
+ )
+ const blankIndex = requested.indexOf('')
+ if (blankIndex >= 0) {
+ return [
+ 400,
+ {
+ type: 'validation_error',
+ code: 'blank',
+ detail: 'This field may not be blank.',
+ attr: `environment__${blankIndex}`,
+ },
+ ]
+ }
+ const nullCharacterIndex = requested.findIndex((name) => name.includes('\0'))
+ if (nullCharacterIndex >= 0) {
+ return [
+ 400,
+ {
+ type: 'validation_error',
+ code: 'null_characters_not_allowed',
+ detail: 'Null characters are not allowed.',
+ attr: `environment__${nullCharacterIndex}`,
+ },
+ ]
+ }
+ const invalidEnvironment = requested.find((name) => !available.has(name))
+ if (invalidEnvironment) {
+ if (invalidEnvironment === 'missing-delayed') {
+ await invalidRequest
+ }
+ return [
+ 400,
+ {
+ type: 'validation_error',
+ code: 'invalid_choice',
+ detail: `"${invalidEnvironment}" is not a valid choice.`,
+ attr: 'environment',
+ },
+ ]
+ }
+ if (params.get('repo') === 'example/repo') {
+ await scopedRequest
+ return [
+ 200,
+ {
+ ...DORA,
+ environment_scope: 'staging',
+ environments: ['staging'],
+ selected_environments: ['staging'],
+ },
+ ]
+ }
+ return [
+ 200,
+ {
+ ...DORA,
+ environment_scope: requested.length ? requested.join(', ') : DORA.environment_scope,
+ selected_environments: requested.length ? requested : DORA.selected_environments,
+ },
+ ]
+ },
+ '/api/projects/:team_id/engineering_analytics/sources/': [],
+ '/api/projects/:team_id/engineering_analytics/ci_cards/': {
+ open_prs: 0,
+ repos: 0,
+ stuck: 0,
+ failing_ci: 0,
+ },
+ '/api/projects/:team_id/engineering_analytics/pull_requests/': {
+ items: [],
+ truncated: false,
+ limit: 1000,
+ },
+ '/api/projects/:team_id/engineering_analytics/workflow_health/': [],
+ '/api/projects/:team_id/engineering_analytics/quarantine/': {
+ available: false,
+ entries: [],
+ parse_errors: [],
+ parse_warnings: [],
+ repo: null,
+ source_url: '',
+ generated_at: '2026-01-01T00:00:00Z',
+ },
+ '/api/projects/:team_id/engineering_analytics/trunk_quarantine/': {
+ available: false,
+ owners_resolved: true,
+ ttl_days: 15,
+ repository: 'example/repo',
+ trunk_url: null,
+ teams: [],
+ tests: [],
+ },
+ },
+ })
+ initKeaTests()
+ ApiConfig.setCurrentProjectId(1)
+ logic = doraLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ resumeKeaLoadersErrors()
+ logic.unmount()
+ })
+
+ it('shows both resolved production regions as selected on first load', async () => {
+ await expectLogic(logic).toDispatchActions(['loadDoraSuccess'])
+ expect(requests[0].getAll('environment')).toEqual([])
+ expect(logic.values.selectedEnvironments).toEqual(['prod-us', 'prod-eu'])
+ expect(logic.values.environmentOptions.map(({ key }) => key)).toEqual(['dev', 'prod-us', 'prod-eu'])
+ })
+
+ it('sends the visible selections as repeated parameters and restores production when cleared', async () => {
+ await expectLogic(logic).toDispatchActions(['loadDoraSuccess'])
+ await expectLogic(logic, () => logic.actions.setEnvironments(['prod-eu', 'dev'])).toDispatchActions([
+ 'loadDoraSuccess',
+ ])
+ expect(requests.at(-1)?.getAll('environment')).toEqual(['prod-eu', 'dev'])
+ expect(logic.values.selectedEnvironments).toEqual(['prod-eu', 'dev'])
+
+ await expectLogic(logic, () => logic.actions.setEnvironments([])).toDispatchActions(['loadDoraSuccess'])
+ expect(requests.at(-1)?.getAll('environment')).toEqual([])
+ expect(logic.values.selectedEnvironments).toEqual(['prod-us', 'prod-eu'])
+ })
+
+ it('uses the backend-validated environment selection and options', async () => {
+ await expectLogic(logic).toDispatchActions(['loadDoraSuccess'])
+ await expectLogic(logic, () =>
+ logic.actions.setEnvironments([' prod-eu ', 'prod-eu', 'preview-pr-2'])
+ ).toDispatchActions(['loadDoraSuccess'])
+
+ expect(logic.values.selectedEnvironments).toEqual(['prod-eu', 'preview-pr-2'])
+ expect(logic.values.environmentScopeLabel).toBe('prod-eu, preview-pr-2')
+ expect(logic.values.environmentOptions.map(({ key }) => key)).toEqual([
+ 'dev',
+ 'prod-us',
+ 'prod-eu',
+ 'preview-pr-2',
+ ])
+
+ silenceKeaLoadersErrors()
+ for (const environments of [['missing'], ['prod-eu', ''], ['prod-eu', '\0']]) {
+ await expectLogic(logic, () => logic.actions.setEnvironments(environments))
+ .toDispatchActions(['loadDoraFailure', 'restoreEnvironments'])
+ .toMatchValues({
+ doraLoading: false,
+ doraFailed: true,
+ environments: ['prod-eu', 'preview-pr-2'],
+ selectedEnvironments: ['prod-eu', 'preview-pr-2'],
+ environmentScopeLabel: 'prod-eu, preview-pr-2',
+ })
+ expect(logic.values.environmentOptions.map(({ key }) => key)).toEqual([
+ 'dev',
+ 'prod-us',
+ 'prod-eu',
+ 'preview-pr-2',
+ ])
+
+ await expectLogic(logic, () => logic.actions.loadDora()).toDispatchActions(['loadDoraSuccess'])
+ expect(requests.at(-1)?.getAll('environment')).toEqual(['prod-eu', 'preview-pr-2'])
+ }
+ })
+
+ it('clears a rejected selection when the previously valid environment set becomes unavailable', async () => {
+ await expectLogic(logic).toDispatchActions(['loadDoraSuccess'])
+ await expectLogic(logic, () => logic.actions.setEnvironments(['prod-eu', 'preview-pr-2'])).toDispatchActions([
+ 'loadDoraSuccess',
+ ])
+ availableEnvironments = [...DORA.environments]
+ silenceKeaLoadersErrors()
+
+ await expectLogic(logic, () => logic.actions.setEnvironments(['prod-eu', 'preview-pr-2']))
+ .toDispatchActions(['loadDoraFailure', 'restoreEnvironments'])
+ .toMatchValues({ environments: [], doraFailed: true })
+
+ await expectLogic(logic, () => logic.actions.loadDora()).toDispatchActions(['loadDoraSuccess'])
+ expect(requests.at(-1)?.getAll('environment')).toEqual([])
+ })
+
+ it.each([
+ [
+ 'an unrelated validation error',
+ new ApiError('Bad date.', 400, undefined, { code: 'invalid_input', attr: 'date_from' }),
+ ],
+ ['a server error', new ApiError('Server error.', 500)],
+ ])('preserves the environment filter after %s', async (_, error) => {
+ await expectLogic(logic).toDispatchActions(['loadDoraSuccess'])
+ await expectLogic(logic, () => logic.actions.setEnvironments(['dev'])).toDispatchActions(['loadDoraSuccess'])
+ silenceKeaLoadersErrors()
+
+ logic.actions.loadDoraFailure(error.message, error)
+
+ expect(logic.values.environments).toEqual(['dev'])
+ })
+
+ it('discards an older validation failure after a newer selection succeeds', async () => {
+ await expectLogic(logic).toDispatchActions(['loadDoraSuccess'])
+ logic.actions.setEnvironments(['missing-delayed'])
+ await expectLogic(logic, () => logic.actions.setEnvironments(['dev'])).toDispatchActions(['loadDoraSuccess'])
+
+ await expectLogic(logic, () => releaseInvalidRequest()).toFinishAllListeners()
+
+ expect(logic.values.doraFailed).toBe(false)
+ expect(logic.values.environments).toEqual(['dev'])
+ expect(logic.values.selectedEnvironments).toEqual(['dev'])
+ })
+
+ it('resolves the new repository default instead of retaining an old environment or team', async () => {
+ await expectLogic(logic).toDispatchActions(['loadDoraSuccess'])
+ await expectLogic(logic, () => {
+ logic.actions.setEnvironments(['dev'])
+ logic.actions.setGithubTeam('team-example')
+ }).toFinishAllListeners()
+ engineeringAnalyticsLogic.actions.setScope('source-2', 'example/repo')
+ expect(logic.values.selectedEnvironments).toEqual([])
+ expect(logic.values.environmentOptions).toEqual([])
+ expect(logic.values.environmentScopeLabel).toBe('production')
+
+ await expectLogic(logic, () => releaseScopedRequest()).toFinishAllListeners()
+ expect(requests.at(-1)?.get('source_id')).toEqual('source-2')
+ expect(requests.at(-1)?.get('repo')).toEqual('example/repo')
+ expect(requests.at(-1)?.getAll('environment')).toEqual([])
+ expect(requests.at(-1)?.has('github_team')).toBe(false)
+ expect(logic.values.dora).toMatchObject({ selected_environments: ['staging'] })
+ expect(logic.values.selectedEnvironments).toEqual(['staging'])
+ expect(logic.values.environmentOptions.map(({ key }) => key)).toEqual(['staging'])
+ })
+})
diff --git a/products/engineering_analytics/frontend/scenes/doraLogic.ts b/products/engineering_analytics/frontend/scenes/doraLogic.ts
index a82f3d2d3532..1716d8f144a6 100644
--- a/products/engineering_analytics/frontend/scenes/doraLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/doraLogic.ts
@@ -1,7 +1,7 @@
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
-import { ApiConfig } from 'lib/api'
+import { ApiConfig, ApiError } from 'lib/api'
import { intervals } from 'lib/components/IntervalFilter/intervals'
import type { BoxPlotBucket } from '../components/LeadTimeBoxPlot'
@@ -14,6 +14,19 @@ const projectId = (): string => String(ApiConfig.getCurrentProjectId())
type LeadTimeSeriesApi = DoraOverviewApi['merge_to_deploy_series']
+function isEnvironmentValidationError(errorObject: unknown): errorObject is ApiError {
+ return (
+ errorObject instanceof ApiError &&
+ errorObject.status === 400 &&
+ (errorObject.attr === 'environment' || /^environment__\d+$/.test(errorObject.attr ?? ''))
+ )
+}
+
+function hasSameNormalizedEnvironmentSet(requested: string[], selected: string[]): boolean {
+ const normalizedRequested = new Set(requested.map((name) => name.trim()))
+ return normalizedRequested.size === selected.length && selected.every((name) => normalizedRequested.has(name))
+}
+
function toBoxPlotBuckets(series: LeadTimeSeriesApi | undefined, granularity: string): BoxPlotBucket[] {
return (series ?? []).map((bucket) => ({
label: formatBucket(bucket.bucket_start, granularity as WorkflowGranularity),
@@ -61,6 +74,7 @@ export interface doraLogicValues {
granularity: DoraGranularity | null
openToDeployBuckets: BoxPlotBucket[]
openToMergeBuckets: BoxPlotBucket[]
+ selectedEnvironments: string[]
showAllLeadTimeStages: boolean
}
@@ -84,6 +98,9 @@ export interface doraLogicActions {
resetGranularity: () => {
value: true
}
+ restoreEnvironments: (environments: string[]) => {
+ environments: string[]
+ }
setEnvironments: (environments: string[]) => {
environments: string[]
}
@@ -104,16 +121,14 @@ export interface doraLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface doraLogicMeta {
__keaTypeGenInternalSelectorTypes: {
+ selectedEnvironments: (dora: DoraOverviewApi | null, doraLoading: boolean, environments: string[]) => string[]
boxPlotBuckets: (dora: DoraOverviewApi | null) => BoxPlotBucket[]
openToMergeBuckets: (dora: DoraOverviewApi | null) => BoxPlotBucket[]
openToDeployBuckets: (dora: DoraOverviewApi | null) => BoxPlotBucket[]
frequencyCounts: (dora: DoraOverviewApi | null) => number[]
frequencyIsoLabels: (dora: DoraOverviewApi | null) => string[]
- environmentScopeLabel: (dora: DoraOverviewApi | null, environments: string[]) => string
- environmentOptions: (
- dora: DoraOverviewApi | null,
- environments: string[]
- ) => {
+ environmentScopeLabel: (dora: DoraOverviewApi | null, selectedEnvironments: string[]) => string
+ environmentOptions: (dora: DoraOverviewApi | null) => {
key: string
label: string
}[]
@@ -136,6 +151,7 @@ export const doraLogic = kea<doraLogicType>([
})),
actions({
+ restoreEnvironments: (environments: string[]) => ({ environments }),
setEnvironments: (environments: string[]) => ({ environments }),
setExcludeOutliers: (excludeOutliers: boolean) => ({ excludeOutliers }),
setGithubTeam: (githubTeam: string | null) => ({ githubTeam }),
@@ -149,25 +165,35 @@ export const doraLogic = kea<doraLogicType>([
null as DoraOverviewApi | null,
{
loadDora: async (_: void, breakpoint): Promise<DoraOverviewApi> => {
- const response = await engineeringAnalyticsDora(projectId(), {
- date_from: values.dateFrom ?? undefined,
- date_to: values.dateTo ?? undefined,
- environment: values.environments.length ? values.environments : undefined,
- github_team: values.githubTeam ?? undefined,
- granularity: values.granularity ?? undefined,
- source_id: values.sourceId ?? undefined,
- repo: values.scopeRepo ?? undefined,
- })
- // breakpoint() throws if a newer loadDora call has started, discarding this stale response.
- breakpoint()
- return response
+ try {
+ return await engineeringAnalyticsDora(projectId(), {
+ date_from: values.dateFrom ?? undefined,
+ date_to: values.dateTo ?? undefined,
+ environment: values.environments.length ? values.environments : undefined,
+ github_team: values.githubTeam ?? undefined,
+ granularity: values.granularity ?? undefined,
+ source_id: values.sourceId ?? undefined,
+ repo: values.scopeRepo ?? undefined,
+ })
+ } finally {
+ // The API promise can reject before a post-await breakpoint, so check both paths here.
+ breakpoint()
+ }
},
},
],
})),
reducers(() => ({
- // Non-400 failure only; the shared 400 "not connected" state comes from engineeringAnalyticsLogic.
+ dora: [
+ null as DoraOverviewApi | null,
+ {
+ loadDoraSuccess: (_, { dora }) => dora,
+ [engineeringAnalyticsLogic.actionTypes.setSourceId]: () => null,
+ [engineeringAnalyticsLogic.actionTypes.setScope]: () => null,
+ },
+ ],
+ // Shared source-connection failures surface through engineeringAnalyticsLogic; DORA-specific failures stay here.
doraFailed: [
false,
{
@@ -176,13 +202,13 @@ export const doraLogic = kea<doraLogicType>([
loadDoraFailure: () => true,
},
],
- // Empty means the backend's default scope: the busiest production-marked environment,
- // falling back to the busiest persistent one. Reset on a source/repo scope change: an
+ // Empty requests the backend's production default. Reset on a source/repo scope change: an
// environment or team from the old repo may not exist on the new one, and would
// otherwise be sent as a silently-empty exact filter.
environments: [
[] as string[],
{
+ restoreEnvironments: (_, { environments }) => environments,
setEnvironments: (_, { environments }) => environments,
[engineeringAnalyticsLogic.actionTypes.setSourceId]: () => [],
[engineeringAnalyticsLogic.actionTypes.setScope]: () => [],
@@ -218,6 +244,19 @@ export const doraLogic = kea<doraLogicType>([
})),
selectors({
+ selectedEnvironments: [
+ (s) => [s.dora, s.doraLoading, s.environments],
+ (dora: DoraOverviewApi | null, doraLoading: boolean, environments: string[]): string[] => {
+ if (doraLoading && environments.length) {
+ const validatedOptions = new Set([
+ ...(dora?.environments ?? []),
+ ...(dora?.selected_environments ?? []),
+ ])
+ return environments.filter((name) => validatedOptions.has(name))
+ }
+ return dora?.selected_environments ?? []
+ },
+ ],
boxPlotBuckets: [
(s) => [s.dora],
(dora: DoraOverviewApi | null): BoxPlotBucket[] =>
@@ -246,27 +285,22 @@ export const doraLogic = kea<doraLogicType>([
(dora?.deployment_frequency_series ?? []).map((bucket) => bucket.bucket_start),
],
environmentScopeLabel: [
- (s) => [s.dora, s.environments],
- (dora: DoraOverviewApi | null, environments: string[]): string =>
- environments.length
- ? environments.join(', ')
- : !dora
- ? 'production'
- : dora.environment_scope === 'persistent'
- ? 'all persistent environments'
- : dora.environment_scope,
+ (s) => [s.dora, s.selectedEnvironments],
+ (dora: DoraOverviewApi | null, selectedEnvironments: string[]): string => {
+ if (selectedEnvironments.length) {
+ return selectedEnvironments.join(', ')
+ }
+ return !dora
+ ? 'production'
+ : dora.environment_scope === 'persistent'
+ ? 'all persistent environments'
+ : dora.environment_scope
+ },
],
- // selected_environments carries the resolved default scope while the selection is empty. Its
- // names can fall outside the capped environments list, so they must be offered explicitly.
- // Picked names stay selectable options.
environmentOptions: [
- (s) => [s.dora, s.environments],
- (dora: DoraOverviewApi | null, environments: string[]): { key: string; label: string }[] => {
- const names = new Set([
- ...(dora?.environments ?? []),
- ...(dora?.selected_environments ?? []),
- ...environments,
- ])
+ (s) => [s.dora],
+ (dora: DoraOverviewApi | null): { key: string; label: string }[] => {
+ const names = new Set([...(dora?.environments ?? []), ...(dora?.selected_environments ?? [])])
return [...names].map((name) => ({ key: name, label: name }))
},
],
@@ -280,6 +314,14 @@ export const doraLogic = kea<doraLogicType>([
}),
listeners(({ actions, values, cache }) => ({
+ loadDoraFailure: ({ errorObject }) => {
+ if (isEnvironmentValidationError(errorObject)) {
+ const selected = values.dora?.selected_environments ?? []
+ actions.restoreEnvironments(
+ hasSameNormalizedEnvironmentSet(values.environments, selected) ? [] : selected
+ )
+ }
+ },
setEnvironments: () => actions.loadDora(),
setGithubTeam: () => actions.loadDora(),
// Grouping and the date range co-adjust, sharing insights' interval mechanism: picking a