: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(metrics): gate private-alpha product behind the metrics flag (#72089)
Daniel Visca69efa59b3b42
diff --git a/posthog/permissions.py b/posthog/permissions.pyindex 8516ca49ffe2..baae400bff98 100644--- a/posthog/permissions.py+++ b/posthog/permissions.py@@ -1,5 +1,6 @@import osimport time+import uuidfrom typing import Optional, castfrom django.conf import settings@@ -867,6 +868,43 @@ _raw = os.environ.get("POSTHOG_FEATURE_FLAGS_FORCE_ENABLED", "")_FORCE_ENABLED_FLAGS: frozenset[str] = frozenset(f.strip() for f in _raw.split(",") if f.strip())+def posthog_feature_flag_enabled(+ flag: str,+ distinct_id: str,+ *,+ organization_id: str | uuid.UUID,+ team_id: int | None = None,+) -> bool:+ """Server-side check of a PostHog-internal gating flag with org/project group context.++ Matches in-app flag evaluation: posthog-js often has project (team) context; server-only org+ groups miss per-environment rollouts (e.g. logs-settings-drop-rules for project 2 only).+ Use this wherever a flag gates access outside a DRF view (query runners, tasks) so evaluation+ can't drift from PostHogFeatureFlagPermission.+ """+ if flag in _FORCE_ENABLED_FLAGS:+ return True++ org_id = str(organization_id)+ groups: dict[str, str] = {"organization": org_id}+ group_properties: dict[str, dict[str, str]] = {"organization": {"id": org_id}}+ if team_id is not None:+ project_id = str(team_id)+ groups["project"] = project_id+ group_properties["project"] = {"id": project_id}++ return bool(+ posthoganalytics.feature_enabled(+ flag,+ distinct_id,+ groups=groups,+ group_properties=group_properties,+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )++class PostHogFeatureFlagPermission(BasePermission):def has_permission(self, request, view) -> bool:user = cast(User, request.user)@@ -887,30 +925,16 @@ class PostHogFeatureFlagPermission(BasePermission):for required_flag, actions in config.items():if "*" in actions or view.action in actions:- if required_flag in _FORCE_ENABLED_FLAGS:- return True-- org_id = str(organization.id)- groups: dict[str, str] = {"organization": org_id}- group_properties: dict[str, dict[str, str]] = {"organization": {"id": org_id}}- # Match in-app flag evaluation: posthog-js often has project (team) context; server-only org- # groups miss per-environment rollouts (e.g. logs-settings-drop-rules for project 2 only).try:team_for_flag = view.teamexcept (ValueError, KeyError, AttributeError):team_for_flag = None- if team_for_flag is not None:- project_id = str(team_for_flag.id)- groups["project"] = project_id- group_properties["project"] = {"id": project_id}- enabled = posthoganalytics.feature_enabled(+ enabled = posthog_feature_flag_enabled(required_flag,str(user.distinct_id),- groups=groups,- group_properties=group_properties,- only_evaluate_locally=False,- send_feature_flag_events=False,+ organization_id=organization.id,+ team_id=team_for_flag.id if team_for_flag is not None else None,)if enabled:diff --git a/products/metrics/backend/facade/contracts.py b/products/metrics/backend/facade/contracts.pyindex 4d39b2972903..10b7a60b551b 100644--- a/products/metrics/backend/facade/contracts.py+++ b/products/metrics/backend/facade/contracts.py@@ -28,6 +28,10 @@ from .enums import AttributeScope, FilterOp, MetricAggregation, MetricType# the clause count per request is hard-capped.MAX_CLAUSES_PER_QUERY = 10+# Private-alpha gate. Every read surface (viewset, query runner, MCP tools)+# must check the same flag, or one of them becomes a bypass.+METRICS_FEATURE_FLAG = "metrics"+@dataclass(frozen=True, slots=True)class MetricFilter:diff --git a/products/metrics/backend/hogql_queries/metrics_query_runner.py b/products/metrics/backend/hogql_queries/metrics_query_runner.pyindex 875d06cf3503..ec0de0ac7be0 100644--- a/products/metrics/backend/hogql_queries/metrics_query_runner.py+++ b/products/metrics/backend/hogql_queries/metrics_query_runner.py@@ -8,7 +8,7 @@ query path."""from datetime import datetime-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Optional, castfrom posthog.schema import (CachedMetricsQueryResponse,@@ -24,10 +24,18 @@ from posthog.hogql import astfrom posthog.hogql_queries.query_runner import AnalyticsQueryRunnerfrom posthog.hogql_queries.utils.query_date_range import QueryDateRange-from posthog.rbac.user_access_control import UserAccessControl+from posthog.permissions import posthog_feature_flag_enabled+from posthog.rbac.user_access_control import UserAccessControl, UserAccessControlError+from posthog.shared_link_user import SharedLinkUserfrom products.metrics.backend.facade.api import run_metric_query-from products.metrics.backend.facade.contracts import MetricFilter, MetricGroupBy, MetricQueryClause, MetricQueryRequest+from products.metrics.backend.facade.contracts import (+ METRICS_FEATURE_FLAG,+ MetricFilter,+ MetricGroupBy,+ MetricQueryClause,+ MetricQueryRequest,+)from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation, MetricTypeif TYPE_CHECKING:@@ -44,7 +52,35 @@ class MetricsQueryRunner(AnalyticsQueryRunner[MetricsQueryResponse]):def validate_query_runner_access(self, user: "User") -> bool:user_access_control = UserAccessControl(user=user, team=self.team)- return user_access_control.assert_access_level_for_resource("metrics", "viewer")+ user_access_control.assert_access_level_for_resource("metrics", "viewer")+ # Private alpha: RBAC alone isn't enough — mirror MetricsViewSet's flag gate here,+ # or POST /query with a MetricsQuery bypasses it.+ if not posthog_feature_flag_enabled(+ METRICS_FEATURE_FLAG,+ str(user.distinct_id),+ organization_id=self.team.organization_id,+ team_id=self.team.pk,+ ):+ raise UserAccessControlError("metrics", "viewer")+ return True++ def _enforce_alpha_gate_for_anonymous_viewers(self) -> None:+ # Shared-link renders execute with an anonymous SharedLinkUser, which skips+ # validate_query_runner_access (the share link is its authorization) — so the+ # alpha flag gate must also hold here. Userless runs (scheduled refreshes,+ # cache warming) stay allowed: they only ever refresh flagged teams' insights.+ # user is typed Optional[User] but runtime also passes SharedLinkUser (shared+ # renders); broaden for is_anonymous.+ user = cast("Optional[User | SharedLinkUser]", self.user)+ if user is None or not user.is_anonymous:+ return+ if not posthog_feature_flag_enabled(+ METRICS_FEATURE_FLAG,+ str(getattr(user, "distinct_id", None) or f"shared-viewer-{self.team.pk}"),+ organization_id=self.team.organization_id,+ team_id=self.team.pk,+ ):+ raise UserAccessControlError("metrics", "viewer")def to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:raise NotImplementedError(@@ -98,6 +134,7 @@ class MetricsQueryRunner(AnalyticsQueryRunner[MetricsQueryResponse]):)def _calculate(self) -> MetricsQueryResponse:+ self._enforce_alpha_gate_for_anonymous_viewers()series = run_metric_query(team=self.team, request=self._to_request())return MetricsQueryResponse(results=[diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.pyindex 5508ae081717..95958333627b 100644--- a/products/metrics/backend/presentation/api.py+++ b/products/metrics/backend/presentation/api.py@@ -20,6 +20,7 @@ from posthog.api.documentation import _FallbackSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.event_usage import report_user_action+from posthog.permissions import PostHogFeatureFlagPermissionfrom posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottlefrom products.metrics.backend.facade.api import (@@ -33,6 +34,7 @@ from products.metrics.backend.facade.api import ()from products.metrics.backend.facade.contracts import (MAX_CLAUSES_PER_QUERY,+ METRICS_FEATURE_FLAG,MetricFilter,MetricGroupBy,MetricQueryClause,@@ -549,6 +551,11 @@ class _MetricSamplesResponseSerializer(serializers.Serializer):class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):scope_object = "metrics"serializer_class = _FallbackSerializer+ # Metrics is in private alpha: gate the API behind the `metrics` flag so only+ # PostHog and directly-added teams can reach it. Added to the mixin's default+ # permissions (team/org/access-control), not replacing them.+ posthog_feature_flag = METRICS_FEATURE_FLAG+ permission_classes = [PostHogFeatureFlagPermission]@extend_schema(responses={200: _HasMetricsResponseSerializer})@action(detail=False, methods=["GET"], required_scopes=["metrics:read"])diff --git a/products/metrics/backend/tests/conftest.py b/products/metrics/backend/tests/conftest.pynew file mode 100644index 000000000000..9f3bbde359a7--- /dev/null+++ b/products/metrics/backend/tests/conftest.py@@ -0,0 +1,17 @@+from collections.abc import Iterator++import pytest+from unittest.mock import patch++[email protected](autouse=True)+def enable_metrics_feature_flag() -> Iterator[None]:+ # MetricsViewSet is gated behind the `metrics` feature flag (private alpha), so every+ # endpoint test in this package would 403 without it. Enable only the metrics flag and+ # leave all others at their default (False), matching production for non-alpha teams.+ # The dedicated gate test overrides this to assert the 403.+ def _feature_enabled(flag_key: str, *args: object, **kwargs: object) -> bool:+ return flag_key == "metrics"++ with patch("posthoganalytics.feature_enabled", side_effect=_feature_enabled):+ yielddiff --git a/products/metrics/backend/tests/test_api.py b/products/metrics/backend/tests/test_api.pyindex 710fa2680d2d..32a04babd7fe 100644--- a/products/metrics/backend/tests/test_api.py+++ b/products/metrics/backend/tests/test_api.py@@ -42,6 +42,23 @@ class TestMetricsValuesApi(APIBaseTest):assert response.json()["attr"] == "limit"+class TestMetricsFeatureFlagGate(APIBaseTest):+ @parameterized.expand(+ [+ ("enabled", True, status.HTTP_200_OK),+ ("disabled", False, status.HTTP_403_FORBIDDEN),+ ]+ )+ def test_metrics_flag_gates_the_api(self, _name: str, flag_enabled: bool, expected_status: int) -> None:+ with (+ patch("posthoganalytics.feature_enabled", return_value=flag_enabled),+ patch("products.metrics.backend.presentation.api.team_has_metrics", return_value=True),+ ):+ response = self.client.get(f"/api/projects/{self.team.id}/metrics/has_metrics/")++ assert response.status_code == expected_status++@pytest.mark.eeclass TestMetricsAccessControl(APIBaseTest):def setUp(self) -> None:diff --git a/products/metrics/backend/tests/test_metrics_query_runner.py b/products/metrics/backend/tests/test_metrics_query_runner.pyindex 7bba65be9ecd..2f18d76c94cd 100644--- a/products/metrics/backend/tests/test_metrics_query_runner.py+++ b/products/metrics/backend/tests/test_metrics_query_runner.py@@ -1,8 +1,10 @@import datetime as dt+from typing import castimport pytestfrom freezegun import freeze_timefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin+from unittest.mock import patchfrom parameterized import parameterized@@ -16,9 +18,12 @@ from posthog.schema import ()from posthog.constants import AvailableFeature+from posthog.models import Userfrom posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.rbac.user_access_control import UserAccessControlError+from posthog.shared_link_user import SharedLinkUserfrom products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation, MetricTypefrom products.metrics.backend.hogql_queries.metrics_query_runner import MetricsQueryRunner@@ -140,6 +145,31 @@ class TestMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):assert self._runner(query).validate_query_runner_access(self.user) is True+ def test_validate_query_runner_access_denied_without_feature_flag(self) -> None:+ query = MetricsQuery(clauses=[MetricsQueryClause(name="a", metricName="queue_depth", aggregation="sum")])++ with patch("posthoganalytics.feature_enabled", return_value=False):+ with pytest.raises(UserAccessControlError):+ self._runner(query).validate_query_runner_access(self.user)++ def test_calculate_denied_for_shared_link_viewer_without_feature_flag(self) -> None:+ # Shared-link renders execute with an anonymous SharedLinkUser, which skips+ # validate_query_runner_access — the flag gate must also hold at calculation time.+ sharing_config = SharingConfiguration.objects.create(team=self.team, enabled=True)+ query = MetricsQuery(clauses=[MetricsQueryClause(name="a", metricName="queue_depth", aggregation="sum")])+ runner = MetricsQueryRunner(query=query, team=self.team, user=cast(User, SharedLinkUser(sharing_config)))++ with patch("posthoganalytics.feature_enabled", return_value=False):+ with pytest.raises(UserAccessControlError):+ runner.calculate()++ def test_calculate_allowed_for_shared_link_viewer_with_feature_flag(self) -> None:+ sharing_config = SharingConfiguration.objects.create(team=self.team, enabled=True)+ query = MetricsQuery(clauses=[MetricsQueryClause(name="a", metricName="queue_depth", aggregation="sum")])+ runner = MetricsQueryRunner(query=query, team=self.team, user=cast(User, SharedLinkUser(sharing_config)))++ assert runner.calculate().results is not None+def test_validate_query_runner_access_denied_without_resource_access(self) -> None:AccessControl.objects.create(team=self.team, resource="metrics", access_level="none")self.organization.available_product_features = [diff --git a/products/metrics/frontend/MetricsScene.tsx b/products/metrics/frontend/MetricsScene.tsxindex b1c2b87e09cc..25626afae40c 100644--- a/products/metrics/frontend/MetricsScene.tsx+++ b/products/metrics/frontend/MetricsScene.tsx@@ -6,6 +6,7 @@ import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { sceneConfigurations } from 'scenes/scenes'import { Scene, SceneExport } from 'scenes/sceneTypes'+import { FeaturePreviewSceneGate } from '~/layout/scenes/components/FeaturePreviewSceneGate'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'@@ -15,6 +16,7 @@ import { MetricsSetupPrompt } from './components/MetricsSetupPrompt'import { MetricsSqlEditor } from './components/MetricsSqlEditor'import { metricsUsageTrackingLogic } from './components/metricsUsageTrackingLogic'import { MetricsViewer } from './components/MetricsViewer'+import { metricsFeaturePreviewGate } from './featurePreviewGate'import { metricsIngestionLogic } from './metricsIngestionLogic'import { MetricsSceneActiveTab, metricsSceneLogic } from './metricsSceneLogic'@@ -33,9 +35,11 @@ export const scene: SceneExport = {export function MetricsScene(): JSX.Element {return (- <SceneContent className="h-[calc(var(--scene-layout-rect-height,_100vh)_-_1rem)]">- <MetricsSceneContent />- </SceneContent>+ <FeaturePreviewSceneGate config={metricsFeaturePreviewGate}>+ <SceneContent className="h-[calc(var(--scene-layout-rect-height,_100vh)_-_1rem)]">+ <MetricsSceneContent />+ </SceneContent>+ </FeaturePreviewSceneGate>)}diff --git a/products/metrics/frontend/featurePreviewGate.ts b/products/metrics/frontend/featurePreviewGate.tsnew file mode 100644index 000000000000..b21020290aca--- /dev/null+++ b/products/metrics/frontend/featurePreviewGate.ts@@ -0,0 +1,11 @@+import { FEATURE_FLAGS } from 'lib/constants'++import { FeaturePreviewGateConfig } from '~/types'++export const metricsFeaturePreviewGate: FeaturePreviewGateConfig = {+ flag: FEATURE_FLAGS.METRICS,+ title: 'Metrics is in private alpha',+ description:+ "Metrics is available to select teams while we polish it. You can already send metrics with any OpenTelemetry client. Join the waitlist and we'll turn on the viewer for your team.",+ docsURL: 'https://posthog.com/docs/metrics',+}diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.pyindex 5ad6a1a8b5e5..80dc8ba01216 100644--- a/products/product_analytics/backend/api/insight.py+++ b/products/product_analytics/backend/api/insight.py@@ -1313,7 +1313,10 @@ class InsightSerializer(InsightBasicSerializer):is_cached=False,query_status=dict(QueryStatus(- id=self.context["request"].query_params.get("client_query_id"),+ # QueryStatus.id is a required str; without a client_query_id this+ # fallback used to crash pydantic validation and turn the degraded+ # error state into a 500.+ id=self.context["request"].query_params.get("client_query_id") or "",team_id=insight.team_id,insight_id=str(insight.id),dashboard_id=str(dashboard.id) if dashboard else None,@@ -1336,7 +1339,10 @@ class InsightSerializer(InsightBasicSerializer):is_cached=False,query_status=dict(QueryStatus(- id=self.context["request"].query_params.get("client_query_id"),+ # QueryStatus.id is a required str; without a client_query_id this+ # fallback used to crash pydantic validation and turn the degraded+ # error state into a 500.+ id=self.context["request"].query_params.get("client_query_id") or "",team_id=insight.team_id,insight_id=str(insight.id),dashboard_id=str(dashboard.id) if dashboard else None,