: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(data-warehouse): don't crash on bad variable values or credentials (#70448)
Ben Lead095a8743c1a
diff --git a/frontend/src/lib/lemon-ui/LemonSelect/LemonSelect.tsx b/frontend/src/lib/lemon-ui/LemonSelect/LemonSelect.tsxindex 533bf2be5672..2f54ee6f62eb 100644--- a/frontend/src/lib/lemon-ui/LemonSelect/LemonSelect.tsx+++ b/frontend/src/lib/lemon-ui/LemonSelect/LemonSelect.tsx@@ -188,13 +188,30 @@ export function LemonSelect<T extends string | number | boolean | null>({? renderButtonContent(activeLeaf): activeLeaf? activeLeaf.label- : ((value ?? placeholder) as React.ReactNode)}+ : formatValueFallback(value, placeholder)}</span></LemonButton></LemonMenu>)}+// `value` is typed as a scalar, but data from JSON-backed sources can violate that at+// runtime, and objects aren't valid React children (React error #31) — show them as+// JSON rather than crash the page.+function formatValueFallback(value: unknown, placeholder: string): React.ReactNode {+ if (value == null) {+ return placeholder+ }+ if (typeof value === 'object') {+ try {+ return JSON.stringify(value)+ } catch {+ return String(value)+ }+ }+ return value as React.ReactNode+}+/*** The select can receive `options` that are either Options or Sections.*diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableFields.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableFields.test.tsnew file mode 100644index 000000000000..ba73eefd5582--- /dev/null+++ b/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableFields.test.ts@@ -0,0 +1,38 @@+import { ListVariable } from '../../types'+import { coerceListVariableValue, getListVariableValues } from './VariableFields'++const listVariable = (values: unknown): ListVariable =>+ ({+ id: '1',+ name: 'Test',+ code_name: 'test',+ type: 'List',+ values,+ default_value: '',+ }) as ListVariable++describe('VariableFields', () => {+ // `values` is a JSONField, so API-created variables can hold non-string entries.+ // Rendering those directly crashes React (error #31), so everything must coerce+ // to a string.+ test.each([+ ['strings pass through', ['a', 'b'], ['a', 'b']],+ ['numbers become strings', [1, 2.5], ['1', '2.5']],+ ['booleans become strings', [true, false], ['true', 'false']],+ ['option-shaped objects use their value', [{ label: 'School 1', value: '1' }], ['1']],+ ['label-only objects use their label', [{ label: 'School 2' }], ['School 2']],+ ['unrecognized objects become JSON', [{ foo: 'bar' }], ['{"foo":"bar"}']],+ ['null entries are dropped', [null, 'a', undefined], ['a']],+ ['non-array values become an empty list', 'not-an-array', []],+ ])('getListVariableValues: %s', (_name, values, expected) => {+ expect(getListVariableValues(listVariable(values))).toEqual(expected)+ })++ test.each([+ ['null stays null', null, null],+ ['scalar becomes string', 5, '5'],+ ['array becomes JSON', [1, 2, 3], '[1,2,3]'],+ ])('coerceListVariableValue: %s', (_name, value, expected) => {+ expect(coerceListVariableValue(value)).toBe(expected)+ })+})diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableFields.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableFields.tsxindex e2027743cc1e..67c2356a8da7 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableFields.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableFields.tsx@@ -43,10 +43,45 @@ export const formatVariableReference = (codeName: string): string => {return `{variables.${codeName}}`}-// `values` is backed by a JSONField that can hold non-array data for older records,-// so coerce defensively before mapping/rendering to avoid runtime crashes.+// `values` is backed by a JSONField, so API-created variables can hold entries that+// aren't strings — e.g. option-shaped objects like {label, value} from migration+// scripts. Objects aren't valid React children (React error #31), so everything must+// be coerced to a string before rendering.+export const coerceListVariableValue = (value: unknown): string | null => {+ if (value == null) {+ return null+ }+ if (typeof value === 'string') {+ return value+ }+ if (typeof value === 'number' || typeof value === 'boolean') {+ return String(value)+ }+ if (typeof value === 'object' && !Array.isArray(value)) {+ const record = value as Record<string, unknown>+ for (const key of ['value', 'label']) {+ const inner = record[key]+ if (typeof inner === 'string') {+ return inner+ }+ if (typeof inner === 'number' || typeof inner === 'boolean') {+ return String(inner)+ }+ }+ }+ try {+ return JSON.stringify(value) ?? null+ } catch {+ return String(value)+ }+}++// `values` can also be non-array data for older records, so coerce defensively+// before mapping/rendering to avoid runtime crashes.export const getListVariableValues = (variable: ListVariable): string[] =>- Array.isArray(variable.values) ? variable.values : []+ Array.isArray(variable.values)+ ? variable.values.map(coerceListVariableValue).filter((value): value is string => value !== null)+ : []// Field components for direct prop binding (used in modal)export interface DirectFieldProps<T extends Variable = Variable> {@@ -100,7 +135,7 @@ export const ListDefaultField = ({ variable, updateVariable }: DirectFieldProps<<LemonSelectclassName="w-full"placeholder="Select default value"- value={variable.default_value}+ value={coerceListVariableValue(variable.default_value)}options={getListVariableValues(variable).map((n: string) => ({ label: n, value: n }))}onChange={(value) => updateVariable({ ...variable, default_value: value ?? '' })}allowCleardiff --git a/frontend/src/queries/nodes/DataVisualization/Components/Variables/Variables.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Variables/Variables.tsxindex 465b3c8629b2..d16e4121c05c 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Variables/Variables.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/Variables/Variables.tsx@@ -26,7 +26,7 @@ import { dataVisualizationLogic } from '../../dataVisualizationLogic'import { Variable } from '../../types'import { NewVariableModal } from './NewVariableModal'import { VariableCalendar } from './VariableCalendar'-import { getListVariableValues } from './VariableFields'+import { coerceListVariableValue, getListVariableValues } from './VariableFields'import { variableModalLogic } from './variableModalLogic'import { variablesLogic } from './variablesLogic'@@ -121,6 +121,10 @@ export const VariableInput = ({return dayjs().format('YYYY-MM-DD HH:mm:00')}+ if (variable.type === 'List') {+ return coerceListVariableValue(val) ?? ''+ }+return String(val ?? '')})const [isNull, setIsNull] = useState<boolean>(variable.isNull ?? false)@@ -130,7 +134,7 @@ export const VariableInput = ({useEffect(() => {inputRef.current?.focus()- }, [inputRef.current])+ }, [])const variableAsHogQL = `{variables.${variable.code_name}}`@@ -346,7 +350,7 @@ export const VariableComponent = ({<LemonField.Pure label={variable.name} className="gap-0" info={tooltip}><LemonSelectdisabledReason={variableOverridesAreSet && 'Discard dashboard variables to change'}- value={variable.isNull ? null : (variable.value ?? variable.default_value ?? null)}+ value={variable.isNull ? null : coerceListVariableValue(variable.value ?? variable.default_value)}onChange={(value) => onChange(variable.id, value, !value)}options={getListVariableValues(variable).map((n) => ({ label: n, value: n }))}size={size}diff --git a/frontend/src/scenes/data-management/variables/SqlVariableEditScene.tsx b/frontend/src/scenes/data-management/variables/SqlVariableEditScene.tsxindex 032df53d5243..0f2ca6d54fc3 100644--- a/frontend/src/scenes/data-management/variables/SqlVariableEditScene.tsx+++ b/frontend/src/scenes/data-management/variables/SqlVariableEditScene.tsx@@ -20,11 +20,16 @@ import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'-import { ListVariable, Variable, VariableType } from '~/queries/nodes/DataVisualization/types'+import { getListVariableValues } from '~/queries/nodes/DataVisualization/Components/Variables/VariableFields'+import { ListVariable, VariableType } from '~/queries/nodes/DataVisualization/types'import { VARIABLE_TYPE_OPTIONS, formatVariableReference, getCodeName } from './constants'import { VARIABLE_INSIGHT_COLUMNS } from './insightColumns'-import { SqlVariableEditSceneLogicProps, sqlVariableEditSceneLogic } from './sqlVariableEditSceneLogic'+import {+ SqlVariableEditSceneLogicProps,+ sqlVariableEditSceneLogic,+ variableToFormValues,+} from './sqlVariableEditSceneLogic'export const scene: SceneExport<SqlVariableEditSceneLogicProps> = {component: SqlVariableEditScene,@@ -91,7 +96,7 @@ function VariableTypeFields(): JSX.Element {className="w-full"placeholder="Select default value"value={value}- options={((variableForm as ListVariable).values || []).map((n: string) => ({+ options={getListVariableValues(variableForm as ListVariable).map((n: string) => ({label: n,value: n,}))}@@ -163,13 +168,7 @@ export function SqlVariableEditScene(): JSX.Element {disabledReason={!isNew && !hasChanges ? 'No changes to discard' : undefined}onClick={() => {if (variable) {- resetVariableForm({- name: variable.name,- type: variable.type,- default_value: variable.default_value,- code_name: variable.code_name,- ...('values' in variable && { values: variable.values }),- } as Partial<Variable>)+ resetVariableForm(variableToFormValues(variable))setVariableType(variable.type)}}}diff --git a/frontend/src/scenes/data-management/variables/sqlVariableEditSceneLogic.ts b/frontend/src/scenes/data-management/variables/sqlVariableEditSceneLogic.tsindex ad4eb04e3285..af91bc23d67f 100644--- a/frontend/src/scenes/data-management/variables/sqlVariableEditSceneLogic.ts+++ b/frontend/src/scenes/data-management/variables/sqlVariableEditSceneLogic.ts@@ -9,7 +9,11 @@ import api from 'lib/api'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'-import { Variable, VariableType } from '~/queries/nodes/DataVisualization/types'+import {+ coerceListVariableValue,+ getListVariableValues,+} from '~/queries/nodes/DataVisualization/Components/Variables/VariableFields'+import { ListVariable, Variable, VariableType } from '~/queries/nodes/DataVisualization/types'import { QueryBasedInsightModel } from '~/types'import { fetchInsightsUsingVariable } from './insightsLoader'@@ -26,6 +30,19 @@ const NEW_VARIABLE_DEFAULTS: Partial<Variable> = {code_name: '',}+// List `values` come from a JSONField and may hold non-string entries (e.g. objects+// from API-created variables), which crash React if rendered — sanitize on the way+// into the form so editing and saving repairs them.+export const variableToFormValues = (variable: Variable): Partial<Variable> =>+ ({+ name: variable.name,+ type: variable.type,+ default_value:+ variable.type === 'List' ? (coerceListVariableValue(variable.default_value) ?? '') : variable.default_value,+ code_name: variable.code_name,+ ...(variable.type === 'List' && { values: getListVariableValues(variable as ListVariable) }),+ }) as Partial<Variable>+export const sqlVariableEditSceneLogic = kea<sqlVariableEditSceneLogicType>([props({} as SqlVariableEditSceneLogicProps),path(['scenes', 'data-management', 'variables', 'sqlVariableEditSceneLogic']),@@ -135,14 +152,23 @@ export const sqlVariableEditSceneLogic = kea<sqlVariableEditSceneLogicType>([if (!variable || variableLoading) {return false}+ // Normalize the saved side exactly as `variableToFormValues` normalizes the+ // form, otherwise a freshly loaded List variable holding legacy (non-string)+ // values compares unequal to its own coerced form and reports perpetual changes.+ const isList = variable.type === 'List'const defaultValueForm = variableForm.default_value ?? ''- const defaultValueSaved = variable.default_value ?? ''+ const defaultValueSaved = isList+ ? (coerceListVariableValue(variable.default_value) ?? '')+ : (variable.default_value ?? '')+ const valuesForm = (variableForm as any).values ?? null+ const valuesSaved = isList+ ? getListVariableValues(variable as ListVariable)+ : ((variable as any).values ?? null)return ((variableForm.name ?? '') !== (variable.name ?? '') ||variableType !== variable.type ||JSON.stringify(defaultValueForm) !== JSON.stringify(defaultValueSaved) ||- JSON.stringify((variableForm as any).values ?? null) !==- JSON.stringify((variable as any).values ?? null)+ JSON.stringify(valuesForm) !== JSON.stringify(valuesSaved))},],@@ -164,17 +190,7 @@ export const sqlVariableEditSceneLogic = kea<sqlVariableEditSceneLogicType>([listeners(({ actions }) => ({loadVariableSuccess: ({ variable }: { variable: Variable | null }) => {if (variable) {- // TypeScript can't narrow discriminated union types properly here,- // but we know the data is valid since it comes from a typed Variable object- const formValues = {- name: variable.name,- type: variable.type,- default_value: variable.default_value,- code_name: variable.code_name,- ...(variable.type === 'List' && { values: (variable as any).values }),- } as Partial<Variable>-- actions.resetVariableForm(formValues)+ actions.resetVariableForm(variableToFormValues(variable))actions.loadInsightsUsingVariable()}},diff --git a/frontend/src/scenes/data-pipelines/DataPipelinesSelfManagedSource.tsx b/frontend/src/scenes/data-pipelines/DataPipelinesSelfManagedSource.tsxindex 46bbd8829717..0c2357fc9d64 100644--- a/frontend/src/scenes/data-pipelines/DataPipelinesSelfManagedSource.tsx+++ b/frontend/src/scenes/data-pipelines/DataPipelinesSelfManagedSource.tsx@@ -38,10 +38,10 @@ export function DataPipelinesSelfManagedSourceTable({ table, updateTable }: Prop...(table.credential?.access_key || table.credential?.access_secret? {credential: {- ...(table.credential.access_key+ ...(table.credential?.access_key? { access_key: table.credential.access_key }: {}),- ...(table.credential.access_secret+ ...(table.credential?.access_secret? { access_secret: table.credential.access_secret }: {}),},diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 34355fc51879..9f43fe39946c 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5999,7 +5999,8 @@ export interface DataWarehouseTable {name: stringformat: DataWarehouseTableTypesurl_pattern: string- credential: DataWarehouseCredential+ /** Null for tables without user-provided credentials, e.g. created by a managed pipeline. */+ credential: DataWarehouseCredential | nullexternal_data_source?: ExternalDataSourceexternal_schema?: SimpleExternalDataSourceSchemaoptions?: { csv_allow_double_quotes?: boolean | null }diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/selfManagedSourceLogic.test.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/selfManagedSourceLogic.test.tsnew file mode 100644index 000000000000..2c1837f3025c--- /dev/null+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/selfManagedSourceLogic.test.ts@@ -0,0 +1,35 @@+import { DataWarehouseTable } from '~/types'++import { selfManagedTableFormErrors } from './selfManagedSourceLogic'++const validTable: Partial<DataWarehouseTable> = {+ name: 'stripe_invoices',+ url_pattern: 'https://your-org.s3.amazonaws.com/invoices/*.pqt',+ format: 'Parquet',+ credential: { access_key: 'key', access_secret: 'secret' },+}++describe('selfManagedTableFormErrors', () => {+ // The API serves `credential: null` for tables saved without one (e.g. created by a+ // managed pipeline) — reading through it used to crash the source scene.+ it('validates a table with a null credential instead of throwing', () => {+ const errors = selfManagedTableFormErrors({ ...validTable, credential: null })++ expect(errors.credential).toEqual({+ access_key: 'Please enter an access key.',+ access_secret: 'Please enter an access secret.',+ })+ expect(errors.name).toBeFalsy()+ expect(errors.url_pattern).toBeFalsy()+ expect(errors.format).toBeFalsy()+ })++ it('returns no errors for a fully valid table', () => {+ const errors = selfManagedTableFormErrors(validTable)++ expect(errors.name).toBeFalsy()+ expect(errors.url_pattern).toBeFalsy()+ expect(errors.format).toBeFalsy()+ expect(errors.credential).toEqual({ access_key: false, access_secret: false })+ })+})diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/selfManagedSourceLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/selfManagedSourceLogic.tsxindex 59ea52205c11..f06cc8e342dc 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/selfManagedSourceLogic.tsx+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/selfManagedSourceLogic.tsx@@ -32,6 +32,48 @@ const NEW_WAREHOUSE_TABLE: DataWarehouseTable = {},}+// `credential` is null on tables saved without one (the API only enforces credentials on+// creation via this form), so it must be guarded — reading through it crashed the page.+export function selfManagedTableFormErrors({+ name,+ url_pattern,+ credential,+ format,+}: Partial<DataWarehouseTable>): Record<string, unknown> {+ const HOGQL_TABLE_NAME_REGEX = /^[a-zA-Z_][a-zA-Z0-9_]*$/+ // Let the empty-name case fall through to the friendlier "Please enter a name." below,+ // rather than the naming-rules error which only makes sense once something's been typed.+ if (name && !HOGQL_TABLE_NAME_REGEX.test(name)) {+ return {+ name: 'Invalid table name. Table names must start with a letter or underscore and contain only alphanumeric characters or underscores.',+ }+ }++ if (url_pattern?.startsWith('s3://')) {+ return {+ url_pattern:+ 'Please use the https version of your bucket url e.g. https://your-org.s3.amazonaws.com/airbyte/stripe/invoices/*.pqt',+ }+ }++ if (url_pattern?.startsWith('https://storage.cloud.google.com')) {+ return {+ url_pattern:+ 'Google Cloud links must start with "https://storage.googleapis.com". Please update your URL pattern.',+ }+ }++ return {+ name: !name && 'Please enter a name.',+ url_pattern: !url_pattern && 'Please enter a url pattern.',+ credential: {+ access_secret: !credential?.access_secret && 'Please enter an access secret.',+ access_key: !credential?.access_key && 'Please enter an access key.',+ },+ format: !format && 'Please enter the format of your files.',+ }+}+export const selfManagedSourceLogic = kea<selfManagedSourceLogicType>([path(['products', 'dataWarehouse', 'selfManagedSourceLogic']),props({} as TableLogicProps),@@ -101,40 +143,7 @@ export const selfManagedSourceLogic = kea<selfManagedSourceLogicType>([forms(({ actions, props }) => ({table: {defaults: { ...NEW_WAREHOUSE_TABLE } as DataWarehouseTable,- errors: ({ name, url_pattern, credential, format }) => {- const HOGQL_TABLE_NAME_REGEX = /^[a-zA-Z_][a-zA-Z0-9_]*$/- // Let the empty-name case fall through to the friendlier "Please enter a name." below,- // rather than the naming-rules error which only makes sense once something's been typed.- if (name && !HOGQL_TABLE_NAME_REGEX.test(name)) {- return {- name: 'Invalid table name. Table names must start with a letter or underscore and contain only alphanumeric characters or underscores.',- }- }-- if (url_pattern?.startsWith('s3://')) {- return {- url_pattern:- 'Please use the https version of your bucket url e.g. https://your-org.s3.amazonaws.com/airbyte/stripe/invoices/*.pqt',- }- }-- if (url_pattern?.startsWith('https://storage.cloud.google.com')) {- return {- url_pattern:- 'Google Cloud links must start with "https://storage.googleapis.com". Please update your URL pattern.',- }- }-- return {- name: !name && 'Please enter a name.',- url_pattern: !url_pattern && 'Please enter a url pattern.',- credential: {- access_secret: !credential.access_secret && 'Please enter an access secret.',- access_key: !credential.access_key && 'Please enter an access key.',- },- format: !format && 'Please enter the format of your files.',- }- },+ errors: selfManagedTableFormErrors,submit: async (tablePayload) => {try {if (props.id && props.id !== 'new') {diff --git a/products/product_analytics/backend/api/insight_variable.py b/products/product_analytics/backend/api/insight_variable.pyindex fabaf72c4243..cc09562bd188 100644--- a/products/product_analytics/backend/api/insight_variable.py+++ b/products/product_analytics/backend/api/insight_variable.py@@ -1,3 +1,5 @@+import json+from django_filters.rest_framework import DjangoFilterBackendfrom drf_spectacular.utils import extend_schemafrom rest_framework import pagination, serializers, viewsets@@ -11,6 +13,36 @@ from posthog.auth import SharingAccessTokenAuthentication, SharingPasswordProtecfrom products.product_analytics.backend.models.insight_variable import InsightVariable+def _scalar_to_str(value: object) -> str | None:+ """Coerce a scalar to its string form, or None if it isn't a scalar."""+ if isinstance(value, str):+ return value+ if isinstance(value, bool):+ # bool before int/float: bool is an int subclass, and the UI uses lowercase+ return "true" if value else "false"+ if isinstance(value, int | float):+ return str(value)+ return None+++def _coerce_list_value_lenient(value: object) -> str | None:+ """Mirror the frontend's read-side coercion: option-shaped objects use their+ value/label, scalars stringify, null drops, anything else renders as JSON. Never+ raises — used on read so legacy rows round-trip cleanly instead of failing a later+ write against the stricter validation."""+ if value is None:+ return None+ scalar = _scalar_to_str(value)+ if scalar is not None:+ return scalar+ if isinstance(value, dict):+ for key in ("value", "label"):+ inner = _scalar_to_str(value.get(key))+ if inner is not None:+ return inner+ return json.dumps(value)++class InsightVariableSerializer(serializers.ModelSerializer):class Meta:model = InsightVariable@@ -34,18 +66,48 @@ class InsightVariableSerializer(serializers.ModelSerializer):def validate(self, attrs):variable_type = attrs.get("type", getattr(self.instance, "type", None))if variable_type == InsightVariable.Type.LIST:- values = attrs.get("values", getattr(self.instance, "values", None))- if not isinstance(values, list):- attrs["values"] = []+ # Only validate `values` when the payload provides it — instance data may hold+ # legacy shapes that shouldn't block unrelated updates (reads normalize them).+ if "values" in attrs:+ values = attrs["values"]+ attrs["values"] = self._coerce_list_values(values) if isinstance(values, list) else []+ # `default_value` is a single option; coerce leniently so a legacy shape or a+ # round-tripped read can't be stored as non-string (the UI treats it as text).+ if "default_value" in attrs:+ attrs["default_value"] = _coerce_list_value_lenient(attrs["default_value"]) or ""return attrs+ def _coerce_list_values(self, values: list) -> list[str]:+ coerced: list[str] = []+ for index, value in enumerate(values):+ if value is None:+ continue+ scalar = _scalar_to_str(value)+ if scalar is None:+ shape = "an object" if isinstance(value, dict) else "an array"+ raise ValidationError(+ {+ "values": f"List variable values must be strings or numbers (got {shape} at index {index}). Enter each value as plain text or a number."+ }+ )+ coerced.append(scalar)+ return coerced+def to_representation(self, instance):data = super().to_representation(instance)- # `values` is a JSONField; older List records may hold null or a non-array- # value, which crashes clients that iterate it. Always present an array.- if instance.type == InsightVariable.Type.LIST and not isinstance(data.get("values"), list):- data["values"] = []+ # `values` is a JSONField; older List records may hold null, a non-array value, or+ # non-string elements (e.g. option-shaped objects). Normalize on read so clients+ # always get a clean string array — and so writing this data back round-trips+ # instead of tripping the stricter write validation.+ if instance.type == InsightVariable.Type.LIST:+ raw_values = data.get("values")+ data["values"] = (+ [coerced for value in raw_values if (coerced := _coerce_list_value_lenient(value)) is not None]+ if isinstance(raw_values, list)+ else []+ )+ data["default_value"] = _coerce_list_value_lenient(data.get("default_value"))return datadef create(self, validated_data):diff --git a/products/product_analytics/backend/api/test/test_insight_variable.py b/products/product_analytics/backend/api/test/test_insight_variable.pyindex 801e509be150..6aafbea38378 100644--- a/products/product_analytics/backend/api/test/test_insight_variable.py+++ b/products/product_analytics/backend/api/test/test_insight_variable.py@@ -169,6 +169,63 @@ class TestInsightVariable(APIBaseTest):variable.refresh_from_db()assert variable.values == []+ @parameterized.expand(+ [+ ("object_elements", [{"label": "School 1", "value": "1"}], 400, None),+ ("array_elements", [["nested"]], 400, None),+ ("numeric_elements", [1, 2.5], 200, ["1", "2.5"]),+ ("boolean_elements", [True], 200, ["true"]),+ ("null_elements_dropped", [None, "a"], 200, ["a"]),+ ]+ )+ def test_update_list_variable_values_element_shapes(self, _name, new_values, expected_status, expected_values):+ variable = InsightVariable.objects.create(+ team=self.team, name="List Var", type="List", code_name="list_var", values=["a"]+ )+ response = self.client.patch(+ f"/api/environments/{self.team.pk}/insight_variables/{variable.id}/",+ data={"values": new_values},+ content_type="application/json",+ )+ assert response.status_code == expected_status+ variable.refresh_from_db()+ if expected_status == 200:+ assert response.json()["values"] == expected_values+ assert variable.values == expected_values+ else:+ assert response.json()["attr"] == "values"+ assert variable.values == ["a"]++ def test_update_unrelated_field_with_legacy_object_values_succeeds(self):+ legacy_values = [{"label": "School 1", "value": "1"}]+ variable = InsightVariable.objects.create(+ team=self.team, name="List Var", type="List", code_name="list_var", values=legacy_values+ )+ response = self.client.patch(+ f"/api/environments/{self.team.pk}/insight_variables/{variable.id}/",+ data={"name": "Renamed"},+ content_type="application/json",+ )+ assert response.status_code == 200+ variable.refresh_from_db()+ assert variable.name == "Renamed"+ assert variable.values == legacy_values++ def test_list_variable_with_legacy_values_is_coerced_on_read(self):+ variable = InsightVariable.objects.create(+ team=self.team,+ name="List Var",+ type="List",+ code_name="list_var",+ values=[{"label": "School 1", "value": "1"}, 2, None, "keep"],+ default_value={"value": "1"},+ )+ response = self.client.get(f"/api/environments/{self.team.pk}/insight_variables/{variable.id}/")+ assert response.status_code == 200+ body = response.json()+ assert body["values"] == ["1", "2", "keep"]+ assert body["default_value"] == "1"+def test_update_type_to_list_coerces_null_values(self):variable = InsightVariable.objects.create(team=self.team, name="Str Var", type="String", code_name="str_var")response = self.client.patch(