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(insights): handle non-array values on List SQL variables (#62019)

Sam Pennington7ca467e29da6
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableFields.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableFields.tsx
index 6d9b15dc7ba5..e2027743cc1e 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableFields.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Variables/VariableFields.tsx
@@ -43,6 +43,11 @@ 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.
+export const getListVariableValues = (variable: ListVariable): string[] =>
+ Array.isArray(variable.values) ? variable.values : []
+
// Field components for direct prop binding (used in modal)
export interface DirectFieldProps<T extends Variable = Variable> {
variable: T
@@ -81,7 +86,7 @@ export const BooleanField = ({ variable, updateVariable }: DirectFieldProps<Bool
export const ListValuesField = ({ variable, updateVariable }: DirectFieldProps<ListVariable>): JSX.Element => (
<LemonInputSelect
- value={variable.values}
+ value={getListVariableValues(variable)}
onChange={(value) => updateVariable({ ...variable, values: value })}
placeholder="Options..."
mode="multiple"
@@ -96,7 +101,7 @@ export const ListDefaultField = ({ variable, updateVariable }: DirectFieldProps<
className="w-full"
placeholder="Select default value"
value={variable.default_value}
- options={(variable.values ?? []).map((n: string) => ({ label: n, value: n }))}
+ options={getListVariableValues(variable).map((n: string) => ({ label: n, value: n }))}
onChange={(value) => updateVariable({ ...variable, default_value: value ?? '' })}
allowClear
dropdownMaxContentWidth
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Variables/Variables.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Variables/Variables.tsx
index 98de6a30a3a4..465b3c8629b2 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Variables/Variables.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Variables/Variables.tsx
@@ -26,6 +26,7 @@ import { dataVisualizationLogic } from '../../dataVisualizationLogic'
import { Variable } from '../../types'
import { NewVariableModal } from './NewVariableModal'
import { VariableCalendar } from './VariableCalendar'
+import { getListVariableValues } from './VariableFields'
import { variableModalLogic } from './variableModalLogic'
import { variablesLogic } from './variablesLogic'
@@ -185,7 +186,7 @@ export const VariableInput = ({
className="grow"
value={localInputValue}
onChange={(value) => setLocalInputValue(String(value))}
- options={(variable.values ?? []).map((n) => ({ label: n, value: n }))}
+ options={getListVariableValues(variable).map((n) => ({ label: n, value: n }))}
/>
)}
{variable.type === 'Date' && (
@@ -347,7 +348,7 @@ export const VariableComponent = ({
disabledReason={variableOverridesAreSet && 'Discard dashboard variables to change'}
value={variable.isNull ? null : (variable.value ?? variable.default_value ?? null)}
onChange={(value) => onChange(variable.id, value, !value)}
- options={(variable.values ?? []).map((n) => ({ label: n, value: n }))}
+ options={getListVariableValues(variable).map((n) => ({ label: n, value: n }))}
size={size}
allowClear
/>
diff --git a/products/product_analytics/backend/api/insight_variable.py b/products/product_analytics/backend/api/insight_variable.py
index 5d837e18c74e..fabaf72c4243 100644
--- a/products/product_analytics/backend/api/insight_variable.py
+++ b/products/product_analytics/backend/api/insight_variable.py
@@ -35,11 +35,19 @@ class InsightVariableSerializer(serializers.ModelSerializer):
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 values is None:
+ if not isinstance(values, list):
attrs["values"] = []
return attrs
+ 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"] = []
+ return data
+
def create(self, validated_data):
validated_data["team_id"] = self.context["team_id"]
validated_data["created_by"] = self.context["request"].user
diff --git a/products/product_analytics/backend/api/test/test_insight_variable.py b/products/product_analytics/backend/api/test/test_insight_variable.py
index 165ba9922299..801e509be150 100644
--- a/products/product_analytics/backend/api/test/test_insight_variable.py
+++ b/products/product_analytics/backend/api/test/test_insight_variable.py
@@ -133,6 +133,42 @@ class TestInsightVariable(APIBaseTest):
assert response.status_code == 200
assert response.json()["values"] == ["a", "b", "c"]
+ @parameterized.expand(
+ [
+ ("null_values", None),
+ ("dict_values", {"unexpected": "shape"}),
+ ("string_values", "not-a-list"),
+ ]
+ )
+ def test_list_variable_with_non_array_values_is_normalized_on_read(self, _name, stored_values):
+ variable = InsightVariable.objects.create(
+ team=self.team, name="List Var", type="List", code_name="list_var", values=stored_values
+ )
+ response = self.client.get(f"/api/environments/{self.team.pk}/insight_variables/{variable.id}/")
+ assert response.status_code == 200
+ assert response.json()["values"] == []
+
+ @parameterized.expand(
+ [
+ ("null_values", None),
+ ("dict_values", {"unexpected": "shape"}),
+ ("string_values", "not-a-list"),
+ ]
+ )
+ def test_update_list_variable_with_non_array_values_coerces_to_empty_list(self, _name, new_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 == 200
+ assert response.json()["values"] == []
+ variable.refresh_from_db()
+ assert variable.values == []
+
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(