: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(flags): support evaluation contexts in Max create_feature_flag tool (#62081)
Ben Lea58dc0960143f
diff --git a/products/feature_flags/backend/max_tools.py b/products/feature_flags/backend/max_tools.pyindex e90b83838112..979fea847a2d 100644--- a/products/feature_flags/backend/max_tools.py+++ b/products/feature_flags/backend/max_tools.py@@ -2,6 +2,7 @@ from textwrap import dedentfrom types import SimpleNamespacefrom typing import Any+import posthoganalyticsfrom pydantic import BaseModel, Fieldfrom rest_framework.exceptions import ValidationError@@ -13,6 +14,7 @@ from posthog.scopes import APIScopeObjectfrom posthog.sync import database_sync_to_asyncfrom products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer+from products.feature_flags.backend.models.evaluation_context import TeamDefaultEvaluationContextfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.hogai.tool import MaxTool@@ -56,6 +58,13 @@ class FeatureFlagCreationSchema(BaseModel):"Common example: [{'key': 'control', 'name': 'Control', 'rollout_percentage': 50}, ""{'key': 'test', 'name': 'Test', 'rollout_percentage': 50}]",)+ evaluation_contexts: list[str] | None = Field(+ default=None,+ description="Evaluation context names (e.g. 'production', 'staging') that control where this flag "+ "evaluates at runtime. Some projects require at least one evaluation context on every new flag. "+ "If omitted, the project's default evaluation contexts are applied automatically when configured. "+ "An explicit empty list skips the defaults.",+ )FEATURE_FLAG_CREATION_TOOL_DESCRIPTION = dedent("""@@ -102,6 +111,10 @@ class CreateFeatureFlagToolArgs(BaseModel):- **groups**: Array of targeting groups (see Groups Structure below)- **tags**: Array of tag strings for organizing flags- **variants**: Array of variants for A/B testing (see Variants Structure below)+ - **evaluation_contexts**: Array of evaluation context names (e.g. ['production', 'staging'])+ controlling where the flag evaluates at runtime. Some projects require at least one on every+ new flag; omit this field entirely to apply the project's configured defaults when set+ (an explicit empty list skips the defaults).# Groups StructureEach group defines targeting criteria with AND logic within the group:@@ -257,6 +270,13 @@ class CreateFeatureFlagTool(MaxTool):"_should_create_usage_dashboard": False,}+ # Unspecified (None) falls back to the project defaults; an explicit empty list is left as-is.+ evaluation_contexts = flag_schema.evaluation_contexts+ if evaluation_contexts is None:+ evaluation_contexts = await self._get_default_evaluation_contexts()+ if evaluation_contexts:+ serializer_data["evaluation_contexts"] = evaluation_contexts+# Mock request following established patternsmock_request = SimpleNamespace(user=self._user,@@ -285,14 +305,18 @@ class CreateFeatureFlagTool(MaxTool):flag_url = f"/project/{self._team.project_id}/feature_flags/{flag.id}"targeting_info = self._format_targeting_info(flag_schema, group_type_display_name)+ contexts_info = (+ f" with evaluation contexts: {', '.join(evaluation_contexts)}" if evaluation_contexts else ""+ )return (- f"Successfully created feature flag '{flag_schema.name}' (key: {flag_schema.key}){targeting_info}. View at {flag_url}",+ f"Successfully created feature flag '{flag_schema.name}' (key: {flag_schema.key}){targeting_info}{contexts_info}. View at {flag_url}",{"flag_id": flag.id,"flag_key": flag_schema.key,"flag_name": flag_schema.name,"url": flag_url,+ "evaluation_contexts": evaluation_contexts,},)@@ -332,6 +356,33 @@ class CreateFeatureFlagTool(MaxTool):capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})return f"Failed to create feature flag: {str(e)}", {"error": str(e)}+ @database_sync_to_async+ def _get_default_evaluation_contexts(self) -> list[str]:+ """Return the project's default evaluation context names, if defaults are enabled."""+ if not self._team.default_evaluation_contexts_enabled:+ return []++ # Mirror the web UI, which applies defaults only when this gate is also on (featureFlagLogic.ts).+ organization = self._user.organization+ distinct_id = self._user.distinct_id+ if organization is None or distinct_id is None:+ return []+ if not posthoganalytics.feature_enabled(+ "default-evaluation-environments",+ distinct_id,+ groups={"organization": str(organization.id)},+ group_properties={"organization": {"id": str(organization.id)}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ ):+ return []++ return list(+ TeamDefaultEvaluationContext.objects.filter(team=self._team)+ .select_related("evaluation_context")+ .values_list("evaluation_context__name", flat=True)+ )+def _format_targeting_info(self, schema: FeatureFlagCreationSchema, group_display_name: str | None) -> str:"""Format targeting information for success message."""parts = []diff --git a/products/feature_flags/backend/test/test_max_tools.py b/products/feature_flags/backend/test/test_max_tools.pyindex 10a0e4a1dae7..df8eebf58973 100644--- a/products/feature_flags/backend/test/test_max_tools.py+++ b/products/feature_flags/backend/test/test_max_tools.py@@ -1,16 +1,19 @@from posthog.test.base import APIBaseTest+from unittest.mock import patchfrom parameterized import parameterizedfrom posthog.schema import FeatureFlagGroupType, GroupPropertyFilter, PersonPropertyFilter, PropertyOperatorfrom posthog.models.group_type_mapping import GroupTypeMapping+from posthog.sync import database_sync_to_asyncfrom products.feature_flags.backend.max_tools import (CreateFeatureFlagTool,FeatureFlagCreationSchema,MultivariateVariant,)+from products.feature_flags.backend.models.evaluation_context import EvaluationContext, TeamDefaultEvaluationContextfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.hogai.utils.types import AssistantState@@ -18,6 +21,12 @@ from ee.hogai.utils.types import AssistantStateALL_USERS_GROUP = FeatureFlagGroupType(properties=[], rollout_percentage=None)+def _enable_gates(*gates: str):+ """Patch helper so only the named feature gates report enabled, keeping tests honest about what they need."""+ enabled = set(gates)+ return lambda key, *args, **kwargs: key in enabled++class TestCreateFeatureFlagTool(APIBaseTest):def _create_tool(self) -> CreateFeatureFlagTool:return CreateFeatureFlagTool(@@ -459,6 +468,140 @@ class TestCreateFeatureFlagTool(APIBaseTest):assert "Failed to create feature flag" in resultassert "invalid regex pattern" in result+ async def test_create_flag_with_explicit_evaluation_contexts(self):+ with patch("posthoganalytics.feature_enabled", side_effect=_enable_gates("flag-evaluation-tags")):+ tool = self._create_tool()++ schema = FeatureFlagCreationSchema(+ key="eval-context-flag",+ name="Eval Context Flag",+ groups=[ALL_USERS_GROUP],+ evaluation_contexts=["production", "staging"],+ )++ result, artifact = await tool._arun_impl(feature_flag=schema)++ assert "Successfully created" in result+ assert "evaluation contexts: production, staging" in result+ assert set(artifact["evaluation_contexts"]) == {"production", "staging"}++ flag = await FeatureFlag.objects.aget(key="eval-context-flag", team=self.team)+ assert await self._get_evaluation_context_names(flag) == {"production", "staging"}++ @parameterized.expand(+ [+ ("defaults_applied", True, None, {"production"}),+ ("explicit_empty_skips_defaults", True, [], set()),+ ("disabled_skips_defaults", False, None, set()),+ ]+ )+ async def test_create_flag_default_evaluation_contexts(self, name, default_enabled, contexts, expected_names):+ self.team.default_evaluation_contexts_enabled = default_enabled+ await database_sync_to_async(self.team.save)()+ await self._create_default_context("production")++ with patch(+ "posthoganalytics.feature_enabled",+ side_effect=_enable_gates("flag-evaluation-tags", "default-evaluation-environments"),+ ):+ tool = self._create_tool()++ schema = FeatureFlagCreationSchema(+ key=f"default-context-flag-{name}",+ name=f"Default Context Flag {name}",+ groups=[ALL_USERS_GROUP],+ evaluation_contexts=contexts,+ )++ result, _ = await tool._arun_impl(feature_flag=schema)++ assert "Successfully created" in result++ flag = await FeatureFlag.objects.aget(key=f"default-context-flag-{name}", team=self.team)+ assert await self._get_evaluation_context_names(flag) == expected_names++ async def test_create_flag_satisfies_required_evaluation_contexts(self):+ # Reproduces the gap where projects requiring an evaluation context rejected every Max-created flag.+ self.team.require_evaluation_contexts = True+ await database_sync_to_async(self.team.save)()++ with patch("posthoganalytics.feature_enabled", side_effect=_enable_gates("flag-evaluation-tags")):+ tool = self._create_tool()++ schema = FeatureFlagCreationSchema(+ key="required-context-flag",+ name="Required Context Flag",+ groups=[ALL_USERS_GROUP],+ evaluation_contexts=["production"],+ )++ result, artifact = await tool._arun_impl(feature_flag=schema)++ assert "Successfully created" in result+ assert artifact.get("error") is None++ flag = await FeatureFlag.objects.aget(key="required-context-flag", team=self.team)+ assert await self._get_evaluation_context_names(flag) == {"production"}++ async def test_create_flag_required_contexts_satisfied_by_defaults(self):+ # The primary fix: an enforced project creates successfully when the model omits contexts and+ # the project has defaults configured — the tool auto-applies them.+ self.team.require_evaluation_contexts = True+ self.team.default_evaluation_contexts_enabled = True+ await database_sync_to_async(self.team.save)()+ await self._create_default_context("production")++ with patch(+ "posthoganalytics.feature_enabled",+ side_effect=_enable_gates("flag-evaluation-tags", "default-evaluation-environments"),+ ):+ tool = self._create_tool()++ schema = FeatureFlagCreationSchema(+ key="required-default-context-flag",+ name="Required Default Context Flag",+ groups=[ALL_USERS_GROUP],+ )++ result, artifact = await tool._arun_impl(feature_flag=schema)++ assert "Successfully created" in result+ assert artifact.get("error") is None++ flag = await FeatureFlag.objects.aget(key="required-default-context-flag", team=self.team)+ assert await self._get_evaluation_context_names(flag) == {"production"}++ async def test_create_flag_required_contexts_without_defaults_returns_readable_error(self):+ # Still-reachable failure: enforced project, no defaults, model omits contexts → the serializer's+ # ValidationError must surface as a readable message rather than escaping _arun_impl.+ self.team.require_evaluation_contexts = True+ await database_sync_to_async(self.team.save)()++ with patch("posthoganalytics.feature_enabled", side_effect=_enable_gates("flag-evaluation-tags")):+ tool = self._create_tool()++ schema = FeatureFlagCreationSchema(+ key="required-no-default-context-flag",+ name="Required No Default Context Flag",+ groups=[ALL_USERS_GROUP],+ )++ result, artifact = await tool._arun_impl(feature_flag=schema)++ assert "Failed to create feature flag" in result+ assert "At least one evaluation context is required" in result+ assert artifact.get("error") == "validation_error"++ @database_sync_to_async+ def _create_default_context(self, name: str) -> None:+ ctx, _ = EvaluationContext.objects.get_or_create(name=name, team=self.team)+ TeamDefaultEvaluationContext.objects.get_or_create(team=self.team, evaluation_context=ctx)++ @staticmethod+ @database_sync_to_async+ def _get_evaluation_context_names(flag: FeatureFlag) -> set[str]:+ return set(flag.flag_evaluation_contexts.values_list("evaluation_context__name", flat=True))+@staticmethodasync def _get_tag_names(flag: FeatureFlag) -> list[str]:from posthog.models import TaggedItem