: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
feat(clickhouse): per-team kill switch override (#58257)
posthog[bot]7d51a3364d6e
diff --git a/frontend/src/scenes/instance/SystemStatus/systemStatusLogic.ts b/frontend/src/scenes/instance/SystemStatus/systemStatusLogic.tsindex 44e4f469bcea..b43349c9c864 100644--- a/frontend/src/scenes/instance/SystemStatus/systemStatusLogic.ts+++ b/frontend/src/scenes/instance/SystemStatus/systemStatusLogic.ts@@ -59,6 +59,8 @@ const EDITABLE_INSTANCE_SETTINGS = ['RATE_LIMIT_ENABLED','RATE_LIMITING_ALLOW_LIST_TEAMS','CLICKHOUSE_KILL_SWITCH',+ 'CLICKHOUSE_KILL_SWITCH_LIGHT_TEAMS',+ 'CLICKHOUSE_KILL_SWITCH_FULL_TEAMS','CLICKHOUSE_HEDGED_APP_QUERIES','CLICKHOUSE_ENABLE_ANALYZER_TEAMS','SENTRY_AUTH_TOKEN',diff --git a/posthog/clickhouse/client/execute.py b/posthog/clickhouse/client/execute.pyindex 08dc76d46940..0581a394a190 100644--- a/posthog/clickhouse/client/execute.py+++ b/posthog/clickhouse/client/execute.py@@ -112,11 +112,33 @@ _KILL_SWITCH_SETTINGS: dict[KillSwitchLevel, dict[str, int]] = {},}+_KILL_SWITCH_SEVERITY: dict[KillSwitchLevel, int] = {+ KillSwitchLevel.OFF: 0,+ KillSwitchLevel.LIGHT: 1,+ KillSwitchLevel.FULL: 2,+}+def get_kill_switch_level() -> KillSwitchLevel:return _get_kill_switch_level(round(time.time() / 60))+def get_team_kill_switch_level(team_id: int) -> KillSwitchLevel:+ """+ Per-team kill switch override.++ Returns FULL or LIGHT if `team_id` is in the corresponding admin-managed list,+ else OFF. This is independent of the global `CLICKHOUSE_KILL_SWITCH` — callers+ that want the combined effect should take the more severe of the two levels.+ """+ full_teams, light_teams = _get_kill_switch_team_sets(round(time.time() / 60))+ if team_id in full_teams:+ return KillSwitchLevel.FULL+ if team_id in light_teams:+ return KillSwitchLevel.LIGHT+ return KillSwitchLevel.OFF++def get_hedged_app_queries_enabled() -> bool:return _get_hedged_app_queries_enabled(round(time.time() / 60))@@ -139,6 +161,45 @@ def _get_kill_switch_level(_ttl: int) -> KillSwitchLevel:return KillSwitchLevel.OFF+@lru_cache(maxsize=1)+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 [])+ 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 [])+ except Exception:+ logger.exception("Failed to read CLICKHOUSE_KILL_SWITCH_LIGHT_TEAMS; per-team kill switch disabled for light")+ light_teams = frozenset()+ return full_teams, light_teams+++def resolve_kill_switch_level(team_id: Optional[int]) -> KillSwitchLevel:+ """+ Effective kill switch level: the more severe of the global level and any+ per-team override. If `team_id` is None, returns the global level unchanged.++ Examples:+ - global=light, team=full -> full+ - global=full, team=light -> full+ - global=off, team=light -> light+ - global=light, team=off -> light+ """+ level = get_kill_switch_level()+ if team_id is None:+ return level+ team_level = get_team_kill_switch_level(team_id)+ if _KILL_SWITCH_SEVERITY[team_level] > _KILL_SWITCH_SEVERITY[level]:+ return team_level+ return level++@lru_cache(maxsize=1)def default_settings() -> dict:# https://clickhouse.com/blog/clickhouse-fully-supports-joins-how-to-choose-the-right-algorithm-part5@@ -283,7 +344,7 @@ def sync_execute(if team_id is not None and is_enable_analyzer_team(team_id):core_settings.setdefault("enable_analyzer", 1)- kill_switch_level = KillSwitchLevel.OFF if TEST else get_kill_switch_level()+ kill_switch_level = KillSwitchLevel.OFF if TEST else resolve_kill_switch_level(team_id)if kill_switch_level != KillSwitchLevel.OFF and ch_user not in _KILL_SWITCH_EXEMPT_USERS:overrides = _KILL_SWITCH_SETTINGS[kill_switch_level]core_settings.update({k: min(core_settings.get(k, v), v) for k, v in overrides.items()})diff --git a/posthog/clickhouse/test/test_kill_switch.py b/posthog/clickhouse/test/test_kill_switch.pyindex b6818d230c2f..8b9728f58e72 100644--- a/posthog/clickhouse/test/test_kill_switch.py+++ b/posthog/clickhouse/test/test_kill_switch.py@@ -6,8 +6,11 @@ from posthog.clickhouse.client.execute import (_KILL_SWITCH_SETTINGS,KillSwitchLevel,_get_kill_switch_level,+ _get_kill_switch_team_sets,default_settings,get_kill_switch_level,+ get_team_kill_switch_level,+ resolve_kill_switch_level,)@@ -36,6 +39,102 @@ class TestGetKillSwitchLevel:_get_kill_switch_level.cache_clear()+class TestGetTeamKillSwitchLevel:+ @parameterized.expand(+ [+ ("team_in_full_list_gets_full", [42], [], 42, KillSwitchLevel.FULL),+ ("team_in_light_list_gets_light", [], [42], 42, KillSwitchLevel.LIGHT),+ ("team_not_in_any_list_is_off", [99], [99], 42, KillSwitchLevel.OFF),+ ("team_in_both_lists_picks_full", [42], [42], 42, KillSwitchLevel.FULL),+ ]+ )+ def test_per_team_lookup(+ self,+ _name: str,+ full: list[int],+ light: list[int],+ 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_global_get_kill_switch_level_ignores_per_team_lists(self):+ """The global resolver must remain unchanged — per-team overrides are opt-in."""+ _get_kill_switch_level.cache_clear()+ _get_kill_switch_team_sets.cache_clear()+ settings = {+ "CLICKHOUSE_KILL_SWITCH": "off",+ "CLICKHOUSE_KILL_SWITCH_FULL_TEAMS": [42],+ "CLICKHOUSE_KILL_SWITCH_LIGHT_TEAMS": [],+ }+ with patch("posthog.models.instance_setting.get_instance_setting", side_effect=lambda name: settings[name]):+ assert get_kill_switch_level() == KillSwitchLevel.OFF+ _get_kill_switch_level.cache_clear()+ _get_kill_switch_team_sets.cache_clear()++ def test_team_sets_are_cached(self):+ _get_kill_switch_team_sets.cache_clear()+ settings = {+ "CLICKHOUSE_KILL_SWITCH_FULL_TEAMS": [42],+ "CLICKHOUSE_KILL_SWITCH_LIGHT_TEAMS": [7],+ }+ mock = MagicMock(side_effect=lambda name: settings[name])+ with patch("posthog.models.instance_setting.get_instance_setting", mock):+ get_team_kill_switch_level(42)+ get_team_kill_switch_level(42)+ # 2 calls for the per-team sets (full + light) over the same minute, no additional calls on the second invocation+ assert mock.call_count == 2+ _get_kill_switch_team_sets.cache_clear()+++class TestResolveKillSwitchLevel:+ """+ Exercises the real precedence resolver used by `sync_execute`. The effective level+ must be the more severe of the global level and any per-team override.+ """++ @parameterized.expand(+ [+ ("global_light_team_full_wins_full", KillSwitchLevel.LIGHT, KillSwitchLevel.FULL, KillSwitchLevel.FULL),+ ("global_full_team_light_wins_full", KillSwitchLevel.FULL, KillSwitchLevel.LIGHT, KillSwitchLevel.FULL),+ ("global_off_team_full_wins_full", KillSwitchLevel.OFF, KillSwitchLevel.FULL, KillSwitchLevel.FULL),+ ("global_off_team_light_wins_light", KillSwitchLevel.OFF, KillSwitchLevel.LIGHT, KillSwitchLevel.LIGHT),+ ("global_light_team_off_wins_light", KillSwitchLevel.LIGHT, KillSwitchLevel.OFF, KillSwitchLevel.LIGHT),+ ("global_full_team_off_wins_full", KillSwitchLevel.FULL, KillSwitchLevel.OFF, KillSwitchLevel.FULL),+ ("global_off_team_off_is_off", KillSwitchLevel.OFF, KillSwitchLevel.OFF, KillSwitchLevel.OFF),+ ("global_full_team_full_is_full", KillSwitchLevel.FULL, KillSwitchLevel.FULL, KillSwitchLevel.FULL),+ ]+ )+ def test_precedence(+ self,+ _name: str,+ global_level: KillSwitchLevel,+ team_level: KillSwitchLevel,+ expected: KillSwitchLevel,+ ):+ with (+ patch("posthog.clickhouse.client.execute.get_kill_switch_level", return_value=global_level),+ patch("posthog.clickhouse.client.execute.get_team_kill_switch_level", return_value=team_level),+ ):+ assert resolve_kill_switch_level(team_id=42) == expected++ def test_none_team_id_returns_global_only(self):+ team_mock = MagicMock(return_value=KillSwitchLevel.FULL)+ with (+ patch("posthog.clickhouse.client.execute.get_kill_switch_level", return_value=KillSwitchLevel.LIGHT),+ patch("posthog.clickhouse.client.execute.get_team_kill_switch_level", team_mock),+ ):+ assert resolve_kill_switch_level(team_id=None) == KillSwitchLevel.LIGHT+ team_mock.assert_not_called()++class TestKillSwitchResourceLimits:@parameterized.expand([diff --git a/posthog/settings/dynamic_settings.py b/posthog/settings/dynamic_settings.pyindex 00984c04daaf..ff359e537176 100644--- a/posthog/settings/dynamic_settings.py+++ b/posthog/settings/dynamic_settings.py@@ -234,6 +234,16 @@ CONSTANCE_CONFIG = {"ClickHouse overload protection. Values: 'off', 'light' (reduce resources, shed background work), 'full' (aggressive caps on everything).",str,),+ "CLICKHOUSE_KILL_SWITCH_LIGHT_TEAMS": (+ get_from_env("CLICKHOUSE_KILL_SWITCH_LIGHT_TEAMS", default=[], type_cast=list[int]),+ "Comma-separated team IDs always subject to the 'light' ClickHouse kill switch, even when the global kill switch is 'off'. Use this to restrict heavy or abusive teams without degrading the rest of the cluster. The global level wins if higher.",+ list[int],+ ),+ "CLICKHOUSE_KILL_SWITCH_FULL_TEAMS": (+ get_from_env("CLICKHOUSE_KILL_SWITCH_FULL_TEAMS", default=[], type_cast=list[int]),+ "Comma-separated team IDs always subject to the 'full' ClickHouse kill switch, even when the global kill switch is 'off'. Use this to restrict heavy or abusive teams without degrading the rest of the cluster.",+ list[int],+ ),"CLICKHOUSE_HEDGED_APP_QUERIES": (get_from_env("CLICKHOUSE_HEDGED_APP_QUERIES", False, type_cast=str_to_bool),"Enable hedged requests for online APP queries to ClickHouse.",@@ -319,6 +329,8 @@ SETTINGS_ALLOWING_API_OVERRIDE = ("RATE_LIMIT_ENABLED","RATE_LIMITING_ALLOW_LIST_TEAMS","CLICKHOUSE_KILL_SWITCH",+ "CLICKHOUSE_KILL_SWITCH_LIGHT_TEAMS",+ "CLICKHOUSE_KILL_SWITCH_FULL_TEAMS","CLICKHOUSE_HEDGED_APP_QUERIES","CLICKHOUSE_ENABLE_ANALYZER_TEAMS","WEB_ANALYTICS_EVENTS_PREFILTER_TEAM_IDS",