: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): match trigger group flags stored as objects (#119939)
Phil Haack13dd7d061003
diff --git a/posthog/models/remote_config.py b/posthog/models/remote_config.pyindex 2d9687ea376d..4677741a8a99 100644--- a/posthog/models/remote_config.py+++ b/posthog/models/remote_config.py@@ -21,7 +21,9 @@ from posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.team.js_snippet_config import TeamJsSnippetConfigfrom posthog.models.team.team import Teamfrom posthog.models.utils import UUIDTModel, execute_with_timeout+from posthog.ph_client import feature_enabled_or_falsefrom posthog.storage.hypercache import HyperCache, HyperCacheStoreMissing+from posthog.utils import get_instance_regionfrom products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.cdp.backend.models.plugin import PluginConfig@@ -67,6 +69,34 @@ def indent_js(js_content: str, indent: int = 4) -> str:return joined+# Converting a trigger group's flag object starts recordings that the group never made before.+# This PostHog flag targets the project group by id and region.+# PostHog turns it on for a team only after it notifies that team.+TRIGGER_GROUP_OBJECT_FLAGS_ROLLOUT = "replay-trigger-group-object-flags"+++def _converts_trigger_group_object_flags(team_id: int) -> bool:+ # Local evaluation keeps a config build from waiting on a remote call. A flag that cannot be evaluated reads as off.+ # Each region numbers its teams separately. EU evaluates a mirror of the US flag.+ # Every condition must filter on region, or it also matches the project with the same id in the other region.+ region = get_instance_region() or "DEV"+ return feature_enabled_or_false(+ TRIGGER_GROUP_OBJECT_FLAGS_ROLLOUT,+ f"team-{team_id}",+ groups={"project": f"{region}:{team_id}"},+ group_properties={"project": {"id": str(team_id), "region": region}},+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+++def _flag_for_sdk(flag: dict[str, Any]) -> str | dict[str, Any] | None:+ # posthog-js reads a flag gate as a bare key, or as {"flag": key, "variant": variant} to gate on one variant.+ key = flag.get("key")+ variant = flag.get("variant")+ return {"flag": key, "variant": variant} if variant is not None else key++class UnreadableTriggerGroupsError(Exception):"""A team's stored session recording trigger groups hold a shape that posthog-js cannot read.@@ -165,15 +195,8 @@ class RemoteConfig(UUIDTModel):if sample_rate == "1":sample_rate = None- linked_flag = None- linked_flag_config = team.session_recording_linked_flag or None- if isinstance(linked_flag_config, dict):- linked_flag_key = linked_flag_config.get("key", None)- linked_flag_variant = linked_flag_config.get("variant", None)- if linked_flag_variant is not None:- linked_flag = {"flag": linked_flag_key, "variant": linked_flag_variant}- else:- linked_flag = linked_flag_key+ linked_flag_config = team.session_recording_linked_flag+ linked_flag = _flag_for_sdk(linked_flag_config) if isinstance(linked_flag_config, dict) else Nonev1_fields = {"sampleRate": sample_rate,@@ -203,16 +226,22 @@ class RemoteConfig(UUIDTModel):continueevents = conditions.get("events")if isinstance(events, list):- group = {- **group,- "conditions": {- **conditions,- "events": [{"name": e} if isinstance(e, str) else e for e in events],- },- }+ conditions = {**conditions, "events": [{"name": e} if isinstance(e, str) else e for e in events]}elif events is not None:continue- normalized_groups.append(group)+ flag = conditions.get("flag")+ # A flag object without a non-empty string key stays as stored. Its flag condition then never matches.+ # Converting a missing or empty key would send an empty flag.+ # The SDK reads an empty flag as no flag condition.+ # A group with no other condition then records every session.+ if (+ isinstance(flag, dict)+ and isinstance(key := flag.get("key"), str)+ and key+ and _converts_trigger_group_object_flags(team.id)+ ):+ conditions = {**conditions, "flag": _flag_for_sdk(flag)}+ normalized_groups.append({**group, "conditions": conditions})if not isinstance(groups, list) or len(normalized_groups) < len(groups):capture_exception(diff --git a/posthog/models/test/test_remote_config.py b/posthog/models/test/test_remote_config.pyindex 1d63fab90048..b36e4fd980d5 100644--- a/posthog/models/test/test_remote_config.py+++ b/posthog/models/test/test_remote_config.py@@ -17,6 +17,7 @@ from posthog.models.integration import Integrationfrom posthog.models.project import Projectfrom posthog.models.remote_config import (REMOTE_CONFIG_CACHE_EXPIRY_SORTED_SET,+ TRIGGER_GROUP_OBJECT_FLAGS_ROLLOUT,RemoteConfig,RemoteConfigTokenChangeSyncError,UnreadableTriggerGroupsError,@@ -32,11 +33,10 @@ CONFIG_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"},-}+++def _flag_group(flag: str | dict[str, Any], **conditions: Any) -> dict[str, Any]:+ return {"id": "g4", "sampleRate": 1, "conditions": {"matchType": "all", "flag": flag, **conditions}}@pytest.mark.usefixtures("unittest_snapshot")@@ -341,6 +341,20 @@ class TestRemoteConfig(_RemoteConfigBase):session_recording = config["sessionRecording"]assert session_recording["sampleRate"] == expected+ @parameterized.expand(+ [+ ("without_variant", {"id": 7, "key": "k"}, "k"),+ ("with_variant", {"id": 7, "key": "k", "variant": "test"}, {"flag": "k", "variant": "test"}),+ ]+ )+ def test_session_recording_linked_flag(+ self, _name: str, stored: dict[str, Any], expected: str | dict[str, Any]+ ) -> None:+ self.team.session_recording_linked_flag = stored+ self.team.save()+ self.sync_remote_config()+ assert self.remote_config.config["sessionRecording"]["linkedFlag"] == expected+def test_session_recording_domains(self):self.team.session_recording_opt_in = Trueself.team.recording_domains = ["https://posthog.com", "https://*.posthog.com"]@@ -362,8 +376,8 @@ class TestRemoteConfig(_RemoteConfigBase):),("events_null",- {"version": 2, "groups": [_FLAG_GROUP_WITH_NULL_EVENTS]},- [_FLAG_GROUP_WITH_NULL_EVENTS],+ {"version": 2, "groups": [_flag_group("k", events=None)]},+ [_flag_group("k", events=None)],False,),(@@ -376,9 +390,27 @@ class TestRemoteConfig(_RemoteConfigBase):("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),+ (+ "flag_object_converted",+ {+ "version": 2,+ "groups": [+ _flag_group({"id": 7, "key": "k"}, events=["purchase"]),+ _flag_group({"id": 7, "key": "k", "variant": "test"}),+ ],+ },+ [_flag_group("k", events=[{"name": "purchase"}]), _flag_group({"flag": "k", "variant": "test"})],+ False,+ ),+ (+ "flag_object_without_usable_key",+ {"version": 2, "groups": [_flag_group({"id": 7}), _flag_group({"key": ""})]},+ [_flag_group({"id": 7}), _flag_group({"key": ""})],+ False,+ ),])- def test_session_recording_trigger_groups_send_only_readable_groups(+ def test_session_recording_trigger_groups_sent_to_sdk(self,_name: str,stored: Any,@@ -386,7 +418,13 @@ class TestRemoteConfig(_RemoteConfigBase):expect_reported: bool,) -> None:self.team.session_recording_trigger_groups = stored- with patch("posthog.models.remote_config.capture_exception") as mock_capture_exception:+ with (+ patch("posthog.models.remote_config.capture_exception") as mock_capture_exception,+ patch(+ "posthoganalytics.feature_enabled",+ side_effect=lambda key, *args, **kwargs: key == TRIGGER_GROUP_OBJECT_FLAGS_ROLLOUT,+ ),+ ):self.team.save()self.sync_remote_config()reported = any(@@ -400,6 +438,35 @@ class TestRemoteConfig(_RemoteConfigBase):assert session_recording["version"] == 2assert session_recording["triggerGroups"] == expected_trigger_groups+ @parameterized.expand(+ [+ ("rollout_region", "US", {"flag": "k", "variant": "test"}),+ ("same_project_id_other_region", "EU", {"id": 7, "key": "k", "variant": "test"}),+ ]+ )+ def test_session_recording_trigger_group_flag_rollout_targets_one_region(+ self, _name: str, region: str, expected_flag: dict[str, Any]+ ) -> None:+ def rollout_for_us_project(key: str, *args: Any, group_properties: Any = None, **kwargs: Any) -> bool:+ project = (group_properties or {}).get("project", {})+ return (+ key == TRIGGER_GROUP_OBJECT_FLAGS_ROLLOUT+ and project.get("id") == str(self.team.id)+ and project.get("region") == "US"+ )++ flag = {"id": 7, "key": "k", "variant": "test"}+ self.team.session_recording_trigger_groups = {"version": 2, "groups": [_flag_group(flag, events=["purchase"])]}+ with (+ override_settings(CLOUD_DEPLOYMENT=region),+ patch("posthoganalytics.feature_enabled", side_effect=rollout_for_us_project),+ ):+ self.team.save()+ self.sync_remote_config()+ assert self.remote_config.config["sessionRecording"]["triggerGroups"] == [+ _flag_group(expected_flag, events=[{"name": "purchase"}])+ ]+def test_extra_settings_recorder_script(self):self.team.session_recording_opt_in = Trueself.team.extra_settings = {"recorder_script": "custom-recorder"}