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.

feat(apm): evaluate the product flag for the requesting user (#124355)

Daniel Viscac49e6415c450
diff --git a/products/apm/backend/feature_flags.py b/products/apm/backend/feature_flags.py
index 2175ae1a01b1..36d24f8a9115 100644
--- a/products/apm/backend/feature_flags.py
+++ b/products/apm/backend/feature_flags.py
@@ -5,10 +5,14 @@ APM is unreleased, so nothing that lands here runs for a team until
a whole. A capability that needs its own rollout, like anomaly detection, gets
its own flag layered on top of this one rather than reusing it.
-The gate evaluates against the ``project`` group keyed on team ID alone, so it
-needs no ``Team`` row and no database read. That matters because work landing
-here is expected to run per team on a schedule, where a fetch per team per tick
-would be pure overhead.
+The gate always sends the ``project`` group keyed on team ID, so it needs no
+``Team`` row and no database read. That matters because work landing here is
+expected to run per team on a schedule, where a fetch per team per tick would be
+pure overhead. A request made by a user also passes that user's distinct ID and
+email, so the flag can target people (for example an internal cohort) as well as
+projects. A user who anonymizes their data passes an explicit null email, as the
+frontend does, so a stored email cannot match. Scheduled work has no user and
+matches only project conditions.
"""
from __future__ import annotations
@@ -22,12 +26,13 @@ logger = structlog.get_logger(__name__)
UNIFIED_APM_PRODUCT_FLAG = "unified-apm-product"
-def is_apm_enabled(team_id: int) -> bool:
+def is_apm_enabled(team_id: int, *, distinct_id: str | None = None, email: str | None = None) -> bool:
try:
return feature_enabled_or_false(
UNIFIED_APM_PRODUCT_FLAG,
- str(team_id),
+ distinct_id or str(team_id),
groups={"project": str(team_id)},
+ person_properties={"email": email} if distinct_id else None,
group_properties={"project": {"id": str(team_id)}},
only_evaluate_locally=False,
# Work here is scheduled per team, so leaving this on would emit a
diff --git a/products/apm/backend/presentation/views.py b/products/apm/backend/presentation/views.py
index 9b09f8276bfa..456e04c6db1f 100644
--- a/products/apm/backend/presentation/views.py
+++ b/products/apm/backend/presentation/views.py
@@ -7,6 +7,7 @@ return serialized responses. No business logic here.
from dataclasses import asdict
from datetime import timedelta
+from typing import cast
from django.utils import timezone
@@ -20,6 +21,7 @@ from posthog.schema import ProductKey
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.clickhouse.query_tagging import Feature, tag_queries
+from posthog.models.user import User
from products.apm.backend.facade.api import is_apm_enabled, list_services_health
from products.apm.backend.presentation.serializers import (
@@ -42,7 +44,9 @@ class ServicesHealthViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
scope_object = "tracing"
def _check_flag(self) -> None:
- if not is_apm_enabled(self.team.pk):
+ user = cast(User, self.request.user)
+ email = None if user.anonymize_data else user.email
+ if not is_apm_enabled(self.team.pk, distinct_id=str(user.distinct_id), email=email):
raise PermissionDenied("Application observability is not enabled for this project.")
@extend_schema(parameters=[ServicesHealthRequestSerializer], responses={200: ServicesHealthResponseSerializer})
diff --git a/products/apm/backend/tests/test_feature_flags.py b/products/apm/backend/tests/test_feature_flags.py
index ecadaf0f7d39..921fa13f2fb0 100644
--- a/products/apm/backend/tests/test_feature_flags.py
+++ b/products/apm/backend/tests/test_feature_flags.py
@@ -3,7 +3,7 @@ from unittest.mock import patch
from parameterized import parameterized
-from products.apm.backend.feature_flags import is_apm_enabled
+from products.apm.backend.feature_flags import UNIFIED_APM_PRODUCT_FLAG, is_apm_enabled
class TestApmFeatureFlag(TestCase):
@@ -21,3 +21,28 @@ class TestApmFeatureFlag(TestCase):
def test_gate_stays_closed_when_flag_service_raises(self) -> None:
with patch("posthoganalytics.feature_enabled", side_effect=RuntimeError("flags unreachable")):
assert is_apm_enabled(team_id=1) is False
+
+ def test_gate_evaluates_for_the_user_when_one_is_given(self) -> None:
+ with patch("posthoganalytics.feature_enabled", return_value=True) as feature_enabled:
+ is_apm_enabled(team_id=7, distinct_id="user-distinct-id", email="[email protected]")
+
+ args, kwargs = feature_enabled.call_args
+ assert args == (UNIFIED_APM_PRODUCT_FLAG, "user-distinct-id")
+ assert kwargs["person_properties"] == {"email": "[email protected]"}
+ assert kwargs["groups"] == {"project": "7"}
+
+ def test_gate_sends_an_explicit_null_email_for_an_anonymized_user(self) -> None:
+ with patch("posthoganalytics.feature_enabled", return_value=True) as feature_enabled:
+ is_apm_enabled(team_id=7, distinct_id="user-distinct-id", email=None)
+
+ _, kwargs = feature_enabled.call_args
+ assert kwargs["person_properties"] == {"email": None}
+
+ def test_gate_evaluates_for_the_team_when_no_user_is_given(self) -> None:
+ with patch("posthoganalytics.feature_enabled", return_value=True) as feature_enabled:
+ is_apm_enabled(team_id=7)
+
+ args, kwargs = feature_enabled.call_args
+ assert args == (UNIFIED_APM_PRODUCT_FLAG, "7")
+ assert not kwargs["person_properties"]
+ assert kwargs["groups"] == {"project": "7"}
diff --git a/products/apm/backend/tests/test_services_health_api.py b/products/apm/backend/tests/test_services_health_api.py
index 0a2582525317..06bfaa3807c6 100644
--- a/products/apm/backend/tests/test_services_health_api.py
+++ b/products/apm/backend/tests/test_services_health_api.py
@@ -173,6 +173,20 @@ class TestServicesHealthAPI(ClickhouseTestMixin, APIBaseTest):
response = self.client.get(f"/api/projects/{self.team.id}/apm/services/")
self.assertEqual(response.status_code, 403)
+ def test_flag_is_evaluated_for_the_requesting_user(self) -> None:
+ with patch(FLAG_PATCH, return_value=False) as is_apm_enabled:
+ self.client.get(f"/api/projects/{self.team.id}/apm/services/")
+ is_apm_enabled.assert_called_once_with(
+ self.team.pk, distinct_id=str(self.user.distinct_id), email=self.user.email
+ )
+
+ def test_flag_gets_no_email_when_the_user_anonymizes_data(self) -> None:
+ self.user.anonymize_data = True
+ self.user.save()
+ with patch(FLAG_PATCH, return_value=False) as is_apm_enabled:
+ self.client.get(f"/api/projects/{self.team.id}/apm/services/")
+ is_apm_enabled.assert_called_once_with(self.team.pk, distinct_id=str(self.user.distinct_id), email=None)
+
def test_unauthenticated_is_rejected(self) -> None:
self.client.logout()
response = self.client.get(f"/api/projects/{self.team.id}/apm/services/")