: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(flags): implement early exit functionality for feature flag conditions (#57321)
Gustavo H. Strassburger0cff83a04b07
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 12370a6a66ee..4332f445cb41 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -296,6 +296,7 @@ export const FEATURE_FLAGS = {FEATURE_FLAG_COHORT_CREATION: 'feature-flag-cohort-creation', // owner: #team-feature-flagsFEATURE_FLAG_CREATION_INTENTS: 'feature-flag-creation-intents', // owner: #team-feature-flagsFEATURE_FLAG_DRAG_DROP_CONDITIONS: 'feature-flag-drag-drop-conditions', // owner: @gustavo #team-feature-flags+ FEATURE_FLAG_EARLY_EXIT: 'feature-flag-early-exit', // owner: @gustavo #team-feature-flagsFEATURE_FLAG_MIXED_TARGETING: 'feature-flag-mixed-targeting', // owner: @dmarticus #team-feature-flagsFEATURE_FLAG_NOTIFICATIONS: 'feature-flag-notifications', // owner: @reecejones #team-platform-featuresFEATURE_FLAG_USAGE_DASHBOARD_CHECKBOX: 'feature-flag-usage-dashboard-checkbox', // owner: #team-feature-flags, globally disabled, enables opt-out of auto dashboard creationdiff --git a/frontend/src/scenes/feature-flags/DefaultReleaseConditions.tsx b/frontend/src/scenes/feature-flags/DefaultReleaseConditions.tsxindex 935cc2e86b4b..94610c570139 100644--- a/frontend/src/scenes/feature-flags/DefaultReleaseConditions.tsx+++ b/frontend/src/scenes/feature-flags/DefaultReleaseConditions.tsx@@ -46,6 +46,7 @@ export function DefaultReleaseConditions(): JSX.Element {setLocalGroups(updatedFilters.groups)}}isDisabled={!!restrictedReason}+ hideEarlyExit/></div>)}diff --git a/frontend/src/scenes/feature-flags/EarlyExitIndicator.tsx b/frontend/src/scenes/feature-flags/EarlyExitIndicator.tsxnew file mode 100644index 000000000000..50622518382a--- /dev/null+++ b/frontend/src/scenes/feature-flags/EarlyExitIndicator.tsx@@ -0,0 +1,13 @@+import { IconInfo } from '@posthog/icons'+import { Tooltip } from '@posthog/lemon-ui'++export function EarlyExitIndicator(): JSX.Element {+ return (+ <div className="flex items-center gap-1.5 text-xs text-muted">+ <Tooltip title="Conditions are evaluated in order — the first matching condition set determines the result and later conditions are skipped.">+ <IconInfo className="text-sm" />+ </Tooltip>+ <span>Stops evaluation at first matching condition set</span>+ </div>+ )+}diff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsxindex dc5f4f04e606..33f1d5d37006 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsCollapsible.tsx@@ -32,6 +32,7 @@ import {import {LemonBanner,LemonButton,+ LemonCheckbox,LemonInput,LemonLabel,LemonMenu,@@ -71,6 +72,7 @@ import {import { INTENT_METADATA } from 'products/feature_flags/frontend/featureFlagTemplateConstants'import { COHORTS_ONLY_SUPPORT_IN_PICKER_PROPS } from './cohortPickerProps'+import { EarlyExitIndicator } from './EarlyExitIndicator'import { FeatureFlagConditionDragHandle } from './FeatureFlagConditionDragHandle'import { FeatureFlagConditionWarning } from './FeatureFlagConditionWarning'import { FlagIntent, featureFlagIntentWarningLogic } from './featureFlagIntentWarningLogic'@@ -91,6 +93,8 @@ interface FeatureFlagReleaseConditionsCollapsibleProps extends FeatureFlagReleasevaluationRuntime?: FeatureFlagEvaluationRuntime/** When true, hides the "Match by" User/Group selector. Use when the aggregation type is inherited from the parent flag. */hideMatchOptions?: boolean+ /** When true, hides the early exit toggle. Use in contexts where early_exit cannot be persisted (e.g. default release conditions). */+ hideEarlyExit?: boolean}const PERSON = 'person' as const@@ -801,6 +805,7 @@ export function FeatureFlagReleaseConditionsCollapsible({onBucketingIdentifierChange,evaluationRuntime,hideMatchOptions,+ hideEarlyExit,}: FeatureFlagReleaseConditionsCollapsibleProps): JSX.Element {const releaseConditionsLogic = featureFlagReleaseConditionsLogic({id,@@ -851,6 +856,7 @@ export function FeatureFlagReleaseConditionsCollapsible({switchToMixedTargeting,setIsAnyItemDragging,setDraggedGroup,+ setEarlyExit,} = useActions(releaseConditionsLogic)const handleAddConditionSet = (): void => {@@ -912,6 +918,7 @@ export function FeatureFlagReleaseConditionsCollapsible({return (<div className="flex flex-col gap-2"><LemonLabel>Release conditions</LemonLabel>+ {releaseFilters.early_exit && <EarlyExitIndicator />}{filterGroups.map((group: FeatureFlagGroupType, index: number) => {// Use description if available, otherwise summarize the filtersconst summary =@@ -1078,10 +1085,31 @@ export function FeatureFlagReleaseConditionsCollapsible({<LemonLabel>Release conditions</LemonLabel></div><p className="text-xs text-muted mb-2">- Target users for this flag. Conditions are evaluated top to bottom – the first match wins. A condition- matches when all property filters pass AND the target falls within the rollout percentage.+ Target users for this flag. A condition matches when all property filters pass AND the target falls+ within the rollout percentage.</p>+ {!!featureFlags[FEATURE_FLAGS.FEATURE_FLAG_EARLY_EXIT] && !hideEarlyExit && (+ <div className="flex flex-col gap-2 mb-2">+ <div className="flex items-center gap-2">+ <LemonCheckbox+ data-attr="flag-early-exit"+ checked={releaseFilters.early_exit ?? false}+ onChange={(checked) => setEarlyExit(checked)}+ label="Stop evaluation at first matching condition set"+ info="When enabled, conditions are evaluated in order — the first matching condition set determines the result and later conditions are skipped. When disabled, all conditions are evaluated, and a pass on any condition is a pass."+ />+ </div>+ {releaseFilters.early_exit && (+ <LemonBanner type="warning" className="mt-1">+ Early exit is not applied when a server-side SDK evaluates this flag with local evaluation —+ those SDKs evaluate all condition sets. It takes effect when the flag is evaluated through+ the <code>/flags</code> endpoint.+ </LemonBanner>+ )}+ </div>+ )}+{isDisabled && (<LemonBanner type="info" className="mb-3">This flag is currently <b>disabled</b>. These release conditions won't take effect until you enablediff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsReadonly.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsReadonly.tsxindex 75237ad52d29..d8ecfb25078d 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsReadonly.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsReadonly.tsx@@ -18,6 +18,7 @@ import {PropertyFilterType,} from '~/types'+import { EarlyExitIndicator } from './EarlyExitIndicator'import { FeatureFlagConditionWarning } from './FeatureFlagConditionWarning'import { featureFlagReleaseConditionsLogic } from './featureFlagReleaseConditionsLogic'@@ -125,6 +126,8 @@ export function FeatureFlagReleaseConditionsReadonly({Condition sets are evaluated top to bottom — the first match wins.</p>+ {filters.early_exit && <EarlyExitIndicator />}+<FeatureFlagConditionWarning properties={properties} evaluationRuntime={evaluationRuntime} /><div className={isDisabled ? 'opacity-60' : ''}>diff --git a/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.test.tsindex e3ad4eda69d5..66f03c95cbd8 100644--- a/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.test.ts@@ -785,6 +785,34 @@ describe('the feature flag release conditions logic', () => {})})+ describe('early exit', () => {+ it('enables early exit at the flag level', () => {+ logic.actions.setEarlyExit(true)++ expect(logic.values.filters.early_exit).toBe(true)+ })++ it('disables early exit', () => {+ logic.actions.setEarlyExit(true)+ logic.actions.setEarlyExit(false)++ expect(logic.values.filters.early_exit).toBe(false)+ })++ it('preserves condition sets when toggling early exit', () => {+ const filters = generateFeatureFlagFilters([+ { properties: [], rollout_percentage: 50, variant: null, sort_key: 'A' },+ { properties: [], rollout_percentage: 75, variant: null, sort_key: 'B' },+ ])+ logic.actions.setFilters(filters)++ logic.actions.setEarlyExit(true)++ expect(logic.values.filters.early_exit).toBe(true)+ expect(logic.values.filters.groups).toEqual(filters.groups)+ })+ })+describe('open conditions state', () => {it('initializes first condition as open when there is only one group', async () => {logic?.unmount()diff --git a/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.ts b/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.tsindex d320ce6f7d66..c1a07ae92b71 100644--- a/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.ts@@ -105,6 +105,7 @@ export const featureFlagReleaseConditionsLogic = kea<featureFlagReleaseConditionnewVariant,newDescription,}),+ setEarlyExit: (earlyExit: boolean) => ({ earlyExit }),setConditionAggregation: (index: number, groupTypeIndex: number | null) => ({index,groupTypeIndex,@@ -252,6 +253,12 @@ export const featureFlagReleaseConditionsLogic = kea<featureFlagReleaseConditionreturn { ...state, groups }},+ setEarlyExit: (state, { earlyExit }) => {+ if (!state) {+ return state+ }+ return { ...state, early_exit: earlyExit }+ },switchToMixedTargeting: (state) => {if (!state) {return statediff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 3b8029dd0f72..dbdabd065ed8 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -4095,6 +4095,7 @@ export interface FeatureFlagFilters {multivariate?: MultivariateFlagOptions | nullaggregation_group_type_index?: integer | nullpayloads?: Record<string, JsonType>+ early_exit?: booleanfeature_enrollment?: boolean}diff --git a/posthog/api/documentation.py b/posthog/api/documentation.pyindex 915c0ab41e03..21d3e2e24c52 100644--- a/posthog/api/documentation.py+++ b/posthog/api/documentation.py@@ -531,6 +531,11 @@ class FeatureFlagFiltersSchemaSerializer(serializers.Serializer):allow_null=True,help_text="Whether this flag has early access feature enrollment enabled. When true, the flag is evaluated against the person property $feature_enrollment/{flag_key}.",)+ early_exit = serializers.BooleanField(+ required=False,+ default=False,+ help_text="When true, condition evaluation stops at the first matching condition set rather than continuing to evaluate subsequent groups.",+ )property_help_text = "Filter events by event property, person property, cohort, groups and more."diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 063689eaa848..8214f8eb0501 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -117,6 +117,7 @@ BEHAVIOURAL_COHORT_FOUND_ERROR_CODE = "behavioral_cohort_found"REALTIME_COHORT_FLAG_TARGETING_FLAG = "realtime-cohort-flag-targeting"MIXED_TARGETING_FLAG = "feature-flag-mixed-targeting"+EARLY_EXIT_FLAG = "feature-flag-early-exit"# Fields that Rust's FeatureFlag struct expects for historical evaluationRUST_FLAG_FIELDS = (@@ -1077,6 +1078,22 @@ class FeatureFlagSerializer(if p.get("operator") in ("regex", "not_regex") and isinstance(p.get("value"), str):existing_patterns.add(p["value"])+ early_exit = filters.get("early_exit")+ if early_exit is not None and not isinstance(early_exit, bool):+ raise serializers.ValidationError(f"early_exit must be a boolean or null, got {type(early_exit).__name__}")++ # Gate enabling early_exit behind the feature-flag-early-exit flag. The UI hides+ # the toggle, but the public REST API, MCP tools, and terraform provider all reach+ # this validator — without the gate they could persist early_exit before server-side+ # local evaluation honors it. Only block newly turning it on: leaving an existing+ # truthy value unchanged (or turning it off) always passes, so flags created while+ # the feature was enabled keep working if access is later revoked.+ previously_enabled = (+ bool((self.instance.filters or {}).get("early_exit")) if self.instance is not None else False+ )+ if early_exit and not previously_enabled and not self._is_early_exit_enabled():+ raise serializers.ValidationError("early_exit is not available for this organization.")+for group_index, group in enumerate(filters.get("groups", [])):variant = group.get("variant")if variant is not None and not isinstance(variant, str):@@ -1456,6 +1473,26 @@ class FeatureFlagSerializer(logger.exception("Failed to check mixed targeting flag")return False+ def _is_early_exit_enabled(self) -> bool:+ try:+ request = self.context.get("request")+ if not request:+ return False+ user = getattr(request, "user", None)+ if user is None or user.is_anonymous:+ return False+ return posthoganalytics.feature_enabled(+ EARLY_EXIT_FLAG,+ user.distinct_id,+ groups={"organization": str(user.organization.id)},+ group_properties={"organization": {"id": str(user.organization.id)}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ except Exception:+ logger.exception("Failed to check early exit flag")+ return False+def _check_flag_circular_dependencies(self, filters):"""Check for circular dependencies in feature flag conditions."""diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex bd97ebf18241..1a369a897766 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -638,6 +638,124 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):flag = FeatureFlag.objects.get(key="string-variant-preserved", team=self.team)self.assertEqual(flag.filters["groups"][0]["variant"], "control")+ @parameterized.expand(+ [+ ("true", True),+ ("false", False),+ ]+ )+ @patch("products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled")+ def test_boolean_early_exit_accepted(self, _name, value, mock_feature_enabled):+ mock_feature_enabled.return_value = True+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ data={+ "name": f"Early exit {_name}",+ "key": f"early-exit-{_name}",+ "filters": {+ "early_exit": value,+ "groups": [{"rollout_percentage": 100}],+ },+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ flag = FeatureFlag.objects.get(key=f"early-exit-{_name}", team=self.team)+ self.assertEqual(flag.filters["early_exit"], value)++ @patch("products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled")+ def test_early_exit_rejected_without_feature_flag(self, mock_feature_enabled):+ mock_feature_enabled.return_value = False+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ data={+ "name": "Early exit gated",+ "key": "early-exit-gated",+ "filters": {+ "early_exit": True,+ "groups": [{"rollout_percentage": 100}],+ },+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn("early_exit is not available", response.json()["detail"])++ @patch("products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled")+ def test_early_exit_false_accepted_without_feature_flag(self, mock_feature_enabled):+ mock_feature_enabled.return_value = False+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ data={+ "name": "Early exit off",+ "key": "early-exit-off",+ "filters": {+ "early_exit": False,+ "groups": [{"rollout_percentage": 100}],+ },+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)++ @patch("products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled")+ def test_early_exit_unchanged_truthy_allowed_when_flag_disabled(self, mock_feature_enabled):+ # A flag created while the feature was enabled keeps working if access is later revoked,+ # as long as the PATCH doesn't newly turn early_exit on.+ flag = FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key="early-exit-existing",+ filters={"early_exit": True, "groups": [{"rollout_percentage": 100}]},+ )+ mock_feature_enabled.return_value = False+ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",+ data={"filters": {"early_exit": True, "groups": [{"rollout_percentage": 50}]}},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ def test_null_early_exit_accepted(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ data={+ "name": "Early exit null",+ "key": "early-exit-null",+ "filters": {+ "early_exit": None,+ "groups": [{"rollout_percentage": 100}],+ },+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)++ @parameterized.expand(+ [+ ("int", 1, "int"),+ ("string_true", "true", "str"),+ ("string_false", "false", "str"),+ ("float", 1.5, "float"),+ ]+ )+ def test_non_boolean_early_exit_rejected(self, _name, bad_value, expected_type):+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ data={+ "name": f"Bad early_exit {_name}",+ "key": f"bad-early-exit-{_name}",+ "filters": {+ "early_exit": bad_value,+ "groups": [{"rollout_percentage": 100}],+ },+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn("early_exit must be a boolean", response.json()["detail"])+ self.assertIn(expected_type, response.json()["detail"])+@parameterized.expand([("string_int", "100"),@@ -13730,6 +13848,44 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):# Should only include 'email' since that's referenced in the flag, not 'name' or 'age'self.assertEqual(data["person_properties"], {"email": "[email protected]"})+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")+ @override_settings(INTERNAL_REQUEST_TOKEN="test-token")+ def test_test_evaluation_filters_feature_enrollment_property(self, mock_get_flags):+ flag = FeatureFlag.objects.create(+ team=self.team,+ key="enroll-flag",+ filters={"feature_enrollment": True, "groups": [{"properties": []}]},+ )+ enrollment_key = f"$feature_enrollment/{flag.key}"+ Person.objects.create(+ team=self.team,+ distinct_ids=["test-user"],+ properties={enrollment_key: True, "email": "[email protected]"},+ )++ mock_get_flags.return_value = {+ "flags": {+ "enroll-flag": {+ "enabled": True,+ "variant": None,+ "reason": {"code": "super_condition_value"},+ "metadata": {},+ "conditions": [],+ }+ }+ }++ response = self.client.post(+ f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",+ {"distinct_id": "test-user"},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ # enrollment key is kept; unrelated 'email' is filtered out+ self.assertEqual(data["person_properties"], {enrollment_key: True})+@patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")@override_settings(INTERNAL_REQUEST_TOKEN="test-token")def test_test_evaluation_unexpected_response_type(self, mock_get_flags):diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.tsindex 78b28bf11bb2..d9bbf6b7bfea 100644--- a/products/feature_flags/frontend/generated/api.schemas.ts+++ b/products/feature_flags/frontend/generated/api.schemas.ts@@ -655,6 +655,8 @@ export interface FeatureFlagFiltersSchemaApi {* @nullable*/feature_enrollment?: boolean | null+ /** When true, condition evaluation stops at the first matching condition set rather than continuing to evaluate subsequent groups. */+ early_exit?: boolean}export interface FeatureFlagCreateRequestSchemaApi {diff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.tsindex 24fcc0c2f6af..c44ff81e637c 100644--- a/products/feature_flags/frontend/generated/api.zod.ts+++ b/products/feature_flags/frontend/generated/api.zod.ts@@ -38,6 +38,8 @@ export const FeatureFlagsCopyFlagsCreateBody = /* @__PURE__ */ zod.object({If you're looking to use feature flags on your application, you can either use our JavaScript Library or our dedicated endpoint to check if feature flags are enabled for a given user.*/+export const featureFlagsCreateBodyFiltersOneEarlyExitDefault = false+export const FeatureFlagsCreateBody = /* @__PURE__ */ zod.object({key: zod.string().optional().describe('Feature flag key.'),name: zod@@ -315,6 +317,12 @@ export const FeatureFlagsCreateBody = /* @__PURE__ */ zod.object({.describe('Whether this flag has early access feature enrollment enabled. When true, the flag is evaluated against the person property $feature_enrollment\/{flag_key}.'),+ early_exit: zod+ .boolean()+ .default(featureFlagsCreateBodyFiltersOneEarlyExitDefault)+ .describe(+ 'When true, condition evaluation stops at the first matching condition set rather than continuing to evaluate subsequent groups.'+ ),}).optional().describe('Feature flag targeting configuration.'),@@ -411,6 +419,8 @@ export const FeatureFlagsUpdateBody = /* @__PURE__ */ zodIf you're looking to use feature flags on your application, you can either use our JavaScript Library or our dedicated endpoint to check if feature flags are enabled for a given user.*/+export const featureFlagsPartialUpdateBodyFiltersOneEarlyExitDefault = false+export const FeatureFlagsPartialUpdateBody = /* @__PURE__ */ zod.object({key: zod.string().optional().describe('Feature flag key.'),name: zod@@ -688,6 +698,12 @@ export const FeatureFlagsPartialUpdateBody = /* @__PURE__ */ zod.object({.describe('Whether this flag has early access feature enrollment enabled. When true, the flag is evaluated against the person property $feature_enrollment\/{flag_key}.'),+ early_exit: zod+ .boolean()+ .default(featureFlagsPartialUpdateBodyFiltersOneEarlyExitDefault)+ .describe(+ 'When true, condition evaluation stops at the first matching condition set rather than continuing to evaluate subsequent groups.'+ ),}).optional().describe('Feature flag targeting configuration.'),diff --git a/products/surveys/frontend/generated/api.schemas.ts b/products/surveys/frontend/generated/api.schemas.tsindex 23e6887d35f1..4356223fc4ff 100644--- a/products/surveys/frontend/generated/api.schemas.ts+++ b/products/surveys/frontend/generated/api.schemas.ts@@ -795,6 +795,8 @@ export interface FeatureFlagFiltersSchemaApi {* @nullable*/feature_enrollment?: boolean | null+ /** When true, condition evaluation stops at the first matching condition set rather than continuing to evaluate subsequent groups. */+ early_exit?: boolean}/**diff --git a/products/surveys/frontend/generated/api.zod.ts b/products/surveys/frontend/generated/api.zod.tsindex cd08c758fc14..44753673eeb7 100644--- a/products/surveys/frontend/generated/api.zod.ts+++ b/products/surveys/frontend/generated/api.zod.ts@@ -11,6 +11,7 @@ import * as zod from 'zod'export const surveysCreateBodyNameMax = 400+export const surveysCreateBodyTargetingFlagFiltersOneEarlyExitDefault = falseexport const surveysCreateBodyQuestionsItemThreeBranchingOneThreeIndexMin = 0export const surveysCreateBodyQuestionsItemThreeBranchingOneFourResponseValuesOneMin = 0@@ -369,6 +370,12 @@ export const SurveysCreateBody = /* @__PURE__ */ zod.object({.describe('Whether this flag has early access feature enrollment enabled. When true, the flag is evaluated against the person property $feature_enrollment\/{flag_key}.'),+ early_exit: zod+ .boolean()+ .default(surveysCreateBodyTargetingFlagFiltersOneEarlyExitDefault)+ .describe(+ 'When true, condition evaluation stops at the first matching condition set rather than continuing to evaluate subsequent groups.'+ ),}),zod.null(),])@@ -893,6 +900,7 @@ export const SurveysUpdateBody = /* @__PURE__ */ zodexport const surveysPartialUpdateBodyNameMax = 400+export const surveysPartialUpdateBodyTargetingFlagFiltersOneEarlyExitDefault = falseexport const surveysPartialUpdateBodyQuestionsItemThreeBranchingOneThreeIndexMin = 0export const surveysPartialUpdateBodyQuestionsItemThreeBranchingOneFourResponseValuesOneMin = 0@@ -1252,6 +1260,12 @@ export const SurveysPartialUpdateBody = /* @__PURE__ */ zod.object({.describe('Whether this flag has early access feature enrollment enabled. When true, the flag is evaluated against the person property $feature_enrollment\/{flag_key}.'),+ early_exit: zod+ .boolean()+ .default(surveysPartialUpdateBodyTargetingFlagFiltersOneEarlyExitDefault)+ .describe(+ 'When true, condition evaluation stops at the first matching condition set rather than continuing to evaluate subsequent groups.'+ ),}),zod.null(),])diff --git a/rust/feature-flags/src/flags/feature_flag_list.rs b/rust/feature-flags/src/flags/feature_flag_list.rsindex 3df3b877b962..b8f482f2e1dd 100644--- a/rust/feature-flags/src/flags/feature_flag_list.rs+++ b/rust/feature-flags/src/flags/feature_flag_list.rs@@ -1240,6 +1240,7 @@ mod tests {payloads: None,feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),},active: true,diff --git a/rust/feature-flags/src/flags/flag_definitions_cache.rs b/rust/feature-flags/src/flags/flag_definitions_cache.rsindex 9f32a93687b9..449171c93cb0 100644--- a/rust/feature-flags/src/flags/flag_definitions_cache.rs+++ b/rust/feature-flags/src/flags/flag_definitions_cache.rs@@ -832,6 +832,7 @@ mod tests {payloads: None,feature_enrollment: None,holdout: None,+ early_exit: None,extra: filters_extra,};flagdiff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rsindex 532f369ec955..e678b97b901a 100644--- a/rust/feature-flags/src/flags/flag_matching.rs+++ b/rust/feature-flags/src/flags/flag_matching.rs@@ -1292,6 +1292,7 @@ impl FeatureFlagMatcher {let conditions: Vec<(usize, &FlagPropertyGroup)> =flag.get_conditions().iter().enumerate().collect();+ let early_exit_enabled = flag.filters.early_exit.unwrap_or(false);let condition_timer = common_metrics::timing_guard(FLAG_EVALUATE_ALL_CONDITIONS_TIME, &[]);for (index, condition) in conditions {// Each condition resolves its own aggregation, falling back to the flag-level@@ -1412,6 +1413,22 @@ impl FeatureFlagMatcher {request_hash_key_override,)?;+ // OutOfRolloutBound means the condition's property filters (if any) already+ // matched and only the rollout check failed, so re-evaluating later groups+ // can't change the outcome.+ if early_exit_enabled+ && !is_match+ && reason == FeatureFlagMatchReason::OutOfRolloutBound+ {+ return Ok(FeatureFlagMatch {+ matches: false,+ variant: None,+ reason: FeatureFlagMatchReason::OutOfRolloutBound,+ condition_index: Some(index),+ payload: None,+ });+ }+// Update highest_match and highest_indexlet (new_highest_match, new_highest_index) = self.get_highest_priority_match_evaluation(diff --git a/rust/feature-flags/src/flags/flag_models.rs b/rust/feature-flags/src/flags/flag_models.rsindex 3755ee2c6386..6b40abe58214 100644--- a/rust/feature-flags/src/flags/flag_models.rs+++ b/rust/feature-flags/src/flags/flag_models.rs@@ -209,6 +209,10 @@ pub struct FlagFilters {/// Defines a set of users intentionally excluded from a test or experiment.#[serde(default)]pub holdout: Option<Holdout>,+ /// Flag-level toggle: when true, condition evaluation stops at the first+ /// matching group rather than continuing to evaluate subsequent groups.+ #[serde(default)]+ pub early_exit: Option<bool>,/// Captures unknown JSONB keys so they survive the cache round-trip unchanged./// Without this, legacy filter keys (`holdout_groups`), top-level stray keys,/// and field typos (`multivariant` for `multivariate`, `payload` fordiff --git a/rust/feature-flags/src/flags/flag_service.rs b/rust/feature-flags/src/flags/flag_service.rsindex f94917c1d2ef..06729c8c99ff 100644--- a/rust/feature-flags/src/flags/flag_service.rs+++ b/rust/feature-flags/src/flags/flag_service.rs@@ -452,6 +452,7 @@ mod tests {payloads: None,feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),},deleted: false,@@ -474,6 +475,7 @@ mod tests {payloads: None,feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),},deleted: false,@@ -510,6 +512,7 @@ mod tests {payloads: None,feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),},deleted: false,@@ -643,6 +646,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),},ensure_experience_continuity: Some(false),diff --git a/rust/feature-flags/src/flags/test_flag_matching.rs b/rust/feature-flags/src/flags/test_flag_matching.rsindex f25d79ad7b39..27f26ce2b449 100644--- a/rust/feature-flags/src/flags/test_flag_matching.rs+++ b/rust/feature-flags/src/flags/test_flag_matching.rs@@ -383,6 +383,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -468,6 +469,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -722,6 +724,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -1160,6 +1163,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -2056,6 +2060,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -2288,6 +2293,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -2399,6 +2405,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -2495,6 +2502,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -2591,6 +2599,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -2708,6 +2717,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -2804,6 +2814,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -2900,6 +2911,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -2988,6 +3000,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -3071,6 +3084,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -3169,6 +3183,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -3246,6 +3261,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),},ensure_experience_continuity: Some(true)@@ -3351,6 +3367,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),},ensure_experience_continuity: Some(true)@@ -3439,6 +3456,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),},ensure_experience_continuity: Some(true)@@ -3472,6 +3490,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -3595,6 +3614,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -3662,6 +3682,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -3760,6 +3781,7 @@ mod tests {payloads: None,feature_enrollment: None,+ early_exit: None,extra: Default::default(),});@@ -3794,6 +3816,7 @@ mod tests {payloads: None,feature_enrollment: None,+ early_exit: None,extra: Default::default(),});@@ -3828,6 +3851,7 @@ mod tests {payloads: None,feature_enrollment: None,+ early_exit: None,extra: Default::default(),});@@ -3997,6 +4021,7 @@ mod tests {payloads: None,feature_enrollment: None,+ early_exit: None,extra: Default::default(),});@@ -4116,6 +4141,7 @@ mod tests {payloads: None,feature_enrollment: None,+ early_exit: None,extra: Default::default(),});@@ -4203,6 +4229,7 @@ mod tests {payloads: None,feature_enrollment: None,+ early_exit: None,extra: Default::default(),});@@ -4305,6 +4332,7 @@ mod tests {payloads: None,feature_enrollment: None,+ early_exit: None,extra: Default::default(),});@@ -4382,6 +4410,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),},deleted: false,@@ -4531,6 +4560,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -4594,6 +4624,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -4657,6 +4688,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -5155,6 +5187,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -5416,6 +5449,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -5707,6 +5741,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),},deleted: false,@@ -6676,6 +6711,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),},ensure_experience_continuity: Some(true)@@ -6783,6 +6819,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),},ensure_experience_continuity: Some(true)@@ -6943,6 +6980,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),},ensure_experience_continuity: Some(true)@@ -6967,6 +7005,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),},ensure_experience_continuity: Some(true)@@ -6991,6 +7030,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -7106,6 +7146,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),},ensure_experience_continuity: Some(true)@@ -7130,6 +7171,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),},ensure_experience_continuity: Some(true)@@ -7335,6 +7377,7 @@ mod tests {feature_enrollment: Some(true),holdout: None,+ early_exit: None,extra: Default::default(),});@@ -7398,6 +7441,7 @@ mod tests {feature_enrollment: Some(true),holdout: None,+ early_exit: None,extra: Default::default(),});@@ -7468,6 +7512,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -7500,6 +7545,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -7803,6 +7849,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -7897,6 +7944,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -7974,6 +8022,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -8061,6 +8110,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -8210,6 +8260,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -8303,6 +8354,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -8386,6 +8438,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -8466,6 +8519,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -8566,6 +8620,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -8663,6 +8718,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -8736,6 +8792,7 @@ mod tests {feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),});@@ -9081,4 +9138,845 @@ mod tests {assert!(result.is_empty());}}++ #[tokio::test]+ async fn test_early_exit_behavior() {+ let context = TestContext::new(None).await;+ let cohort_cache = Arc::new(CohortCacheManager::new(+ context.non_persons_reader.clone(),+ None,+ None,+ ));+ let team = context.insert_new_team(None).await.unwrap();++ // Create a flag with flag-level early_exit and two conditions:+ // 1. First condition: matches properties but has 0% rollout+ // 2. Second condition: would match all users with 100% rollout+ let flag = mock!(FeatureFlag,+ id: 1,+ team_id: team.id,+ key: "early-exit-test-flag".mock_into(),+ active: true,+ filters: FlagFilters {+ groups: vec![+ FlagPropertyGroup {+ properties: Some(vec![PropertyFilter {+ key: "email".to_string(),+ value: Some(json!("[email protected]")),+ operator: Some(OperatorType::Exact),+ prop_type: PropertyType::Person,+ group_type_index: None,+ negation: None,+ compiled_regex: None,+ extra: Default::default(),+ }]),+ rollout_percentage: Some(0.0),+ variant: None,+ aggregation_group_type_index: None,+ extra: Default::default(),+ },+ FlagPropertyGroup {+ properties: Some(vec![]),+ rollout_percentage: Some(100.0),+ variant: None,+ aggregation_group_type_index: None,+ extra: Default::default(),+ },+ ],+ multivariate: None,+ aggregation_group_type_index: None,+ payloads: None,+ feature_enrollment: None,+ holdout: None,+ early_exit: Some(true),+ extra: Default::default(),+ }+ );++ let mut matcher = FeatureFlagMatcher::new(+ "test_user".to_string(),+ None, // device_id+ team.id,+ context.create_postgres_router(),+ cohort_cache.clone(),+ empty_group_type_cache(),+ None,+ );++ let person_overrides = HashMap::from([("email".to_string(), json!("[email protected]"))]);+ let flags = flag_list_with_metadata(vec![flag.clone()]);+ let result = matcher+ .evaluate_all_feature_flags(+ flags,+ Some(person_overrides),+ None,+ None,+ Uuid::new_v4(),+ None,+ false,+ )+ .await+ .unwrap();++ // Should exit early at the first condition due to early_exit: true+ // Even though the second condition would match with 100% rollout+ let flag_result = result.flags.get("early-exit-test-flag").unwrap();+ assert!(!flag_result.enabled);+ assert_eq!(flag_result.reason.code, "out_of_rollout_bound");+ assert_eq!(flag_result.reason.condition_index, Some(0));+ }++ #[tokio::test]+ async fn test_early_exit_disabled_continues_evaluation() {+ let context = TestContext::new(None).await;+ let cohort_cache = Arc::new(CohortCacheManager::new(+ context.non_persons_reader.clone(),+ None,+ None,+ ));+ let team = context.insert_new_team(None).await.unwrap();++ // Same setup but with flag-level early_exit disabled+ let flag = mock!(FeatureFlag,+ id: 2,+ team_id: team.id,+ key: "no-early-exit-test-flag".mock_into(),+ active: true,+ filters: FlagFilters {+ groups: vec![+ FlagPropertyGroup {+ properties: Some(vec![PropertyFilter {+ key: "email".to_string(),+ value: Some(json!("[email protected]")),+ operator: Some(OperatorType::Exact),+ prop_type: PropertyType::Person,+ group_type_index: None,+ negation: None,+ compiled_regex: None,+ extra: Default::default(),+ }]),+ rollout_percentage: Some(0.0),+ variant: None,+ aggregation_group_type_index: None,+ extra: Default::default(),+ },+ FlagPropertyGroup {+ properties: Some(vec![]),+ rollout_percentage: Some(100.0),+ variant: None,+ aggregation_group_type_index: None,+ extra: Default::default(),+ },+ ],+ multivariate: None,+ aggregation_group_type_index: None,+ payloads: None,+ feature_enrollment: None,+ holdout: None,+ early_exit: Some(false),+ extra: Default::default(),+ }+ );++ let mut matcher = FeatureFlagMatcher::new(+ "test_user".to_string(),+ None, // device_id+ team.id,+ context.create_postgres_router(),+ cohort_cache.clone(),+ empty_group_type_cache(),+ None,+ );++ let person_overrides = HashMap::from([("email".to_string(), json!("[email protected]"))]);+ let flags = flag_list_with_metadata(vec![flag.clone()]);+ let result = matcher+ .evaluate_all_feature_flags(+ flags,+ Some(person_overrides),+ None,+ None,+ Uuid::new_v4(),+ None,+ false,+ )+ .await+ .unwrap();++ let flag_result = result.flags.get("no-early-exit-test-flag").unwrap();+ assert!(flag_result.enabled);+ assert_eq!(flag_result.reason.condition_index, Some(1));+ }++ /// early_exit only fires on the *matching* condition, not at index 0 unconditionally.+ /// Layout: condition 0 = no-match (wrong email), condition 1 = matches props + 0% rollout,+ /// condition 2 = 100% catch-all. early_exit must stop at index 1, never reaching index 2.+ #[tokio::test]+ async fn test_early_exit_non_first_position() {+ let context = TestContext::new(None).await;+ let cohort_cache = Arc::new(CohortCacheManager::new(+ context.non_persons_reader.clone(),+ None,+ None,+ ));+ let team = context.insert_new_team(None).await.unwrap();++ let flag = mock!(FeatureFlag,+ id: 1,+ team_id: team.id,+ key: "early-exit-non-first".mock_into(),+ active: true,+ filters: FlagFilters {+ groups: vec![+ // Condition 0: property does not match — NoConditionMatch, no early exit+ FlagPropertyGroup {+ properties: Some(vec![PropertyFilter {+ key: "email".to_string(),+ value: Some(json!("[email protected]")),+ operator: Some(OperatorType::Exact),+ prop_type: PropertyType::Person,+ group_type_index: None,+ negation: None,+ compiled_regex: None,+ extra: Default::default(),+ }]),+ rollout_percentage: Some(100.0),+ variant: None,+ aggregation_group_type_index: None,+ extra: Default::default(),+ },+ // Condition 1: property matches but 0% rollout — OutOfRolloutBound → early exit+ FlagPropertyGroup {+ properties: Some(vec![PropertyFilter {+ key: "email".to_string(),+ value: Some(json!("[email protected]")),+ operator: Some(OperatorType::Exact),+ prop_type: PropertyType::Person,+ group_type_index: None,+ negation: None,+ compiled_regex: None,+ extra: Default::default(),+ }]),+ rollout_percentage: Some(0.0),+ variant: None,+ aggregation_group_type_index: None,+ extra: Default::default(),+ },+ // Condition 2: catch-all 100% — must never be reached+ FlagPropertyGroup {+ properties: Some(vec![]),+ rollout_percentage: Some(100.0),+ variant: None,+ aggregation_group_type_index: None,+ extra: Default::default(),+ },+ ],+ multivariate: None,+ aggregation_group_type_index: None,+ payloads: None,+ feature_enrollment: None,+ holdout: None,+ early_exit: Some(true),+ extra: Default::default(),+ }+ );++ let mut matcher = FeatureFlagMatcher::new(+ "test_user".to_string(),+ None,+ team.id,+ context.create_postgres_router(),+ cohort_cache,+ empty_group_type_cache(),+ None,+ );++ let person_overrides = HashMap::from([("email".to_string(), json!("[email protected]"))]);+ let flags = flag_list_with_metadata(vec![flag.clone()]);+ let result = matcher+ .evaluate_all_feature_flags(+ flags,+ Some(person_overrides),+ None,+ None,+ Uuid::new_v4(),+ None,+ false,+ )+ .await+ .unwrap();++ let flag_result = result.flags.get("early-exit-non-first").unwrap();+ assert!(!flag_result.enabled);+ assert_eq!(flag_result.reason.code, "out_of_rollout_bound");+ // Must stop at condition 1, not fall through to condition 2+ assert_eq!(flag_result.reason.condition_index, Some(1));+ }++ /// A condition where properties do NOT match produces NoConditionMatch, not+ /// OutOfRolloutBound. early_exit must not fire and evaluation must continue+ /// to the next condition. This guards against any future broadening of the+ /// early-exit guard beyond OutOfRolloutBound.+ #[tokio::test]+ async fn test_early_exit_no_condition_match_does_not_short_circuit() {+ let context = TestContext::new(None).await;+ let cohort_cache = Arc::new(CohortCacheManager::new(+ context.non_persons_reader.clone(),+ None,+ None,+ ));+ let team = context.insert_new_team(None).await.unwrap();++ let flag = mock!(FeatureFlag,+ id: 1,+ team_id: team.id,+ key: "early-exit-no-condition-match".mock_into(),+ active: true,+ filters: FlagFilters {+ groups: vec![+ // Condition 0: property does not match — NoConditionMatch, must not early exit+ FlagPropertyGroup {+ properties: Some(vec![PropertyFilter {+ key: "email".to_string(),+ value: Some(json!("[email protected]")),+ operator: Some(OperatorType::Exact),+ prop_type: PropertyType::Person,+ group_type_index: None,+ negation: None,+ compiled_regex: None,+ extra: Default::default(),+ }]),+ rollout_percentage: Some(0.0),+ variant: None,+ aggregation_group_type_index: None,+ extra: Default::default(),+ },+ // Condition 1: catch-all 100% — must be reached because condition 0 is NoConditionMatch+ FlagPropertyGroup {+ properties: Some(vec![]),+ rollout_percentage: Some(100.0),+ variant: None,+ aggregation_group_type_index: None,+ extra: Default::default(),+ },+ ],+ multivariate: None,+ aggregation_group_type_index: None,+ payloads: None,+ feature_enrollment: None,+ holdout: None,+ early_exit: Some(true),+ extra: Default::default(),+ }+ );++ let mut matcher = FeatureFlagMatcher::new(+ "test_user".to_string(),+ None,+ team.id,+ context.create_postgres_router(),+ cohort_cache,+ empty_group_type_cache(),+ None,+ );++ let person_overrides = HashMap::from([("email".to_string(), json!("[email protected]"))]);+ let flags = flag_list_with_metadata(vec![flag.clone()]);+ let result = matcher+ .evaluate_all_feature_flags(+ flags,+ Some(person_overrides),+ None,+ None,+ Uuid::new_v4(),+ None,+ false,+ )+ .await+ .unwrap();++ // Condition 0 is NoConditionMatch (wrong email), so early_exit must NOT fire.+ // Condition 1 is 100% with no property filter, so the flag must evaluate to true.+ let flag_result = result.flags.get("early-exit-no-condition-match").unwrap();+ assert!(flag_result.enabled);+ assert_eq!(flag_result.reason.condition_index, Some(1));+ }++ /// On a multivariate flag, early_exit returns false with no variant leak.+ /// The user matches condition properties but is excluded by 0% rollout.+ #[tokio::test]+ async fn test_early_exit_multivariate_no_variant_leak() {+ let context = TestContext::new(None).await;+ let cohort_cache = Arc::new(CohortCacheManager::new(+ context.non_persons_reader.clone(),+ None,+ None,+ ));+ let team = context.insert_new_team(None).await.unwrap();++ let flag = mock!(FeatureFlag,+ id: 1,+ team_id: team.id,+ key: "early-exit-multivariate".mock_into(),+ active: true,+ filters: FlagFilters {+ groups: vec![+ FlagPropertyGroup {+ properties: Some(vec![PropertyFilter {+ key: "email".to_string(),+ value: Some(json!("[email protected]")),+ operator: Some(OperatorType::Exact),+ prop_type: PropertyType::Person,+ group_type_index: None,+ negation: None,+ compiled_regex: None,+ extra: Default::default(),+ }]),+ rollout_percentage: Some(0.0),+ variant: None,+ aggregation_group_type_index: None,+ extra: Default::default(),+ },+ FlagPropertyGroup {+ properties: Some(vec![]),+ rollout_percentage: Some(100.0),+ variant: None,+ aggregation_group_type_index: None,+ extra: Default::default(),+ },+ ],+ multivariate: Some(MultivariateFlagOptions {+ variants: vec![+ MultivariateFlagVariant {+ name: Some("Control".to_string()),+ key: "control".to_string(),+ rollout_percentage: 50.0,+ },+ MultivariateFlagVariant {+ name: Some("Test".to_string()),+ key: "test".to_string(),+ rollout_percentage: 50.0,+ },+ ],+ }),+ aggregation_group_type_index: None,+ payloads: None,+ feature_enrollment: None,+ holdout: None,+ early_exit: Some(true),+ extra: Default::default(),+ }+ );++ let mut matcher = FeatureFlagMatcher::new(+ "test_user".to_string(),+ None,+ team.id,+ context.create_postgres_router(),+ cohort_cache,+ empty_group_type_cache(),+ None,+ );++ let person_overrides = HashMap::from([("email".to_string(), json!("[email protected]"))]);+ let flags = flag_list_with_metadata(vec![flag.clone()]);+ let result = matcher+ .evaluate_all_feature_flags(+ flags,+ Some(person_overrides),+ None,+ None,+ Uuid::new_v4(),+ None,+ false,+ )+ .await+ .unwrap();++ let flag_result = result.flags.get("early-exit-multivariate").unwrap();+ assert!(!flag_result.enabled);+ assert_eq!(flag_result.reason.code, "out_of_rollout_bound");+ // No variant must be leaked when early_exit fires+ assert_eq!(flag_result.variant, None);+ }++ /// early_exit fires on a group-aggregated condition. The user matches the group+ /// property filter but is excluded by 0% rollout → OutOfRolloutBound early exit.+ #[tokio::test]+ async fn test_early_exit_group_aggregated_condition() {+ let context = TestContext::new(None).await;+ let cohort_cache = Arc::new(CohortCacheManager::new(+ context.non_persons_reader.clone(),+ None,+ None,+ ));+ let team = context.insert_new_team(None).await.unwrap();++ let flag = mock!(FeatureFlag,+ id: 1,+ team_id: team.id,+ key: "early-exit-group".mock_into(),+ active: true,+ filters: FlagFilters {+ groups: vec![+ FlagPropertyGroup {+ properties: Some(vec![PropertyFilter {+ key: "industry".to_string(),+ value: Some(json!("tech")),+ operator: Some(OperatorType::Exact),+ prop_type: PropertyType::Group,+ group_type_index: Some(1),+ negation: None,+ compiled_regex: None,+ extra: Default::default(),+ }]),+ rollout_percentage: Some(0.0),+ variant: None,+ aggregation_group_type_index: Some(Some(1)),+ extra: Default::default(),+ },+ FlagPropertyGroup {+ properties: Some(vec![]),+ rollout_percentage: Some(100.0),+ variant: None,+ aggregation_group_type_index: Some(Some(1)),+ extra: Default::default(),+ },+ ],+ multivariate: None,+ aggregation_group_type_index: Some(1),+ payloads: None,+ feature_enrollment: None,+ holdout: None,+ early_exit: Some(true),+ extra: Default::default(),+ }+ );++ let group_type_cache =+ mock_group_type_cache([("organization".to_string(), 1)].into_iter().collect());+ let groups = HashMap::from([("organization".to_string(), json!("org_123"))]);+ let group_overrides = HashMap::from([(+ "organization".to_string(),+ HashMap::from([+ ("industry".to_string(), json!("tech")),+ ("$group_key".to_string(), json!("org_123")),+ ]),+ )]);++ let mut matcher = FeatureFlagMatcher::new(+ "test_user".to_string(),+ None,+ team.id,+ context.create_postgres_router(),+ cohort_cache,+ group_type_cache,+ Some(groups),+ );++ let flags = flag_list_with_metadata(vec![flag.clone()]);+ let result = matcher+ .evaluate_all_feature_flags(+ flags,+ None,+ Some(group_overrides),+ None,+ Uuid::new_v4(),+ None,+ false,+ )+ .await+ .unwrap();++ let flag_result = result.flags.get("early-exit-group").unwrap();+ assert!(!flag_result.enabled);+ assert_eq!(flag_result.reason.code, "out_of_rollout_bound");+ assert_eq!(flag_result.reason.condition_index, Some(0));+ }++ /// Cohort-based conditions route through CohortCacheManager and return NoConditionMatch+ /// when the user is not in the cohort. early_exit must NOT fire on NoConditionMatch —+ /// evaluation must continue to the next condition. This guards against any future+ /// broadening of the early-exit guard that would incorrectly short-circuit cohort misses.+ #[tokio::test]+ async fn test_early_exit_cohort_no_condition_match_does_not_short_circuit() {+ let context = TestContext::new(None).await;+ let cohort_cache = Arc::new(CohortCacheManager::new(+ context.non_persons_reader.clone(),+ None,+ None,+ ));+ let team = context.insert_new_team(None).await.unwrap();++ // Cohort requires $browser_version > 125; user has version 100 — NOT in cohort+ let cohort_row = context+ .insert_cohort(+ team.id,+ None,+ json!({+ "properties": {+ "type": "OR",+ "values": [{+ "type": "OR",+ "values": [{+ "key": "$browser_version",+ "type": "person",+ "value": "125",+ "negation": false,+ "operator": "gt"+ }]+ }]+ }+ }),+ false,+ )+ .await+ .unwrap();++ context+ .insert_person(+ team.id,+ "test_user".to_string(),+ Some(json!({"$browser_version": 100})),+ )+ .await+ .unwrap();++ let flag = mock!(FeatureFlag,+ id: 1,+ team_id: team.id,+ key: "early-exit-cohort-no-match".mock_into(),+ active: true,+ filters: FlagFilters {+ groups: vec![+ // Condition 0: NOT in cohort → NoConditionMatch, must NOT trigger early_exit+ FlagPropertyGroup {+ properties: Some(vec![PropertyFilter {+ key: "id".to_string(),+ value: Some(json!(cohort_row.id)),+ operator: Some(OperatorType::In),+ prop_type: PropertyType::Cohort,+ group_type_index: None,+ negation: Some(false),+ compiled_regex: None,+ extra: Default::default(),+ }]),+ rollout_percentage: Some(100.0),+ variant: None,+ aggregation_group_type_index: None,+ extra: Default::default(),+ },+ // Condition 1: catch-all that MUST be reached since condition 0 is NoConditionMatch+ FlagPropertyGroup {+ properties: Some(vec![]),+ rollout_percentage: Some(100.0),+ variant: None,+ aggregation_group_type_index: None,+ extra: Default::default(),+ },+ ],+ multivariate: None,+ aggregation_group_type_index: None,+ payloads: None,+ feature_enrollment: None,+ holdout: None,+ early_exit: Some(true),+ extra: Default::default(),+ }+ );++ let mut matcher = FeatureFlagMatcher::new(+ "test_user".to_string(),+ None,+ team.id,+ context.create_postgres_router(),+ cohort_cache.clone(),+ empty_group_type_cache(),+ None,+ );++ let flags = flag_list_with_metadata(vec![flag.clone()]);+ let result = matcher+ .evaluate_all_feature_flags(flags, None, None, None, Uuid::new_v4(), None, false)+ .await+ .unwrap();++ // Condition 0 is NoConditionMatch (user not in cohort), early_exit must NOT fire.+ // Condition 1 is a 100% catch-all, so the flag must evaluate to true.+ let flag_result = result.flags.get("early-exit-cohort-no-match").unwrap();+ assert!(flag_result.enabled);+ assert_eq!(flag_result.reason.condition_index, Some(1));+ }++ /// feature_enrollment (super condition) is evaluated before the regular condition loop,+ /// so it takes precedence over early_exit. A user whose enrollment property is set+ /// must get SuperConditionValue even when early_exit is enabled and condition 0 would+ /// otherwise trigger an early exit.+ #[tokio::test]+ async fn test_early_exit_feature_enrollment_takes_precedence() {+ let context = TestContext::new(None).await;+ let cohort_cache = Arc::new(CohortCacheManager::new(+ context.non_persons_reader.clone(),+ None,+ None,+ ));+ let team = context.insert_new_team(None).await.unwrap();++ let flag_key = "early-exit-enrollment";++ let flag = mock!(FeatureFlag,+ id: 1,+ team_id: team.id,+ key: flag_key.mock_into(),+ active: true,+ filters: FlagFilters {+ groups: vec![+ // Condition 0: would trigger early exit if the enrollment check didn't win first+ FlagPropertyGroup {+ properties: Some(vec![PropertyFilter {+ key: "email".to_string(),+ value: Some(json!("[email protected]")),+ operator: Some(OperatorType::Exact),+ prop_type: PropertyType::Person,+ group_type_index: None,+ negation: None,+ compiled_regex: None,+ extra: Default::default(),+ }]),+ rollout_percentage: Some(0.0),+ variant: None,+ aggregation_group_type_index: None,+ extra: Default::default(),+ },+ ],+ multivariate: None,+ aggregation_group_type_index: None,+ payloads: None,+ feature_enrollment: Some(true),+ holdout: None,+ early_exit: Some(true),+ extra: Default::default(),+ }+ );++ // Set the enrollment property for the user — this is checked before any condition loop+ let enrollment_key = format!("$feature_enrollment/{flag_key}");+ let person_overrides = HashMap::from([+ ("email".to_string(), json!("[email protected]")),+ (enrollment_key, json!(true)),+ ]);++ let mut matcher = FeatureFlagMatcher::new(+ "test_user".to_string(),+ None,+ team.id,+ context.create_postgres_router(),+ cohort_cache,+ empty_group_type_cache(),+ None,+ );++ let flags = flag_list_with_metadata(vec![flag.clone()]);+ let result = matcher+ .evaluate_all_feature_flags(+ flags,+ Some(person_overrides),+ None,+ None,+ Uuid::new_v4(),+ None,+ false,+ )+ .await+ .unwrap();++ let flag_result = result.flags.get(flag_key).unwrap();+ // Enrollment check wins — flag is enabled with SuperConditionValue reason+ assert!(flag_result.enabled);+ assert_eq!(flag_result.reason.code, "super_condition_value");+ }++ /// Holdout is evaluated before the regular condition loop, so a user in holdout+ /// returns the holdout variant regardless of early_exit on the regular conditions.+ #[tokio::test]+ async fn test_early_exit_holdout_takes_precedence() {+ let context = TestContext::new(None).await;+ let cohort_cache = Arc::new(CohortCacheManager::new(+ context.non_persons_reader.clone(),+ None,+ None,+ ));+ let team = context.insert_new_team(None).await.unwrap();++ // Use a distinct user key that hashes into the holdout exclusion window (< 100%).+ // We configure 100% exclusion so every user is in holdout.+ let flag = mock!(FeatureFlag,+ id: 1,+ team_id: team.id,+ key: "early-exit-holdout".mock_into(),+ active: true,+ filters: FlagFilters {+ groups: vec![+ // Condition 0: would trigger early exit if holdout didn't win first+ FlagPropertyGroup {+ properties: Some(vec![PropertyFilter {+ key: "email".to_string(),+ value: Some(json!("[email protected]")),+ operator: Some(OperatorType::Exact),+ prop_type: PropertyType::Person,+ group_type_index: None,+ negation: None,+ compiled_regex: None,+ extra: Default::default(),+ }]),+ rollout_percentage: Some(0.0),+ variant: None,+ aggregation_group_type_index: None,+ extra: Default::default(),+ },+ ],+ multivariate: None,+ aggregation_group_type_index: None,+ payloads: None,+ feature_enrollment: None,+ holdout: Some(Holdout {+ id: 42,+ exclusion_percentage: 100.0,+ }),+ early_exit: Some(true),+ extra: Default::default(),+ }+ );++ let person_overrides = HashMap::from([("email".to_string(), json!("[email protected]"))]);++ let mut matcher = FeatureFlagMatcher::new(+ "test_user".to_string(),+ None,+ team.id,+ context.create_postgres_router(),+ cohort_cache,+ empty_group_type_cache(),+ None,+ );++ let flags = flag_list_with_metadata(vec![flag.clone()]);+ let result = matcher+ .evaluate_all_feature_flags(+ flags,+ Some(person_overrides),+ None,+ None,+ Uuid::new_v4(),+ None,+ false,+ )+ .await+ .unwrap();++ let flag_result = result.flags.get("early-exit-holdout").unwrap();+ // Holdout check wins — user is in holdout, variant is holdout-42+ assert!(flag_result.enabled);+ assert_eq!(flag_result.variant.as_deref(), Some("holdout-42"));+ }}diff --git a/rust/feature-flags/src/utils/mock.rs b/rust/feature-flags/src/utils/mock.rsindex c3aa0bd119ea..62f135196b06 100644--- a/rust/feature-flags/src/utils/mock.rs+++ b/rust/feature-flags/src/utils/mock.rs@@ -343,6 +343,7 @@ mod tests {payloads: None,feature_enrollment: None,holdout: None,+ early_exit: None,extra: Default::default(),},ensure_experience_continuity: Some(false),diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4787806db915..21ff7c844c1a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -17874,6 +17874,8 @@ export namespace Schemas {* @nullable*/feature_enrollment?: boolean | null;+ /** When true, condition evaluation stops at the first matching condition set rather than continuing to evaluate subsequent groups. */+ early_exit?: boolean;}export interface FeatureFlagCreateRequestSchema {diff --git a/services/mcp/src/generated/feature_flags/api.ts b/services/mcp/src/generated/feature_flags/api.tsindex 594a929849fd..1c1aea1a1b1b 100644--- a/services/mcp/src/generated/feature_flags/api.ts+++ b/services/mcp/src/generated/feature_flags/api.ts@@ -90,6 +90,8 @@ export const FeatureFlagsCreateParams = /* @__PURE__ */ zod.object({),})+export const featureFlagsCreateBodyFiltersOneEarlyExitDefault = false+export const FeatureFlagsCreateBody = /* @__PURE__ */ zod.object({key: zod.string().optional().describe('Feature flag key.'),name: zod@@ -367,6 +369,12 @@ export const FeatureFlagsCreateBody = /* @__PURE__ */ zod.object({.describe('Whether this flag has early access feature enrollment enabled. When true, the flag is evaluated against the person property $feature_enrollment/{flag_key}.'),+ early_exit: zod+ .boolean()+ .default(featureFlagsCreateBodyFiltersOneEarlyExitDefault)+ .describe(+ 'When true, condition evaluation stops at the first matching condition set rather than continuing to evaluate subsequent groups.'+ ),}).optional().describe('Feature flag targeting configuration.'),@@ -406,6 +414,8 @@ export const FeatureFlagsPartialUpdateParams = /* @__PURE__ */ zod.object({),})+export const featureFlagsPartialUpdateBodyFiltersOneEarlyExitDefault = false+export const FeatureFlagsPartialUpdateBody = /* @__PURE__ */ zod.object({key: zod.string().optional().describe('Feature flag key.'),name: zod@@ -683,6 +693,12 @@ export const FeatureFlagsPartialUpdateBody = /* @__PURE__ */ zod.object({.describe('Whether this flag has early access feature enrollment enabled. When true, the flag is evaluated against the person property $feature_enrollment/{flag_key}.'),+ early_exit: zod+ .boolean()+ .default(featureFlagsPartialUpdateBodyFiltersOneEarlyExitDefault)+ .describe(+ 'When true, condition evaluation stops at the first matching condition set rather than continuing to evaluate subsequent groups.'+ ),}).optional().describe('Feature flag targeting configuration.'),diff --git a/services/mcp/src/generated/surveys/api.ts b/services/mcp/src/generated/surveys/api.tsindex 8b19a990bad3..54e3cc1a50f1 100644--- a/services/mcp/src/generated/surveys/api.ts+++ b/services/mcp/src/generated/surveys/api.ts@@ -38,6 +38,7 @@ export const SurveysCreateParams = /* @__PURE__ */ zod.object({export const surveysCreateBodyNameMax = 400+export const surveysCreateBodyTargetingFlagFiltersOneEarlyExitDefault = falseexport const surveysCreateBodyQuestionsItemThreeBranchingOneThreeIndexMin = 0export const surveysCreateBodyQuestionsItemThreeBranchingOneFourResponseValuesOneMin = 0@@ -384,6 +385,12 @@ export const SurveysCreateBody = /* @__PURE__ */ zod.object({.describe('Whether this flag has early access feature enrollment enabled. When true, the flag is evaluated against the person property $feature_enrollment/{flag_key}.'),+ early_exit: zod+ .boolean()+ .default(surveysCreateBodyTargetingFlagFiltersOneEarlyExitDefault)+ .describe(+ 'When true, condition evaluation stops at the first matching condition set rather than continuing to evaluate subsequent groups.'+ ),}),zod.null(),])@@ -827,6 +834,7 @@ export const SurveysPartialUpdateParams = /* @__PURE__ */ zod.object({export const surveysPartialUpdateBodyNameMax = 400+export const surveysPartialUpdateBodyTargetingFlagFiltersOneEarlyExitDefault = falseexport const surveysPartialUpdateBodyQuestionsItemThreeBranchingOneThreeIndexMin = 0export const surveysPartialUpdateBodyQuestionsItemThreeBranchingOneFourResponseValuesOneMin = 0@@ -1174,6 +1182,12 @@ export const SurveysPartialUpdateBody = /* @__PURE__ */ zod.object({.describe('Whether this flag has early access feature enrollment enabled. When true, the flag is evaluated against the person property $feature_enrollment/{flag_key}.'),+ early_exit: zod+ .boolean()+ .default(surveysPartialUpdateBodyTargetingFlagFiltersOneEarlyExitDefault)+ .describe(+ 'When true, condition evaluation stops at the first matching condition set rather than continuing to evaluate subsequent groups.'+ ),}),zod.null(),])diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/create-feature-flag.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/create-feature-flag.jsonindex cd2ddae33f1d..299a253bdde7 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/create-feature-flag.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/create-feature-flag.json@@ -26,6 +26,11 @@],"description": "Group type index for group-based feature flags."},+ "early_exit": {+ "default": false,+ "description": "When true, condition evaluation stops at the first matching condition set rather than continuing to evaluate subsequent groups.",+ "type": "boolean"+ },"feature_enrollment": {"anyOf": [{diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-create.jsonindex 726848f526f3..055a7448e5c6 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-create.json@@ -688,6 +688,11 @@],"description": "Group type index for group-based feature flags."},+ "early_exit": {+ "default": false,+ "description": "When true, condition evaluation stops at the first matching condition set rather than continuing to evaluate subsequent groups.",+ "type": "boolean"+ },"feature_enrollment": {"anyOf": [{diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-update.jsonindex cc4c0692dad6..7766aea33fef 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-update.json@@ -719,6 +719,11 @@],"description": "Group type index for group-based feature flags."},+ "early_exit": {+ "default": false,+ "description": "When true, condition evaluation stops at the first matching condition set rather than continuing to evaluate subsequent groups.",+ "type": "boolean"+ },"feature_enrollment": {"anyOf": [{diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/update-feature-flag.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/update-feature-flag.jsonindex 64929c14ca0d..c71dca32ea2b 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/update-feature-flag.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/update-feature-flag.json@@ -26,6 +26,11 @@],"description": "Group type index for group-based feature flags."},+ "early_exit": {+ "default": false,+ "description": "When true, condition evaluation stops at the first matching condition set rather than continuing to evaluate subsequent groups.",+ "type": "boolean"+ },"feature_enrollment": {"anyOf": [{