: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(replay): skip malformed trigger groups when building remote config (#117314)
Phil Haack2ebfb5b28eeb
diff --git a/posthog/models/remote_config.py b/posthog/models/remote_config.pyindex ab804fa561a4..2d9687ea376d 100644--- a/posthog/models/remote_config.py+++ b/posthog/models/remote_config.py@@ -67,6 +67,14 @@ def indent_js(js_content: str, indent: int = 4) -> str:return joined+class UnreadableTriggerGroupsError(Exception):+ """+ A team's stored session recording trigger groups hold a shape that posthog-js cannot read.+ The Team API rejects these shapes.+ A write that skipped the Team API validation stored this one.+ """++class RemoteConfig(UUIDTModel):"""RemoteConfig is a helper model. There is one per team and stores a highly cacheable JSON object@@ -104,12 +112,13 @@ class RemoteConfig(UUIDTModel):expiry_sorted_set_key=REMOTE_CONFIG_CACHE_EXPIRY_SORTED_SET,)- def _build_session_recording_config(self, team: Team) -> dict:+ def _build_session_recording_config(self, team: Team) -> dict | bool:"""Build session recording configuration with V1/V2 support.V2: If team.session_recording_trigger_groups is set, use new trigger groups formatV1: Otherwise, use legacy trigger fields for backward compatibility+ Returns False when team.session_recording_trigger_groups is set but holds no readable group."""# Build base config (common to both V1 and V2)capture_console_logs = True if team.capture_console_log_opt_in else False@@ -174,28 +183,50 @@ class RemoteConfig(UUIDTModel):"triggerMatchType": team.session_recording_trigger_match_type_config,}+ # The Team API validates this column. A write that skips the Team API can still store malformed JSON.+ trigger_groups_config = team.session_recording_trigger_groups+# V2: If trigger groups configured, send V2 + V1 fallback fields- if team.session_recording_trigger_groups:- trigger_groups_config = team.session_recording_trigger_groups- groups = trigger_groups_config.get("groups", [])+ if trigger_groups_config:+ groups = trigger_groups_config.get("groups", []) if isinstance(trigger_groups_config, dict) else None# Normalize events to objects for SDK: ["purchase"] -> [{"name": "purchase"}]# This future-proofs the contract so WHERE clauses (property filters on events)# can be added later without a breaking SDK change.# Build normalized copies to avoid mutating the team's stored data.normalized_groups = []- for group in groups:- conditions = group.get("conditions", {})- if "events" in conditions:+ for group in groups if isinstance(groups, list) else []:+ # The SDK throws on a group whose conditions is not an object.+ # It also throws on events that is neither null nor a list.+ conditions = group.get("conditions") if isinstance(group, dict) else None+ if not isinstance(conditions, dict):+ continue+ events = conditions.get("events")+ if isinstance(events, list):group = {**group,"conditions": {**conditions,- "events": [{"name": e} if isinstance(e, str) else e for e in conditions["events"]],+ "events": [{"name": e} if isinstance(e, str) else e for e in events],},}+ elif events is not None:+ continuenormalized_groups.append(group)+ if not isinstance(groups, list) or len(normalized_groups) < len(groups):+ capture_exception(+ UnreadableTriggerGroupsError(+ "Dropped session recording trigger groups that posthog-js cannot read"+ ),+ additional_properties={"team_id": team.id, "readable_groups": len(normalized_groups)},+ )+ # posthog-js uses the V1 fields when triggerGroups is empty.+ # A team that set up only trigger groups has empty V1 fields.+ # Empty V1 fields record every session.+ if not normalized_groups:+ return False+return {**base_config,"version": 2,diff --git a/posthog/models/test/test_remote_config.py b/posthog/models/test/test_remote_config.pyindex 625c77feb763..1d63fab90048 100644--- a/posthog/models/test/test_remote_config.py+++ b/posthog/models/test/test_remote_config.py@@ -1,6 +1,6 @@from datetime import timedeltafrom decimal import Decimal-from typing import Any+from typing import Any, Literalimport pytestfrom posthog.test.base import BaseTest@@ -19,6 +19,7 @@ from posthog.models.remote_config import (REMOTE_CONFIG_CACHE_EXPIRY_SORTED_SET,RemoteConfig,RemoteConfigTokenChangeSyncError,+ UnreadableTriggerGroupsError,)from products.actions.backend.models.action import Action@@ -29,6 +30,13 @@ from products.surveys.backend.models import SurveyCONFIG_REFRESH_QUERY_COUNT = 6SITE_HOG = "export function onEvent({ inputs }) { console.log(inputs) }"+_READABLE_GROUP = {"id": "g1", "sampleRate": 1, "conditions": {"matchType": "any", "events": ["purchase"]}}+_SENT_GROUP = {"id": "g1", "sampleRate": 1, "conditions": {"matchType": "any", "events": [{"name": "purchase"}]}}+_FLAG_GROUP_WITH_NULL_EVENTS = {+ "id": "g3",+ "sampleRate": 1,+ "conditions": {"matchType": "any", "events": None, "flag": "k"},+}@pytest.mark.usefixtures("unittest_snapshot")@@ -343,6 +351,55 @@ class TestRemoteConfig(_RemoteConfigBase):session_recording = config["sessionRecording"]assert session_recording["domains"] == self.team.recording_domains+ @parameterized.expand(+ [+ ("group_not_an_object", {"version": 2, "groups": ["not-a-group", _READABLE_GROUP]}, [_SENT_GROUP], True),+ (+ "conditions_missing",+ {"version": 2, "groups": [{"id": "g2", "sampleRate": 1}, _READABLE_GROUP]},+ [_SENT_GROUP],+ True,+ ),+ (+ "events_null",+ {"version": 2, "groups": [_FLAG_GROUP_WITH_NULL_EVENTS]},+ [_FLAG_GROUP_WITH_NULL_EVENTS],+ False,+ ),+ (+ "events_not_a_list",+ {"version": 2, "groups": [{"conditions": {"events": "purchase"}}, _READABLE_GROUP]},+ [_SENT_GROUP],+ True,+ ),+ ("groups_missing", {"version": 2}, [], False),+ ("groups_all_unreadable", {"version": 2, "groups": [{"conditions": {"events": "purchase"}}]}, False, True),+ ("column_not_an_object", ["not-a-config"], False, True),+ ("groups_not_a_list", {"version": 2, "groups": None}, False, True),+ ]+ )+ def test_session_recording_trigger_groups_send_only_readable_groups(+ self,+ _name: str,+ stored: Any,+ expected_trigger_groups: list[dict] | Literal[False],+ expect_reported: bool,+ ) -> None:+ self.team.session_recording_trigger_groups = stored+ with patch("posthog.models.remote_config.capture_exception") as mock_capture_exception:+ self.team.save()+ self.sync_remote_config()+ reported = any(+ isinstance(c.args[0], UnreadableTriggerGroupsError) for c in mock_capture_exception.call_args_list+ )+ assert reported == expect_reported+ session_recording = self.remote_config.config["sessionRecording"]+ if expected_trigger_groups is False:+ assert session_recording is False+ else:+ assert session_recording["version"] == 2+ assert session_recording["triggerGroups"] == expected_trigger_groups+def test_extra_settings_recorder_script(self):self.team.session_recording_opt_in = Trueself.team.extra_settings = {"recorder_script": "custom-recorder"}