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: properly parse and validate list[int] instance settings (#58308)

Paweł Szczur5907467ef1a2
diff --git a/frontend/src/scenes/instance/SystemStatus/InstanceConfigSaveModal.tsx b/frontend/src/scenes/instance/SystemStatus/InstanceConfigSaveModal.tsx
index dc2dcc3e315a..1d0c6573b4dc 100644
--- a/frontend/src/scenes/instance/SystemStatus/InstanceConfigSaveModal.tsx
+++ b/frontend/src/scenes/instance/SystemStatus/InstanceConfigSaveModal.tsx
@@ -11,7 +11,7 @@ import { RenderMetricValue } from './RenderMetricValue'
import { systemStatusLogic } from './systemStatusLogic'
interface ChangeRowInterface extends Pick<SystemStatusRow, 'value'> {
- oldValue?: boolean | string | number | null
+ oldValue?: boolean | string | number | number[] | null
metricKey: string
isSecret?: boolean
}
diff --git a/frontend/src/scenes/instance/SystemStatus/RenderMetricValue.tsx b/frontend/src/scenes/instance/SystemStatus/RenderMetricValue.tsx
index 6c3ba1400dce..1b2581a1fcd0 100644
--- a/frontend/src/scenes/instance/SystemStatus/RenderMetricValue.tsx
+++ b/frontend/src/scenes/instance/SystemStatus/RenderMetricValue.tsx
@@ -9,7 +9,7 @@ const TIMESTAMP_VALUES = new Set(['last_event_ingested_timestamp'])
export interface MetricValue {
key: SystemStatusRow['key']
- value?: SystemStatusRow['value']
+ value?: SystemStatusRow['value'] | number[]
value_type?: InstanceSetting['value_type']
emptyNullLabel?: string
isSecret?: boolean
@@ -53,5 +53,9 @@ export function RenderMetricValue(
return value.toLocaleString('en-US')
}
+ if (Array.isArray(value)) {
+ return value.length > 0 ? value.join(', ') : <LemonTag className="uppercase text-secondary">Empty</LemonTag>
+ }
+
return value.toString()
}
diff --git a/frontend/src/scenes/instance/SystemStatus/RenderMetricValueEdit.tsx b/frontend/src/scenes/instance/SystemStatus/RenderMetricValueEdit.tsx
index cdbaf7dd14e7..d2a7c79ec48b 100644
--- a/frontend/src/scenes/instance/SystemStatus/RenderMetricValueEdit.tsx
+++ b/frontend/src/scenes/instance/SystemStatus/RenderMetricValueEdit.tsx
@@ -29,13 +29,19 @@ export function RenderMetricValueEdit({
)
}
- const parsedValue = isSecret && value ? '' : (value as string | number)
+ const parsedValue = isSecret && value ? '' : Array.isArray(value) ? value.join(', ') : (value as string | number)
return (
<LemonInput
defaultValue={parsedValue as any}
type={value_type === 'int' ? 'number' : 'text'}
- placeholder={isSecret && value ? 'Keep existing secret value' : undefined}
+ placeholder={
+ isSecret && value
+ ? 'Keep existing secret value'
+ : value_type === 'list[int]'
+ ? 'e.g. 1, 2, 3'
+ : undefined
+ }
onBlur={(e) => onValueChanged(key, e.target.value)}
/>
)
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 8a9bf008eb7c..bc1a9152f0ae 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -4901,8 +4901,8 @@ export enum CompareLabelType {
export interface InstanceSetting {
key: string
- value: boolean | string | number | null
- value_type: 'bool' | 'str' | 'int'
+ value: boolean | string | number | number[] | null
+ value_type: 'bool' | 'str' | 'int' | 'list[int]'
description?: string
editable: boolean
is_secret: boolean
diff --git a/posthog/api/instance_settings.py b/posthog/api/instance_settings.py
index 4bf5e1274452..1c3f1f7e81a8 100644
--- a/posthog/api/instance_settings.py
+++ b/posthog/api/instance_settings.py
@@ -1,5 +1,6 @@
import re
-from typing import Any, Optional, Union
+import json
+from typing import Any, Optional, Union, get_args, get_origin
from rest_framework import exceptions, mixins, permissions, serializers, viewsets
@@ -18,14 +19,46 @@ from posthog.settings import (
from posthog.utils import str_to_bool
-def cast_str_to_desired_type(str_value: str, target_type: type) -> Any:
+def cast_str_to_desired_type(value: Any, target_type: type) -> Any:
if target_type is int:
- return int(str_value)
+ return int(value)
if target_type is bool:
- return str_to_bool(str_value)
+ return str_to_bool(value)
+
+ if get_origin(target_type) is list:
+ return _parse_list_value(value, target_type)
+
+ return value
+
+
+def _parse_list_value(value: Any, target_type: type) -> list:
+ args = get_args(target_type)
+ item_type: type = args[0] if args else str
+
+ if isinstance(value, list):
+ items = value
+ elif isinstance(value, str):
+ stripped = value.strip()
+ if not stripped:
+ return []
+ if stripped.startswith("["):
+ try:
+ parsed = json.loads(stripped)
+ except json.JSONDecodeError as e:
+ raise ValueError(f"Invalid JSON array: {e}") from e
+ if not isinstance(parsed, list):
+ raise ValueError(f"Expected a JSON array, got {type(parsed).__name__}")
+ items = parsed
+ else:
+ items = [v.strip() for v in stripped.split(",") if v.strip()]
+ else:
+ raise ValueError(f"Cannot convert {type(value).__name__!r} to {target_type}")
- return str_value
+ try:
+ return [item_type(item) for item in items]
+ except (ValueError, TypeError) as e:
+ raise ValueError(f"All items must be of type {item_type.__name__}: {e}") from e
class InstanceSettingHelper:
@@ -82,7 +115,10 @@ class InstanceSettingsSerializer(serializers.Serializer):
if target_type is bool and isinstance(validated_data["value"], bool):
new_value_parsed = validated_data["value"]
else:
- new_value_parsed = cast_str_to_desired_type(validated_data["value"], target_type)
+ try:
+ new_value_parsed = cast_str_to_desired_type(validated_data["value"], target_type)
+ except (ValueError, TypeError) as e:
+ raise serializers.ValidationError({"value": str(e)})
if instance.key == "RECORDINGS_PERFORMANCE_EVENTS_TTL_WEEKS":
if is_cloud():
diff --git a/posthog/api/test/test_instance_settings.py b/posthog/api/test/test_instance_settings.py
index 669364b7fadb..f32272c3c761 100644
--- a/posthog/api/test/test_instance_settings.py
+++ b/posthog/api/test/test_instance_settings.py
@@ -1,14 +1,53 @@
+import unittest
from posthog.test.base import APIBaseTest
from django.core import mail
+from parameterized import parameterized
from rest_framework import status
-from posthog.api.instance_settings import get_instance_setting as get_instance_setting_helper
+from posthog.api.instance_settings import (
+ cast_str_to_desired_type,
+ get_instance_setting as get_instance_setting_helper,
+)
from posthog.models.instance_setting import get_instance_setting, override_instance_config, set_instance_setting
from posthog.settings import CONSTANCE_CONFIG
+class TestCastStrToDesiredType(unittest.TestCase):
+ @parameterized.expand(
+ [
+ # int
+ ("int_from_str", "42", int, 42),
+ ("int_from_int", 42, int, 42),
+ # bool
+ ("bool_true", "true", bool, True),
+ ("bool_false", "false", bool, False),
+ # str passthrough
+ ("str_passthrough", "hello", str, "hello"),
+ # list[int] — all accepted input formats
+ ("list_from_list", [1, 2, 3], list[int], [1, 2, 3]),
+ ("list_from_csv", "4, 5, 6", list[int], [4, 5, 6]),
+ ("list_from_json_str", "[7, 8, 9]", list[int], [7, 8, 9]),
+ ("list_empty_str", "", list[int], []),
+ ("list_empty_list", [], list[int], []),
+ ]
+ )
+ def test_cast_success(self, _name: str, value: object, target_type: type, expected: object) -> None:
+ self.assertEqual(cast_str_to_desired_type(value, target_type), expected)
+
+ @parameterized.expand(
+ [
+ ("list_non_int_items", "1, two, 3", list[int]),
+ ("list_invalid_json", "[1, 2", list[int]),
+ ("list_non_json_non_list_type", 999, list[int]),
+ ]
+ )
+ def test_cast_raises_on_bad_input(self, _name: str, value: object, target_type: type) -> None:
+ with self.assertRaises((ValueError, TypeError)):
+ cast_str_to_desired_type(value, target_type)
+
+
class TestInstanceSettings(APIBaseTest):
def setUp(self):
super().setUp()
@@ -123,6 +162,36 @@ class TestInstanceSettings(APIBaseTest):
self.assertEqual(response.json()["value"], 48343943943)
self.assertEqual(get_instance_setting("ASYNC_MIGRATIONS_ROLLBACK_TIMEOUT"), 48343943943)
+ def test_update_list_int_setting(self):
+ valid_cases = [
+ ("json_array", [1, 2, 3], [1, 2, 3]),
+ ("comma_separated", "4, 5, 6", [4, 5, 6]),
+ ("json_string", "[7, 8, 9]", [7, 8, 9]),
+ ("empty_string", "", []),
+ ]
+ for name, input_value, expected in valid_cases:
+ with self.subTest(name):
+ response = self.client.patch(
+ "/api/instance_settings/CLICKHOUSE_ENABLE_ANALYZER_TEAMS",
+ {"value": input_value},
+ content_type="application/json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["value"], expected)
+
+ invalid_cases = [
+ ("non_int_items", "1, two, 3"),
+ ("invalid_json", "[1, 2"),
+ ]
+ for name, input_value in invalid_cases:
+ with self.subTest(name):
+ response = self.client.patch(
+ "/api/instance_settings/CLICKHOUSE_ENABLE_ANALYZER_TEAMS",
+ {"value": input_value},
+ content_type="application/json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
def test_cant_update_setting_that_is_not_overridable(self):
response = self.client.patch(f"/api/instance_settings/MATERIALIZED_COLUMNS_ENABLED", {"value": False})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
diff --git a/posthog/clickhouse/client/execute.py b/posthog/clickhouse/client/execute.py
index 0581a394a190..0b288205a858 100644
--- a/posthog/clickhouse/client/execute.py
+++ b/posthog/clickhouse/client/execute.py
@@ -166,14 +166,16 @@ def _get_kill_switch_team_sets(_ttl: int) -> tuple[frozenset[int], frozenset[int
from posthog.models.instance_setting import get_instance_setting
try:
- full_teams = frozenset(get_instance_setting("CLICKHOUSE_KILL_SWITCH_FULL_TEAMS") or [])
+ raw = get_instance_setting("CLICKHOUSE_KILL_SWITCH_FULL_TEAMS")
+ full_teams = frozenset(raw if isinstance(raw, list) else [])
except Exception:
# During an incident, silently falling back to "no override" would hide why the
# per-team kill switch isn't taking effect. Log so operators can see the failure.
logger.exception("Failed to read CLICKHOUSE_KILL_SWITCH_FULL_TEAMS; per-team kill switch disabled for full")
full_teams = frozenset()
try:
- light_teams = frozenset(get_instance_setting("CLICKHOUSE_KILL_SWITCH_LIGHT_TEAMS") or [])
+ raw = get_instance_setting("CLICKHOUSE_KILL_SWITCH_LIGHT_TEAMS")
+ light_teams = frozenset(raw if isinstance(raw, list) else [])
except Exception:
logger.exception("Failed to read CLICKHOUSE_KILL_SWITCH_LIGHT_TEAMS; per-team kill switch disabled for light")
light_teams = frozenset()
diff --git a/posthog/clickhouse/test/test_enable_analyzer.py b/posthog/clickhouse/test/test_enable_analyzer.py
index 76e14be07209..08973fa91e50 100644
--- a/posthog/clickhouse/test/test_enable_analyzer.py
+++ b/posthog/clickhouse/test/test_enable_analyzer.py
@@ -24,6 +24,9 @@ class TestIsEnableAnalyzerTeam:
("none_team", [2, 5, 10], None, False),
("empty_setting", [], 2, False),
("single_team", [7], 7, True),
+ # pre-existing bad DB values (string or None) must not crash and must return False
+ ("string_setting", "2,5,10", 2, False),
+ ("none_setting", None, 2, False),
]
)
def test_returns_expected(self, _name: str, setting_value: list[int], team_id: int | None, expected: bool):
diff --git a/posthog/clickhouse/test/test_kill_switch.py b/posthog/clickhouse/test/test_kill_switch.py
index 8b9728f58e72..e7a70ad5b242 100644
--- a/posthog/clickhouse/test/test_kill_switch.py
+++ b/posthog/clickhouse/test/test_kill_switch.py
@@ -79,6 +79,30 @@ class TestGetTeamKillSwitchLevel:
_get_kill_switch_level.cache_clear()
_get_kill_switch_team_sets.cache_clear()
+ @parameterized.expand(
+ [
+ ("string_full_teams", "1,2,3", [], 1, KillSwitchLevel.OFF),
+ ("none_full_teams", None, [], 1, KillSwitchLevel.OFF),
+ ("string_light_teams", [], "1,2,3", 1, KillSwitchLevel.OFF),
+ ]
+ )
+ def test_non_list_setting_treated_as_empty(
+ self,
+ _name: str,
+ full: object,
+ light: object,
+ team_id: int,
+ expected: KillSwitchLevel,
+ ):
+ _get_kill_switch_team_sets.cache_clear()
+ settings = {
+ "CLICKHOUSE_KILL_SWITCH_FULL_TEAMS": full,
+ "CLICKHOUSE_KILL_SWITCH_LIGHT_TEAMS": light,
+ }
+ with patch("posthog.models.instance_setting.get_instance_setting", side_effect=lambda name: settings[name]):
+ assert get_team_kill_switch_level(team_id) == expected
+ _get_kill_switch_team_sets.cache_clear()
+
def test_team_sets_are_cached(self):
_get_kill_switch_team_sets.cache_clear()
settings = {
diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.py
index 43b2d582525a..3199d23ada82 100644
--- a/posthog/settings/data_stores.py
+++ b/posthog/settings/data_stores.py
@@ -377,7 +377,11 @@ def is_enable_analyzer_team(team_id: int | None) -> bool:
def _get_enable_analyzer_teams(_ttl: int) -> list[int]:
from posthog.models.instance_setting import get_instance_setting
- return get_instance_setting("CLICKHOUSE_ENABLE_ANALYZER_TEAMS")
+ try:
+ value = get_instance_setting("CLICKHOUSE_ENABLE_ANALYZER_TEAMS")
+ return value if isinstance(value, list) else []
+ except Exception:
+ return []
def is_web_analytics_events_prefilter_team(team_id: int | None) -> bool:
@@ -391,7 +395,8 @@ def _get_web_analytics_events_prefilter_teams(_ttl: int) -> list[int]:
from posthog.models.instance_setting import get_instance_setting
try:
- return get_instance_setting("WEB_ANALYTICS_EVENTS_PREFILTER_TEAM_IDS")
+ value = get_instance_setting("WEB_ANALYTICS_EVENTS_PREFILTER_TEAM_IDS")
+ return value if isinstance(value, list) else []
except Exception:
return []
diff --git a/products/web_analytics/dags/cache_warming.py b/products/web_analytics/dags/cache_warming.py
index b8af491ec367..277803799bca 100644
--- a/products/web_analytics/dags/cache_warming.py
+++ b/products/web_analytics/dags/cache_warming.py
@@ -49,7 +49,8 @@ def increment_counter(team_id: int, normalized_query_hash: str, is_cached: bool)
def get_teams_enabled_for_web_analytics_cache_warming() -> list[int]:
- return get_instance_setting("WEB_ANALYTICS_WARMING_TEAMS_TO_WARM")
+ value = get_instance_setting("WEB_ANALYTICS_WARMING_TEAMS_TO_WARM")
+ return value if isinstance(value, list) else []
def queries_to_keep_fresh(