: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(feature-flags): remove legacy super_groups reading from Rust and Python (#59100)
Patricio86739a6c1b7e
diff --git a/agent-os/super-groups-migration-plan.md b/agent-os/super-groups-migration-plan.mdnew file mode 100644index 000000000000..41ba0e479d61--- /dev/null+++ b/agent-os/super-groups-migration-plan.md@@ -0,0 +1,365 @@+# Feature enrollment migration: `super_groups` → `feature_enrollment`++## Problem++The `super_groups` field in feature flag `filters` reuses `FlagPropertyGroup`,+a type designed for regular conditions.+This creates semantic confusion:++- `properties` always contains exactly one entry — `$feature_enrollment/{flag_key}` with `exact` operator and `["true"]` value+- `rollout_percentage` is always `100` — the type suggests partial rollouts, but that's never used+- The name "super groups" doesn't appear in the product UI — users see "Early access features" and "Feature enrollment"+- Payloads are larger than necessary — a complex nested structure where a boolean would suffice++### Current production usage++| Region | Flags with super_groups | Teams |+| ------ | ----------------------- | ----- |+| US | 976 | 419 |+| EU | 582 | 282 |++Higher usage than the holdout migration (~20 rows). Requires batched migration.++## Target format++**Before:**++```json+{+ "super_groups": [+ {+ "properties": [+ {+ "key": "$feature_enrollment/new-dashboard",+ "type": "person",+ "operator": "exact",+ "value": ["true"]+ }+ ],+ "rollout_percentage": 100+ }+ ]+}+```++**After:**++```json+{+ "feature_enrollment": true+}+```++### Why the enrollment key is derivable from the flag key++The enrollment property is **always** `$feature_enrollment/{flag_key}` — this invariant is enforced at every layer:++1. **Every write path** constructs it from the flag key: `f"$feature_enrollment/{feature_flag_key}"` in `products/early_access_features/backend/api.py` (both `create()` and `update()`)+2. **On flag key rename**, `_update_super_groups_for_key_change()` in `posthog/api/feature_flag.py` rewrites the enrollment key to match the new flag key+3. **Migration 0748** (`posthog/migrations/0748_update_featureflag_super_groups.py`) was specifically written to fix historical cases where the enrollment key drifted out of sync — it forced `$feature_enrollment/{flag.key}` for every active flag++There is no case where a flag's super_groups references a _different_ flag's enrollment key. The data is fully redundant with `flag.key`, so evaluation code can construct the key at runtime (same pattern as the Rust service constructing `holdout-{id}` for holdouts).++### Design decisions++- **Boolean `feature_enrollment`, not a string array.**+ Since the enrollment key is derivable (see above), no additional data is needed.+ A boolean is the simplest representation: "this flag has feature enrollment enabled."++- **`feature_enrollment` instead of `feature_enrollments`.**+ A flag either has feature enrollment or it doesn't — it's not a collection.+ The singular form matches the boolean semantics.++- **Not a model field.**+ Keeping it in `filters` JSON avoids a schema migration and keeps the flag definition self-contained for the Rust service+ (which reads filters from Redis/Postgres JSON, not Django model fields).++---++## Migration phases++### Phase 1: Django writes both formats (backwards-compatible)++**Status:** MERGED++**Why first:** Writing is always safer to change first —+it doesn't affect what's currently being read.+If we update Rust first to read `feature_enrollment` before Django writes it,+there's a deployment window where newly created enrollments would only have `super_groups`+while Rust prefers `feature_enrollment`.++**Tasks:**++- [x] Add `feature_enrollment` field support to `FlagFilters` serializer in Django+- [x] Update `super_conditions` lambda in `products/early_access_features/backend/api.py` to also set `feature_enrollment: true`+- [x] Update `_update_super_groups_for_key_change` in `posthog/api/feature_flag.py` — added comment noting `feature_enrollment` is key-independent+- [x] Update `pre_delete` hook in `products/early_access_features/backend/apps.py`+- [x] Add `has_feature_enrollment` property to `FeatureFlag` model+- [x] Tests: all 28 early access feature tests + 1 feature flag key update test pass++### Phase 2: Rust reads new format with fallback++**Status:** MERGED++**Depends on:** Phase 1 deployed++**Tasks:**++- [x] Add `feature_enrollment: Option<bool>` field to `FlagFilters` struct in Rust+- [x] Add `FlagFilters::enrollment_key(flag_key)` shared helper to derive `$feature_enrollment/{flag_key}`+ - Used by both evaluation logic and `requires_db_properties` — avoids format string duplication+- [x] Update super condition evaluation in `flag_matching.rs` to prefer `feature_enrollment` over `super_groups`+ - If `feature_enrollment == Some(true)`: derive enrollment key via helper, check person properties directly+ - Else if `super_groups` present: legacy fallback via `is_super_condition_match`+ - Else: no enrollment, proceed to normal conditions+- [x] Update `requires_db_properties` in `flag_filters.rs` to handle `feature_enrollment`+ - Takes `flag_key` parameter; checks if overrides contain the derived enrollment key+- [x] `SuperConditionEvaluation` kept as-is (still used by legacy fallback, removed in Phase 4)+- [x] Tests:+ - Parameterized `test_feature_enrollment_match_by_property_value` — 4 cases: string `"true"`/`"false"`, boolean `true`/`false`+ - `test_feature_enrollment_no_property_falls_through` — person without enrollment property falls through to regular conditions+ - `test_feature_enrollment_takes_precedence_over_super_groups` — both formats present, new format wins+ - `test_feature_enrollment_requires_db_properties_when_override_missing` / `test_feature_enrollment_skips_db_when_override_present` — unit tests for `requires_db_properties`+ - All 6 existing `super_groups` tests still pass (legacy fallback)+- [x] Updated all `FlagFilters` struct literals across the codebase to include `feature_enrollment: None`++### Phase 3: Backfill existing flags++**Status:** MERGED (1076 was no-op due to bug, 1078 fix verified in production)++**Depends on:** Phase 2 deployed (Rust fallback handles both formats)++**Tasks:**++- [x] Write a Django data migration to convert all existing flags+ - Batched `RunPython` with `.iterator(chunk_size=250)` and `bulk_update` in batches of 250+ - `elidable=True`, `noop` reverse, try/except per flag with logging+ - Defensive Python guards: `isinstance(super_groups, list)`, skip empty, skip already-updated+- [x] Migration 1076 deployed but silently updated 0 rows — `filters__super_groups__isnull=False`+ generates unquoted JSON key in SQL (`filters -> super_groups` instead of `filters -> 'super_groups'`),+ causing the queryset to match nothing+- [x] Migration 1078 fix deployed with corrected queryset:+ - `filters__has_key="super_groups"` + `.exclude(super_groups=None)` + `.exclude(super_groups=[])`+ - `.extra(where=["NOT (filters ? 'feature_enrollment' AND filters->>'feature_enrollment' = 'true')"])`+ for the `feature_enrollment` exclusion (ORM `exclude(filters__feature_enrollment=True)` also+ generates broken SQL with unquoted keys — it excludes ALL rows instead of none)+- [x] Verified in production: ~900 rows updated in both US and EU++**Lesson learned:** Django's JSONField ORM lookups on nested keys (`filters__some_key=value`,+`filters__some_key__isnull=False`) can generate SQL with unquoted key names.+Use `has_key`, `exclude(field=None)`, `exclude(field=[])`, and `.extra(where=[...])` with raw SQL+for reliable JSON key filtering in migrations.++### Phase 4: Remove legacy reading++**Status:** MERGED (#59100)++**Depends on:** Phase 3 complete + verified in production++**Tasks:**++- [x] Remove `super_groups` fallback from Rust evaluation+ - `flag_matching.rs`: only read `feature_enrollment`+ - Remove `super_groups` from `FlagFilters` struct (serde silently ignores unknown JSON keys)+ - Remove `is_super_condition_match` method (replaced by simpler enrollment check)+ - Remove `SuperConditionEvaluation` struct+- [x] Remove `super_groups` reading from Django code+- [x] Update `flag_matching.py` gate and `is_super_condition_match` together to read `feature_enrollment` instead of `super_groups`+ - Replaced `is_super_condition_match` with `is_feature_enrollment_match`: derives enrollment key from flag key, reads from `query_conditions` directly+ - Replaced `_super_condition_matches` and `_super_condition_is_set` with enrollment-aware equivalents+ - Kept `FeatureFlagMatchReason.SUPER_CONDITION_VALUE` — renaming would change the API response string+- [x] Remove `super_conditions` property from `feature_flag.py`+- [x] Tests: deleted 8 legacy super_groups unit tests, 2 filter tests, 1 operations test, 1 cache weigher test; converted 3 integration tests to `feature_enrollment` format; renamed test functions from `super_condition` to `feature_enrollment`; added parameterized Python test for `is_feature_enrollment_match` covering all 4 branches+- [x] Cleaned up all `super_groups: None` struct literals across Rust codebase++**Note:** `SuperConditionValue` reason code rename deferred — changing the serialized string `"super_condition_value"` would break the API response format. Can be revisited independently.++**Note:** One customer (team 361776) has 7 flags with non-standard `super_groups` keys (e.g. `$feature/section-test` instead of `$feature_enrollment/...`). They were emailed in early May to re-save their flags but never did. Their flags will stop matching on the enrollment condition but continue evaluating regular conditions normally.++### Phase 5: Remove legacy writing++**Status:** not started++**Depends on:** Phase 4 deployed + no rollback needed++**Tasks:**++- [ ] Stop writing `super_groups` in early access feature serializer (`products/early_access_features/backend/api.py`)+ - Replace the `super_conditions` lambda with simple `"feature_enrollment": True`+ - All 5 write sites: promote to active (update), create with active stage, GA rollout_to_all, demote/archive, destroy+- [ ] Remove `("super_groups", "rollout_percentage")` from `ROLLOUT_PERCENTAGE_PATHS` in `posthog/approvals/actions/feature_flags.py`+ - Feature enrollment doesn't have a rollout percentage concept — no replacement path needed+- [ ] Remove `_update_super_groups_for_key_change()` from `posthog/api/feature_flag.py`+ - `feature_enrollment` is a boolean — no key-dependent data to update+- [ ] Remove `pre_delete` super_groups cleanup from `products/early_access_features/backend/apps.py`+ - Replace with `feature_enrollment: None` cleanup+- [ ] Update test assertions that check `filters["super_groups"]`:+ - `products/early_access_features/backend/test/test_early_access_feature.py` (multiple tests)+ - `posthog/api/test/test_feature_flag.py` (`test_updating_feature_flag_key_updates_super_groups` — remove or rewrite)+ - `posthog/approvals/tests/test_update_feature_flag_action.py`+- [ ] Update frontend — see [Frontend changes detail](#frontend-changes-detail) below+- [ ] Opportunistic cleanup: strip `super_groups` from `filters` on next flag save (`update()` in `posthog/api/feature_flag.py`)+ - Same pattern as `holdout_groups` cleanup (line 1364)+- [ ] Run `hogli build:openapi` to regenerate TypeScript types++### Phase 6: Data cleanup++**Status:** not started++**Depends on:** Phase 5 deployed++Strip the `super_groups` key from stored `filters` JSON on existing flags. After Phase 5, no code reads or writes `super_groups` — the key is dead data in the JSON column.++**Tasks:**++- [ ] Write a Django data migration to remove `super_groups` from `filters` JSON on all flags+ - Use batched approach: query flags with `filters__has_key="super_groups"`, pop the key, `bulk_update` in batches+ - `elidable=True` since this is purely a data cleanup+ - Consider doing this as a raw SQL migration for efficiency: `UPDATE posthog_featureflag SET filters = filters - 'super_groups' WHERE filters ? 'super_groups'`+- [ ] Alternatively, rely on the opportunistic cleanup from Phase 5 (strip on save) and skip the migration entirely — dead data with no reader impact++---++## Key files to modify++| Component | File | Phase |+| --------------------------------- | ------------------------------------------------------------------------ | ----- |+| Django serializer schema | `posthog/api/feature_flag.py` | 1, 5 |+| Early access feature serializer | `products/early_access_features/backend/api.py` | 1, 5 |+| Early access feature app hooks | `products/early_access_features/backend/apps.py` | 1, 5 |+| Feature flag model | `products/feature_flags/backend/models/feature_flag.py` | 1, 4 |+| Python flag matching | `products/feature_flags/backend/flag_matching.py` | 4 |+| Approvals change tracking | `posthog/approvals/actions/feature_flags.py` | 5 |+| Rust flag models | `rust/feature-flags/src/flags/flag_models.rs` | 2 |+| Rust flag matching | `rust/feature-flags/src/flags/flag_matching.rs` | 2, 4 |+| Rust flag filters | `rust/feature-flags/src/flags/flag_filters.rs` | 2, 4 |+| Rust flag match reason | `rust/feature-flags/src/flags/flag_match_reason.rs` | 4 |+| Rust API types | `rust/feature-flags/src/api/types.rs` | 4 |+| Rust test utilities | `rust/feature-flags/src/utils/test_utils.rs` | 2, 4 |+| Rust flag operations tests | `rust/feature-flags/src/flags/flag_operations.rs` | 2, 4 |+| Rust flag service tests | `rust/feature-flags/src/flags/flag_service.rs` | 2, 4 |+| Rust flag matching tests | `rust/feature-flags/src/flags/test_flag_matching.rs` | 2, 4 |+| Rust integration tests | `rust/feature-flags/tests/test_flags.rs` | 2, 4 |+| Frontend types | `frontend/src/types.ts` | 5 |+| Frontend flag logic | `frontend/src/scenes/feature-flags/featureFlagLogic.ts` | 5 |+| Frontend release conditions logic | `frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.ts` | 5 |+| Frontend flag UI | `frontend/src/scenes/feature-flags/FeatureFlag.tsx` | 5 |+| Frontend flag overview | `frontend/src/scenes/feature-flags/FeatureFlagOverviewV2.tsx` | 5 |+| Data migration (backfill) | `posthog/migrations/XXXX_backfill_feature_enrollment.py` | 3 |+| Data migration (cleanup) | `posthog/migrations/XXXX_strip_super_groups.py` | 6 |++## Frontend changes detail++> **Reminder:** When starting Phase 5, read this section carefully.+> The frontend changes are a net simplification — the entire `isSuper` code path+> through `featureFlagReleaseConditionsLogic` becomes dead code.+> Instead of rendering a complex property filter card for super conditions,+> you just show a boolean "Feature enrollment enabled" state.++### Files to change++1. **`frontend/src/types.ts`** (line 3874)+ - Add `feature_enrollment?: boolean` to `FeatureFlagFilters`+ - Remove `super_groups?: FeatureFlagGroupType[]`++2. **`frontend/src/scenes/feature-flags/FeatureFlag.tsx`** (line 244)+ - Currently checks `featureFlag.filters.super_groups?.length > 0` to render `<FeatureFlagReleaseConditions readOnly isSuper>`+ - Replace with `featureFlag.filters.feature_enrollment` and render a simpler indicator (no need for the full release conditions component)+ - The existing TODO comment at line 243 already calls for this cleanup++3. **`frontend/src/scenes/feature-flags/FeatureFlagOverviewV2.tsx`** (line 343)+ - Same pattern — checks `super_groups?.length > 0` to render `<FeatureFlagSuperConditionsReadonly>`+ - Replace with a simpler display for `feature_enrollment: true`++4. **`frontend/src/scenes/feature-flags/featureFlagLogic.ts`** (line 363)+ - `cleanFlag()` runs `cleanFilterGroups` on `super_groups` to strip `sort_key` — remove entirely, a boolean has no sort keys++5. **`frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.ts`** (lines 59, 82, 513)+ - `isSuper` prop, the key derivation using it, and the `filterGroups` selector branch that returns `filters.super_groups` — all dead code, remove+ - The entire `isSuper` code path can be deleted++6. **`frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.tsx`** (lines 93, 608, 787)+ - `isSuper` prop, title branching ("Super release conditions"), and `renderSuperReleaseConditionGroup` — all removable++7. **`frontend/src/scenes/feature-flags/FeatureFlagReleaseConditionsReadonly.tsx`** (line 227)+ - `FeatureFlagSuperConditionsReadonly` component passes `isSuper: true` — can be simplified or removed++8. **`frontend/src/scenes/surveys/surveyLogic.tsx`** (line 1785)+ - Sets `super_groups: undefined` when constructing filter objects — change to `feature_enrollment: undefined`++### How to test the frontend changes++Test each of these flows manually in the browser:++- [ ] **Create early access feature** in ALPHA/BETA stage → open the linked feature flag → confirm it shows "Feature enrollment enabled" (or the new UI) instead of the old super condition property card+- [ ] **Promote CONCEPT → ALPHA** → flag should now show feature enrollment indicator+- [ ] **Promote to GA with "rollout to all"** → flag should clear enrollment indicator, show 100% rollout in regular conditions+- [ ] **Demote ALPHA → CONCEPT** → enrollment indicator should disappear+- [ ] **Archive an early access feature** → enrollment indicator should disappear+- [ ] **Delete an early access feature** → enrollment indicator should disappear from the flag+- [ ] **Rename a flag key** that has enrollment → confirm nothing breaks (no enrollment key to update anymore — boolean is key-independent)+- [ ] **Feature flag overview page** (V2) → repeat the above checks for the readonly display+- [ ] **Survey with targeting flag** → confirm surveys still render correctly++---++## Risks and mitigations++### Cache staleness after backfill migration++**Risk:** `bulk_update` doesn't fire `post_save` signals, so HyperCache may serve stale data.+**Mitigation:** Phase 2's Rust fallback reads `super_groups` when `feature_enrollment` is missing, so stale cache entries behave identically. Cache refreshes naturally on TTL expiry. No explicit invalidation needed.++### Deployment ordering between Django and Rust++**Risk:** If Rust is deployed before Django, new enrollments created during the gap only have `super_groups`.+**Mitigation:** Deploy Django first (Phase 1), then Rust (Phase 2). The fallback in Rust handles both.++### Higher row count than holdout migration++**Risk:** ~1,558 flags vs ~20 for holdouts. Migration takes longer.+**Mitigation:** Use batched `bulk_update` with `batch_size=500`. Still small enough for a synchronous migration (< 2,000 rows). No need for async migration.++### Reason code rename in API responses++**Risk:** Renaming `super_condition_value` to `feature_enrollment_value` in flag match reasons changes the API response.+**Mitigation:** Check if any SDK or dashboard depends on this string. If so, keep `super_condition_value` as the serialized value (Rust serde rename) while using the new internal name. Alternatively, defer the rename to a separate PR.++### Frontend backward compatibility++**Risk:** If a user has an old frontend loaded that reads `super_groups`, the display may break after Phase 5.+**Mitigation:** Phase 5 frontend changes should handle both formats gracefully during rollout. The `feature_enrollment` boolean is additive; old frontends simply won't render it (they'll see no super_groups). New frontends check `feature_enrollment` first.++### Existing data migration 0748++**Risk:** Migration `0748_update_featureflag_super_groups.py` fixes `$feature_enrollment` keys in super_groups. After Phase 5, this migration references a removed field.+**Mitigation:** This migration is already applied in production and won't run again. No action needed — it's historical.++### Coordination with holdout_groups cleanup++**Risk:** Both this migration and holdout opportunistic cleanup touch `filters` JSON.+**Mitigation:** No conflict — they operate on different keys. The opportunistic strip pattern is independent per key.++## Notes from review++- The "only evaluate first super group" pattern (`super_groups[0]`) is now implicit in the boolean — there's nothing to index+- Feature enrollment is not supported by local evaluation — SDKs ignore `super_groups`, so no SDK changes needed+- Static cohort creation from flags ignores `super_groups` — no changes needed there+- The Python flag matching code in `posthog/models/feature_flag/flag_matching.py` is legacy but still actively used for database-backed evaluation. Unlike holdouts, super_groups ARE evaluated in this code path — Phase 4 must update it.+- The Rust service constructs the enrollment property key (`$feature_enrollment/{flag_key}`) internally from the flag key — this is an implementation detail, not data++## Differences from holdout migration++| Aspect | Holdout migration | Feature enrollment migration |+| ----------------------- | -------------------------------------- | ----------------------------------------------------- |+| Scale | ~20 rows | ~1,558 rows |+| Target format | `{id, exclusion_percentage}` object | `true` boolean |+| Key derivation | `holdout-{id}` variant from holdout ID | `$feature_enrollment/{flag_key}` from flag key |+| Python flag_matching.py | Ignores holdouts (legacy code) | Actively evaluates super_groups — must update |+| Frontend impact | Minimal | Moderate — several components render super conditions |+| Approvals impact | Had exclusion_percentage path | Remove rollout_percentage path (no replacement) |++## Future cleanup (out of scope)++- Consider removing the `$feature_enrollment/{key}` person property pattern entirely and using a dedicated enrollment model. This would decouple enrollment tracking from person properties, but is a much larger change.+- The `FeatureFlagReleaseConditions` component has a TODO comment (FeatureFlag.tsx:244) about cleaning up super_groups rendering — Phase 5 addresses this.diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambrindex 7b058d7f3383..418dc4d1e8b6 100644--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr@@ -761,7 +761,6 @@'rollback_conditions','rollout_percentage','scheduled_changes_dispatcher',- 'super_conditions','surveys_internal_response_sampling_flag','surveys_internal_targeting_flag','surveys_linked_flag',diff --git a/products/feature_flags/backend/flag_matching.py b/products/feature_flags/backend/flag_matching.pyindex 1f4a4904bd86..b3064e9047ba 100644--- a/products/feature_flags/backend/flag_matching.py+++ b/products/feature_flags/backend/flag_matching.py@@ -165,25 +165,23 @@ class FeatureFlagMatcher:highest_priority_evaluation_reason = FeatureFlagMatchReason.NO_CONDITION_MATCHhighest_priority_index = 0- # Match for boolean super condition first- if feature_flag.filters.get("super_groups", None):+ # Match for early access feature enrollment first+ if feature_flag.has_feature_enrollment:(is_match,- super_condition_value,+ enrollment_value,evaluation_reason,- ) = self.is_super_condition_match(feature_flag)+ ) = self.is_feature_enrollment_match(feature_flag)if is_match:- payload = self.get_matching_payload(super_condition_value, None, feature_flag)+ payload = self.get_matching_payload(enrollment_value, None, feature_flag)return FeatureFlagMatch(- match=super_condition_value,+ match=enrollment_value,reason=evaluation_reason,condition_index=0,payload=payload,)# Match for holdout condition- # TODO: Flags shouldn't have both super_groups and holdout- # TODO: Validate only multivariant flags to have holdoutsif feature_flag.filters.get("holdout", None):(is_match,@@ -277,37 +275,21 @@ class FeatureFlagMatcher:variant = f"holdout-{holdout['id']}"return True, variant, FeatureFlagMatchReason.HOLDOUT_CONDITION_VALUE- def is_super_condition_match(self, feature_flag: FeatureFlag) -> tuple[bool, bool, FeatureFlagMatchReason]:- # TODO: Right now super conditions with property overrides bork when the database is down,- # because we're still going to the database in the line below. Ideally, we should not go to the database.- # Don't skip test: test_super_condition_with_override_properties_doesnt_make_database_requests when this is fixed.- # This also doesn't handle the case when the super condition has a property & a non-100 percentage rollout; but- # we don't support that with super conditions anyway.- super_condition_value_is_set = self._super_condition_is_set(feature_flag)- super_condition_value = self._super_condition_matches(feature_flag)-- if super_condition_value_is_set:- return (- True,- super_condition_value,- FeatureFlagMatchReason.SUPER_CONDITION_VALUE,- )+ def is_feature_enrollment_match(self, feature_flag: FeatureFlag) -> tuple[bool, bool, FeatureFlagMatchReason]:+ is_set_key = f"flag_{feature_flag.pk}_enrollment_is_set"+ enrollment_is_set = self.query_conditions.get(is_set_key)- # Evaluate if properties are empty- if feature_flag.super_conditions and len(feature_flag.super_conditions) > 0:- condition = feature_flag.super_conditions[0]+ if enrollment_is_set is None:+ logger.debug(+ "feature_enrollment_query_missing",+ flag_id=feature_flag.pk,+ flag_key=feature_flag.key,+ )+ return False, False, FeatureFlagMatchReason.NO_CONDITION_MATCH- if not condition.get("properties"):- is_match, evaluation_reason = self.is_condition_match(feature_flag, condition, 0)- return (- True,- is_match,- (- FeatureFlagMatchReason.SUPER_CONDITION_VALUE- if evaluation_reason == FeatureFlagMatchReason.CONDITION_MATCH- else evaluation_reason- ),- )+ enrollment_matches = self._get_query_condition(f"flag_{feature_flag.pk}_enrollment")+ if enrollment_is_set:+ return (True, enrollment_matches, FeatureFlagMatchReason.SUPER_CONDITION_VALUE)return False, False, FeatureFlagMatchReason.NO_CONDITION_MATCH@@ -348,12 +330,6 @@ class FeatureFlagMatcher:return True, FeatureFlagMatchReason.CONDITION_MATCH- def _super_condition_matches(self, feature_flag: FeatureFlag) -> bool:- return self._get_query_condition(f"flag_{feature_flag.pk}_super_condition")-- def _super_condition_is_set(self, feature_flag: FeatureFlag) -> Optional[bool]:- return self._get_query_condition(f"flag_{feature_flag.pk}_super_condition_is_set")-def _condition_matches(self,feature_flag: FeatureFlag,@@ -547,24 +523,30 @@ class FeatureFlagMatcher:self.cohorts_cache.update(all_cohorts)# release conditionsfor feature_flag in self.feature_flags:- # super release conditions- if feature_flag.super_conditions and len(feature_flag.super_conditions) > 0:- condition = feature_flag.super_conditions[0]- prop_key = (condition.get("properties") or [{}])[0].get("key")- if prop_key:- key = f"flag_{feature_flag.pk}_super_condition"- condition_eval(key, condition)-- is_set_key = f"flag_{feature_flag.pk}_super_condition_is_set"- is_set_condition = {- "properties": [- {- "key": prop_key,- "operator": "is_set",- }- ]- }- condition_eval(is_set_key, is_set_condition)+ # early access feature enrollment+ if feature_flag.has_feature_enrollment:+ enrollment_key = f"$feature_enrollment/{feature_flag.key}"+ enrollment_condition = {+ "properties": [+ {+ "key": enrollment_key,+ "value": ["true"],+ "operator": "exact",+ "type": "person",+ }+ ]+ }+ condition_eval(f"flag_{feature_flag.pk}_enrollment", enrollment_condition)++ is_set_condition = {+ "properties": [+ {+ "key": enrollment_key,+ "operator": "is_set",+ }+ ]+ }+ condition_eval(f"flag_{feature_flag.pk}_enrollment_is_set", is_set_condition)for index, condition in enumerate(feature_flag.conditions):key = f"flag_{feature_flag.pk}_condition_{index}"diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.pyindex cc74dc792c68..50b0dcf19411 100644--- a/products/feature_flags/backend/flags_cache.py+++ b/products/feature_flags/backend/flags_cache.py@@ -122,8 +122,8 @@ def _extract_cohort_ids_from_flag_filters(flags_data: list[dict[str, Any]]) -> sOnly scans ``groups`` — the other filter sections cannot contain cohortproperties:- - ``super_groups`` are early-access enrollment gates that only use person- properties (``$feature_enrollment/*``).+ - ``feature_enrollment`` is a boolean gate for early-access features,+ evaluated against person properties (``$feature_enrollment/*``).- ``holdout`` uses a different schema for configuring experiment holdoutswith no property filters at all."""diff --git a/products/feature_flags/backend/models/feature_flag.py b/products/feature_flags/backend/models/feature_flag.pyindex db9c43edd1fa..ad17f62e9233 100644--- a/products/feature_flags/backend/models/feature_flag.py+++ b/products/feature_flags/backend/models/feature_flag.py@@ -186,11 +186,6 @@ class FeatureFlag(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models"Each feature flag can have multiple conditions to match, they are OR-ed together."return self.get_filters().get("groups", []) or []- @property- def super_conditions(self):- "Each feature flag can have multiple super conditions to match, they are OR-ed together."- return self.get_filters().get("super_groups", []) or []-@propertydef has_feature_enrollment(self) -> bool:return bool(self.get_filters().get("feature_enrollment", False))diff --git a/products/feature_flags/backend/test/test_flag_matching.py b/products/feature_flags/backend/test/test_flag_matching.pynew file mode 100644index 000000000000..adf020b2e955--- /dev/null+++ b/products/feature_flags/backend/test/test_flag_matching.py@@ -0,0 +1,62 @@+from unittest.mock import MagicMock, PropertyMock, patch++from django.test import SimpleTestCase++from parameterized import parameterized++from products.feature_flags.backend.flag_matching import FeatureFlagMatcher, FeatureFlagMatchReason+++def _make_matcher(query_conditions: dict[str, bool]) -> FeatureFlagMatcher:+ matcher = FeatureFlagMatcher(+ team_id=1,+ project_id=1,+ feature_flags=[],+ distinct_id="test",+ )+ return matcher+++def _make_flag(pk: int = 42, key: str = "test-flag") -> MagicMock:+ flag = MagicMock()+ flag.pk = pk+ flag.key = key+ return flag+++class TestIsFeatureEnrollmentMatch(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "enrollment_is_set_true_and_matches",+ {"flag_42_enrollment_is_set": True, "flag_42_enrollment": True},+ (True, True, FeatureFlagMatchReason.SUPER_CONDITION_VALUE),+ ),+ (+ "enrollment_is_set_true_but_not_matching",+ {"flag_42_enrollment_is_set": True, "flag_42_enrollment": False},+ (True, False, FeatureFlagMatchReason.SUPER_CONDITION_VALUE),+ ),+ (+ "enrollment_is_set_false",+ {"flag_42_enrollment_is_set": False, "flag_42_enrollment": False},+ (False, False, FeatureFlagMatchReason.NO_CONDITION_MATCH),+ ),+ (+ "enrollment_query_missing",+ {},+ (False, False, FeatureFlagMatchReason.NO_CONDITION_MATCH),+ ),+ ],+ )+ def test_is_feature_enrollment_match(+ self,+ _name: str,+ query_conditions: dict[str, bool],+ expected: tuple[bool, bool, FeatureFlagMatchReason],+ ):+ matcher = _make_matcher(query_conditions)+ flag = _make_flag()+ with patch.object(type(matcher), "query_conditions", new_callable=PropertyMock, return_value=query_conditions):+ result = matcher.is_feature_enrollment_match(flag)+ assert result == expecteddiff --git a/rust/feature-flags/src/flags/feature_flag_list.rs b/rust/feature-flags/src/flags/feature_flag_list.rsindex c57aa3c39f90..a17a49770028 100644--- a/rust/feature-flags/src/flags/feature_flag_list.rs+++ b/rust/feature-flags/src/flags/feature_flag_list.rs@@ -69,12 +69,6 @@ impl FeatureFlagList {pub fn prepare_regexes_in_place(flags: &mut [FeatureFlag]) {for flag in flags.iter_mut() {Self::prepare_group_regexes(&mut flag.filters.groups);- // super_groups currently only use Exact operators (early access enrollment),- // so prepare_regex() will no-op for each filter. We walk them anyway for- // forward-compatibility if super_groups ever gain regex-based filters.- if let Some(super_groups) = &mut flag.filters.super_groups {- Self::prepare_group_regexes(super_groups);- }}}@@ -1146,7 +1140,6 @@ mod tests {// Filter structureassert_eq!(full_flag.filters.groups.len(), 1);assert!(full_flag.filters.multivariate.is_some());- assert!(full_flag.filters.super_groups.is_some());assert_eq!(full_flag.filters.feature_enrollment, Some(true));assert!(full_flag.filters.holdout.is_some());let holdout = full_flag.filters.holdout.as_ref().unwrap();@@ -1243,7 +1236,6 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,feature_enrollment: None,holdout: None,},diff --git a/rust/feature-flags/src/flags/flag_definitions_cache.rs b/rust/feature-flags/src/flags/flag_definitions_cache.rsindex 46c08f82b231..ade8fca7da05 100644--- a/rust/feature-flags/src/flags/flag_definitions_cache.rs+++ b/rust/feature-flags/src/flags/flag_definitions_cache.rs@@ -757,58 +757,6 @@ mod tests {);}- /// The weigher must walk `super_groups` as well as `groups` so cache- /// capacity isn't silently overshot for teams whose super_groups carry- /// non-trivial property payloads.- #[test]- fn test_weigher_accounts_for_super_groups() {- use crate::flags::flag_models::FlagPropertyGroup;- use crate::properties::property_models::PropertyType;-- let make_flag = |super_groups: Option<Vec<FlagPropertyGroup>>| {- let mut flag = mock!(FeatureFlag,- name: None,- key: "k".mock_into(),- );- flag.filters.super_groups = super_groups;- flag- };-- let big_str = "x".repeat(10_000);- let big_group = FlagPropertyGroup {- properties: Some(vec![PropertyFilter {- key: "prop".to_string(),- value: Some(json!(big_str)),- operator: Some(OperatorType::Exact),- prop_type: PropertyType::Person,- group_type_index: None,- negation: None,- compiled_regex: None,- }]),- rollout_percentage: Some(100.0),- variant: None,- aggregation_group_type_index: None,- };-- let without = Arc::new(PreparedFlagDefinitions {- flags: PreparedFlags::seal(vec![make_flag(None)]),- evaluation_metadata: Arc::new(EvaluationMetadata::default()),- cohorts: None,- });- let with = Arc::new(PreparedFlagDefinitions {- flags: PreparedFlags::seal(vec![make_flag(Some(vec![big_group]))]),- evaluation_metadata: Arc::new(EvaluationMetadata::default()),- cohorts: None,- });-- let without_sz = without.estimated_size_bytes();- let with_sz = with.estimated_size_bytes();- assert!(- with_sz > without_sz + 9_000,- "weigher must count super_groups property bytes: without={without_sz}, with={with_sz}"- );- }-/// The weigher must include JSON-valued `PropertyFilter.value` bytes so/// large cohort-in-flag filters don't push the cache over its capacity.#[test]diff --git a/rust/feature-flags/src/flags/flag_filters.rs b/rust/feature-flags/src/flags/flag_filters.rsindex 6beb5f224571..eb93d815fc75 100644--- a/rust/feature-flags/src/flags/flag_filters.rs+++ b/rust/feature-flags/src/flags/flag_filters.rs@@ -23,10 +23,6 @@ impl FlagFilters {.groups.iter().any(|group| matches!(group.aggregation_group_type_index, Some(Some(_))))- || self- .super_groups- .as_ref()- .is_some_and(|groups| groups.iter().any(|g| g.requires_db_properties(overrides)))|| self.groups.iter()@@ -151,32 +147,6 @@ mod tests {assert!(f.requires_db_properties(&HashMap::new(), "test-flag"));}- #[test]- fn test_super_groups_require_db_properties_when_overrides_insufficient() {- let mut f = mock!(FlagFilters, groups: vec![]);- f.super_groups = Some(vec![mock!(FlagPropertyGroup,- properties: Some(vec![- mock!(PropertyFilter,- key: "$feature_enrollment/feature-flags-flag-dependency".mock_into()- ),- ])- )]);-- {- // Without overrides, DB lookup is required- assert!(f.requires_db_properties(&HashMap::new(), "test-flag"));- }-- {- // With sufficient overrides, DB lookup is not required- let overrides = HashMap::from([(- "$feature_enrollment/feature-flags-flag-dependency".to_string(),- Value::String("value".to_string()),- )]);- assert!(!f.requires_db_properties(&overrides, "test-flag"));- }- }-#[test]fn test_feature_enrollment_requires_db_properties_when_override_missing() {let mut f = mock!(FlagFilters, groups: vec![]);@@ -197,15 +167,6 @@ mod tests {assert!(!f.requires_db_properties(&overrides, "my-flag"));}- #[test]- fn test_does_not_require_db_properties_when_super_groups_empty() {- let mut f = mock!(FlagFilters, groups: vec![]);- f.super_groups = Some(vec![]);-- // Empty super_groups don't require DB properties- assert!(!f.requires_db_properties(&HashMap::new(), "test-flag"));- }-#[test]fn test_does_not_require_db_properties_when_holdout_set() {use crate::flags::flag_models::Holdout;diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rsindex 7faa09427f21..532f369ec955 100644--- a/rust/feature-flags/src/flags/flag_matching.rs+++ b/rust/feature-flags/src/flags/flag_matching.rs@@ -91,13 +91,6 @@ impl std::fmt::Display for EvaluationType {}}-#[derive(Debug)]-struct SuperConditionEvaluation {- should_evaluate: bool,- is_match: bool,- reason: FeatureFlagMatchReason,-}-#[derive(Debug, PartialEq, Eq, Clone)]pub struct FeatureFlagMatch {pub matches: bool,@@ -1257,13 +1250,7 @@ impl FeatureFlagMatcher {// Evaluate feature enrollment (early access features) first.// Enrollment is a person-level concept — always uses person properties, even for- // group-based flags. The API validates that group-based flags cannot have early access- // features attached.- //- // New format: `feature_enrollment: true` — the enrollment property key is derived- // from the flag key as `$feature_enrollment/{flag_key}`.- // Legacy format: `super_groups` array with explicit property filters.- // New format takes precedence when both are present.+ // group-based flags.if flag.filters.feature_enrollment == Some(true) {let enrollment_key = FlagFilters::enrollment_key(&flag.key);let person_properties = self.get_person_properties(person_property_overrides)?;@@ -1279,45 +1266,9 @@ impl FeatureFlagMatcher {payload,});}- // Person doesn't have enrollment property set — fall through to normal conditions- } else if let Some(super_groups) = &flag.filters.super_groups {- if let Some(super_condition) = super_groups.first() {- // Legacy path: evaluate super_groups property filters directly.- if super_condition- .properties- .as_ref()- .is_some_and(|p| !p.is_empty())- {- if cached_person_properties.is_none() {- cached_person_properties =- Some(self.get_person_properties(person_property_overrides)?);- }- let super_condition_evaluation = self.is_super_condition_match(- flag,- cached_person_properties.as_ref().unwrap(),- hash_key_overrides,- request_hash_key_override,- )?;-- if super_condition_evaluation.should_evaluate {- let payload = self.get_matching_payload(None, flag);- return Ok(FeatureFlagMatch {- matches: super_condition_evaluation.is_match,- variant: None,- reason: super_condition_evaluation.reason,- condition_index: Some(0),- payload,- });- }- // if no match, continue to normal conditions- }- }}- // Match for holdout super condition- // TODO: Flags shouldn't have both super_groups and holdout- // TODO: Validate only multivariant flags to have holdout groups. I could make this implicit by reusing super_groups but- // this will shoot ourselves in the foot when we extend early access to support variants as well.+ // Match for holdout condition// TODO: Validate holdout variant should have 0% default rollout %?// TODO: All this validation we need to do suggests the modelling is imperfect here. Carrying forward for now, we'll only enable// in beta, and potentially rework representation before rolling out to everyone. Probably the problem is holdout groups are an@@ -1473,10 +1424,6 @@ impl FeatureFlagMatcher {highest_index = new_highest_index;if is_match {- if highest_match == FeatureFlagMatchReason::SuperConditionValue {- break; // Exit early if we've found a super condition match- }-// Check for variant override in the conditionlet variant = if let Some(variant_override) = &condition.variant {// Check if the override is a valid variant@@ -1765,66 +1712,6 @@ impl FeatureFlagMatcher {Ok((false, None, FeatureFlagMatchReason::NoConditionMatch))}- /// Check if a super condition matches for a feature flag.- ///- /// This function evaluates the super conditions of a feature flag to determine if any of them should be enabled.- /// It uses pre-computed person properties (DB properties with overrides applied).- /// The function returns a struct indicating whether a super condition should be evaluated,- /// whether it matches if evaluated, and the reason for the match.- ///- /// Note: Super conditions (early access features) always use person properties, even for- /// group-based flags, because early access enrollment is a person-level concept.- fn is_super_condition_match(- &self,- feature_flag: &FeatureFlag,- person_properties: &HashMap<String, Value>,- hash_key_overrides: Option<&HashMap<String, String>>,- request_hash_key_override: &Option<String>,- ) -> Result<SuperConditionEvaluation, FlagError> {- if let Some(super_condition) = feature_flag- .filters- .super_groups- .as_ref()- .and_then(|sc| sc.first())- {- let has_relevant_super_condition_properties =- super_condition.properties.as_ref().is_some_and(|props| {- props- .iter()- .any(|prop| person_properties.contains_key(&prop.key))- });-- if has_relevant_super_condition_properties {- // Super conditions always use person-level aggregation (None)- let empty_group_props = HashMap::new();- let property_context = PropertyContext {- person_properties: Some(person_properties),- group_properties: &empty_group_props,- aggregation: None,- };- let (is_match, _) = self.is_condition_match(- feature_flag,- super_condition,- &property_context,- hash_key_overrides,- request_hash_key_override,- )?;-- return Ok(SuperConditionEvaluation {- should_evaluate: true,- is_match,- reason: FeatureFlagMatchReason::SuperConditionValue,- });- }- }-- Ok(SuperConditionEvaluation {- should_evaluate: false,- is_match: false,- reason: FeatureFlagMatchReason::NoConditionMatch,- })- }-/// Get hashed identifier for flag evaluation.////// Resolves the identifier used for hashing (rollout and variant assignment) based ondiff --git a/rust/feature-flags/src/flags/flag_models.rs b/rust/feature-flags/src/flags/flag_models.rsindex 9e60e9804fc7..074dddf92ebd 100644--- a/rust/feature-flags/src/flags/flag_models.rs+++ b/rust/feature-flags/src/flags/flag_models.rs@@ -172,24 +172,8 @@ pub struct FlagFilters {pub aggregation_group_type_index: Option<i32>,#[serde(default)]pub payloads: Option<serde_json::Value>,- /// Super groups are a special group of feature flag conditions that act as a gate that must be- /// satisfied before any other conditions are evaluated. Currently, we only ever evaluate the first- /// super group. This is used for early access features which is a key and a boolean like so:- /// {- /// "key": "$feature_enrollment/feature-flags-flag-dependency",- /// "type": "person",- /// "value": [- /// "true"- /// ],- /// "operator": "exact"- /// }- /// If they match, the flag is enabled and no other conditions are evaluated. If they don't match,- /// fallback to regular conditions.- #[serde(default)]- pub super_groups: Option<Vec<FlagPropertyGroup>>,- /// New format for early access feature enrollment. When `true`, the flag is evaluated- /// against the person property `$feature_enrollment/{flag_key}`. Takes precedence over- /// `super_groups` when both are present.+ /// Early access feature enrollment. When `true`, the flag is evaluated against the+ /// person property `$feature_enrollment/{flag_key}`.#[serde(default)]pub feature_enrollment: Option<bool>,/// Holdout format: `{"id": 42, "exclusion_percentage": 10}`.@@ -326,11 +310,6 @@ impl PreparedFlagDefinitions {.as_ref().map_or(0, |tags| tags.iter().map(|t| t.len() + 24).sum());let bucketing_size = f.bucketing_identifier.as_ref().map_or(0, |b| b.len());- // Each PropertyFilter with a compiled regex costs ~2KB for the- // DFA/NFA automata inside fancy_regex::Regex. The `value` JSON- // payload can dominate for cohort/group filters, so walk it.- // Include `super_groups` alongside `groups` — `prepare_regexes_in_place`- // compiles regexes in both, so the weigher must account for both.let group_size = |groups: &[FlagPropertyGroup]| -> usize {groups.iter()@@ -352,8 +331,7 @@ impl PreparedFlagDefinitions {}).sum()};- let filters_size: usize = group_size(&f.filters.groups)- + f.filters.super_groups.as_deref().map_or(0, group_size);+ let filters_size: usize = group_size(&f.filters.groups);let payloads_size = f.filters.payloads.as_ref().map_or(0, estimate_json_size);diff --git a/rust/feature-flags/src/flags/flag_operations.rs b/rust/feature-flags/src/flags/flag_operations.rsindex 518d769b3d65..1e700b5388ed 100644--- a/rust/feature-flags/src/flags/flag_operations.rs+++ b/rust/feature-flags/src/flags/flag_operations.rs@@ -523,98 +523,6 @@ mod tests {}}- #[tokio::test]- async fn test_flag_with_super_groups() {- let redis_client = setup_redis_client(None).await;- let context = TestContext::new(None).await;- let team = context- .insert_new_team(None)- .await- .expect("Failed to insert team in pg");-- let flag_with_super_groups = json!({- "id": 1,- "team_id": team.id,- "name": "Flag with Super Groups",- "key": "flag_with_super_groups",- "filters": {- "groups": [- {- "properties": [],- "rollout_percentage": 50- }- ],- "super_groups": [- {- "properties": [- {- "key": "country",- "value": "US",- "type": "person",- "operator": "exact"- }- ],- "rollout_percentage": 100- }- ]- },- "active": true,- "deleted": false- });-- // Insert into Redis- insert_flags_for_team_in_redis(- redis_client.clone(),- team.id,- Some(json!([flag_with_super_groups]).to_string()),- )- .await- .expect("Failed to insert flag in Redis");-- // Insert into Postgres- context- .insert_flag(- team.id,- Some(FeatureFlagRow {- id: 1,- team_id: team.id,- name: Some("Flag with Super Groups".to_string()),- key: "flag_with_super_groups".to_string(),- filters: flag_with_super_groups["filters"].clone(),- deleted: false,- active: true,- ensure_experience_continuity: Some(false),- version: Some(1),- evaluation_runtime: Some("all".to_string()),- evaluation_tags: None,- bucketing_identifier: None,- }),- )- .await- .expect("Failed to insert flag in Postgres");-- // Fetch and verify from Redis- let redis_flags = get_flags_from_redis(redis_client, team.id)- .await- .expect("Failed to fetch flags from Redis");-- assert_eq!(redis_flags.flags.len(), 1);- let redis_flag = &redis_flags.flags[0];- assert_eq!(redis_flag.key, "flag_with_super_groups");- assert!(redis_flag.filters.super_groups.is_some());- assert_eq!(redis_flag.filters.super_groups.as_ref().unwrap().len(), 1);-- // Fetch and verify from Postgres- let pg_flags = FeatureFlagList::from_pg(context.non_persons_reader.clone(), team.id)- .await- .expect("Failed to fetch flags from Postgres");- assert_eq!(pg_flags.len(), 1);- let pg_flag = &pg_flags[0];- assert_eq!(pg_flag.key, "flag_with_super_groups");- assert!(pg_flag.filters.super_groups.is_some());- assert_eq!(pg_flag.filters.super_groups.as_ref().unwrap().len(), 1);- }-#[tokio::test]async fn test_flags_with_different_property_types() {let redis_client = setup_redis_client(None).await;@@ -1289,7 +1197,6 @@ mod tests {assert!(flag.filters.multivariate.is_none());assert!(flag.filters.aggregation_group_type_index.is_none());assert!(flag.filters.payloads.is_none());- assert!(flag.filters.super_groups.is_none());assert!(flag.filters.holdout.is_none());}diff --git a/rust/feature-flags/src/flags/flag_service.rs b/rust/feature-flags/src/flags/flag_service.rsindex 6f1b23182140..eb095535a7d6 100644--- a/rust/feature-flags/src/flags/flag_service.rs+++ b/rust/feature-flags/src/flags/flag_service.rs@@ -449,7 +449,6 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,feature_enrollment: None,holdout: None,},@@ -471,7 +470,6 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,feature_enrollment: None,holdout: None,},@@ -506,7 +504,6 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,feature_enrollment: None,holdout: None,},@@ -637,7 +634,6 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,feature_enrollment: None,holdout: None,diff --git a/rust/feature-flags/src/flags/test_flag_matching.rs b/rust/feature-flags/src/flags/test_flag_matching.rsindex 580e68c601cb..a074bf730584 100644--- a/rust/feature-flags/src/flags/test_flag_matching.rs+++ b/rust/feature-flags/src/flags/test_flag_matching.rs@@ -379,7 +379,7 @@ mod tests {multivariate: None,aggregation_group_type_index: Some(0),payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,}@@ -462,7 +462,7 @@ mod tests {multivariate: None,aggregation_group_type_index: Some(1),payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,}@@ -713,7 +713,7 @@ mod tests {}),aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,}@@ -1148,7 +1148,7 @@ mod tests {}),aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,}@@ -2037,7 +2037,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,}@@ -2266,7 +2266,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,@@ -2310,7 +2310,7 @@ mod tests {}#[tokio::test]- async fn test_super_condition_matches_boolean() {+ async fn test_basic_cohort_matching() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -2319,64 +2319,62 @@ mod tests {));let team = context.insert_new_team(None).await.unwrap();+ // Insert a cohort with the condition that matches the test user's properties+ 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();++ // Insert a person with properties that match the cohort condition+ context+ .insert_person(+ team.id,+ "test_user".to_string(),+ Some(json!({"$browser_version": 126})),+ )+ .await+ .unwrap();++ // Define a flag with a cohort filterlet flag = mock!(FeatureFlag,team_id: team.id,- name: "Super Condition Flag".mock_into(),- key: "super_condition_flag".mock_into(),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,- }]),- rollout_percentage: Some(0.0),- variant: None,- ..Default::default()- },- 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,- }]),- rollout_percentage: Some(100.0),- variant: None,- ..Default::default()- },- FlagPropertyGroup {- properties: None,- rollout_percentage: Some(50.0),- variant: None,- ..Default::default()- },- ],- multivariate: None,- aggregation_group_type_index: None,- payloads: None,- super_groups: Some(vec![FlagPropertyGroup {+ groups: vec![FlagPropertyGroup {properties: Some(vec![PropertyFilter {- key: "is_enabled".to_string(),- value: Some(json!(["true"])),- operator: Some(OperatorType::Exact),- prop_type: PropertyType::Person,+ key: "id".to_string(),+ value: Some(json!(cohort_row.id)),+ operator: Some(OperatorType::In),+ prop_type: PropertyType::Cohort,group_type_index: None,- negation: None,+ negation: Some(false),compiled_regex: None,}]),rollout_percentage: Some(100.0),variant: None,..Default::default()- }]),+ }],+ multivariate: None,+ aggregation_group_type_index: None,+ payloads: None,feature_enrollment: None,@@ -2384,48 +2382,9 @@ mod tests {});- context- .insert_person(- team.id,- "test_id".to_string(),- Some(json!({"email": "[email protected]", "is_enabled": true})),- )- .await- .unwrap();-- context- .insert_person(team.id, "lil_id".to_string(), None)- .await- .unwrap();-- context- .insert_person(team.id, "another_id".to_string(), None)- .await- .unwrap();-let router = context.create_postgres_router();- let mut matcher_test_id = FeatureFlagMatcher::new(- "test_id".to_string(),- None, // device_id- team.id,- router.clone(),- cohort_cache.clone(),- empty_group_type_cache(),- None,- );-- let mut matcher_example_id = FeatureFlagMatcher::new(- "lil_id".to_string(),- None, // device_id- team.id,- router.clone(),- cohort_cache.clone(),- empty_group_type_cache(),- None,- );-- let mut matcher_another_id = FeatureFlagMatcher::new(- "another_id".to_string(),+ let mut matcher = FeatureFlagMatcher::new(+ "test_user".to_string(),None, // device_idteam.id,router,@@ -2434,41 +2393,18 @@ mod tests {None,);- matcher_test_id- .prepare_flag_evaluation_state(&[&flag])- .await- .unwrap();-- matcher_example_id- .prepare_flag_evaluation_state(&[&flag])- .await- .unwrap();-- matcher_another_id+ matcher.prepare_flag_evaluation_state(&[&flag]).await.unwrap();- let result_test_id = matcher_test_id- .get_match(&flag, None, None, None, &None)- .unwrap();- let result_example_id = matcher_example_id- .get_match(&flag, None, None, None, &None)- .unwrap();- let result_another_id = matcher_another_id- .get_match(&flag, None, None, None, &None)- .unwrap();+ let result = matcher.get_match(&flag, None, None, None, &None).unwrap();- assert!(result_test_id.matches);- assert!(result_test_id.reason == FeatureFlagMatchReason::SuperConditionValue);- assert!(result_example_id.matches);- assert!(result_example_id.reason == FeatureFlagMatchReason::ConditionMatch);- assert!(!result_another_id.matches);- assert!(result_another_id.reason == FeatureFlagMatchReason::OutOfRolloutBound);+ assert!(result.matches);}#[tokio::test]- async fn test_super_condition_matches_string() {+ async fn test_not_in_cohort_matching() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -2477,73 +2413,62 @@ mod tests {));let team = context.insert_new_team(None).await.unwrap();+ // Insert a cohort with a condition that does not match the test user's properties+ let cohort_row = context+ .insert_cohort(+ team.id,+ None,+ json!({+ "properties": {+ "type": "OR",+ "values": [{+ "type": "OR",+ "values": [{+ "key": "$browser_version",+ "type": "person",+ "value": "130",+ "negation": false,+ "operator": "gt"+ }]+ }]+ }+ }),+ false,+ )+ .await+ .unwrap();++ // Insert a person with properties that do not match the cohort conditioncontext.insert_person(team.id,- "test_id".to_string(),- Some(json!({"email": "[email protected]", "is_enabled": "true"})),+ "test_user".to_string(),+ Some(json!({"$browser_version": 126})),).await.unwrap();+ // Define a flag with a NotIn cohort filterlet flag = mock!(FeatureFlag,team_id: team.id,- name: "Super Condition Flag".mock_into(),- key: "super_condition_flag".mock_into(),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,- }]),- rollout_percentage: Some(0.0),- variant: None,- ..Default::default()- },- 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,- }]),- rollout_percentage: Some(100.0),- variant: None,- ..Default::default()- },- FlagPropertyGroup {- properties: None,- rollout_percentage: Some(50.0),- variant: None,- ..Default::default()- },- ],- multivariate: None,- aggregation_group_type_index: None,- payloads: None,- super_groups: Some(vec![FlagPropertyGroup {+ groups: vec![FlagPropertyGroup {properties: Some(vec![PropertyFilter {- key: "is_enabled".to_string(),- value: Some(json!("true")),- operator: Some(OperatorType::Exact),- prop_type: PropertyType::Person,+ key: "id".to_string(),+ value: Some(json!(cohort_row.id)),+ operator: Some(OperatorType::NotIn),+ prop_type: PropertyType::Cohort,group_type_index: None,- negation: None,+ negation: Some(false),compiled_regex: None,}]),rollout_percentage: Some(100.0),variant: None,..Default::default()- }]),+ }],+ multivariate: None,+ aggregation_group_type_index: None,+ payloads: None,feature_enrollment: None,@@ -2553,7 +2478,7 @@ mod tests {let router = context.create_postgres_router();let mut matcher = FeatureFlagMatcher::new(- "test_id".to_string(),+ "test_user".to_string(),None, // device_idteam.id,router,@@ -2570,12 +2495,10 @@ mod tests {let result = matcher.get_match(&flag, None, None, None, &None).unwrap();assert!(result.matches);- assert_eq!(result.reason, FeatureFlagMatchReason::SuperConditionValue);- assert_eq!(result.condition_index, Some(0));}#[tokio::test]- async fn test_super_condition_matches_and_false() {+ async fn test_not_in_cohort_matching_user_in_cohort() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -2584,83 +2507,62 @@ mod tests {));let team = context.insert_new_team(None).await.unwrap();- context- .insert_person(+ // Insert a cohort with a condition that matches the test user's properties+ let cohort_row = context+ .insert_cohort(team.id,- "test_id".to_string(),- Some(json!({"email": "[email protected]", "is_enabled": true})),+ None,+ json!({+ "properties": {+ "type": "OR",+ "values": [{+ "type": "OR",+ "values": [{+ "key": "$browser_version",+ "type": "person",+ "value": "125",+ "negation": false,+ "operator": "gt"+ }]+ }]+ }+ }),+ false,).await.unwrap();+ // Insert a person with properties that match the cohort conditioncontext- .insert_person(team.id, "another_id".to_string(), None)- .await- .unwrap();-- context- .insert_person(team.id, "lil_id".to_string(), None)+ .insert_person(+ team.id,+ "test_user".to_string(),+ Some(json!({"$browser_version": 126})),+ ).await.unwrap();+ // Define a flag with a NotIn cohort filterlet flag = mock!(FeatureFlag,team_id: team.id,- name: "Super Condition Flag".mock_into(),- key: "super_condition_flag".mock_into(),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,- }]),- rollout_percentage: Some(0.0),- variant: None,- ..Default::default()- },- 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,- }]),- rollout_percentage: Some(100.0),- variant: None,- ..Default::default()- },- FlagPropertyGroup {- properties: None,- rollout_percentage: Some(50.0),- variant: None,- ..Default::default()- },- ],- multivariate: None,- aggregation_group_type_index: None,- payloads: None,- super_groups: Some(vec![FlagPropertyGroup {+ groups: vec![FlagPropertyGroup {properties: Some(vec![PropertyFilter {- key: "is_enabled".to_string(),- value: Some(json!(false)),- operator: Some(OperatorType::Exact),- prop_type: PropertyType::Person,+ key: "id".to_string(),+ value: Some(json!(cohort_row.id)),+ operator: Some(OperatorType::NotIn),+ prop_type: PropertyType::Cohort,group_type_index: None,- negation: None,+ negation: Some(false),compiled_regex: None,}]),rollout_percentage: Some(100.0),variant: None,..Default::default()- }]),+ }],+ multivariate: None,+ aggregation_group_type_index: None,+ payloads: None,feature_enrollment: None,@@ -2669,28 +2571,8 @@ mod tests {);let router = context.create_postgres_router();- let mut matcher_test_id = FeatureFlagMatcher::new(- "test_id".to_string(),- None, // device_id- team.id,- router.clone(),- cohort_cache.clone(),- empty_group_type_cache(),- None,- );-- let mut matcher_example_id = FeatureFlagMatcher::new(- "lil_id".to_string(),- None, // device_id- team.id,- router.clone(),- cohort_cache.clone(),- empty_group_type_cache(),- None,- );-- let mut matcher_another_id = FeatureFlagMatcher::new(- "another_id".to_string(),+ let matcher = FeatureFlagMatcher::new(+ "test_user".to_string(),None, // device_idteam.id,router,@@ -2699,55 +2581,14 @@ mod tests {None,);- matcher_test_id- .prepare_flag_evaluation_state(&[&flag])- .await- .unwrap();-- matcher_example_id- .prepare_flag_evaluation_state(&[&flag])- .await- .unwrap();-- matcher_another_id- .prepare_flag_evaluation_state(&[&flag])- .await- .unwrap();-- let result_test_id = matcher_test_id- .get_match(&flag, None, None, None, &None)- .unwrap();- let result_example_id = matcher_example_id- .get_match(&flag, None, None, None, &None)- .unwrap();- let result_another_id = matcher_another_id- .get_match(&flag, None, None, None, &None)- .unwrap();-- assert!(!result_test_id.matches);- assert_eq!(- result_test_id.reason,- FeatureFlagMatchReason::SuperConditionValue- );- assert_eq!(result_test_id.condition_index, Some(0));-- assert!(result_example_id.matches);- assert_eq!(- result_example_id.reason,- FeatureFlagMatchReason::ConditionMatch- );- assert_eq!(result_example_id.condition_index, Some(2));+ let result = matcher.get_match(&flag, None, None, None, &None).unwrap();- assert!(!result_another_id.matches);- assert_eq!(- result_another_id.reason,- FeatureFlagMatchReason::OutOfRolloutBound- );- assert_eq!(result_another_id.condition_index, Some(2));+ // The user matches the cohort, but the flag is set to NotIn, so it should evaluate to false+ assert!(!result.matches);}#[tokio::test]- async fn test_basic_cohort_matching() {+ async fn test_cohort_dependent_on_another_cohort() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -2756,8 +2597,8 @@ mod tests {));let team = context.insert_new_team(None).await.unwrap();- // Insert a cohort with the condition that matches the test user's properties- let cohort_row = context+ // Insert a base cohort+ let base_cohort_row = context.insert_cohort(team.id,None,@@ -2781,7 +2622,32 @@ mod tests {.await.unwrap();- // Insert a person with properties that match the cohort condition+ // Insert a dependent cohort that includes the base cohort+ let dependent_cohort_row = context+ .insert_cohort(+ team.id,+ None,+ json!({+ "properties": {+ "type": "OR",+ "values": [{+ "type": "OR",+ "values": [{+ "key": "id",+ "type": "cohort",+ "value": base_cohort_row.id,+ "negation": false,+ "operator": "in"+ }]+ }]+ }+ }),+ false,+ )+ .await+ .unwrap();++ // Insert a person with properties that match the base cohort conditioncontext.insert_person(team.id,@@ -2791,14 +2657,14 @@ mod tests {.await.unwrap();- // Define a flag with a cohort filter+ // Define a flag with a cohort filter that depends on another cohortlet flag = mock!(FeatureFlag,team_id: team.id,filters: FlagFilters {groups: vec![FlagPropertyGroup {properties: Some(vec![PropertyFilter {key: "id".to_string(),- value: Some(json!(cohort_row.id)),+ value: Some(json!(dependent_cohort_row.id)),operator: Some(OperatorType::In),prop_type: PropertyType::Cohort,group_type_index: None,@@ -2812,7 +2678,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,@@ -2841,7 +2707,7 @@ mod tests {}#[tokio::test]- async fn test_not_in_cohort_matching() {+ async fn test_in_cohort_matching_user_not_in_cohort() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -2880,12 +2746,12 @@ mod tests {.insert_person(team.id,"test_user".to_string(),- Some(json!({"$browser_version": 126})),+ Some(json!({"$browser_version": 125})),).await.unwrap();- // Define a flag with a NotIn cohort filter+ // Define a flag with an In cohort filterlet flag = mock!(FeatureFlag,team_id: team.id,filters: FlagFilters {@@ -2893,7 +2759,7 @@ mod tests {properties: Some(vec![PropertyFilter {key: "id".to_string(),value: Some(json!(cohort_row.id)),- operator: Some(OperatorType::NotIn),+ operator: Some(OperatorType::In),prop_type: PropertyType::Cohort,group_type_index: None,negation: Some(false),@@ -2906,7 +2772,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,@@ -2931,11 +2797,12 @@ mod tests {let result = matcher.get_match(&flag, None, None, None, &None).unwrap();- assert!(result.matches);+ // The user does not match the cohort, and the flag is set to In, so it should evaluate to false+ assert!(!result.matches);}#[tokio::test]- async fn test_not_in_cohort_matching_user_in_cohort() {+ async fn test_static_cohort_matching_user_in_cohort() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -2944,50 +2811,49 @@ mod tests {));let team = context.insert_new_team(None).await.unwrap();- // Insert a cohort with a condition that matches the test user's properties- let cohort_row = context+ // Insert a static cohort+ let cohort = 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,+ Some("Static Cohort".to_string()),+ json!({}), // Static cohorts don't have property filters+ true, // is_static = true).await.unwrap();- // Insert a person with properties that match the cohort condition+ // Insert a person+ let distinct_id = "static_user".to_string();context.insert_person(team.id,- "test_user".to_string(),- Some(json!({"$browser_version": 126})),+ distinct_id.clone(),+ Some(json!({"email": "[email protected]"})),).await.unwrap();- // Define a flag with a NotIn cohort filter+ // Retrieve the person's ID+ let person_id = context+ .get_person_id_by_distinct_id(team.id, &distinct_id)+ .await+ .unwrap();++ // Associate the person with the static cohort+ context+ .add_person_to_cohort(cohort.id, person_id)+ .await+ .unwrap();++ // Define a flag with an 'In' cohort filterlet flag = mock!(FeatureFlag,team_id: team.id,filters: FlagFilters {groups: vec![FlagPropertyGroup {properties: Some(vec![PropertyFilter {key: "id".to_string(),- value: Some(json!(cohort_row.id)),- operator: Some(OperatorType::NotIn),+ value: Some(json!(cohort.id)),+ operator: Some(OperatorType::In),prop_type: PropertyType::Cohort,group_type_index: None,negation: Some(false),@@ -3000,7 +2866,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,@@ -3008,8 +2874,8 @@ mod tests {);let router = context.create_postgres_router();- let matcher = FeatureFlagMatcher::new(- "test_user".to_string(),+ let mut matcher = FeatureFlagMatcher::new(+ distinct_id.clone(),None, // device_idteam.id,router,@@ -3018,14 +2884,21 @@ mod tests {None,);+ matcher+ .prepare_flag_evaluation_state(&[&flag])+ .await+ .unwrap();+let result = matcher.get_match(&flag, None, None, None, &None).unwrap();- // The user matches the cohort, but the flag is set to NotIn, so it should evaluate to false- assert!(!result.matches);+ assert!(+ result.matches,+ "User should match the static cohort and flag"+ );}#[tokio::test]- async fn test_cohort_dependent_on_another_cohort() {+ async fn test_static_cohort_matching_user_not_in_cohort() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -3034,74 +2907,38 @@ mod tests {));let team = context.insert_new_team(None).await.unwrap();- // Insert a base cohort- let base_cohort_row = context+ // Insert a static cohort+ let cohort = 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,+ Some("Another Static Cohort".to_string()),+ json!({}), // Static cohorts don't have property filters+ true,).await.unwrap();- // Insert a dependent cohort that includes the base cohort- let dependent_cohort_row = context- .insert_cohort(+ // Insert a person+ let distinct_id = "non_static_user".to_string();+ context+ .insert_person(team.id,- None,- json!({- "properties": {- "type": "OR",- "values": [{- "type": "OR",- "values": [{- "key": "id",- "type": "cohort",- "value": base_cohort_row.id,- "negation": false,- "operator": "in"- }]- }]- }- }),- false,+ distinct_id.clone(),+ Some(json!({"email": "[email protected]"})),).await.unwrap();- // Insert a person with properties that match the base cohort condition- context- .insert_person(- team.id,- "test_user".to_string(),- Some(json!({"$browser_version": 126})),- )- .await- .unwrap();+ // Note: Do NOT associate the person with the static cohort- // Define a flag with a cohort filter that depends on another cohort+ // Define a flag with an 'In' cohort filterlet flag = mock!(FeatureFlag,team_id: team.id,filters: FlagFilters {groups: vec![FlagPropertyGroup {properties: Some(vec![PropertyFilter {key: "id".to_string(),- value: Some(json!(dependent_cohort_row.id)),+ value: Some(json!(cohort.id)),operator: Some(OperatorType::In),prop_type: PropertyType::Cohort,group_type_index: None,@@ -3115,7 +2952,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,@@ -3123,8 +2960,8 @@ mod tests {);let router = context.create_postgres_router();- let mut matcher = FeatureFlagMatcher::new(- "test_user".to_string(),+ let matcher = FeatureFlagMatcher::new(+ distinct_id.clone(),None, // device_idteam.id,router,@@ -3133,18 +2970,16 @@ mod tests {None,);- matcher- .prepare_flag_evaluation_state(&[&flag])- .await- .unwrap();-let result = matcher.get_match(&flag, None, None, None, &None).unwrap();- assert!(result.matches);+ assert!(+ !result.matches,+ "User should not match the static cohort and flag"+ );}#[tokio::test]- async fn test_in_cohort_matching_user_not_in_cohort() {+ async fn test_static_cohort_not_in_matching_user_not_in_cohort() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -3153,50 +2988,39 @@ mod tests {));let team = context.insert_new_team(None).await.unwrap();- // Insert a cohort with a condition that does not match the test user's properties- let cohort_row = context+ // Insert a static cohort+ let cohort = context.insert_cohort(team.id,- None,- json!({- "properties": {- "type": "OR",- "values": [{- "type": "OR",- "values": [{- "key": "$browser_version",- "type": "person",- "value": "130",- "negation": false,- "operator": "gt"- }]- }]- }- }),- false,+ Some("Static Cohort NotIn".to_string()),+ json!({}), // Static cohorts don't have property filters+ true, // is_static = true).await.unwrap();- // Insert a person with properties that do not match the cohort condition+ // Insert a person+ let distinct_id = "not_in_static_user".to_string();context.insert_person(team.id,- "test_user".to_string(),- Some(json!({"$browser_version": 125})),+ distinct_id.clone(),+ Some(json!({"email": "[email protected]"})),).await.unwrap();- // Define a flag with an In cohort filter+ // No association with the static cohort++ // Define a flag with a 'NotIn' cohort filterlet flag = mock!(FeatureFlag,team_id: team.id,filters: FlagFilters {groups: vec![FlagPropertyGroup {properties: Some(vec![PropertyFilter {key: "id".to_string(),- value: Some(json!(cohort_row.id)),- operator: Some(OperatorType::In),+ value: Some(json!(cohort.id)),+ operator: Some(OperatorType::NotIn),prop_type: PropertyType::Cohort,group_type_index: None,negation: Some(false),@@ -3209,7 +3033,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,@@ -3218,7 +3042,7 @@ mod tests {let router = context.create_postgres_router();let mut matcher = FeatureFlagMatcher::new(- "test_user".to_string(),+ distinct_id.clone(),None, // device_idteam.id,router,@@ -3234,12 +3058,14 @@ mod tests {let result = matcher.get_match(&flag, None, None, None, &None).unwrap();- // The user does not match the cohort, and the flag is set to In, so it should evaluate to false- assert!(!result.matches);+ assert!(+ result.matches,+ "User not in the static cohort should match the 'NotIn' flag"+ );}#[tokio::test]- async fn test_static_cohort_matching_user_in_cohort() {+ async fn test_static_cohort_not_in_matching_user_in_cohort() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -3252,7 +3078,7 @@ mod tests {let cohort = context.insert_cohort(team.id,- Some("Static Cohort".to_string()),+ Some("Static Cohort NotIn User In".to_string()),json!({}), // Static cohorts don't have property filterstrue, // is_static = true)@@ -3260,12 +3086,12 @@ mod tests {.unwrap();// Insert a person- let distinct_id = "static_user".to_string();+ let distinct_id = "in_not_in_static_user".to_string();context.insert_person(team.id,distinct_id.clone(),- Some(json!({"email": "[email protected]"})),+ Some(json!({"email": "[email protected]"})),).await.unwrap();@@ -3282,7 +3108,7 @@ mod tests {.await.unwrap();- // Define a flag with an 'In' cohort filter+ // Define a flag with a 'NotIn' cohort filterlet flag = mock!(FeatureFlag,team_id: team.id,filters: FlagFilters {@@ -3290,7 +3116,7 @@ mod tests {properties: Some(vec![PropertyFilter {key: "id".to_string(),value: Some(json!(cohort.id)),- operator: Some(OperatorType::In),+ operator: Some(OperatorType::NotIn),prop_type: PropertyType::Cohort,group_type_index: None,negation: Some(false),@@ -3303,7 +3129,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,@@ -3311,7 +3137,7 @@ mod tests {);let router = context.create_postgres_router();- let mut matcher = FeatureFlagMatcher::new(+ let matcher = FeatureFlagMatcher::new(distinct_id.clone(),None, // device_idteam.id,@@ -3321,21 +3147,16 @@ mod tests {None,);- matcher- .prepare_flag_evaluation_state(&[&flag])- .await- .unwrap();-let result = matcher.get_match(&flag, None, None, None, &None).unwrap();assert!(- result.matches,- "User should match the static cohort and flag"+ !result.matches,+ "User in the static cohort should not match the 'NotIn' flag");}#[tokio::test]- async fn test_static_cohort_matching_user_not_in_cohort() {+ async fn test_evaluate_feature_flags_with_experience_continuity() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -3343,43 +3164,37 @@ mod tests {None,));let team = context.insert_new_team(None).await.unwrap();+ let distinct_id = "user3".to_string();- // Insert a static cohort- let cohort = context- .insert_cohort(- team.id,- Some("Another Static Cohort".to_string()),- json!({}), // Static cohorts don't have property filters- true,- )- .await- .unwrap();-- // Insert a person- let distinct_id = "non_static_user".to_string();+ // Insert personcontext.insert_person(team.id,distinct_id.clone(),- Some(json!({"email": "[email protected]"})),+ Some(json!({"email": "[email protected]"})),).await.unwrap();- // Note: Do NOT associate the person with the static cohort+ let group_type_cache = Arc::new(GroupTypeCacheManager::new(+ context.non_persons_reader.clone(),+ None,+ None,+ ));- // Define a flag with an 'In' cohort filter+ // Create flag with experience continuitylet flag = mock!(FeatureFlag,team_id: team.id,+ key: "flag_continuity".mock_into(),filters: FlagFilters {groups: vec![FlagPropertyGroup {properties: Some(vec![PropertyFilter {- key: "id".to_string(),- value: Some(json!(cohort.id)),- operator: Some(OperatorType::In),- prop_type: PropertyType::Cohort,+ key: "email".to_string(),+ value: Some(json!("[email protected]")),+ operator: None,+ prop_type: PropertyType::Person,group_type_index: None,- negation: Some(false),+ negation: None,compiled_regex: None,}]),rollout_percentage: Some(100.0),@@ -3389,34 +3204,63 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,- }+ },+ ensure_experience_continuity: Some(true));+ // Set hash key overridelet router = context.create_postgres_router();- let matcher = FeatureFlagMatcher::new(+ set_feature_flag_hash_key_overrides(+ &router,+ team.id,+ vec![distinct_id.clone()],+ "hash_key_continuity".to_string(),+ )+ .await+ .unwrap();++ let flags = flag_list_with_metadata(vec![flag.clone()]);++ let router = context.create_postgres_router();+ let result = FeatureFlagMatcher::new(distinct_id.clone(),None, // device_idteam.id,router,cohort_cache.clone(),- empty_group_type_cache(),+ group_type_cache.clone(),None,- );-- let result = matcher.get_match(&flag, None, None, None, &None).unwrap();+ )+ .evaluate_all_feature_flags(+ flags,+ None,+ None,+ Some("hash_key_continuity".to_string()),+ Uuid::new_v4(),+ None,+ false,+ )+ .await+ .unwrap();+ let legacy_response = LegacyFlagsResponse::from_response(result);assert!(- !result.matches,- "User should not match the static cohort and flag"+ !legacy_response.errors_while_computing_flags,+ "No error should occur"+ );+ assert_eq!(+ legacy_response.feature_flags.get("flag_continuity"),+ Some(&FlagValue::Boolean(true)),+ "Flag should be evaluated as true with continuity");}#[tokio::test]- async fn test_static_cohort_not_in_matching_user_not_in_cohort() {+ async fn test_evaluate_feature_flags_with_continuity_missing_override() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -3424,43 +3268,36 @@ mod tests {None,));let team = context.insert_new_team(None).await.unwrap();+ let distinct_id = "user4".to_string();- // Insert a static cohort- let cohort = context- .insert_cohort(- team.id,- Some("Static Cohort NotIn".to_string()),- json!({}), // Static cohorts don't have property filters- true, // is_static = true- )- .await- .unwrap();-- // Insert a person- let distinct_id = "not_in_static_user".to_string();context.insert_person(team.id,distinct_id.clone(),- Some(json!({"email": "[email protected]"})),+ Some(json!({"email": "[email protected]"})),).await.unwrap();- // No association with the static cohort+ let group_type_cache = Arc::new(GroupTypeCacheManager::new(+ context.non_persons_reader.clone(),+ None,+ None,+ ));- // Define a flag with a 'NotIn' cohort filter+ // Create flag with experience continuitylet flag = mock!(FeatureFlag,team_id: team.id,+ key: "flag_continuity_missing".mock_into(),filters: FlagFilters {groups: vec![FlagPropertyGroup {properties: Some(vec![PropertyFilter {- key: "id".to_string(),- value: Some(json!(cohort.id)),- operator: Some(OperatorType::NotIn),- prop_type: PropertyType::Cohort,+ key: "email".to_string(),+ value: Some(json!("[email protected]")),+ operator: None,+ prop_type: PropertyType::Person,group_type_index: None,- negation: Some(false),+ negation: None,compiled_regex: None,}]),rollout_percentage: Some(100.0),@@ -3470,39 +3307,46 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,- }+ },+ ensure_experience_continuity: Some(true));+ let flags = flag_list_with_metadata(vec![flag.clone()]);+let router = context.create_postgres_router();- let mut matcher = FeatureFlagMatcher::new(+ let result = FeatureFlagMatcher::new(distinct_id.clone(),None, // device_idteam.id,router,cohort_cache.clone(),- empty_group_type_cache(),+ group_type_cache.clone(),None,- );-- matcher- .prepare_flag_evaluation_state(&[&flag])- .await- .unwrap();+ )+ .evaluate_all_feature_flags(flags, None, None, None, Uuid::new_v4(), None, false)+ .await+ .unwrap();- let result = matcher.get_match(&flag, None, None, None, &None).unwrap();+ assert!(result.flags.get("flag_continuity_missing").unwrap().enabled);+ let legacy_response = LegacyFlagsResponse::from_response(result);assert!(- result.matches,- "User not in the static cohort should match the 'NotIn' flag"+ !legacy_response.errors_while_computing_flags,+ "No error should occur");- }+ assert_eq!(+ legacy_response.feature_flags.get("flag_continuity_missing"),+ Some(&FlagValue::Boolean(true)),+ "Flag should be evaluated as true even without continuity override"+ );+ }#[tokio::test]- async fn test_static_cohort_not_in_matching_user_in_cohort() {+ async fn test_evaluate_all_feature_flags_mixed_continuity() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -3510,53 +3354,36 @@ mod tests {None,));let team = context.insert_new_team(None).await.unwrap();+ let distinct_id = "user5".to_string();- // Insert a static cohort- let cohort = context- .insert_cohort(- team.id,- Some("Static Cohort NotIn User In".to_string()),- json!({}), // Static cohorts don't have property filters- true, // is_static = true- )- .await- .unwrap();-- // Insert a person- let distinct_id = "in_not_in_static_user".to_string();context.insert_person(team.id,distinct_id.clone(),- Some(json!({"email": "[email protected]"})),+ Some(json!({"email": "[email protected]"})),).await.unwrap();- // Retrieve the person's ID- let person_id = context- .get_person_id_by_distinct_id(team.id, &distinct_id)- .await- .unwrap();-- // Associate the person with the static cohort- context- .add_person_to_cohort(cohort.id, person_id)- .await- .unwrap();+ let group_type_cache = Arc::new(GroupTypeCacheManager::new(+ context.non_persons_reader.clone(),+ None,+ None,+ ));- // Define a flag with a 'NotIn' cohort filter- let flag = mock!(FeatureFlag,+ // Create flag with continuity+ let flag_continuity = mock!(FeatureFlag,team_id: team.id,+ key: "flag_continuity_mix".mock_into(),filters: FlagFilters {groups: vec![FlagPropertyGroup {properties: Some(vec![PropertyFilter {- key: "id".to_string(),- value: Some(json!(cohort.id)),- operator: Some(OperatorType::NotIn),- prop_type: PropertyType::Cohort,+ key: "email".to_string(),+ value: Some(json!("[email protected]")),+ operator: None,+ prop_type: PropertyType::Person,group_type_index: None,- negation: Some(false),+ negation: None,compiled_regex: None,}]),rollout_percentage: Some(100.0),@@ -3566,69 +3393,25 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,- }- );-- let router = context.create_postgres_router();- let matcher = FeatureFlagMatcher::new(- distinct_id.clone(),- None, // device_id- team.id,- router,- cohort_cache.clone(),- empty_group_type_cache(),- None,- );-- let result = matcher.get_match(&flag, None, None, None, &None).unwrap();-- assert!(- !result.matches,- "User in the static cohort should not match the 'NotIn' flag"+ },+ ensure_experience_continuity: Some(true));- }-- #[tokio::test]- async fn test_evaluate_feature_flags_with_experience_continuity() {- 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 distinct_id = "user3".to_string();-- // Insert person- context- .insert_person(- team.id,- distinct_id.clone(),- Some(json!({"email": "[email protected]"})),- )- .await- .unwrap();-- let group_type_cache = Arc::new(GroupTypeCacheManager::new(- context.non_persons_reader.clone(),- None,- None,- ));- // Create flag with experience continuity- let flag = mock!(FeatureFlag,+ // Create flag without continuity+ let flag_no_continuity = mock!(FeatureFlag,+ id: 2,team_id: team.id,- key: "flag_continuity".mock_into(),+ key: "flag_no_continuity_mix".mock_into(),filters: FlagFilters {groups: vec![FlagPropertyGroup {properties: Some(vec![PropertyFilter {- key: "email".to_string(),- value: Some(json!("[email protected]")),- operator: None,+ key: "age".to_string(),+ value: Some(json!(30)),+ operator: Some(OperatorType::Gt),prop_type: PropertyType::Person,group_type_index: None,negation: None,@@ -3641,26 +3424,26 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,- },- ensure_experience_continuity: Some(true)+ });- // Set hash key override- let router = context.create_postgres_router();+ // Set hash key override for the continuity flag+ let router2 = context.create_postgres_router();set_feature_flag_hash_key_overrides(- &router,+ &router2,team.id,vec![distinct_id.clone()],- "hash_key_continuity".to_string(),+ "hash_key_mixed".to_string(),).await.unwrap();- let flags = flag_list_with_metadata(vec![flag.clone()]);+ let flags =+ flag_list_with_metadata(vec![flag_continuity.clone(), flag_no_continuity.clone()]);let router = context.create_postgres_router();let result = FeatureFlagMatcher::new(@@ -3674,9 +3457,9 @@ mod tests {).evaluate_all_feature_flags(flags,+ Some(HashMap::from([("age".to_string(), json!(35))])),None,- None,- Some("hash_key_continuity".to_string()),+ Some("hash_key_mixed".to_string()),Uuid::new_v4(),None,false,@@ -3690,14 +3473,19 @@ mod tests {"No error should occur");assert_eq!(- legacy_response.feature_flags.get("flag_continuity"),+ legacy_response.feature_flags.get("flag_continuity_mix"),Some(&FlagValue::Boolean(true)),- "Flag should be evaluated as true with continuity"+ "Continuity flag should be evaluated as true"+ );+ assert_eq!(+ legacy_response.feature_flags.get("flag_no_continuity_mix"),+ Some(&FlagValue::Boolean(true)),+ "Non-continuity flag should be evaluated based on properties");}#[tokio::test]- async fn test_evaluate_feature_flags_with_continuity_missing_override() {+ async fn test_variant_override_in_condition() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -3705,32 +3493,27 @@ mod tests {None,));let team = context.insert_new_team(None).await.unwrap();- let distinct_id = "user4".to_string();+ let distinct_id = "test_user".to_string();+ // Insert a person with properties that will match our conditioncontext.insert_person(team.id,distinct_id.clone(),- Some(json!({"email": "[email protected]"})),+ Some(json!({"email": "[email protected]"})),).await.unwrap();- let group_type_cache = Arc::new(GroupTypeCacheManager::new(- context.non_persons_reader.clone(),- None,- None,- ));-- // Create flag with experience continuity+ // Create a flag with multiple variants and a condition with a variant overridelet flag = mock!(FeatureFlag,team_id: team.id,- key: "flag_continuity_missing".mock_into(),+ key: "test_flag".mock_into(),filters: FlagFilters {groups: vec![FlagPropertyGroup {properties: Some(vec![PropertyFilter {key: "email".to_string(),- value: Some(json!("[email protected]")),+ value: Some(json!("[email protected]")),operator: None,prop_type: PropertyType::Person,group_type_index: None,@@ -3738,85 +3521,69 @@ mod tests {compiled_regex: None,}]),rollout_percentage: Some(100.0),- variant: None,+ variant: Some("control".to_string()), // Override to always show "control" variant..Default::default()}],- multivariate: None,+ multivariate: Some(MultivariateFlagOptions {+ variants: vec![+ MultivariateFlagVariant {+ name: Some("Control".to_string()),+ key: "control".to_string(),+ rollout_percentage: 25.0,+ },+ MultivariateFlagVariant {+ name: Some("Test".to_string()),+ key: "test".to_string(),+ rollout_percentage: 25.0,+ },+ MultivariateFlagVariant {+ name: Some("Test2".to_string()),+ key: "test2".to_string(),+ rollout_percentage: 50.0,+ },+ ],+ }),aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,- },- ensure_experience_continuity: Some(true)+ });- let flags = flag_list_with_metadata(vec![flag.clone()]);-let router = context.create_postgres_router();- let result = FeatureFlagMatcher::new(+ let mut matcher = FeatureFlagMatcher::new(distinct_id.clone(),None, // device_idteam.id,router,cohort_cache.clone(),- group_type_cache.clone(),+ empty_group_type_cache(),None,- )- .evaluate_all_feature_flags(flags, None, None, None, Uuid::new_v4(), None, false)- .await- .unwrap();-- assert!(result.flags.get("flag_continuity_missing").unwrap().enabled);-- let legacy_response = LegacyFlagsResponse::from_response(result);- assert!(- !legacy_response.errors_while_computing_flags,- "No error should occur");- assert_eq!(- legacy_response.feature_flags.get("flag_continuity_missing"),- Some(&FlagValue::Boolean(true)),- "Flag should be evaluated as true even without continuity override"- );- }-- #[tokio::test]- async fn test_evaluate_all_feature_flags_mixed_continuity() {- 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 distinct_id = "user5".to_string();- context- .insert_person(- team.id,- distinct_id.clone(),- Some(json!({"email": "[email protected]"})),- )+ matcher+ .prepare_flag_evaluation_state(&[&flag]).await.unwrap();- let group_type_cache = Arc::new(GroupTypeCacheManager::new(- context.non_persons_reader.clone(),- None,- None,- ));+ let result = matcher.get_match(&flag, None, None, None, &None).unwrap();- // Create flag with continuity- let flag_continuity = mock!(FeatureFlag,+ // The condition matches and has a variant override, so it should return "control"+ // regardless of what the hash-based variant computation would return+ assert!(result.matches);+ assert_eq!(result.variant, Some("control".to_string()));++ // Now test with an invalid variant override+ let flag_invalid_override = mock!(FeatureFlag,team_id: team.id,- key: "flag_continuity_mix".mock_into(),+ key: "test_flag_invalid".mock_into(),filters: FlagFilters {groups: vec![FlagPropertyGroup {properties: Some(vec![PropertyFilter {key: "email".to_string(),- value: Some(json!("[email protected]")),+ value: Some(json!("[email protected]")),operator: None,prop_type: PropertyType::Person,group_type_index: None,@@ -3824,211 +3591,7 @@ mod tests {compiled_regex: None,}]),rollout_percentage: Some(100.0),- variant: None,- ..Default::default()- }],- multivariate: None,- aggregation_group_type_index: None,- payloads: None,- super_groups: None,- feature_enrollment: None,-- holdout: None,- },- ensure_experience_continuity: Some(true)- );-- // Create flag without continuity- let flag_no_continuity = mock!(FeatureFlag,- id: 2,- team_id: team.id,- key: "flag_no_continuity_mix".mock_into(),- filters: FlagFilters {- groups: vec![FlagPropertyGroup {- properties: Some(vec![PropertyFilter {- key: "age".to_string(),- value: Some(json!(30)),- operator: Some(OperatorType::Gt),- prop_type: PropertyType::Person,- group_type_index: None,- negation: None,- compiled_regex: None,- }]),- rollout_percentage: Some(100.0),- variant: None,- ..Default::default()- }],- multivariate: None,- aggregation_group_type_index: None,- payloads: None,- super_groups: None,- feature_enrollment: None,-- holdout: None,- }- );-- // Set hash key override for the continuity flag- let router2 = context.create_postgres_router();- set_feature_flag_hash_key_overrides(- &router2,- team.id,- vec![distinct_id.clone()],- "hash_key_mixed".to_string(),- )- .await- .unwrap();-- let flags =- flag_list_with_metadata(vec![flag_continuity.clone(), flag_no_continuity.clone()]);-- let router = context.create_postgres_router();- let result = FeatureFlagMatcher::new(- distinct_id.clone(),- None, // device_id- team.id,- router,- cohort_cache.clone(),- group_type_cache.clone(),- None,- )- .evaluate_all_feature_flags(- flags,- Some(HashMap::from([("age".to_string(), json!(35))])),- None,- Some("hash_key_mixed".to_string()),- Uuid::new_v4(),- None,- false,- )- .await- .unwrap();-- let legacy_response = LegacyFlagsResponse::from_response(result);- assert!(- !legacy_response.errors_while_computing_flags,- "No error should occur"- );- assert_eq!(- legacy_response.feature_flags.get("flag_continuity_mix"),- Some(&FlagValue::Boolean(true)),- "Continuity flag should be evaluated as true"- );- assert_eq!(- legacy_response.feature_flags.get("flag_no_continuity_mix"),- Some(&FlagValue::Boolean(true)),- "Non-continuity flag should be evaluated based on properties"- );- }-- #[tokio::test]- async fn test_variant_override_in_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 distinct_id = "test_user".to_string();-- // Insert a person with properties that will match our condition- context- .insert_person(- team.id,- distinct_id.clone(),- Some(json!({"email": "[email protected]"})),- )- .await- .unwrap();-- // Create a flag with multiple variants and a condition with a variant override- let flag = mock!(FeatureFlag,- team_id: team.id,- key: "test_flag".mock_into(),- filters: FlagFilters {- groups: vec![FlagPropertyGroup {- properties: Some(vec![PropertyFilter {- key: "email".to_string(),- value: Some(json!("[email protected]")),- operator: None,- prop_type: PropertyType::Person,- group_type_index: None,- negation: None,- compiled_regex: None,- }]),- rollout_percentage: Some(100.0),- variant: Some("control".to_string()), // Override to always show "control" variant- ..Default::default()- }],- multivariate: Some(MultivariateFlagOptions {- variants: vec![- MultivariateFlagVariant {- name: Some("Control".to_string()),- key: "control".to_string(),- rollout_percentage: 25.0,- },- MultivariateFlagVariant {- name: Some("Test".to_string()),- key: "test".to_string(),- rollout_percentage: 25.0,- },- MultivariateFlagVariant {- name: Some("Test2".to_string()),- key: "test2".to_string(),- rollout_percentage: 50.0,- },- ],- }),- aggregation_group_type_index: None,- payloads: None,- super_groups: None,- feature_enrollment: None,-- holdout: None,- }- );-- let router = context.create_postgres_router();- let mut matcher = FeatureFlagMatcher::new(- distinct_id.clone(),- None, // device_id- team.id,- router,- cohort_cache.clone(),- empty_group_type_cache(),- None,- );-- matcher- .prepare_flag_evaluation_state(&[&flag])- .await- .unwrap();-- let result = matcher.get_match(&flag, None, None, None, &None).unwrap();-- // The condition matches and has a variant override, so it should return "control"- // regardless of what the hash-based variant computation would return- assert!(result.matches);- assert_eq!(result.variant, Some("control".to_string()));-- // Now test with an invalid variant override- let flag_invalid_override = mock!(FeatureFlag,- team_id: team.id,- key: "test_flag_invalid".mock_into(),- filters: FlagFilters {- groups: vec![FlagPropertyGroup {- properties: Some(vec![PropertyFilter {- key: "email".to_string(),- value: Some(json!("[email protected]")),- operator: None,- prop_type: PropertyType::Person,- group_type_index: None,- negation: None,- compiled_regex: None,- }]),- rollout_percentage: Some(100.0),- variant: Some("nonexistent_variant".to_string()), // Override with invalid variant+ variant: Some("nonexistent_variant".to_string()), // Override with invalid variant..Default::default()}],multivariate: Some(MultivariateFlagOptions {@@ -4047,7 +3610,7 @@ mod tests {}),aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,@@ -4145,7 +3708,7 @@ mod tests {multivariate: Some(multivariate_json.clone()),aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,});@@ -4177,7 +3740,7 @@ mod tests {multivariate: Some(multivariate_json.clone()),aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,});@@ -4209,7 +3772,7 @@ mod tests {multivariate: Some(multivariate_json),aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,});@@ -4376,7 +3939,7 @@ mod tests {multivariate: Some(multivariate_json.clone()),aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,});@@ -4493,7 +4056,7 @@ mod tests {multivariate: Some(multivariate_json),aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,});@@ -4578,7 +4141,7 @@ mod tests {}),aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,});@@ -4678,7 +4241,7 @@ mod tests {}),aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,});@@ -4752,7 +4315,7 @@ mod tests {}),aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,@@ -4899,7 +4462,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,@@ -4960,7 +4523,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,@@ -5022,7 +4585,7 @@ mod tests {multivariate: None,aggregation_group_type_index: Some(1),payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,@@ -5141,207 +4704,7 @@ mod tests {}#[tokio::test]- async fn test_complex_super_condition_matching() {- 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,- team_id: team.id,- key: "complex_flag".mock_into(),- filters: FlagFilters {- groups: vec![- FlagPropertyGroup {- properties: Some(vec![PropertyFilter {- key: "email".to_string(),- value: Some(json!("@storytell.ai")),- operator: Some(OperatorType::Icontains),- prop_type: PropertyType::Person,- group_type_index: None,- negation: None,- compiled_regex: None,- }]),- rollout_percentage: Some(100.0),- variant: None,- ..Default::default()- },- FlagPropertyGroup {- properties: Some(vec![PropertyFilter {- key: "email".to_string(),- value: Some(json!([- "[email protected]",- "[email protected]",- "[email protected]",- ])),- operator: Some(OperatorType::Exact),- prop_type: PropertyType::Person,- group_type_index: None,- negation: None,- compiled_regex: None,- }]),- rollout_percentage: Some(100.0),- variant: None,- ..Default::default()- },- FlagPropertyGroup {- properties: Some(vec![PropertyFilter {- key: "email".to_string(),- value: Some(json!("@posthog.com")),- operator: Some(OperatorType::Icontains),- prop_type: PropertyType::Person,- group_type_index: None,- negation: None,- compiled_regex: None,- }]),- rollout_percentage: Some(100.0),- variant: None,- ..Default::default()- },- ],- multivariate: None,- aggregation_group_type_index: None,- payloads: None,- super_groups: Some(vec![FlagPropertyGroup {- properties: Some(vec![PropertyFilter {- key: "$feature_enrollment/my-flag".to_string(),- value: Some(json!(["true"])),- operator: Some(OperatorType::Exact),- prop_type: PropertyType::Person,- group_type_index: None,- negation: None,- compiled_regex: None,- }]),- rollout_percentage: Some(100.0),- variant: None,- ..Default::default()- }]),-- feature_enrollment: None,-- holdout: None,- }- );-- // Test case 1: User with super condition property set to true- context- .insert_person(- team.id,- "super_user".to_string(),- Some(json!({- "email": "[email protected]",- "$feature_enrollment/my-flag": true- })),- )- .await- .unwrap();-- // Test case 2: User with matching email but no super condition- context- .insert_person(- team.id,- "posthog_user".to_string(),- Some(json!({- "email": "[email protected]",- "$feature_enrollment/my-flag": false- })),- )- .await- .unwrap();-- // Test case 3: User with neither super condition nor matching email- context- .insert_person(- team.id,- "regular_user".to_string(),- Some(json!({- "email": "[email protected]"- })),- )- .await- .unwrap();-- // Test super condition user- let router = context.create_postgres_router();- let mut matcher = FeatureFlagMatcher::new(- "super_user".to_string(),- None, // device_id- team.id,- router,- cohort_cache.clone(),- empty_group_type_cache(),- None,- );-- matcher- .prepare_flag_evaluation_state(&[&flag])- .await- .unwrap();-- let result = matcher.get_match(&flag, None, None, None, &None).unwrap();- assert!(result.matches, "Super condition user should match");- assert_eq!(- result.reason,- FeatureFlagMatchReason::SuperConditionValue,- "Match reason should be SuperConditionValue"- );-- // Test PostHog user- let router2 = context.create_postgres_router();- let mut matcher = FeatureFlagMatcher::new(- "posthog_user".to_string(),- None, // device_id- team.id,- router2,- cohort_cache.clone(),- empty_group_type_cache(),- None,- );-- matcher- .prepare_flag_evaluation_state(&[&flag])- .await- .unwrap();-- let result = matcher.get_match(&flag, None, None, None, &None).unwrap();- assert!(!result.matches, "PostHog user should not match");- assert_eq!(- result.reason,- FeatureFlagMatchReason::SuperConditionValue,- "Match reason should be SuperConditionValue"- );-- // Test regular user- let router3 = context.create_postgres_router();- let mut matcher = FeatureFlagMatcher::new(- "regular_user".to_string(),- None, // device_id- team.id,- router3,- cohort_cache.clone(),- empty_group_type_cache(),- None,- );-- matcher- .prepare_flag_evaluation_state(&[&flag])- .await- .unwrap();-- let result = matcher.get_match(&flag, None, None, None, &None).unwrap();- assert!(!result.matches, "Regular user should not match");- assert_eq!(- result.reason,- FeatureFlagMatchReason::NoConditionMatch,- "Match reason should be NoConditionMatch"- );- }- #[tokio::test]- async fn test_filters_with_distinct_id_exact() {+ async fn test_filters_with_distinct_id_exact() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -5715,7 +5078,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,@@ -5971,7 +5334,7 @@ mod tests {multivariate: None,aggregation_group_type_index: Some(1), // This is a group-based flagpayloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,@@ -6260,7 +5623,7 @@ mod tests {}),aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,@@ -7025,269 +6388,10 @@ mod tests {);}- // ======== Integration tests for experience continuity optimization ========-- #[tokio::test]- async fn test_optimization_enabled_100_percent_rollout_evaluates_correctly() {- 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 distinct_id = "optimization_user_1".to_string();-- context- .insert_person(- team.id,- distinct_id.clone(),- Some(json!({"email": "[email protected]"})),- )- .await- .unwrap();-- // Create a flag with 100% rollout and experience continuity enabled- // This flag should NOT need a hash key override lookup- let flag = mock!(FeatureFlag,- team_id: team.id,- key: "opt_100_percent".mock_into(),- filters: mock!(FlagFilters,- groups: vec![mock!(FlagPropertyGroup, properties: None)]- ),- ensure_experience_continuity: Some(true)- );-- let flags = flag_list_with_metadata(vec![flag.clone()]);-- // Reset counter before the test- reset_hash_key_override_lookup_count();-- let router = context.create_postgres_router();- let result = FeatureFlagMatcher::new(- distinct_id.clone(),- None,- team.id,- router,- cohort_cache.clone(),- empty_group_type_cache(),- None,- )- .evaluate_all_feature_flags(- flags,- None,- None,- Some("anon_distinct_id".to_string()),- Uuid::new_v4(),- None,- true, // optimization enabled- )- .await- .unwrap();-- // Verify the optimization actually skipped the hash key override lookup- let lookup_count = get_hash_key_override_lookup_count();- assert_eq!(- lookup_count, 0,- "100% rollout flag should skip hash key override lookup, but got {lookup_count} lookups"- );-- // Flag should evaluate correctly even with optimization enabled- assert!(- result.flags.get("opt_100_percent").unwrap().enabled,- "100% rollout flag should be enabled with optimization"- );- assert!(- !result.errors_while_computing_flags,- "No errors should occur"- );- }-- #[tokio::test]- async fn test_optimization_enabled_partial_rollout_evaluates_correctly() {- 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 distinct_id = "optimization_user_2".to_string();-- context- .insert_person(- team.id,- distinct_id.clone(),- Some(json!({"email": "[email protected]"})),- )- .await- .unwrap();-- // Create a flag with 50% rollout and experience continuity enabled- // This flag SHOULD need a hash key override lookup- let flag = mock!(FeatureFlag,- id: 2,- team_id: team.id,- key: "opt_partial_rollout".mock_into(),- filters: mock!(FlagFilters,- groups: vec![mock!(FlagPropertyGroup, properties: None, rollout_percentage: Some(50.0))]- ),- ensure_experience_continuity: Some(true)- );-- let flags = flag_list_with_metadata(vec![flag.clone()]);-- // Reset counter before the test- reset_hash_key_override_lookup_count();-- let router = context.create_postgres_router();- let result = FeatureFlagMatcher::new(- distinct_id.clone(),- None,- team.id,- router,- cohort_cache.clone(),- empty_group_type_cache(),- None,- )- .evaluate_all_feature_flags(- flags,- None,- None,- Some("anon_distinct_id".to_string()),- Uuid::new_v4(),- None,- true, // optimization enabled- )- .await- .unwrap();-- // Verify the lookup DID happen for partial rollout (optimization doesn't skip it)- let lookup_count = get_hash_key_override_lookup_count();- assert_eq!(- lookup_count, 1,- "Partial rollout flag should perform hash key override lookup, but got {lookup_count} lookups"- );-- // Flag should evaluate (result depends on hash)- assert!(- result.flags.contains_key("opt_partial_rollout"),- "Partial rollout flag should be evaluated with optimization"- );- assert!(- !result.errors_while_computing_flags,- "No errors should occur"- );- }-- #[tokio::test]- async fn test_optimization_enabled_multivariate_evaluates_correctly() {- 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 distinct_id = "optimization_user_3".to_string();-- context- .insert_person(- team.id,- distinct_id.clone(),- Some(json!({"email": "[email protected]"})),- )- .await- .unwrap();-- // Create a multivariate flag with experience continuity- // This flag SHOULD need a hash key override lookup- let flag = mock!(FeatureFlag,- id: 3,- team_id: team.id,- key: "opt_multivariate".mock_into(),- filters: FlagFilters {- groups: vec![FlagPropertyGroup {- properties: None,- rollout_percentage: Some(100.0),- variant: None,- ..Default::default()- }],- multivariate: Some(MultivariateFlagOptions {- variants: vec![- MultivariateFlagVariant {- key: "control".to_string(),- name: Some("Control".to_string()),- rollout_percentage: 50.0,- },- MultivariateFlagVariant {- key: "test".to_string(),- name: Some("Test".to_string()),- rollout_percentage: 50.0,- },- ],- }),- aggregation_group_type_index: None,- payloads: None,- super_groups: None,- feature_enrollment: None,- holdout: None,- },- ensure_experience_continuity: Some(true)- );-- let flags = flag_list_with_metadata(vec![flag.clone()]);-- // Reset counter before the test- reset_hash_key_override_lookup_count();-- let router = context.create_postgres_router();- let result = FeatureFlagMatcher::new(- distinct_id.clone(),- None,- team.id,- router,- cohort_cache.clone(),- empty_group_type_cache(),- None,- )- .evaluate_all_feature_flags(- flags,- None,- None,- Some("anon_distinct_id".to_string()),- Uuid::new_v4(),- None,- true, // optimization enabled- )- .await- .unwrap();-- // Verify the lookup DID happen for multivariate (optimization doesn't skip it)- let lookup_count = get_hash_key_override_lookup_count();- assert_eq!(- lookup_count, 1,- "Multivariate flag should perform hash key override lookup, but got {lookup_count} lookups"- );-- // Flag should evaluate with a variant- let flag_result = result.flags.get("opt_multivariate").unwrap();- assert!(- flag_result.enabled,- "Multivariate flag should be enabled with optimization"- );- assert!(- flag_result.variant.is_some(),- "Multivariate flag should have a variant assigned"- );- assert!(- !result.errors_while_computing_flags,- "No errors should occur"- );- }-+ // ======== Integration tests for experience continuity optimization ========+#[tokio::test]- async fn test_optimization_enabled_multivariate_with_100_percent_variant() {+ async fn test_optimization_enabled_100_percent_rollout_evaluates_correctly() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -7295,50 +6399,25 @@ mod tests {None,));let team = context.insert_new_team(None).await.unwrap();- let distinct_id = "optimization_user_4".to_string();+ let distinct_id = "optimization_user_1".to_string();context.insert_person(team.id,distinct_id.clone(),- Some(json!({"email": "[email protected]"})),+ Some(json!({"email": "[email protected]"})),).await.unwrap();- // Create a multivariate flag where one variant is at 100%- // This flag should NOT need a hash key override lookup (optimization applies)+ // Create a flag with 100% rollout and experience continuity enabled+ // This flag should NOT need a hash key override lookuplet flag = mock!(FeatureFlag,- id: 4,team_id: team.id,- key: "opt_multivariate_100".mock_into(),- filters: FlagFilters {- groups: vec![FlagPropertyGroup {- properties: None,- rollout_percentage: Some(100.0),- variant: None,- ..Default::default()- }],- multivariate: Some(MultivariateFlagOptions {- variants: vec![- MultivariateFlagVariant {- key: "control".to_string(),- name: Some("Control".to_string()),- rollout_percentage: 100.0, // 100% variant- },- MultivariateFlagVariant {- key: "test".to_string(),- name: Some("Test".to_string()),- rollout_percentage: 0.0,- },- ],- }),- aggregation_group_type_index: None,- payloads: None,- super_groups: None,- feature_enrollment: None,- holdout: None,- },+ key: "opt_100_percent".mock_into(),+ filters: mock!(FlagFilters,+ groups: vec![mock!(FlagPropertyGroup, properties: None)]+ ),ensure_experience_continuity: Some(true));@@ -7369,23 +6448,17 @@ mod tests {.await.unwrap();- // Verify the optimization skipped the lookup (100% variant = no hashing needed)+ // Verify the optimization actually skipped the hash key override lookuplet lookup_count = get_hash_key_override_lookup_count();assert_eq!(lookup_count, 0,- "Multivariate flag with 100% variant should skip hash key override lookup, but got {lookup_count} lookups"+ "100% rollout flag should skip hash key override lookup, but got {lookup_count} lookups");- // Flag should evaluate with the 100% variant- let flag_result = result.flags.get("opt_multivariate_100").unwrap();+ // Flag should evaluate correctly even with optimization enabledassert!(- flag_result.enabled,- "Flag with 100% variant should be enabled"- );- assert_eq!(- flag_result.variant,- Some("control".to_string()),- "Should get the 100% variant"+ result.flags.get("opt_100_percent").unwrap().enabled,+ "100% rollout flag should be enabled with optimization");assert!(!result.errors_while_computing_flags,@@ -7394,7 +6467,7 @@ mod tests {}#[tokio::test]- async fn test_optimization_disabled_legacy_behavior() {+ async fn test_optimization_enabled_partial_rollout_evaluates_correctly() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -7402,30 +6475,34 @@ mod tests {None,));let team = context.insert_new_team(None).await.unwrap();- let distinct_id = "legacy_user".to_string();+ let distinct_id = "optimization_user_2".to_string();context.insert_person(team.id,distinct_id.clone(),- Some(json!({"email": "[email protected]"})),+ Some(json!({"email": "[email protected]"})),).await.unwrap();- // Create a flag with 100% rollout and experience continuity+ // Create a flag with 50% rollout and experience continuity enabled+ // This flag SHOULD need a hash key override lookuplet flag = mock!(FeatureFlag,- id: 5,+ id: 2,team_id: team.id,- key: "legacy_flag".mock_into(),+ key: "opt_partial_rollout".mock_into(),filters: mock!(FlagFilters,- groups: vec![mock!(FlagPropertyGroup, properties: None)]+ groups: vec![mock!(FlagPropertyGroup, properties: None, rollout_percentage: Some(50.0))]),ensure_experience_continuity: Some(true));let flags = flag_list_with_metadata(vec![flag.clone()]);+ // Reset counter before the test+ reset_hash_key_override_lookup_count();+let router = context.create_postgres_router();let result = FeatureFlagMatcher::new(distinct_id.clone(),@@ -7443,15 +6520,22 @@ mod tests {Some("anon_distinct_id".to_string()),Uuid::new_v4(),None,- false, // optimization disabled (legacy behavior)+ true, // optimization enabled).await.unwrap();- // Flag should still evaluate correctly in legacy mode+ // Verify the lookup DID happen for partial rollout (optimization doesn't skip it)+ let lookup_count = get_hash_key_override_lookup_count();+ assert_eq!(+ lookup_count, 1,+ "Partial rollout flag should perform hash key override lookup, but got {lookup_count} lookups"+ );++ // Flag should evaluate (result depends on hash)assert!(- result.flags.get("legacy_flag").unwrap().enabled,- "Flag should be enabled in legacy mode"+ result.flags.contains_key("opt_partial_rollout"),+ "Partial rollout flag should be evaluated with optimization");assert!(!result.errors_while_computing_flags,@@ -7460,7 +6544,7 @@ mod tests {}#[tokio::test]- async fn test_optimization_mixed_flags() {+ async fn test_optimization_enabled_multivariate_evaluates_correctly() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -7468,21 +6552,23 @@ mod tests {None,));let team = context.insert_new_team(None).await.unwrap();- let distinct_id = "mixed_user".to_string();+ let distinct_id = "optimization_user_3".to_string();context.insert_person(team.id,distinct_id.clone(),- Some(json!({"email": "[email protected]"})),+ Some(json!({"email": "[email protected]"})),).await.unwrap();- // Flag 1: 100% rollout with continuity (can be optimized)- let flag_optimizable = mock!(FeatureFlag,+ // Create a multivariate flag with experience continuity+ // This flag SHOULD need a hash key override lookup+ let flag = mock!(FeatureFlag,+ id: 3,team_id: team.id,- key: "flag_optimizable".mock_into(),+ key: "opt_multivariate".mock_into(),filters: FlagFilters {groups: vec![FlagPropertyGroup {properties: None,@@ -7490,67 +6576,30 @@ mod tests {variant: None,..Default::default()}],- multivariate: None,+ multivariate: Some(MultivariateFlagOptions {+ variants: vec![+ MultivariateFlagVariant {+ key: "control".to_string(),+ name: Some("Control".to_string()),+ rollout_percentage: 50.0,+ },+ MultivariateFlagVariant {+ key: "test".to_string(),+ name: Some("Test".to_string()),+ rollout_percentage: 50.0,+ },+ ],+ }),aggregation_group_type_index: None,payloads: None,- super_groups: None,- feature_enrollment: None,-- holdout: None,- },- ensure_experience_continuity: Some(true)- );- // Flag 2: 50% rollout with continuity (needs lookup)- let flag_needs_lookup = mock!(FeatureFlag,- id: 2,- team_id: team.id,- key: "flag_needs_lookup".mock_into(),- filters: FlagFilters {- groups: vec![FlagPropertyGroup {- properties: None,- rollout_percentage: Some(50.0),- variant: None,- ..Default::default()- }],- multivariate: None,- aggregation_group_type_index: None,- payloads: None,- super_groups: None,feature_enrollment: None,-holdout: None,},ensure_experience_continuity: Some(true));- // Flag 3: 100% rollout without continuity (no lookup needed)- let flag_no_continuity = mock!(FeatureFlag,- id: 3,- team_id: team.id,- key: "flag_no_continuity".mock_into(),- filters: FlagFilters {- groups: vec![FlagPropertyGroup {- properties: None,- rollout_percentage: Some(100.0),- variant: None,- ..Default::default()- }],- multivariate: None,- aggregation_group_type_index: None,- payloads: None,- super_groups: None,- feature_enrollment: None,-- holdout: None,- }- );-- let flags = flag_list_with_metadata(vec![- flag_optimizable.clone(),- flag_needs_lookup.clone(),- flag_no_continuity.clone(),- ]);+ let flags = flag_list_with_metadata(vec![flag.clone()]);// Reset counter before the testreset_hash_key_override_lookup_count();@@ -7577,50 +6626,31 @@ mod tests {.await.unwrap();- // Verify the lookup DID happen because flag_needs_lookup requires it.- // Even though flag_optimizable could be optimized, the presence of- // flag_needs_lookup forces a lookup for all flags with experience continuity.+ // Verify the lookup DID happen for multivariate (optimization doesn't skip it)let lookup_count = get_hash_key_override_lookup_count();assert_eq!(lookup_count, 1,- "Mixed flags should perform lookup when at least one flag needs it, but got {lookup_count} lookups"- );-- // All flags should be evaluated- assert!(- result.flags.contains_key("flag_optimizable"),- "Optimizable flag should be evaluated"- );- assert!(- result.flags.contains_key("flag_needs_lookup"),- "Needs-lookup flag should be evaluated"- );- assert!(- result.flags.contains_key("flag_no_continuity"),- "No-continuity flag should be evaluated"+ "Multivariate flag should perform hash key override lookup, but got {lookup_count} lookups");- // 100% rollout flags should be enabled+ // Flag should evaluate with a variant+ let flag_result = result.flags.get("opt_multivariate").unwrap();assert!(- result.flags.get("flag_optimizable").unwrap().enabled,- "100% rollout flag should be enabled"+ flag_result.enabled,+ "Multivariate flag should be enabled with optimization");assert!(- result.flags.get("flag_no_continuity").unwrap().enabled,- "100% rollout no-continuity flag should be enabled"+ flag_result.variant.is_some(),+ "Multivariate flag should have a variant assigned");-assert!(!result.errors_while_computing_flags,"No errors should occur");}- /// Tests that flag_keys filtering is applied before computing optimization stats.- /// When only optimizable flags are requested via flag_keys, the lookup should be skipped- /// even if other flags (not being evaluated) would require it.#[tokio::test]- async fn test_optimization_respects_flag_keys_filter() {+ async fn test_optimization_enabled_multivariate_with_100_percent_variant() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -7628,21 +6658,23 @@ mod tests {None,));let team = context.insert_new_team(None).await.unwrap();- let distinct_id = "flag_keys_user".to_string();+ let distinct_id = "optimization_user_4".to_string();context.insert_person(team.id,distinct_id.clone(),- Some(json!({"email": "[email protected]"})),+ Some(json!({"email": "[email protected]"})),).await.unwrap();- // Flag 1: 100% rollout with continuity (can be optimized)- let flag_optimizable = mock!(FeatureFlag,+ // Create a multivariate flag where one variant is at 100%+ // This flag should NOT need a hash key override lookup (optimization applies)+ let flag = mock!(FeatureFlag,+ id: 4,team_id: team.id,- key: "flag_optimizable".mock_into(),+ key: "opt_multivariate_100".mock_into(),filters: FlagFilters {groups: vec![FlagPropertyGroup {properties: None,@@ -7650,42 +6682,30 @@ mod tests {variant: None,..Default::default()}],- multivariate: None,- aggregation_group_type_index: None,- payloads: None,- super_groups: None,- feature_enrollment: None,-- holdout: None,- },- ensure_experience_continuity: Some(true)- );-- // Flag 2: 50% rollout with continuity (needs lookup)- let flag_needs_lookup = mock!(FeatureFlag,- id: 2,- team_id: team.id,- key: "flag_needs_lookup".mock_into(),- filters: FlagFilters {- groups: vec![FlagPropertyGroup {- properties: None,- rollout_percentage: Some(50.0),- variant: None,- ..Default::default()- }],- multivariate: None,+ multivariate: Some(MultivariateFlagOptions {+ variants: vec![+ MultivariateFlagVariant {+ key: "control".to_string(),+ name: Some("Control".to_string()),+ rollout_percentage: 100.0, // 100% variant+ },+ MultivariateFlagVariant {+ key: "test".to_string(),+ name: Some("Test".to_string()),+ rollout_percentage: 0.0,+ },+ ],+ }),aggregation_group_type_index: None,payloads: None,- super_groups: None,- feature_enrollment: None,+ feature_enrollment: None,holdout: None,},ensure_experience_continuity: Some(true));- let flags =- flag_list_with_metadata(vec![flag_optimizable.clone(), flag_needs_lookup.clone()]);+ let flags = flag_list_with_metadata(vec![flag.clone()]);// Reset counter before the testreset_hash_key_override_lookup_count();@@ -7706,53 +6726,38 @@ mod tests {None,Some("anon_distinct_id".to_string()),Uuid::new_v4(),- Some(vec!["flag_optimizable".to_string()]), // Only request the optimizable flag- true, // optimization enabled+ None,+ true, // optimization enabled).await.unwrap();- // Verify the lookup was SKIPPED because we only requested flag_optimizable,- // which is 100% rollout and doesn't need the hash key override lookup.- // The flag_needs_lookup exists but wasn't requested, so it shouldn't trigger a lookup.+ // Verify the optimization skipped the lookup (100% variant = no hashing needed)let lookup_count = get_hash_key_override_lookup_count();assert_eq!(lookup_count, 0,- "Lookup should be skipped when flag_keys filters to only optimizable flags, but got {lookup_count} lookups"+ "Multivariate flag with 100% variant should skip hash key override lookup, but got {lookup_count} lookups");- // Only the requested flag should be evaluated- assert!(- result.flags.contains_key("flag_optimizable"),- "Optimizable flag should be evaluated"- );+ // Flag should evaluate with the 100% variant+ let flag_result = result.flags.get("opt_multivariate_100").unwrap();assert!(- !result.flags.contains_key("flag_needs_lookup"),- "Needs-lookup flag should NOT be evaluated when not in flag_keys"+ flag_result.enabled,+ "Flag with 100% variant should be enabled");-- // The optimizable flag should be enabled (100% rollout)- assert!(- result.flags.get("flag_optimizable").unwrap().enabled,- "100% rollout flag should be enabled"+ assert_eq!(+ flag_result.variant,+ Some("control".to_string()),+ "Should get the 100% variant");-assert!(!result.errors_while_computing_flags,"No errors should occur");}- /// Tests that hash key lookup is NOT skipped when a requested flag depends on a flag that needs it.- /// This ensures the optimization correctly considers transitive dependencies.- ///- /// Scenario:- /// - Flag B: 50% rollout + experience continuity (needs hash lookup)- /// - Flag A: 100% rollout + experience continuity, depends on Flag B (doesn't need lookup itself)- /// - User requests only Flag A via flag_keys- /// - The lookup should happen because Flag B (a dependency) requires it#[tokio::test]- async fn test_optimization_considers_dependencies_for_flag_keys() {+ async fn test_optimization_disabled_legacy_behavior() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -7760,43 +6765,29 @@ mod tests {None,));let team = context.insert_new_team(None).await.unwrap();- let distinct_id = "dependency_user".to_string();+ let distinct_id = "legacy_user".to_string();context.insert_person(team.id,distinct_id.clone(),- Some(json!({"email": "[email protected]"})),+ Some(json!({"email": "[email protected]"})),).await.unwrap();- // Flag B: 50% rollout with experience continuity (NEEDS hash lookup)- // This is the dependency that requires the hash key override- let flag_needs_lookup = mock!(FeatureFlag,+ // Create a flag with 100% rollout and experience continuity+ let flag = mock!(FeatureFlag,+ id: 5,team_id: team.id,- key: "flag_needs_lookup".mock_into(),+ key: "legacy_flag".mock_into(),filters: mock!(FlagFilters,- groups: vec![mock!(FlagPropertyGroup, properties: None, rollout_percentage: Some(50.0))]+ groups: vec![mock!(FlagPropertyGroup, properties: None)]),ensure_experience_continuity: Some(true));- // Flag A: Depends on Flag B, with 100% rollout and experience continuity.- // This flag itself wouldn't need a hash lookup (100% rollout), but its dependency does.- let flag_depends_on_b = mock!(FeatureFlag,- id: 2,- team_id: team.id,- key: "flag_depends_on_b".mock_into(),- filters: dep_filter(1, FlagValue::Boolean(true)).mock_into(),- ensure_experience_continuity: Some(true)- );-- let flags =- flag_list_with_metadata(vec![flag_needs_lookup.clone(), flag_depends_on_b.clone()]);-- // Reset counter before the test- reset_hash_key_override_lookup_count();+ let flags = flag_list_with_metadata(vec![flag.clone()]);let router = context.create_postgres_router();let result = FeatureFlagMatcher::new(@@ -7814,33 +6805,17 @@ mod tests {None,Some("anon_distinct_id".to_string()),Uuid::new_v4(),- Some(vec!["flag_depends_on_b".to_string()]), // Only request the dependent flag- true, // optimization enabled+ None,+ false, // optimization disabled (legacy behavior)).await.unwrap();- // The lookup SHOULD happen because flag_needs_lookup (a dependency) requires it,- // even though flag_depends_on_b itself wouldn't need it (100% rollout).- // Before the fix, this would incorrectly be 0.- let lookup_count = get_hash_key_override_lookup_count();- assert_eq!(- lookup_count, 1,- "Hash key lookup should happen because dependency flag_needs_lookup requires it"- );-- // The dependent flag should be evaluated- assert!(- result.flags.contains_key("flag_depends_on_b"),- "Dependent flag should be evaluated"- );-- // The dependency flag should also be in the result since it was evaluated as a dependency+ // Flag should still evaluate correctly in legacy modeassert!(- result.flags.contains_key("flag_needs_lookup"),- "Dependency flag should also be evaluated"+ result.flags.get("legacy_flag").unwrap().enabled,+ "Flag should be enabled in legacy mode");-assert!(!result.errors_while_computing_flags,"No errors should occur"@@ -7848,10 +6823,7 @@ mod tests {}#[tokio::test]- async fn test_super_condition_matches_with_override_no_person_in_db() {- // Test that super_condition can match using person_property_overrides- // even when the person doesn't exist in the database.- // This is a key scenario for early access feature enrollment.+ async fn test_optimization_mixed_flags() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -7859,49 +6831,96 @@ mod tests {None,));let team = context.insert_new_team(None).await.unwrap();- let flag = mock!(FeatureFlag,+ let distinct_id = "mixed_user".to_string();++ context+ .insert_person(+ team.id,+ distinct_id.clone(),+ Some(json!({"email": "[email protected]"})),+ )+ .await+ .unwrap();++ // Flag 1: 100% rollout with continuity (can be optimized)+ let flag_optimizable = mock!(FeatureFlag,team_id: team.id,- name: "Early Access Flag".mock_into(),- key: "early_access_flag".mock_into(),+ key: "flag_optimizable".mock_into(),filters: FlagFilters {groups: vec![FlagPropertyGroup {properties: None,- rollout_percentage: Some(0.0),+ rollout_percentage: Some(100.0),variant: None,..Default::default()}],multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: Some(vec![FlagPropertyGroup {- properties: Some(vec![PropertyFilter {- key: "$feature_enrollment/my-flag".to_string(),- value: Some(json!(["true"])),- operator: Some(OperatorType::Exact),- prop_type: PropertyType::Person,- group_type_index: None,- negation: None,- compiled_regex: None,- }]),++ feature_enrollment: None,++ holdout: None,+ },+ ensure_experience_continuity: Some(true)+ );++ // Flag 2: 50% rollout with continuity (needs lookup)+ let flag_needs_lookup = mock!(FeatureFlag,+ id: 2,+ team_id: team.id,+ key: "flag_needs_lookup".mock_into(),+ filters: FlagFilters {+ groups: vec![FlagPropertyGroup {+ properties: None,+ rollout_percentage: Some(50.0),+ variant: None,+ ..Default::default()+ }],+ multivariate: None,+ aggregation_group_type_index: None,+ payloads: None,++ feature_enrollment: None,++ holdout: None,+ },+ ensure_experience_continuity: Some(true)+ );++ // Flag 3: 100% rollout without continuity (no lookup needed)+ let flag_no_continuity = mock!(FeatureFlag,+ id: 3,+ team_id: team.id,+ key: "flag_no_continuity".mock_into(),+ filters: FlagFilters {+ groups: vec![FlagPropertyGroup {+ properties: None,rollout_percentage: Some(100.0),variant: None,..Default::default()- }]),+ }],+ multivariate: None,+ aggregation_group_type_index: None,+ payloads: None,feature_enrollment: None,holdout: None,});- let person_property_overrides =- HashMap::from([("$feature_enrollment/my-flag".to_string(), json!("true"))]);- let flags = flag_list_with_metadata(vec![flag.clone()]);- reset_fetch_calls_count();+ let flags = flag_list_with_metadata(vec![+ flag_optimizable.clone(),+ flag_needs_lookup.clone(),+ flag_no_continuity.clone(),+ ]);++ // Reset counter before the test+ reset_hash_key_override_lookup_count();let router = context.create_postgres_router();let result = FeatureFlagMatcher::new(- "new_user_not_in_db".to_string(),+ distinct_id.clone(),None,team.id,router,@@ -7911,44 +6930,60 @@ mod tests {).evaluate_all_feature_flags(flags,- Some(person_property_overrides),None,None,+ Some("anon_distinct_id".to_string()),Uuid::new_v4(),None,- false,+ true, // optimization enabled).await.unwrap();- // Verify no DB fetch was needed since all required properties are in overrides- let fetch_calls = get_fetch_calls_count();+ // Verify the lookup DID happen because flag_needs_lookup requires it.+ // Even though flag_optimizable could be optimized, the presence of+ // flag_needs_lookup forces a lookup for all flags with experience continuity.+ let lookup_count = get_hash_key_override_lookup_count();assert_eq!(- fetch_calls, 0,- "Should not need DB fetch when super_group properties are in overrides"+ lookup_count, 1,+ "Mixed flags should perform lookup when at least one flag needs it, but got {lookup_count} lookups");++ // All flags should be evaluatedassert!(- !result.errors_while_computing_flags,- "Should not have errors"+ result.flags.contains_key("flag_optimizable"),+ "Optimizable flag should be evaluated"+ );+ assert!(+ result.flags.contains_key("flag_needs_lookup"),+ "Needs-lookup flag should be evaluated"+ );+ assert!(+ result.flags.contains_key("flag_no_continuity"),+ "No-continuity flag should be evaluated");- let flag_result = result.flags.get("early_access_flag").unwrap();- assert_eq!(- flag_result.to_value(),- FlagValue::Boolean(true),- "Flag should match via super_condition override even without person in DB"+ // 100% rollout flags should be enabled+ assert!(+ result.flags.get("flag_optimizable").unwrap().enabled,+ "100% rollout flag should be enabled");- assert_eq!(- flag_result.reason.code,- FeatureFlagMatchReason::SuperConditionValue.to_string(),- "Match reason should be SuperConditionValue"+ assert!(+ result.flags.get("flag_no_continuity").unwrap().enabled,+ "100% rollout no-continuity flag should be enabled"+ );++ assert!(+ !result.errors_while_computing_flags,+ "No errors should occur");}+ /// Tests that flag_keys filtering is applied before computing optimization stats.+ /// When only optimizable flags are requested via flag_keys, the lookup should be skipped+ /// even if other flags (not being evaluated) would require it.#[tokio::test]- async fn test_super_condition_override_takes_precedence_over_db() {- // Test that person_property_overrides take precedence over DB values- // for super_condition evaluation.+ async fn test_optimization_respects_flag_keys_filter() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -7956,62 +6991,71 @@ mod tests {None,));let team = context.insert_new_team(None).await.unwrap();- let flag = mock!(FeatureFlag,+ let distinct_id = "flag_keys_user".to_string();++ context+ .insert_person(+ team.id,+ distinct_id.clone(),+ Some(json!({"email": "[email protected]"})),+ )+ .await+ .unwrap();++ // Flag 1: 100% rollout with continuity (can be optimized)+ let flag_optimizable = mock!(FeatureFlag,+ team_id: team.id,+ key: "flag_optimizable".mock_into(),+ filters: FlagFilters {+ groups: vec![FlagPropertyGroup {+ properties: None,+ rollout_percentage: Some(100.0),+ variant: None,+ ..Default::default()+ }],+ multivariate: None,+ aggregation_group_type_index: None,+ payloads: None,++ feature_enrollment: None,++ holdout: None,+ },+ ensure_experience_continuity: Some(true)+ );++ // Flag 2: 50% rollout with continuity (needs lookup)+ let flag_needs_lookup = mock!(FeatureFlag,+ id: 2,team_id: team.id,- name: "Early Access Flag".mock_into(),- key: "early_access_flag".mock_into(),+ key: "flag_needs_lookup".mock_into(),filters: FlagFilters {groups: vec![FlagPropertyGroup {properties: None,- rollout_percentage: Some(0.0),+ rollout_percentage: Some(50.0),variant: None,..Default::default()}],multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: Some(vec![FlagPropertyGroup {- properties: Some(vec![PropertyFilter {- key: "$feature_enrollment/my-flag".to_string(),- value: Some(json!(["true"])),- operator: Some(OperatorType::Exact),- prop_type: PropertyType::Person,- group_type_index: None,- negation: None,- compiled_regex: None,- }]),- rollout_percentage: Some(100.0),- variant: None,- ..Default::default()- }]),feature_enrollment: None,holdout: None,- }+ },+ ensure_experience_continuity: Some(true));- // Person exists in DB with enrollment set to FALSE- context- .insert_person(- team.id,- "test_user".to_string(),- Some(json!({- "email": "[email protected]",- "$feature_enrollment/my-flag": "false"- })),- )- .await- .unwrap();+ let flags =+ flag_list_with_metadata(vec![flag_optimizable.clone(), flag_needs_lookup.clone()]);- // Override says TRUE - this should win- let person_property_overrides =- HashMap::from([("$feature_enrollment/my-flag".to_string(), json!("true"))]);+ // Reset counter before the test+ reset_hash_key_override_lookup_count();- let flags = flag_list_with_metadata(vec![flag.clone()]);let router = context.create_postgres_router();let result = FeatureFlagMatcher::new(- "test_user".to_string(),+ distinct_id.clone(),None,team.id,router,@@ -8021,37 +7065,57 @@ mod tests {).evaluate_all_feature_flags(flags,- Some(person_property_overrides),None,None,+ Some("anon_distinct_id".to_string()),Uuid::new_v4(),- None,- false,+ Some(vec!["flag_optimizable".to_string()]), // Only request the optimizable flag+ true, // optimization enabled).await.unwrap();+ // Verify the lookup was SKIPPED because we only requested flag_optimizable,+ // which is 100% rollout and doesn't need the hash key override lookup.+ // The flag_needs_lookup exists but wasn't requested, so it shouldn't trigger a lookup.+ let lookup_count = get_hash_key_override_lookup_count();+ assert_eq!(+ lookup_count, 0,+ "Lookup should be skipped when flag_keys filters to only optimizable flags, but got {lookup_count} lookups"+ );++ // Only the requested flag should be evaluatedassert!(- !result.errors_while_computing_flags,- "Should not have errors"+ result.flags.contains_key("flag_optimizable"),+ "Optimizable flag should be evaluated");- let flag_result = result.flags.get("early_access_flag").unwrap();- assert_eq!(- flag_result.to_value(),- FlagValue::Boolean(true),- "Override should take precedence over DB value for super_condition"+ assert!(+ !result.flags.contains_key("flag_needs_lookup"),+ "Needs-lookup flag should NOT be evaluated when not in flag_keys");- assert_eq!(- flag_result.reason.code,- FeatureFlagMatchReason::SuperConditionValue.to_string(),- "Match reason should be SuperConditionValue"++ // The optimizable flag should be enabled (100% rollout)+ assert!(+ result.flags.get("flag_optimizable").unwrap().enabled,+ "100% rollout flag should be enabled"+ );++ assert!(+ !result.errors_while_computing_flags,+ "No errors should occur");}+ /// Tests that hash key lookup is NOT skipped when a requested flag depends on a flag that needs it.+ /// This ensures the optimization correctly considers transitive dependencies.+ ///+ /// Scenario:+ /// - Flag B: 50% rollout + experience continuity (needs hash lookup)+ /// - Flag A: 100% rollout + experience continuity, depends on Flag B (doesn't need lookup itself)+ /// - User requests only Flag A via flag_keys+ /// - The lookup should happen because Flag B (a dependency) requires it#[tokio::test]- async fn test_super_condition_with_override_person_exists_without_property() {- // Test that super_condition matches when person exists in DB- // but doesn't have the enrollment property, and we provide it via override.+ async fn test_optimization_considers_dependencies_for_flag_keys() {let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(context.non_persons_reader.clone(),@@ -8059,62 +7123,47 @@ mod tests {None,));let team = context.insert_new_team(None).await.unwrap();- let flag = mock!(FeatureFlag,- team_id: team.id,- name: "Early Access Flag".mock_into(),- key: "early_access_flag".mock_into(),- filters: FlagFilters {- groups: vec![FlagPropertyGroup {- properties: None,- rollout_percentage: Some(0.0),- variant: None,- ..Default::default()- }],- multivariate: None,- aggregation_group_type_index: None,- payloads: None,- super_groups: Some(vec![FlagPropertyGroup {- properties: Some(vec![PropertyFilter {- key: "$feature_enrollment/my-flag".to_string(),- value: Some(json!(["true"])),- operator: Some(OperatorType::Exact),- prop_type: PropertyType::Person,- group_type_index: None,- negation: None,- compiled_regex: None,- }]),- rollout_percentage: Some(100.0),- variant: None,- ..Default::default()- }]),-- feature_enrollment: None,-- holdout: None,- }- );+ let distinct_id = "dependency_user".to_string();- // Person exists in DB but does NOT have the enrollment propertycontext.insert_person(team.id,- "test_user".to_string(),- Some(json!({- "email": "[email protected]"- })),+ distinct_id.clone(),+ Some(json!({"email": "[email protected]"})),).await.unwrap();- // Override provides the enrollment property- let person_property_overrides =- HashMap::from([("$feature_enrollment/my-flag".to_string(), json!("true"))]);+ // Flag B: 50% rollout with experience continuity (NEEDS hash lookup)+ // This is the dependency that requires the hash key override+ let flag_needs_lookup = mock!(FeatureFlag,+ team_id: team.id,+ key: "flag_needs_lookup".mock_into(),+ filters: mock!(FlagFilters,+ groups: vec![mock!(FlagPropertyGroup, properties: None, rollout_percentage: Some(50.0))]+ ),+ ensure_experience_continuity: Some(true)+ );- let flags = flag_list_with_metadata(vec![flag.clone()]);+ // Flag A: Depends on Flag B, with 100% rollout and experience continuity.+ // This flag itself wouldn't need a hash lookup (100% rollout), but its dependency does.+ let flag_depends_on_b = mock!(FeatureFlag,+ id: 2,+ team_id: team.id,+ key: "flag_depends_on_b".mock_into(),+ filters: dep_filter(1, FlagValue::Boolean(true)).mock_into(),+ ensure_experience_continuity: Some(true)+ );++ let flags =+ flag_list_with_metadata(vec![flag_needs_lookup.clone(), flag_depends_on_b.clone()]);++ // Reset counter before the test+ reset_hash_key_override_lookup_count();let router = context.create_postgres_router();let result = FeatureFlagMatcher::new(- "test_user".to_string(),+ distinct_id.clone(),None,team.id,router,@@ -8124,30 +7173,40 @@ mod tests {).evaluate_all_feature_flags(flags,- Some(person_property_overrides),None,None,+ Some("anon_distinct_id".to_string()),Uuid::new_v4(),- None,- false,+ Some(vec!["flag_depends_on_b".to_string()]), // Only request the dependent flag+ true, // optimization enabled).await.unwrap();+ // The lookup SHOULD happen because flag_needs_lookup (a dependency) requires it,+ // even though flag_depends_on_b itself wouldn't need it (100% rollout).+ // Before the fix, this would incorrectly be 0.+ let lookup_count = get_hash_key_override_lookup_count();+ assert_eq!(+ lookup_count, 1,+ "Hash key lookup should happen because dependency flag_needs_lookup requires it"+ );++ // The dependent flag should be evaluatedassert!(- !result.errors_while_computing_flags,- "Should not have errors"+ result.flags.contains_key("flag_depends_on_b"),+ "Dependent flag should be evaluated");- let flag_result = result.flags.get("early_access_flag").unwrap();- assert_eq!(- flag_result.to_value(),- FlagValue::Boolean(true),- "Override should provide missing property for super_condition match"++ // The dependency flag should also be in the result since it was evaluated as a dependency+ assert!(+ result.flags.contains_key("flag_needs_lookup"),+ "Dependency flag should also be evaluated");- assert_eq!(- flag_result.reason.code,- FeatureFlagMatchReason::SuperConditionValue.to_string(),- "Match reason should be SuperConditionValue"++ assert!(+ !result.errors_while_computing_flags,+ "No errors should occur");}@@ -8162,7 +7221,6 @@ mod tests {#[case] expected_match: bool,#[case] expected_reason: FeatureFlagMatchReason,) {- // New feature_enrollment format: flag has `feature_enrollment: true` instead of super_groups.// The enrollment property key is derived as `$feature_enrollment/{flag_key}`.let context = TestContext::new(None).await;let cohort_cache = Arc::new(CohortCacheManager::new(@@ -8186,7 +7244,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: Some(true),holdout: None,}@@ -8248,7 +7306,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: Some(true),holdout: None,}@@ -8282,86 +7340,6 @@ mod tests {assert_eq!(result.reason, FeatureFlagMatchReason::OutOfRolloutBound);}- #[tokio::test]- async fn test_feature_enrollment_takes_precedence_over_super_groups() {- // When both feature_enrollment and super_groups are present,- // feature_enrollment should be used (new format wins).- 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,- team_id: team.id,- name: "Dual Format Flag".mock_into(),- key: "dual-format-flag".mock_into(),- filters: FlagFilters {- groups: vec![FlagPropertyGroup {- properties: None,- rollout_percentage: Some(0.0),- variant: None,- ..Default::default()- }],- multivariate: None,- aggregation_group_type_index: None,- payloads: None,- // Legacy super_groups with a DIFFERENT key (to prove feature_enrollment is used)- super_groups: Some(vec![FlagPropertyGroup {- properties: Some(vec![PropertyFilter {- key: "wrong_key".to_string(),- value: Some(json!(["true"])),- operator: Some(OperatorType::Exact),- prop_type: PropertyType::Person,- group_type_index: None,- negation: None,- compiled_regex: None,- }]),- rollout_percentage: Some(100.0),- variant: None,- ..Default::default()- }]),- feature_enrollment: Some(true),- holdout: None,- }- );-- // Person has the feature_enrollment property (derived from flag key)- // but NOT the wrong_key property from super_groups- context- .insert_person(- team.id,- "test_user".to_string(),- Some(json!({"$feature_enrollment/dual-format-flag": "true"})),- )- .await- .unwrap();-- let router = context.create_postgres_router();- let mut matcher = FeatureFlagMatcher::new(- "test_user".to_string(),- None,- team.id,- router,- cohort_cache.clone(),- empty_group_type_cache(),- None,- );-- matcher- .prepare_flag_evaluation_state(&[&flag])- .await- .unwrap();-- let result = matcher.get_match(&flag, None, None, None, &None).unwrap();-- // Should match via feature_enrollment (not super_groups which uses wrong_key)- assert!(result.matches);- assert_eq!(result.reason, FeatureFlagMatchReason::SuperConditionValue);- }-#[tokio::test]async fn test_paired_group_identifiers_avoid_cartesian_product() {use crate::utils::test_utils::create_group_in_pg;@@ -8395,7 +7373,7 @@ mod tests {multivariate: None,aggregation_group_type_index: Some(0),payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,@@ -8425,7 +7403,7 @@ mod tests {multivariate: None,aggregation_group_type_index: Some(1),payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,@@ -8727,7 +7705,7 @@ mod tests {multivariate: None,aggregation_group_type_index: Some(1),payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,}@@ -8818,7 +7796,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,}@@ -8892,7 +7870,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,}@@ -8974,7 +7952,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,}@@ -9117,7 +8095,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,}@@ -9205,7 +8183,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,}@@ -9285,7 +8263,7 @@ mod tests {multivariate: None,aggregation_group_type_index: Some(1), // Flag-level aggregationpayloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,}@@ -9362,7 +8340,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None, // Flag-level says personpayloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,}@@ -9458,7 +8436,7 @@ mod tests {}),aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,}@@ -9550,7 +8528,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,}@@ -9620,7 +8598,7 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,+feature_enrollment: None,holdout: None,}diff --git a/rust/feature-flags/src/utils/mock.rs b/rust/feature-flags/src/utils/mock.rsindex a93a19036b87..39f7d6268ed4 100644--- a/rust/feature-flags/src/utils/mock.rs+++ b/rust/feature-flags/src/utils/mock.rs@@ -340,7 +340,6 @@ mod tests {multivariate: None,aggregation_group_type_index: None,payloads: None,- super_groups: None,feature_enrollment: None,holdout: None,},diff --git a/rust/feature-flags/tests/test_flags.rs b/rust/feature-flags/tests/test_flags.rsindex 0f621e9b5be3..87eb0a95a90d 100644--- a/rust/feature-flags/tests/test_flags.rs+++ b/rust/feature-flags/tests/test_flags.rs@@ -1518,7 +1518,7 @@ async fn test_complex_regex_and_name_match_flag() -> Result<()> {}#[tokio::test]-async fn test_super_condition_with_complex_request() -> Result<()> {+async fn test_feature_enrollment_with_complex_request() -> Result<()> {let config = DEFAULT_TEST_CONFIG.clone();let distinct_id = "test_user".to_string();let redis_client = setup_redis_client(Some(config.redis_url.clone())).await;@@ -1560,15 +1560,7 @@ async fn test_super_condition_with_complex_request() -> Result<()> {"rollout_percentage": 100}],- "super_groups": [{- "properties": [{- "key": "$feature_enrollment/my-flag",- "type": "person",- "value": ["true"],- "operator": "exact"- }],- "rollout_percentage": 100- }]+ "feature_enrollment": true}}]);@@ -2924,14 +2916,14 @@ async fn test_numeric_group_ids_work_correctly() -> Result<()> {}#[tokio::test]-async fn test_super_condition_property_overrides_bug_fix() -> Result<()> {- // This test specifically addresses the bug where super condition property overrides+async fn test_feature_enrollment_property_overrides_bug_fix() -> Result<()> {+ // This test specifically addresses the bug where feature enrollment property overrides// were ignored when evaluating flags. The bug was that if you sent:- // "$feature_enrollment/discussions": false- // as an override, it would be ignored if the flag's super_groups checked for that property.+ // "$feature_enrollment/discussions-flag": false+ // as an override, it would be ignored if the flag's feature_enrollment gate checked for that property.let config = DEFAULT_TEST_CONFIG.clone();- let distinct_id = "super_condition_user".to_string();+ let distinct_id = "feature_enrollment_user".to_string();let client = setup_redis_client(Some(config.redis_url.clone())).await;let team = insert_new_team_in_redis(client.clone()).await.unwrap();@@ -2946,7 +2938,7 @@ async fn test_super_condition_property_overrides_bug_fix() -> Result<()> {team.id,distinct_id.clone(),Some(json!({- "$feature_enrollment/discussions": true, // DB has it as true+ "$feature_enrollment/discussions-flag": true, // DB has it as true"email": "[email protected]"})),)@@ -2968,15 +2960,7 @@ async fn test_super_condition_property_overrides_bug_fix() -> Result<()> {"rollout_percentage": 100}],- "super_groups": [{- "properties": [{- "key": "$feature_enrollment/discussions",- "type": "person",- "value": ["true"],- "operator": "exact"- }],- "rollout_percentage": 100- }]+ "feature_enrollment": true}}]);@@ -3002,7 +2986,7 @@ async fn test_super_condition_property_overrides_bug_fix() -> Result<()> {let json_data = res.json::<Value>().await?;- // Should be enabled because DB has $feature_enrollment/discussions = true+ // Should be enabled because DB has $feature_enrollment/discussions-flag = trueassert_json_include!(actual: json_data,expected: json!({@@ -3025,7 +3009,7 @@ async fn test_super_condition_property_overrides_bug_fix() -> Result<()> {"token": token,"distinct_id": distinct_id,"person_properties": {- "$feature_enrollment/discussions": false // Override to false+ "$feature_enrollment/discussions-flag": false // Override to false}});@@ -3064,7 +3048,7 @@ async fn test_super_condition_property_overrides_bug_fix() -> Result<()> {team.id,"another_user".to_string(),Some(json!({- "$feature_enrollment/discussions": false, // DB has it as false+ "$feature_enrollment/discussions-flag": false, // DB has it as false"email": "[email protected]"})),)@@ -3075,7 +3059,7 @@ async fn test_super_condition_property_overrides_bug_fix() -> Result<()> {"token": token,"distinct_id": "another_user","person_properties": {- "$feature_enrollment/discussions": true // Override to true+ "$feature_enrollment/discussions-flag": true // Override to true}});@@ -3246,9 +3230,9 @@ async fn test_property_override_bug_real_scenario() -> Result<()> {}#[tokio::test]-async fn test_super_condition_with_cohort_filters() -> Result<()> {+async fn test_feature_enrollment_with_cohort_filters() -> Result<()> {let config = DEFAULT_TEST_CONFIG.clone();- let distinct_id = "super_condition_cohort_user".to_string();+ let distinct_id = "feature_enrollment_cohort_user".to_string();let client = setup_redis_client(Some(config.redis_url.clone())).await;let team = insert_new_team_in_redis(client.clone()).await.unwrap();@@ -3263,7 +3247,7 @@ async fn test_super_condition_with_cohort_filters() -> Result<()> {team.id,distinct_id.clone(),Some(json!({- "$feature_enrollment/discussions": false, // Super condition property in DB+ "$feature_enrollment/discussions-with-cohort": false, // Super condition property in DB"email": "[email protected]"})),)@@ -3271,7 +3255,7 @@ async fn test_super_condition_with_cohort_filters() -> Result<()> {.unwrap();// Create a flag that matches your production example:- // - Has a super condition that checks "$feature_enrollment/discussions"+ // - Has a super condition that checks "$feature_enrollment/discussions-with-cohort"// - Has a regular condition with a cohort filterlet flag_json = json!([{"id": 1,@@ -3292,15 +3276,7 @@ async fn test_super_condition_with_cohort_filters() -> Result<()> {}],"payloads": {},"multivariate": null,- "super_groups": [{- "properties": [{- "key": "$feature_enrollment/discussions",- "type": "person",- "value": ["true"],- "operator": "exact"- }],- "rollout_percentage": 100- }]+ "feature_enrollment": true}}]);@@ -3326,7 +3302,7 @@ async fn test_super_condition_with_cohort_filters() -> Result<()> {let json_data = res.json::<Value>().await?;- // Should be disabled because DB has $feature_enrollment/discussions = false+ // Should be disabled because DB has $feature_enrollment/discussions-with-cohort = falseassert_json_include!(actual: json_data,expected: json!({@@ -3348,7 +3324,7 @@ async fn test_super_condition_with_cohort_filters() -> Result<()> {"token": token,"distinct_id": distinct_id,"person_properties": {- "$feature_enrollment/discussions": true // Override super condition property to true+ "$feature_enrollment/discussions-with-cohort": true // Override super condition property to true}});@@ -3365,8 +3341,8 @@ async fn test_super_condition_with_cohort_filters() -> Result<()> {let json_override = res_override.json::<Value>().await?;// This is the key test: the flag should now be enabled because:- // 1. Super condition can be evaluated from override (discussions = true)- // 2. Super condition matches, so we return early with super_condition_value+ // 1. Feature enrollment can be evaluated from override (discussions = true)+ // 2. Enrollment matches, so we return early with super_condition_value// 3. We don't even need to evaluate the cohort filter in the regular conditionassert_json_include!(actual: json_override,@@ -3389,7 +3365,7 @@ async fn test_super_condition_with_cohort_filters() -> Result<()> {"token": token,"distinct_id": distinct_id,"person_properties": {- "$feature_enrollment/discussions": false // Override to false+ "$feature_enrollment/discussions-with-cohort": false // Override to false}});@@ -6031,8 +6007,7 @@ async fn test_api_cohort_flag_integration() -> Result<()> {],"multivariate": null,"aggregation_group_type_index": null,- "payloads": {},- "super_groups": []+ "payloads": {}}}]);@@ -6110,8 +6085,7 @@ async fn test_api_cohort_flag_integration_no_match() -> Result<()> {],"multivariate": null,"aggregation_group_type_index": null,- "payloads": {},- "super_groups": []+ "payloads": {}}}]);