: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
chore(feature_flags): move feature flag models to products app (#51923)
Julian Bezb887450285c9
diff --git a/.semgrep/rules/max-tools-require-serializer.py b/.semgrep/rules/max-tools-require-serializer.pyindex 3da43d42656b..4f68edf0c0e6 100644--- a/.semgrep/rules/max-tools-require-serializer.py+++ b/.semgrep/rules/max-tools-require-serializer.py@@ -4,8 +4,9 @@# Note: This rule only applies to files named max_tools.py, but semgrep's test# framework runs tests against this .py file directly, so we test the patterns here.-from posthog.api.feature_flag import FeatureFlagSerializer-from posthog.models import FeatureFlag, Tag, TaggedItem+from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer+from posthog.models import Tag, TaggedItem+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.experiments.backend.models.experiment import Experimentfrom products.surveys.backend.models import Surveydiff --git a/.semgrep/rules/tests/celery-team-scope.py b/.semgrep/rules/tests/celery-team-scope.pyindex 6d582efa9a07..c4a8eae24db7 100644--- a/.semgrep/rules/tests/celery-team-scope.py+++ b/.semgrep/rules/tests/celery-team-scope.py@@ -1,8 +1,7 @@# Test cases for celery-team-scope semgrep rulefrom celery import shared_task--from posthog.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom posthog.models.scoping import with_team_scopediff --git a/ee/api/rbac/test/test_access_control.py b/ee/api/rbac/test/test_access_control.pyindex 9564c4bf67ed..8181d7e84612 100644--- a/ee/api/rbac/test/test_access_control.py+++ b/ee/api/rbac/test/test_access_control.py@@ -5,7 +5,6 @@ from unittest.mock import MagicMock, patchfrom rest_framework import statusfrom posthog.constants import AvailableFeature-from posthog.models.feature_flag.feature_flag import FeatureFlagfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team.team import Team@@ -14,6 +13,7 @@ from posthog.rbac.user_access_control import AccessSourcefrom posthog.utils import render_templatefrom products.dashboards.backend.models.dashboard import Dashboard+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebookfrom ee.api.test.base import APILicensedTestdiff --git a/ee/api/test/test_tagged_item.py b/ee/api/test/test_tagged_item.pyindex 24286e514db8..d7fe6b5ea71a 100644--- a/ee/api/test/test_tagged_item.py+++ b/ee/api/test/test_tagged_item.py@@ -6,10 +6,11 @@ from posthog.test.base import APIBaseTestfrom rest_framework import status-from posthog.models import FeatureFlag, Insight, Tag+from posthog.models import Insight, Tagfrom posthog.models.tagged_item import TaggedItemfrom products.dashboards.backend.models.dashboard import Dashboard+from products.feature_flags.backend.models.feature_flag import FeatureFlag# This serializer only tests the business logic of getting and setting of ee descriptions. It uses the dashboard model# as an example, since model specific functionality is already tested in their models' respective serializer tests.diff --git a/ee/api/vercel/test/test_vercel_sso.py b/ee/api/vercel/test/test_vercel_sso.pyindex 4ee352d5fccb..cf85a3154233 100644--- a/ee/api/vercel/test/test_vercel_sso.py+++ b/ee/api/vercel/test/test_vercel_sso.py@@ -225,7 +225,7 @@ class TestSSORedirectSuccess(BaseSSOMockTest):assert sso_setup["user"].current_team != team # Team switching happens after login verificationdef test_sso_redirect_with_experimentation_item(self, sso_setup):- from posthog.models import FeatureFlag+ from products.feature_flags.backend.models.feature_flag import FeatureFlagteam = Team.objects.create(organization=sso_setup["organization"], name="Test Team")flag = FeatureFlag.objects.create(diff --git a/ee/clickhouse/queries/experiments/secondary_experiment_result.py b/ee/clickhouse/queries/experiments/secondary_experiment_result.pyindex 1df37988cb81..083584962de1 100644--- a/ee/clickhouse/queries/experiments/secondary_experiment_result.py+++ b/ee/clickhouse/queries/experiments/secondary_experiment_result.py@@ -4,10 +4,11 @@ from typing import Optionalfrom rest_framework.exceptions import ValidationErrorfrom posthog.constants import INSIGHT_FUNNELS, INSIGHT_TRENDS-from posthog.models.feature_flag import FeatureFlagfrom posthog.models.filters.filter import Filterfrom posthog.models.team import Team+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from ee.clickhouse.queries.experiments.funnel_experiment_result import ClickhouseFunnelExperimentResultfrom ee.clickhouse.queries.experiments.trend_experiment_result import (ClickhouseTrendExperimentResult,diff --git a/ee/clickhouse/queries/experiments/trend_experiment_result.py b/ee/clickhouse/queries/experiments/trend_experiment_result.pyindex 2a7d695739ae..7774c9583737 100644--- a/ee/clickhouse/queries/experiments/trend_experiment_result.py+++ b/ee/clickhouse/queries/experiments/trend_experiment_result.py@@ -21,13 +21,13 @@ from posthog.hogql_queries.experiments.trends_statistics import (calculate_credible_intervals,calculate_probabilities,)-from posthog.models.feature_flag import FeatureFlagfrom posthog.models.filters.filter import Filterfrom posthog.models.team import Teamfrom posthog.queries.trends.trends import Trendsfrom posthog.queries.trends.util import ALL_SUPPORTED_MATH_FUNCTIONSfrom products.experiments.backend.models.experiment import ExperimentHoldout+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.clickhouse.queries.experiments import CONTROL_VARIANT_KEYdiff --git a/ee/clickhouse/views/experiment_holdouts.py b/ee/clickhouse/views/experiment_holdouts.pyindex b45bdef32484..2c178915adac 100644--- a/ee/clickhouse/views/experiment_holdouts.py+++ b/ee/clickhouse/views/experiment_holdouts.py@@ -8,11 +8,11 @@ from rest_framework.exceptions import ValidationErrorfrom rest_framework.request import Requestfrom rest_framework.response import Response-from posthog.api.feature_flag import FeatureFlagSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom products.experiments.backend.models.experiment import ExperimentHoldout, holdout_filters_for_flag+from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializerclass ExperimentHoldoutSerializer(serializers.ModelSerializer):diff --git a/ee/clickhouse/views/test/test_experiment_holdouts.py b/ee/clickhouse/views/test/test_experiment_holdouts.pyindex 600dc91463af..6fc42db2d063 100644--- a/ee/clickhouse/views/test/test_experiment_holdouts.py+++ b/ee/clickhouse/views/test/test_experiment_holdouts.py@@ -1,8 +1,7 @@from rest_framework import status-from posthog.models.feature_flag import FeatureFlag-from products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.api.test.base import APILicensedTestdiff --git a/ee/hogai/context/entity_search/context.py b/ee/hogai/context/entity_search/context.pyindex 699adac0d4be..fa5139e4c6a5 100644--- a/ee/hogai/context/entity_search/context.py+++ b/ee/hogai/context/entity_search/context.py@@ -14,7 +14,7 @@ from posthog.api.search import (EntityConfig,search_entities as search_entities_fts,)-from posthog.models import Cohort, FeatureFlag, Insight, Team, User+from posthog.models import Cohort, Insight, Team, Userfrom posthog.rbac.user_access_control import UserAccessControlfrom posthog.sync import database_sync_to_async@@ -22,6 +22,7 @@ from products.actions.backend.models.action import Actionfrom products.alerts.backend.models.alert import AlertConfigurationfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebookfrom products.surveys.backend.models import Surveydiff --git a/ee/hogai/context/entity_search/test/test_context.py b/ee/hogai/context/entity_search/test/test_context.pyindex bb6b590696dd..f2e3fc0ba8ba 100644--- a/ee/hogai/context/entity_search/test/test_context.py+++ b/ee/hogai/context/entity_search/test/test_context.py@@ -7,12 +7,13 @@ from django.utils import timezonefrom parameterized import parameterized-from posthog.models import Cohort, FeatureFlag, Insight+from posthog.models import Cohort, Insightfrom posthog.models.insight import InsightViewedfrom products.actions.backend.models.action import Actionfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.surveys.backend.models import Surveyfrom ee.hogai.context import AssistantContextManagerdiff --git a/ee/hogai/context/feature_flag/context.py b/ee/hogai/context/feature_flag/context.pyindex b44127f1aa25..5aec6df7d9ef 100644--- a/ee/hogai/context/feature_flag/context.py+++ b/ee/hogai/context/feature_flag/context.py@@ -1,7 +1,8 @@from posthog.models import Team-from posthog.models.feature_flag import FeatureFlagfrom posthog.sync import database_sync_to_async+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from .prompts import (FEATURE_FLAG_CONTEXT_TEMPLATE,FEATURE_FLAG_NOT_FOUND_TEMPLATE,diff --git a/ee/hogai/eval/ci/eval_surveys.py b/ee/hogai/eval/ci/eval_surveys.pyindex 6a7d8fbb3712..da49582c5b49 100644--- a/ee/hogai/eval/ci/eval_surveys.py+++ b/ee/hogai/eval/ci/eval_surveys.py@@ -8,8 +8,7 @@ from autoevals.partial import ScorerWithPartialfrom autoevals.ragas import AnswerSimilarityfrom braintrust import EvalCase, Score-from posthog.models import FeatureFlag-+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.surveys.backend.max_tools import CreateSurveyTool, SimpleSurveyQuestionfrom products.surveys.backend.models import Surveydiff --git a/ee/hogai/eval/ci/max_tools/eval_experiment_summary.py b/ee/hogai/eval/ci/max_tools/eval_experiment_summary.pyindex d18338f6cfa6..e809404677e6 100644--- a/ee/hogai/eval/ci/max_tools/eval_experiment_summary.py+++ b/ee/hogai/eval/ci/max_tools/eval_experiment_summary.py@@ -25,9 +25,8 @@ from posthog.schema import (MaxExperimentVariantResultFrequentist,)-from posthog.models import FeatureFlag-from products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.hogai.chat_agent import AssistantGraphfrom ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointerdiff --git a/ee/hogai/eval/sandboxed/experiments/seeders.py b/ee/hogai/eval/sandboxed/experiments/seeders.pyindex 718b997cfbe5..59b3ebce0463 100644--- a/ee/hogai/eval/sandboxed/experiments/seeders.py+++ b/ee/hogai/eval/sandboxed/experiments/seeders.py@@ -67,9 +67,8 @@ def seed_running_experiment(context: CustomPromptSandboxContext) -> dict[str, Anparameterising this one — the eval framework passes only ``context`` to seeders, socase-specific config has to live in the seeder definition."""- from posthog.models import FeatureFlag-from products.experiments.backend.models.experiment import Experiment+ from products.feature_flags.backend.models.feature_flag import FeatureFlagteam_id = context.team_iduser_id = context.user_id@@ -125,9 +124,8 @@ def seed_uneven_split_experiment(context: CustomPromptSandboxContext) -> dict[strecognise that an 80/20 split combined with Exclude systematically removesoverlap users from the smaller variant, biasing the test arm."""- from posthog.models import FeatureFlag-from products.experiments.backend.models.experiment import Experiment+ from products.feature_flags.backend.models.feature_flag import FeatureFlagteam_id = context.team_iduser_id = context.user_id@@ -176,9 +174,8 @@ def seed_inactive_flag_experiment(context: CustomPromptSandboxContext) -> dict[scan never fire, so the exposure-shape snapshot will be empty and thediagnostic is B0 (flag inactive / experiment not actually live)."""- from posthog.models import FeatureFlag-from products.experiments.backend.models.experiment import Experiment+ from products.feature_flags.backend.models.feature_flag import FeatureFlagteam_id = context.team_iduser_id = context.user_id@@ -238,10 +235,10 @@ def seed_ended_experiment_with_flag_flip(context: CustomPromptSandboxContext) ->would emit — before-state is a 50/50 multivariate with no signatureproperties; after-state is the live 0/100 + signature filters payload."""- from posthog.models import FeatureFlagfrom posthog.models.activity_logging.activity_log import ActivityLog, Change, Detailfrom products.experiments.backend.models.experiment import Experiment+ from products.feature_flags.backend.models.feature_flag import FeatureFlagteam_id = context.team_iduser_id = context.user_iddiff --git a/ee/hogai/eval/sandboxed/seeders/survey.py b/ee/hogai/eval/sandboxed/seeders/survey.pyindex f7853d45b8fd..e098bc308989 100644--- a/ee/hogai/eval/sandboxed/seeders/survey.py+++ b/ee/hogai/eval/sandboxed/seeders/survey.py@@ -5,8 +5,7 @@ from __future__ import annotationsimport loggingfrom typing import Any-from posthog.models import FeatureFlag-+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContextlogger = logging.getLogger(__name__)diff --git a/ee/hogai/tools/read_data/test/test_tool.py b/ee/hogai/tools/read_data/test/test_tool.pyindex 37de856b7840..9e8756335a06 100644--- a/ee/hogai/tools/read_data/test/test_tool.py+++ b/ee/hogai/tools/read_data/test/test_tool.py@@ -18,12 +18,12 @@ from posthog.schema import ()from posthog.models import Insight-from posthog.models.feature_flag import FeatureFlagfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.llm_analytics.backend.summarization.llm.schema import (InterestingNote,SummarizationResponse,diff --git a/ee/migrations/0045_migrate_feature_flags_models.py b/ee/migrations/0045_migrate_feature_flags_models.pynew file mode 100644index 000000000000..e8b07baa03ff--- /dev/null+++ b/ee/migrations/0045_migrate_feature_flags_models.py@@ -0,0 +1,29 @@+# Generated by Django 5.2.13 on 2026-05-20 15:38++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("ee", "0044_conversation_deleted_conversation_deleted_at"),+ ("feature_flags", "0002_migrate_feature_flags_models"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AlterField(+ model_name="featureflagroleaccess",+ name="feature_flag",+ field=models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="access",+ related_query_name="access",+ to="feature_flags.featureflag",+ ),+ ),+ ],+ database_operations=[],+ ),+ ]diff --git a/ee/migrations/max_migration.txt b/ee/migrations/max_migration.txtindex ec53f3ad0119..bfc21c1368e0 100644--- a/ee/migrations/max_migration.txt+++ b/ee/migrations/max_migration.txt@@ -1 +1 @@-0044_conversation_deleted_conversation_deleted_at+0045_migrate_feature_flags_modelsdiff --git a/ee/models/feature_flag_role_access.py b/ee/models/feature_flag_role_access.pyindex bfe07cb4a4b7..bc5541b1dcd8 100644--- a/ee/models/feature_flag_role_access.py+++ b/ee/models/feature_flag_role_access.py@@ -4,7 +4,7 @@ from django.db import models# DEPRECATED - do not useclass FeatureFlagRoleAccess(models.Model):feature_flag = models.ForeignKey(- "posthog.FeatureFlag",+ "feature_flags.FeatureFlag",on_delete=models.CASCADE,related_name="access",related_query_name="access",diff --git a/ee/tasks/auto_rollback_feature_flag.py b/ee/tasks/auto_rollback_feature_flag.pyindex c3dee9dfdb75..2e18478ed64b 100644--- a/ee/tasks/auto_rollback_feature_flag.py+++ b/ee/tasks/auto_rollback_feature_flag.py@@ -4,12 +4,13 @@ from zoneinfo import ZoneInfofrom celery import shared_taskfrom posthog.clickhouse.query_tagging import Feature, Product, tags_context-from posthog.models.feature_flag import FeatureFlagfrom posthog.models.filters.filter import Filterfrom posthog.models.team import Teamfrom posthog.queries.trends.trends import Trendsfrom posthog.scoping_audit import skip_team_scope_audit+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from ee.api.sentry_stats import get_stats_for_timerangediff --git a/ee/tasks/test/test_auto_rollback_feature_flag.py b/ee/tasks/test/test_auto_rollback_feature_flag.pyindex 1cab456b6de3..f012616240f0 100644--- a/ee/tasks/test/test_auto_rollback_feature_flag.py+++ b/ee/tasks/test/test_auto_rollback_feature_flag.py@@ -2,7 +2,7 @@ from freezegun import freeze_timefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_eventfrom unittest.mock import patch-from posthog.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.tasks.auto_rollback_feature_flag import (calculate_rolling_average,diff --git a/ee/vercel/integration.py b/ee/vercel/integration.pyindex 3e8833fe8938..79ee37f78e00 100644--- a/ee/vercel/integration.py+++ b/ee/vercel/integration.py@@ -23,7 +23,6 @@ from posthog.schema import ProductIntentContext, ProductKeyfrom posthog.cloud_utils import get_cached_instance_licensefrom posthog.event_usage import report_user_signed_upfrom posthog.exceptions_capture import capture_exception-from posthog.models.feature_flag import FeatureFlagfrom posthog.models.integration import Integrationfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.organization_integration import OrganizationIntegration@@ -33,6 +32,7 @@ from posthog.models.user import Userfrom posthog.utils import absolute_urifrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.api.authentication import VercelAuthenticationfrom ee.api.vercel.types import VercelClaims, VercelUserClaimsdiff --git a/ee/vercel/test/test_integration.py b/ee/vercel/test/test_integration.pyindex 9c953a5be9e3..8187e7b595a2 100644--- a/ee/vercel/test/test_integration.py+++ b/ee/vercel/test/test_integration.py@@ -10,7 +10,6 @@ from parameterized import parameterizedfrom rest_framework import exceptionsfrom rest_framework.exceptions import NotFound, ValidationError-from posthog.models.feature_flag import FeatureFlagfrom posthog.models.integration import Integrationfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.organization_integration import OrganizationIntegration@@ -18,6 +17,7 @@ from posthog.models.team import Teamfrom posthog.models.user import Userfrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.api.vercel.types import VercelUserClaimsfrom ee.vercel.integration import VercelIntegrationdiff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex a35ee99714af..0a0e2df30806 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -2335,15 +2335,6 @@ export interface PatchedFileSystemApi {readonly last_viewed_at?: string | null}-export interface FlagValueItemApi {- name: unknown-}--export interface FlagValueResponseApi {- results: FlagValueItemApi[]- refreshing: boolean-}-export interface SharePasswordApi {readonly id: numberreadonly created_at: string@@ -3423,13 +3414,6 @@ export type FileSystemListParams = {search?: string}-export type FlagValueValuesRetrieveParams = {- /**- * The flag ID- */- key?: string-}-export type ProjectSecretApiKeysListParams = {/*** Number of results to return per page.diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.tsindex 0eb8ea85632d..7ca3b1613898 100644--- a/frontend/src/generated/core/api.ts+++ b/frontend/src/generated/core/api.ts@@ -21,8 +21,6 @@ import type {ExportsListParams,FileSystemApi,FileSystemListParams,- FlagValueResponseApi,- FlagValueValuesRetrieveParams,InvitesListParams,OauthApplicationsListParams,OnboardingSkipRequestApi,@@ -1250,42 +1248,6 @@ export const fileSystemUnfiledRetrieve = async (projectId: string, options?: Req})}-export const getFlagValueValuesRetrieveUrl = (projectId: string, params?: FlagValueValuesRetrieveParams) => {- const normalizedParams = new URLSearchParams()-- Object.entries(params || {}).forEach(([key, value]) => {- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : value.toString())- }- })-- const stringifiedParams = normalizedParams.toString()-- return stringifiedParams.length > 0- ? `/api/projects/${projectId}/flag_value/values/?${stringifiedParams}`- : `/api/projects/${projectId}/flag_value/values/`-}--/**- * Get possible values for a feature flag.--Query parameters:-- key: The flag ID (required)-Returns:--- Array of objects with 'name' field containing possible values- */-export const flagValueValuesRetrieve = async (- projectId: string,- params?: FlagValueValuesRetrieveParams,- options?: RequestInit-): Promise<FlagValueResponseApi> => {- return apiMutator<FlagValueResponseApi>(getFlagValueValuesRetrieveUrl(projectId, params), {- ...options,- method: 'GET',- })-}-export const getInsightsSharingListUrl = (projectId: string, insightId: number) => {return `/api/projects/${projectId}/insights/${insightId}/sharing/`}diff --git a/posthog/admin/admins/experiment_admin.py b/posthog/admin/admins/experiment_admin.pyindex 5a004931fe70..0ea1e482ff17 100644--- a/posthog/admin/admins/experiment_admin.py+++ b/posthog/admin/admins/experiment_admin.py@@ -7,7 +7,7 @@ from django.shortcuts import redirectfrom django.urls import path, reversefrom django.utils.html import format_html-from posthog.models import Cohort, FeatureFlag+from posthog.models import Cohortfrom posthog.models.utils import convert_legacy_metricsfrom products.experiments.backend.models.experiment import (@@ -16,6 +16,7 @@ from products.experiments.backend.models.experiment import (ExperimentSavedMetric,ExperimentToSavedMetric,)+from products.feature_flags.backend.models.feature_flag import FeatureFlagclass ExperimentAdminForm(ModelForm):diff --git a/posthog/admin/admins/organization_admin.py b/posthog/admin/admins/organization_admin.pyindex d436295da6ab..a8010a4fe79c 100644--- a/posthog/admin/admins/organization_admin.py+++ b/posthog/admin/admins/organization_admin.py@@ -36,7 +36,11 @@ BULK_DELETE_MODEL_REGISTRY: tuple[tuple[str, str, str], ...] = ("team_id","Error Tracking Fingerprints",),- ("posthog.models.feature_flag.feature_flag.FeatureFlagHashKeyOverride", "team_id", "Feature Flag Overrides"),+ (+ "products.feature_flags.backend.models.feature_flag.FeatureFlagHashKeyOverride",+ "team_id",+ "Feature Flag Overrides",+ ),("posthog.models.group.group.Group", "team_id", "Groups"),("posthog.models.group_type_mapping.GroupTypeMapping", "team_id", "Group Type Mappings"),("posthog.models.person.Person", "team_id", "Persons"),diff --git a/posthog/api/__init__.py b/posthog/api/__init__.pyindex 813ac8911488..969eb0c27b27 100644--- a/posthog/api/__init__.py+++ b/posthog/api/__init__.py@@ -80,6 +80,7 @@ from products.error_tracking.backend.api import (ErrorTrackingSymbolSetViewSet,GitProviderFileLinksViewSet,)+from products.feature_flags.backend.api import feature_flag, flag_value, organization_feature_flag, scheduled_changefrom products.llm_analytics.backend.api import (ClusteringConfigViewSet,ClusteringJobViewSet,@@ -161,8 +162,6 @@ from . import (event_definition,event_schema,exports,- feature_flag,- flag_value,health_issue,hog,hog_function,@@ -176,7 +175,6 @@ from . import (object_media_preview,organization,organization_domain,- organization_feature_flag,organization_integration,organization_invite,organization_member,@@ -189,7 +187,6 @@ from . import (quick_filters,resource_transfer,role_external_reference,- scheduled_change,schema_property_group,search,sharing,diff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex fe8b80c1fd43..4bb458cfb053 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -44,7 +44,7 @@ from posthog.constants import LIMIT, OFFSET, PropertyOperatorTypefrom posthog.event_usage import report_user_actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.metrics import LABEL_TEAM_ID-from posthog.models import Cohort, FeatureFlag, Person, User+from posthog.models import Cohort, Person, Userfrom posthog.models.activity_logging.activity_log import (Change,Detail,@@ -63,11 +63,6 @@ from posthog.models.cohort.util import (get_friendly_error_message,)from posthog.models.cohort.validation import CohortTypeValidationSerializer-from posthog.models.feature_flag.flag_matching import (- FeatureFlagMatcher,- FlagsMatcherCache,- get_feature_flag_hash_key_overrides,-)from posthog.models.filters.filter import Filterfrom posthog.models.insight import Insightfrom posthog.models.person.person import READ_DB_FOR_PERSONS, PersonDistinctId@@ -82,6 +77,13 @@ from posthog.queries.util import get_earliest_timestampfrom posthog.renderers import SafeJSONRendererfrom posthog.utils import format_query_params_absolute_url+from products.feature_flags.backend.flag_matching import (+ FeatureFlagMatcher,+ FlagsMatcherCache,+ get_feature_flag_hash_key_overrides,+)+from products.feature_flags.backend.models.feature_flag import FeatureFlag+# Mirrors SerializedPerson in posthog/queries/actor_base_query.py.# Nullability mirrors the TypedDict: only Optional[...] fields are nullable; matched_recordings@@ -1158,7 +1160,7 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi# backfilled are allowed through.if self.request.query_params.get("hide_behavioral_cohorts", "false").lower() == "true":# Avoid circular import: feature_flag imports cohort models- from posthog.api.feature_flag import _is_realtime_cohort_flag_targeting_enabled+ from products.feature_flags.backend.api.feature_flag import _is_realtime_cohort_flag_targeting_enabledallow_realtime_backfilled = _is_realtime_cohort_flag_targeting_enabled(self.request)all_cohorts = {cohort.id: cohort for cohort in queryset.all()}diff --git a/posthog/api/documentation.py b/posthog/api/documentation.pyindex 50018e622338..b4bff5b08048 100644--- a/posthog/api/documentation.py+++ b/posthog/api/documentation.py@@ -20,10 +20,11 @@ from rest_framework import fields, serializersfrom rest_framework.exceptions import PermissionDeniedfrom posthog.models.entity import MathType-from posthog.models.feature_flag.types import PropertyFilterTypefrom posthog.models.property import OperatorType, PropertyTypefrom posthog.permissions import APIScopePermission+from products.feature_flags.backend.types import PropertyFilterType+# Path parameters that are resolved at runtime by TeamAndOrgViewSetMixin and# therefore cannot be derived from any model field. We pre-supply their# OpenAPI types so drf-spectacular never falls through to the warning path.diff --git a/posthog/api/file_system/registrations.py b/posthog/api/file_system/registrations.pyindex 6af21b50634c..0eb0a6b61cd8 100644--- a/posthog/api/file_system/registrations.py+++ b/posthog/api/file_system/registrations.py@@ -357,7 +357,7 @@ def register_core_file_system_types() -> None:register_file_system_type("feature_flag",- "posthog",+ "feature_flags","FeatureFlag",undo_message="Send PATCH /api/projects/@current/feature_flags/{id} with deleted=false.",)diff --git a/posthog/api/file_system/test/test_file_system.py b/posthog/api/file_system/test/test_file_system.pyindex 51d84043a42d..94f1e5debd1e 100644--- a/posthog/api/file_system/test/test_file_system.py+++ b/posthog/api/file_system/test/test_file_system.py@@ -11,7 +11,7 @@ from rest_framework import statusfrom rest_framework.test import APIRequestFactoryfrom posthog.api.file_system.file_system import DELETE_PREVIEW_ENTRY_LIMIT-from posthog.models import FeatureFlag, Insight, Project, Team, User+from posthog.models import Insight, Project, Team, Userfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.cohort import Cohortfrom posthog.models.file_system.file_system import FileSystem@@ -21,6 +21,7 @@ from posthog.session_recordings.models.session_recording_playlist import Sessionfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.links.backend.models import Linkfrom products.notebooks.backend.models import Notebookfrom products.surveys.backend.models import Surveydiff --git a/posthog/api/hog_flow.py b/posthog/api/hog_flow.pyindex 989b85553e7d..7542931bc2c9 100644--- a/posthog/api/hog_flow.py+++ b/posthog/api/hog_flow.py@@ -33,15 +33,15 @@ from posthog.cdp.validation import (generate_template_bytecode,)from posthog.models import Team-from posthog.models.feature_flag.user_blast_radius import (- PERSON_BATCH_SIZE,- get_user_blast_radius,- get_user_blast_radius_persons,-)from posthog.models.hog_flow.hog_flow import BILLABLE_ACTION_TYPES, HogFlowfrom posthog.models.hog_function_template import HogFunctionTemplatefrom posthog.plugins.plugin_server_api import create_hog_flow_invocation_test, create_hog_flow_scheduled_invocation+from products.feature_flags.backend.user_blast_radius import (+ PERSON_BATCH_SIZE,+ get_user_blast_radius,+ get_user_blast_radius_persons,+)from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJobfrom products.workflows.backend.models.hog_flow_schedule import SCHEDULED_TRIGGER_TYPES, HogFlowSchedulefrom products.workflows.backend.utils.rrule_utils import compute_next_occurrences, validate_rrulediff --git a/posthog/api/my_notifications.py b/posthog/api/my_notifications.pyindex da51ca0f0644..0845d8d0b147 100644--- a/posthog/api/my_notifications.py+++ b/posthog/api/my_notifications.py@@ -12,9 +12,10 @@ from rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import ServerTimingsGathered, action-from posthog.models import ActivityLog, Cohort, FeatureFlag, HogFunction, Insight, NotificationViewed, User+from posthog.models import ActivityLog, Cohort, HogFunction, Insight, NotificationViewed, Userfrom posthog.models.comment import Comment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebookdiff --git a/posthog/api/search.py b/posthog/api/search.pyindex 222266422741..2d8d757b892c 100644--- a/posthog/api/search.py+++ b/posthog/api/search.py@@ -12,13 +12,14 @@ from rest_framework.response import Responsefrom posthog.api.documentation import _FallbackSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.helpers.full_text_search import build_rank, process_query-from posthog.models import Cohort, EventDefinition, FeatureFlag, Insight, PropertyDefinition+from posthog.models import Cohort, EventDefinition, Insight, PropertyDefinitionfrom posthog.models.hog_flow.hog_flow import HogFlowfrom products.actions.backend.models.action import Actionfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebookfrom products.surveys.backend.models import Surveydiff --git a/posthog/api/team.py b/posthog/api/team.pyindex 7f0c6afd2e54..721c93c03398 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -42,7 +42,6 @@ from posthog.models.activity_logging.activity_log import ()from posthog.models.activity_logging.activity_page import activity_page_responsefrom posthog.models.data_color_theme import DataColorTheme-from posthog.models.evaluation_context import EvaluationContext, TeamDefaultEvaluationContext, normalize_context_namefrom posthog.models.event_ingestion_restriction_config import EventIngestionRestrictionConfigfrom posthog.models.filters.utils import validate_group_type_indexfrom posthog.models.group_type_mapping import cached_group_types_for_team@@ -89,6 +88,11 @@ from posthog.utils import (from products.customer_analytics.backend.models.team_customer_analytics_config import TeamCustomerAnalyticsConfigfrom products.feature_flags.backend.models import TeamFeatureFlagDefaultsConfig+from products.feature_flags.backend.models.evaluation_context import (+ EvaluationContext,+ TeamDefaultEvaluationContext,+ normalize_context_name,+)from products.signals.backend.models import SignalSourceConfigtracer = trace.get_tracer(__name__)diff --git a/posthog/api/test/__snapshots__/test_remote_config.ambr b/posthog/api/test/__snapshots__/test_remote_config.ambrdeleted file mode 100644index f0df872cc8bd..000000000000--- a/posthog/api/test/__snapshots__/test_remote_config.ambr+++ /dev/null@@ -1,68 +0,0 @@-# serializer version: 1-# name: TestRemoteConfig.test_valid_array_js- b'(function() {\n window._POSTHOG_REMOTE_CONFIG = window._POSTHOG_REMOTE_CONFIG || {};\n window._POSTHOG_REMOTE_CONFIG[\'token123\'] = {\n config: {"analytics": {"endpoint": "/i/v0/e/"}, "autocaptureExceptions": false, "autocapture_opt_out": false, "captureDeadClicks": false, "capturePerformance": {"network_timing": true, "web_vitals": false, "web_vitals_allowed_metrics": null}, "conversations": false, "defaultIdentifiedOnly": true, "elementsChainAsString": true, "errorTracking": {"autocaptureExceptions": false, "suppressionRules": []}, "hasFeatureFlags": false, "heatmaps": false, "logs": {"captureConsoleLogs": false}, "productTours": false, "sessionRecording": {"canvasFps": null, "canvasQuality": null, "consoleLogRecordingEnabled": true, "endpoint": "/s/", "eventTriggers": [], "linkedFlag": null, "masking": null, "minimumDurationMilliseconds": null, "networkPayloadCapture": null, "recordCanvas": false, "recorderVersion": "v2", "sampleRate": null, "scriptConfig": {"script": "posthog-recorder"}, "triggerMatchType": null, "urlBlocklist": [], "urlTriggers": [], "version": 1}, "supportedCompression": ["gzip", "gzip-js"], "surveys": false, "token": "token123"},\n siteApps: []\n }\n})();\n\n[MOCKED_ARRAY_JS_CONTENT]'-# ----# name: TestRemoteConfig.test_valid_config- dict({- 'analytics': dict({- 'endpoint': '/i/v0/e/',- }),- 'autocaptureExceptions': False,- 'autocapture_opt_out': False,- 'captureDeadClicks': False,- 'capturePerformance': dict({- 'network_timing': True,- 'web_vitals': False,- 'web_vitals_allowed_metrics': None,- }),- 'conversations': False,- 'defaultIdentifiedOnly': True,- 'elementsChainAsString': True,- 'errorTracking': dict({- 'autocaptureExceptions': False,- 'suppressionRules': list([- ]),- }),- 'hasFeatureFlags': False,- 'heatmaps': False,- 'logs': dict({- 'captureConsoleLogs': False,- }),- 'productTours': False,- 'sessionRecording': dict({- 'canvasFps': None,- 'canvasQuality': None,- 'consoleLogRecordingEnabled': True,- 'endpoint': '/s/',- 'eventTriggers': list([- ]),- 'linkedFlag': None,- 'masking': None,- 'minimumDurationMilliseconds': None,- 'networkPayloadCapture': None,- 'recordCanvas': False,- 'recorderVersion': 'v2',- 'sampleRate': None,- 'scriptConfig': dict({- 'script': 'posthog-recorder',- }),- 'triggerMatchType': None,- 'urlBlocklist': list([- ]),- 'urlTriggers': list([- ]),- 'version': 1,- }),- 'siteApps': list([- ]),- 'supportedCompression': list([- 'gzip',- 'gzip-js',- ]),- 'surveys': False,- 'token': 'token123',- })-# ----# name: TestRemoteConfig.test_valid_config_js- b'(function() {\n window._POSTHOG_REMOTE_CONFIG = window._POSTHOG_REMOTE_CONFIG || {};\n window._POSTHOG_REMOTE_CONFIG[\'token123\'] = {\n config: {"analytics": {"endpoint": "/i/v0/e/"}, "autocaptureExceptions": false, "autocapture_opt_out": false, "captureDeadClicks": false, "capturePerformance": {"network_timing": true, "web_vitals": false, "web_vitals_allowed_metrics": null}, "conversations": false, "defaultIdentifiedOnly": true, "elementsChainAsString": true, "errorTracking": {"autocaptureExceptions": false, "suppressionRules": []}, "hasFeatureFlags": false, "heatmaps": false, "logs": {"captureConsoleLogs": false}, "productTours": false, "sessionRecording": {"canvasFps": null, "canvasQuality": null, "consoleLogRecordingEnabled": true, "endpoint": "/s/", "eventTriggers": [], "linkedFlag": null, "masking": null, "minimumDurationMilliseconds": null, "networkPayloadCapture": null, "recordCanvas": false, "recorderVersion": "v2", "sampleRate": null, "scriptConfig": {"script": "posthog-recorder"}, "triggerMatchType": null, "urlBlocklist": [], "urlTriggers": [], "version": 1}, "supportedCompression": ["gzip", "gzip-js"], "surveys": false, "token": "token123"},\n siteApps: []\n }\n})();'-# ---diff --git a/posthog/api/test/__snapshots__/test_survey.ambr b/posthog/api/test/__snapshots__/test_survey.ambrdeleted file mode 100644index 0221335211a9..000000000000--- a/posthog/api/test/__snapshots__/test_survey.ambr+++ /dev/null@@ -1,518 +0,0 @@-# serializer version: 1-# name: TestResponsesCount.test_responses_count- '''- /* user_id:0 request:_snapshot_ */- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$survey_id'), '^"|"$', '') as survey_id,- count()- FROM events- WHERE team_id = 99999- AND event = 'survey sent'- AND timestamp >= '2024-01-21 14:40:09'- AND uuid IN- (SELECT argMax(uuid, timestamp)- FROM events- WHERE team_id = 99999- AND timestamp >= '2024-01-21 14:40:09'- AND event = 'survey sent'- GROUP BY replaceRegexpAll(JSONExtractRaw(properties, '$survey_id'), '^"|"$', ''),- CASE- WHEN COALESCE(replaceRegexpAll(JSONExtractRaw(properties, '$survey_submission_id'), '^"|"$', ''), '') = '' THEN toString(uuid)- ELSE replaceRegexpAll(JSONExtractRaw(properties, '$survey_submission_id'), '^"|"$', '')- END)- GROUP BY survey_id- '''-# ----# name: TestResponsesCount.test_responses_count_only_after_first_survey_started- '''- /* user_id:0 request:_snapshot_ */- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$survey_id'), '^"|"$', '') as survey_id,- count()- FROM events- WHERE team_id = 99999- AND event = 'survey sent'- AND timestamp >= '2024-04-25 14:40:09'- AND uuid IN- (SELECT argMax(uuid, timestamp)- FROM events- WHERE team_id = 99999- AND timestamp >= '2024-04-25 14:40:09'- AND event = 'survey sent'- GROUP BY replaceRegexpAll(JSONExtractRaw(properties, '$survey_id'), '^"|"$', ''),- CASE- WHEN COALESCE(replaceRegexpAll(JSONExtractRaw(properties, '$survey_submission_id'), '^"|"$', ''), '') = '' THEN toString(uuid)- ELSE replaceRegexpAll(JSONExtractRaw(properties, '$survey_submission_id'), '^"|"$', '')- END)- GROUP BY survey_id- '''-# ----# name: TestResponsesCount.test_responses_count_with_partial_responses- '''- /* user_id:0 request:_snapshot_ */- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$survey_id'), '^"|"$', '') as survey_id,- count()- FROM events- WHERE team_id = 99999- AND event = 'survey sent'- AND timestamp >= '2024-06-10 11:00:00'- AND uuid IN- (SELECT argMax(uuid, timestamp)- FROM events- WHERE team_id = 99999- AND timestamp >= '2024-06-10 11:00:00'- AND event = 'survey sent'- GROUP BY replaceRegexpAll(JSONExtractRaw(properties, '$survey_id'), '^"|"$', ''),- CASE- WHEN COALESCE(replaceRegexpAll(JSONExtractRaw(properties, '$survey_submission_id'), '^"|"$', ''), '') = '' THEN toString(uuid)- ELSE replaceRegexpAll(JSONExtractRaw(properties, '$survey_submission_id'), '^"|"$', '')- END)- GROUP BY survey_id- '''-# ----# name: TestSurveysAPIList.test_list_surveys- '''- SELECT "posthog_filesystem"."team_id",- "posthog_filesystem"."id",- "posthog_filesystem"."path",- "posthog_filesystem"."depth",- "posthog_filesystem"."type",- "posthog_filesystem"."ref",- "posthog_filesystem"."href",- "posthog_filesystem"."shortcut",- "posthog_filesystem"."meta",- "posthog_filesystem"."created_at",- "posthog_filesystem"."created_by_id",- "posthog_filesystem"."project_id"- FROM "posthog_filesystem"- WHERE ("posthog_filesystem"."ref" = '0001'- AND "posthog_filesystem"."team_id" = 99999- AND "posthog_filesystem"."type" = 'survey'- AND NOT ("posthog_filesystem"."shortcut"- AND "posthog_filesystem"."shortcut" IS NOT NULL))- '''-# ----# name: TestSurveysAPIList.test_list_surveys.1- '''- SELECT "posthog_filesystem"."team_id",- "posthog_filesystem"."id",- "posthog_filesystem"."path",- "posthog_filesystem"."depth",- "posthog_filesystem"."type",- "posthog_filesystem"."ref",- "posthog_filesystem"."href",- "posthog_filesystem"."shortcut",- "posthog_filesystem"."meta",- "posthog_filesystem"."created_at",- "posthog_filesystem"."created_by_id",- "posthog_filesystem"."project_id"- FROM "posthog_filesystem"- WHERE ("posthog_filesystem"."ref" = '0001'- AND "posthog_filesystem"."team_id" = 99999- AND "posthog_filesystem"."type" = 'feature_flag'- AND NOT ("posthog_filesystem"."shortcut"- AND "posthog_filesystem"."shortcut" IS NOT NULL))- '''-# ----# name: TestSurveysAPIList.test_list_surveys.10- '''- SELECT "posthog_team"."id",- "posthog_team"."uuid",- "posthog_team"."organization_id",- "posthog_team"."parent_team_id",- "posthog_team"."project_id",- "posthog_team"."api_token",- "posthog_team"."app_urls",- "posthog_team"."name",- "posthog_team"."slack_incoming_webhook",- "posthog_team"."created_at",- "posthog_team"."updated_at",- "posthog_team"."anonymize_ips",- "posthog_team"."completed_snippet_onboarding",- "posthog_team"."has_completed_onboarding_for",- "posthog_team"."onboarding_tasks",- "posthog_team"."ingested_event",- "posthog_team"."person_processing_opt_out",- "posthog_team"."secret_api_token",- "posthog_team"."secret_api_token_backup",- "posthog_team"."session_recording_opt_in",- "posthog_team"."session_recording_sample_rate",- "posthog_team"."session_recording_minimum_duration_milliseconds",- "posthog_team"."session_recording_linked_flag",- "posthog_team"."session_recording_network_payload_capture_config",- "posthog_team"."session_recording_masking_config",- "posthog_team"."session_recording_url_trigger_config",- "posthog_team"."session_recording_url_blocklist_config",- "posthog_team"."session_recording_event_trigger_config",- "posthog_team"."session_recording_trigger_match_type_config",- "posthog_team"."session_recording_trigger_groups",- "posthog_team"."session_replay_config",- "posthog_team"."session_recording_retention_period",- "posthog_team"."conversations_enabled",- "posthog_team"."conversations_settings",- "posthog_team"."proactive_tasks_enabled",- "posthog_team"."survey_config",- "posthog_team"."surveys_opt_in",- "posthog_team"."product_tours_opt_in",- "posthog_team"."capture_console_log_opt_in",- "posthog_team"."capture_performance_opt_in",- "posthog_team"."capture_dead_clicks",- "posthog_team"."autocapture_opt_out",- "posthog_team"."autocapture_web_vitals_opt_in",- "posthog_team"."autocapture_web_vitals_allowed_metrics",- "posthog_team"."autocapture_exceptions_opt_in",- "posthog_team"."autocapture_exceptions_errors_to_ignore",- "posthog_team"."logs_settings",- "posthog_team"."heatmaps_opt_in",- "posthog_team"."receive_org_level_activity_logs",- "posthog_team"."web_analytics_pre_aggregated_tables_enabled",- "posthog_team"."web_analytics_pre_aggregated_tables_version",- "posthog_team"."flags_persistence_default",- "posthog_team"."feature_flag_confirmation_enabled",- "posthog_team"."feature_flag_confirmation_message",- "posthog_team"."default_evaluation_environments_enabled",- "posthog_team"."require_evaluation_environment_tags",- "posthog_team"."default_evaluation_contexts_enabled",- "posthog_team"."require_evaluation_contexts",- "posthog_team"."session_recording_version",- "posthog_team"."signup_token",- "posthog_team"."is_demo",- "posthog_team"."access_control",- "posthog_team"."week_start_day",- "posthog_team"."inject_web_apps",- "posthog_team"."test_account_filters",- "posthog_team"."test_account_filters_default_checked",- "posthog_team"."path_cleaning_filters",- "posthog_team"."timezone",- "posthog_team"."data_attributes",- "posthog_team"."person_display_name_properties",- "posthog_team"."live_events_columns",- "posthog_team"."recording_domains",- "posthog_team"."human_friendly_comparison_periods",- "posthog_team"."cookieless_server_hash_mode",- "posthog_team"."primary_dashboard_id",- "posthog_team"."default_data_theme",- "posthog_team"."extra_settings",- "posthog_team"."modifiers",- "posthog_team"."correlation_config",- "posthog_team"."session_recording_retention_period_days",- "posthog_team"."external_data_workspace_id",- "posthog_team"."external_data_workspace_last_synced_at",- "posthog_team"."api_query_rate_limit",- "posthog_team"."revenue_tracking_config",- "posthog_team"."drop_events_older_than",- "posthog_team"."base_currency",- "posthog_team"."experiment_recalculation_time",- "posthog_team"."default_experiment_confidence_level",- "posthog_team"."default_experiment_stats_method",- "posthog_team"."business_model"- FROM "posthog_team"- WHERE "posthog_team"."api_token" = 'token123'- LIMIT 21- '''-# ----# name: TestSurveysAPIList.test_list_surveys.11- '''- SELECT "posthog_survey"."id",- "posthog_survey"."team_id",- "posthog_survey"."name",- "posthog_survey"."description",- "posthog_survey"."linked_flag_id",- "posthog_survey"."targeting_flag_id",- "posthog_survey"."linked_insight_id",- "posthog_survey"."internal_targeting_flag_id",- "posthog_survey"."internal_response_sampling_flag_id",- "posthog_survey"."type",- "posthog_survey"."conditions",- "posthog_survey"."questions",- "posthog_survey"."appearance",- "posthog_survey"."created_at",- "posthog_survey"."created_by_id",- "posthog_survey"."start_date",- "posthog_survey"."end_date",- "posthog_survey"."updated_at",- "posthog_survey"."archived",- "posthog_survey"."responses_limit",- "posthog_survey"."response_sampling_start_date",- "posthog_survey"."response_sampling_interval_type",- "posthog_survey"."response_sampling_interval",- "posthog_survey"."response_sampling_limit",- "posthog_survey"."response_sampling_daily_limits",- "posthog_survey"."iteration_count",- "posthog_survey"."iteration_frequency_days",- "posthog_survey"."iteration_start_dates",- "posthog_survey"."current_iteration",- "posthog_survey"."current_iteration_start_date",- "posthog_survey"."schedule",- "posthog_survey"."enable_partial_responses",- "posthog_survey"."enable_iframe_embedding",- "posthog_survey"."headline_summary",- "posthog_survey"."headline_response_count",- "posthog_survey"."question_summaries",- "posthog_survey"."form_content",- "posthog_survey"."translations",- "posthog_featureflag"."id",- "posthog_featureflag"."key",- "posthog_featureflag"."name",- "posthog_featureflag"."filters",- "posthog_featureflag"."team_id",- "posthog_featureflag"."created_by_id",- "posthog_featureflag"."created_at",- "posthog_featureflag"."updated_at",- "posthog_featureflag"."deleted",- "posthog_featureflag"."active",- "posthog_featureflag"."version",- "posthog_featureflag"."last_modified_by_id",- "posthog_featureflag"."rollback_conditions",- "posthog_featureflag"."performed_rollback",- "posthog_featureflag"."ensure_experience_continuity",- "posthog_featureflag"."usage_dashboard_id",- "posthog_featureflag"."has_enriched_analytics",- "posthog_featureflag"."is_remote_configuration",- "posthog_featureflag"."has_encrypted_payloads",- "posthog_featureflag"."evaluation_runtime",- "posthog_featureflag"."bucketing_identifier",- "posthog_featureflag"."last_called_at",- T5."id",- T5."key",- T5."name",- T5."filters",- T5."team_id",- T5."created_by_id",- T5."created_at",- T5."updated_at",- T5."deleted",- T5."active",- T5."version",- T5."last_modified_by_id",- T5."rollback_conditions",- T5."performed_rollback",- T5."ensure_experience_continuity",- T5."usage_dashboard_id",- T5."has_enriched_analytics",- T5."is_remote_configuration",- T5."has_encrypted_payloads",- T5."evaluation_runtime",- T5."bucketing_identifier",- T5."last_called_at",- T6."id",- T6."key",- T6."name",- T6."filters",- T6."team_id",- T6."created_by_id",- T6."created_at",- T6."updated_at",- T6."deleted",- T6."active",- T6."version",- T6."last_modified_by_id",- T6."rollback_conditions",- T6."performed_rollback",- T6."ensure_experience_continuity",- T6."usage_dashboard_id",- T6."has_enriched_analytics",- T6."is_remote_configuration",- T6."has_encrypted_payloads",- T6."evaluation_runtime",- T6."bucketing_identifier",- T6."last_called_at"- FROM "posthog_survey"- INNER JOIN "posthog_team" ON ("posthog_survey"."team_id" = "posthog_team"."id")- LEFT OUTER JOIN "posthog_featureflag" ON ("posthog_survey"."linked_flag_id" = "posthog_featureflag"."id")- LEFT OUTER JOIN "posthog_featureflag" T5 ON ("posthog_survey"."targeting_flag_id" = T5."id")- LEFT OUTER JOIN "posthog_featureflag" T6 ON ("posthog_survey"."internal_targeting_flag_id" = T6."id")- WHERE ("posthog_team"."project_id" = 99999- AND NOT ("posthog_survey"."archived"))- '''-# ----# name: TestSurveysAPIList.test_list_surveys.12- '''- SELECT ("posthog_survey_actions"."survey_id") AS "_prefetch_related_val_survey_id",- "posthog_action"."id",- "posthog_action"."name",- "posthog_action"."description",- "posthog_action"."team_id",- "posthog_action"."project_id",- "posthog_action"."created_at",- "posthog_action"."created_by_id",- "posthog_action"."deleted",- "posthog_action"."post_to_slack",- "posthog_action"."slack_message_format",- "posthog_action"."updated_at",- "posthog_action"."bytecode",- "posthog_action"."bytecode_error",- "posthog_action"."steps_json",- "posthog_action"."pinned_at",- "posthog_action"."summary",- "posthog_action"."last_summarized_at",- "posthog_action"."embedding_last_synced_at",- "posthog_action"."embedding_version",- "posthog_action"."is_calculating",- "posthog_action"."last_calculated_at"- FROM "posthog_action"- INNER JOIN "posthog_survey_actions" ON ("posthog_action"."id" = "posthog_survey_actions"."action_id")- WHERE 'posthog_survey_actions'.'survey_id' IN ('00000000-0000-0000-0000-000000000000'::uuid,- '00000000-0000-0000-0000-000000000001'::uuid, /* ... */])- '''-# ----# name: TestSurveysAPIList.test_list_surveys.2- '''- SELECT "posthog_integration"."id",- "posthog_integration"."team_id",- "posthog_integration"."kind",- "posthog_integration"."integration_id",- "posthog_integration"."config",- "posthog_integration"."sensitive_config",- "posthog_integration"."errors",- "posthog_integration"."created_at",- "posthog_integration"."created_by_id"- FROM "posthog_integration"- WHERE ("posthog_integration"."kind" = 'vercel'- AND "posthog_integration"."team_id" = 99999)- LIMIT 21- '''-# ----# name: TestSurveysAPIList.test_list_surveys.3- '''- SELECT "posthog_filesystem"."team_id",- "posthog_filesystem"."id",- "posthog_filesystem"."path",- "posthog_filesystem"."depth",- "posthog_filesystem"."type",- "posthog_filesystem"."ref",- "posthog_filesystem"."href",- "posthog_filesystem"."shortcut",- "posthog_filesystem"."meta",- "posthog_filesystem"."created_at",- "posthog_filesystem"."created_by_id",- "posthog_filesystem"."project_id"- FROM "posthog_filesystem"- WHERE ("posthog_filesystem"."ref" = '0001'- AND "posthog_filesystem"."team_id" = 99999- AND "posthog_filesystem"."type" = 'feature_flag'- AND NOT ("posthog_filesystem"."shortcut"- AND "posthog_filesystem"."shortcut" IS NOT NULL))- '''-# ----# name: TestSurveysAPIList.test_list_surveys.4- '''- SELECT "posthog_integration"."id",- "posthog_integration"."team_id",- "posthog_integration"."kind",- "posthog_integration"."integration_id",- "posthog_integration"."config",- "posthog_integration"."sensitive_config",- "posthog_integration"."errors",- "posthog_integration"."created_at",- "posthog_integration"."created_by_id"- FROM "posthog_integration"- WHERE ("posthog_integration"."kind" = 'vercel'- AND "posthog_integration"."team_id" = 99999)- LIMIT 21- '''-# ----# name: TestSurveysAPIList.test_list_surveys.5- '''- SELECT "posthog_filesystem"."team_id",- "posthog_filesystem"."id",- "posthog_filesystem"."path",- "posthog_filesystem"."depth",- "posthog_filesystem"."type",- "posthog_filesystem"."ref",- "posthog_filesystem"."href",- "posthog_filesystem"."shortcut",- "posthog_filesystem"."meta",- "posthog_filesystem"."created_at",- "posthog_filesystem"."created_by_id",- "posthog_filesystem"."project_id"- FROM "posthog_filesystem"- WHERE ("posthog_filesystem"."ref" = '0001'- AND "posthog_filesystem"."team_id" = 99999- AND "posthog_filesystem"."type" = 'feature_flag'- AND NOT ("posthog_filesystem"."shortcut"- AND "posthog_filesystem"."shortcut" IS NOT NULL))- '''-# ----# name: TestSurveysAPIList.test_list_surveys.6- '''- SELECT "posthog_integration"."id",- "posthog_integration"."team_id",- "posthog_integration"."kind",- "posthog_integration"."integration_id",- "posthog_integration"."config",- "posthog_integration"."sensitive_config",- "posthog_integration"."errors",- "posthog_integration"."created_at",- "posthog_integration"."created_by_id"- FROM "posthog_integration"- WHERE ("posthog_integration"."kind" = 'vercel'- AND "posthog_integration"."team_id" = 99999)- LIMIT 21- '''-# ----# name: TestSurveysAPIList.test_list_surveys.7- '''- SELECT "posthog_filesystem"."team_id",- "posthog_filesystem"."id",- "posthog_filesystem"."path",- "posthog_filesystem"."depth",- "posthog_filesystem"."type",- "posthog_filesystem"."ref",- "posthog_filesystem"."href",- "posthog_filesystem"."shortcut",- "posthog_filesystem"."meta",- "posthog_filesystem"."created_at",- "posthog_filesystem"."created_by_id",- "posthog_filesystem"."project_id"- FROM "posthog_filesystem"- WHERE ("posthog_filesystem"."ref" = '0001'- AND "posthog_filesystem"."team_id" = 99999- AND "posthog_filesystem"."type" = 'survey'- AND NOT ("posthog_filesystem"."shortcut"- AND "posthog_filesystem"."shortcut" IS NOT NULL))- '''-# ----# name: TestSurveysAPIList.test_list_surveys.8- '''- SELECT "posthog_user"."id",- "posthog_user"."password",- "posthog_user"."last_login",- "posthog_user"."first_name",- "posthog_user"."last_name",- "posthog_user"."is_staff",- "posthog_user"."date_joined",- "posthog_user"."uuid",- "posthog_user"."current_organization_id",- "posthog_user"."current_team_id",- "posthog_user"."email",- "posthog_user"."pending_email",- "posthog_user"."distinct_id",- "posthog_user"."is_email_verified",- "posthog_user"."requested_2fa_reset_at",- "posthog_user"."has_seen_product_intro_for",- "posthog_user"."strapi_id",- "posthog_user"."is_active",- "posthog_user"."role_at_organization",- "posthog_user"."theme_mode",- "posthog_user"."partial_notification_settings",- "posthog_user"."anonymize_data",- "posthog_user"."allow_impersonation",- "posthog_user"."toolbar_mode",- "posthog_user"."hedgehog_config",- "posthog_user"."allow_sidebar_suggestions",- "posthog_user"."shortcut_position",- "posthog_user"."passkeys_enabled_for_2fa",- "posthog_user"."events_column_config",- "posthog_user"."email_opt_in"- FROM "posthog_user"- WHERE "posthog_user"."id" = 99999- LIMIT 21- '''-# ----# name: TestSurveysAPIList.test_list_surveys.9- '''- SELECT "posthog_team"."id"- FROM "posthog_team"- WHERE ("posthog_team"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid- AND "posthog_team"."receive_org_level_activity_logs")- '''-# ---diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.pyindex d653d97d7e07..724fa2c72dbf 100644--- a/posthog/api/test/test_authentication.py+++ b/posthog/api/test/test_authentication.py@@ -47,7 +47,7 @@ from posthog.helpers.user_devices import (has_valid_known_device_cookie,)from posthog.middleware import KnownLoginDeviceCookieMiddleware-from posthog.models import FeatureFlag, User+from posthog.models import Userfrom posthog.models.instance_setting import set_instance_settingfrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.organization import Organization, OrganizationMembership@@ -56,6 +56,8 @@ from posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team.team import Teamfrom posthog.models.utils import generate_random_token_personal, hash_key_value+from products.feature_flags.backend.models.feature_flag import FeatureFlag+VALID_TEST_PASSWORD = "mighty-strong-secure-1337!!"diff --git a/posthog/api/test/test_circular_dependency_detection.py b/posthog/api/test/test_circular_dependency_detection.pyindex 8cf2182e597c..ff40bf1f3370 100644--- a/posthog/api/test/test_circular_dependency_detection.py+++ b/posthog/api/test/test_circular_dependency_detection.py@@ -7,7 +7,7 @@ from posthog.test.base import APIBaseTestfrom parameterized import parameterizedfrom rest_framework import status-from posthog.models import FeatureFlag+from products.feature_flags.backend.models.feature_flag import FeatureFlagclass TestCircularDependencyDetection(APIBaseTest):diff --git a/posthog/api/test/test_classify_auth_method.py b/posthog/api/test/test_classify_auth_method.pyindex ed957fed27ce..7127a5f672f4 100644--- a/posthog/api/test/test_classify_auth_method.py+++ b/posthog/api/test/test_classify_auth_method.py@@ -2,7 +2,6 @@ from django.test import TestCasefrom parameterized import parameterized-from posthog.api.feature_flag import _classify_auth_methodfrom posthog.auth import (JwtAuthentication,OAuthAccessTokenAuthentication,@@ -11,6 +10,8 @@ from posthog.auth import (SessionAuthentication,)+from products.feature_flags.backend.api.feature_flag import _classify_auth_method+class TestClassifyAuthMethod(TestCase):@parameterized.expand(diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex 4de4eba8980e..953a575cf4a4 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -24,7 +24,7 @@ from posthog.schema import PersonsOnEventsMode, PropertyOperatorfrom posthog.api.test.test_exports import TestExportMixinfrom posthog.clickhouse.client.execute import sync_execute-from posthog.models import FeatureFlag, Person, User+from posthog.models import Person, Userfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.async_deletion.async_deletion import AsyncDeletionfrom posthog.models.cohort import Cohort@@ -41,6 +41,7 @@ from posthog.tasks.calculate_cohort import ()from products.actions.backend.models.action import Action+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.clickhouse.materialized_columns.analyze import materialize@@ -1792,7 +1793,7 @@ [email protected],("realtime_backfilled_flag_off", CohortType.REALTIME, True, False, False),])- @patch("posthog.api.feature_flag._is_realtime_cohort_flag_targeting_enabled")+ @patch("products.feature_flags.backend.api.feature_flag._is_realtime_cohort_flag_targeting_enabled")@patch("posthog.api.cohort.report_user_action")def test_behavioral_cohort_dropdown_visibility(self,@@ -1848,7 +1849,7 @@ [email protected],else:self.assertNotIn(behavioral_cohort.id, result_ids)- @patch("posthog.api.feature_flag._is_realtime_cohort_flag_targeting_enabled")+ @patch("products.feature_flags.backend.api.feature_flag._is_realtime_cohort_flag_targeting_enabled")@patch("posthog.api.cohort.report_user_action")def test_nested_cohort_with_flag_compatible_leaf_visible_when_flag_on(self,diff --git a/posthog/api/test/test_file_system.py b/posthog/api/test/test_file_system.pyindex cb19eba670db..d88c3f70f807 100644--- a/posthog/api/test/test_file_system.py+++ b/posthog/api/test/test_file_system.py@@ -20,7 +20,6 @@ from rest_framework.test import APIRequestFactoryfrom posthog.api.file_system.file_system_logging import log_api_file_system_viewfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.cohort.cohort import Cohort-from posthog.models.feature_flag.feature_flag import FeatureFlagfrom posthog.models.file_system.file_system import FileSystemfrom posthog.models.file_system.file_system_view_log import FileSystemViewLogfrom posthog.models.hog_functions.hog_function import HogFunction, HogFunctionType@@ -31,6 +30,7 @@ from products.actions.backend.models.action import Actionfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.links.backend.models import Linkfrom products.notebooks.backend.models import Notebookfrom products.surveys.backend.models import Surveydiff --git a/posthog/api/test/test_flag_value.py b/posthog/api/test/test_flag_value.pyindex 6ea00bb2f5ae..d756df848c82 100644--- a/posthog/api/test/test_flag_value.py+++ b/posthog/api/test/test_flag_value.py@@ -2,7 +2,9 @@ from posthog.test.base import APIBaseTestfrom rest_framework import status-from posthog.models import FeatureFlag, Organization, Team+from posthog.models import Organization, Team++from products.feature_flags.backend.models.feature_flag import FeatureFlagclass TestFlagValueViewSet(APIBaseTest):diff --git a/posthog/api/test/test_hog_flow.py b/posthog/api/test/test_hog_flow.pyindex 409a6be9a603..ab558a9b0f50 100644--- a/posthog/api/test/test_hog_flow.py+++ b/posthog/api/test/test_hog_flow.py@@ -702,7 +702,7 @@ class TestHogFlowAPI(APIBaseTest):def test_hog_flow_user_blast_radius_returns_counts(self):with patch("posthog.api.hog_flow.get_user_blast_radius") as mock_get_user_blast_radius:- from posthog.models.feature_flag.user_blast_radius import BlastRadiusResult+ from products.feature_flags.backend.user_blast_radius import BlastRadiusResultmock_get_user_blast_radius.return_value = BlastRadiusResult(affected=4, total=10)diff --git a/posthog/api/test/test_local_evaluation.py b/posthog/api/test/test_local_evaluation.pyindex 9af4cf15b77f..4079b584e2e3 100644--- a/posthog/api/test/test_local_evaluation.py+++ b/posthog/api/test/test_local_evaluation.py@@ -2,8 +2,7 @@ from posthog.test.base import APIBaseTestfrom rest_framework import status-from posthog.models import FeatureFlag-+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.surveys.backend.models import Surveydiff --git a/posthog/api/test/test_organization.py b/posthog/api/test/test_organization.pyindex 4f81b107a54f..f85359fddf26 100644--- a/posthog/api/test/test_organization.py+++ b/posthog/api/test/test_organization.py@@ -16,13 +16,15 @@ from rest_framework.test import APIRequestFactoryfrom posthog.api.oauth.test_dcr import generate_rsa_keyfrom posthog.api.organization import OrganizationSerializer, _fetch_member_count, _org_serializer_cache_version-from posthog.models import FeatureFlag, Organization, OrganizationMembership, Team+from posthog.models import Organization, OrganizationMembership, Teamfrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.uploaded_media import UploadedMediafrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.user_permissions import UserPermissions+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from ee.models.explicit_team_membership import ExplicitTeamMembershipfrom ee.models.feature_flag_role_access import FeatureFlagRoleAccessfrom ee.models.rbac.access_control import AccessControldiff --git a/posthog/api/test/test_search.py b/posthog/api/test/test_search.pyindex 85daf1f3cd01..9b621cc4bda8 100644--- a/posthog/api/test/test_search.py+++ b/posthog/api/test/test_search.py@@ -7,12 +7,13 @@ from django.test.utils import CaptureQueriesContextfrom posthog.api.search import ENTITY_MAP, class_queryset, search_entitiesfrom posthog.helpers.full_text_search import build_search_vector, process_query-from posthog.models import FeatureFlag, Insight, Team+from posthog.models import Insight, Teamfrom posthog.models.hog_flow.hog_flow import HogFlowfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.event_definitions.backend.models.event_definition import EventDefinition+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebookdiff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.pyindex 2b81c8314ca5..a09e4c543a7a 100644--- a/posthog/api/test/test_team.py+++ b/posthog/api/test/test_team.py@@ -559,11 +559,12 @@ def team_api_test_factory():self.assertEqual(Team.objects.filter(organization=self.organization).count(), 2)from posthog.models.cohort import Cohort, CohortPeople- from posthog.models.feature_flag.feature_flag import FeatureFlag, FeatureFlagHashKeyOverride# from posthog.models.insight_caching_state import InsightCachingStatefrom posthog.models.person import Person+ from products.feature_flags.backend.models.feature_flag import FeatureFlag, FeatureFlagHashKeyOverride+cohort = Cohort.objects.create(team=team, created_by=self.user, name="test")person = Person.objects.create(team=team,diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.pyindex 1fd7df150fa0..bda8d3289e8d 100644--- a/posthog/api/test/test_user.py+++ b/posthog/api/test/test_user.py@@ -1525,7 +1525,7 @@ class TestUserAPI(APIBaseTest):"""Test that prepare_toolbar_preloaded_flags creates a cache entry with feature flags"""from django.core.cache import cache- from posthog.models import FeatureFlag+ from products.feature_flags.backend.models.feature_flag import FeatureFlagpatched_token.return_value = "test-cache-key-123"diff --git a/posthog/api/test/test_web_experiment.py b/posthog/api/test/test_web_experiment.pyindex d51f4250a090..68063b177a25 100644--- a/posthog/api/test/test_web_experiment.py+++ b/posthog/api/test/test_web_experiment.py@@ -32,7 +32,7 @@ class TestWebExperiment(APIBaseTest):format="json",)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_can_create_basic_web_experiment(self, mock_report_user_action):response = self._create_web_experiment()response_data = response.json()diff --git a/posthog/api/web_experiment.py b/posthog/api/web_experiment.pyindex 4a8747ab7b7c..a1032012bdfd 100644--- a/posthog/api/web_experiment.py+++ b/posthog/api/web_experiment.py@@ -11,7 +11,6 @@ from rest_framework.decorators import actionfrom rest_framework.exceptions import ValidationErrorfrom rest_framework.request import Request-from posthog.api.feature_flag import FeatureFlagSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import get_tokenfrom posthog.event_usage import report_user_action@@ -21,6 +20,7 @@ from posthog.utils_cors import cors_responsefrom products.experiments.backend.models.experiment import Experimentfrom products.experiments.backend.models.web_experiment import WebExperiment+from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializerdef validate_no_xss(content: str, field_name: str) -> None:diff --git a/posthog/approvals/actions/feature_flags.py b/posthog/approvals/actions/feature_flags.pyindex 22ecddb32052..f8e05710a997 100644--- a/posthog/approvals/actions/feature_flags.py+++ b/posthog/approvals/actions/feature_flags.py@@ -3,10 +3,11 @@ from typing import Any, Optionalfrom django.db import transaction-from posthog.api.feature_flag import FeatureFlagSerializerfrom posthog.approvals.actions.base import BaseActionfrom posthog.approvals.exceptions import ApplyFailed, PreconditionFailed-from posthog.models import FeatureFlag++from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer+from products.feature_flags.backend.models.feature_flag import FeatureFlagdef _check_version_staleness(intent_data: dict[str, Any], context: Optional[dict[str, Any]] = None) -> bool:diff --git a/posthog/approvals/tests/test_approvals_api.py b/posthog/approvals/tests/test_approvals_api.pyindex 59b1de236c94..285677214619 100644--- a/posthog/approvals/tests/test_approvals_api.py+++ b/posthog/approvals/tests/test_approvals_api.py@@ -17,7 +17,9 @@ from posthog.approvals.models import (ValidationStatus,)from posthog.constants import AvailableFeature-from posthog.models import FeatureFlag, User+from posthog.models import User++from products.feature_flags.backend.models.feature_flag import FeatureFlagclass TestApprovalsFeatureGating(APIBaseTest):diff --git a/posthog/approvals/tests/test_update_feature_flag_action.py b/posthog/approvals/tests/test_update_feature_flag_action.pyindex c1bd64f18580..90c496995b9a 100644--- a/posthog/approvals/tests/test_update_feature_flag_action.py+++ b/posthog/approvals/tests/test_update_feature_flag_action.py@@ -8,7 +8,8 @@ from parameterized import parameterizedfrom posthog.approvals.actions.feature_flags import UpdateFeatureFlagActionfrom posthog.approvals.models import ApprovalPolicy, ChangeRequestfrom posthog.approvals.policies import PolicyEngine-from posthog.models import FeatureFlag++from products.feature_flags.backend.models.feature_flag import FeatureFlagSINGLE_DICT_PATHS = {"holdout"}diff --git a/posthog/apps.py b/posthog/apps.pyindex 9a9bef7122d2..3148e8e8404e 100644--- a/posthog/apps.py+++ b/posthog/apps.py@@ -88,7 +88,7 @@ class PostHogConfig(AppConfig):# the cache is cold. In E2E testing personal_api_key is None, so a cold cache# will result in no flag definitions being loaded — which is acceptable there.if not posthoganalytics.disabled:- from posthog.feature_flags.sdk_cache_provider import HyperCacheFlagProvider+ from products.feature_flags.backend.sdk_cache_provider import HyperCacheFlagProviderposthoganalytics.flag_definition_cache_provider = HyperCacheFlagProvider( # ty: ignore[invalid-assignment]team_id=int(os.environ.get("POSTHOG_SELF_TEAM_ID", "2"))diff --git a/posthog/demo/matrix/matrix.py b/posthog/demo/matrix/matrix.pyindex 5e39d28bb5e6..f639859030a2 100644--- a/posthog/demo/matrix/matrix.py+++ b/posthog/demo/matrix/matrix.py@@ -15,9 +15,10 @@ from posthog.constants import GROUP_TYPES_LIMITfrom posthog.demo.matrix.randomization import PropertiesProviderfrom posthog.helpers.tiktoken_encoding import LLM_TOKEN_COUNT_PROXY_MODEL, get_tiktoken_encoding_for_modelfrom posthog.models import Team, User-from posthog.models.feature_flag.feature_flag import FeatureFlagfrom posthog.models.utils import UUIDT, uuid7+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from .models import Effect, SimPerson, SimServerClientdiff --git a/posthog/demo/products/hedgebox/matrix.py b/posthog/demo/products/hedgebox/matrix.pyindex a3e45ddd787c..7c49c7f0139b 100644--- a/posthog/demo/products/hedgebox/matrix.py+++ b/posthog/demo/products/hedgebox/matrix.py@@ -50,7 +50,7 @@ from posthog.demo.matrix.matrix import Cluster, Matrixfrom posthog.demo.matrix.models import SimEventfrom posthog.demo.matrix.randomization import Industryfrom posthog.exceptions_capture import capture_exception-from posthog.models import Cohort, FeatureFlag, Insight, InsightViewed+from posthog.models import Cohort, Insight, InsightViewedfrom posthog.models.event.util import create_eventfrom posthog.models.oauth import OAuthApplicationfrom posthog.storage import object_storage@@ -74,6 +74,7 @@ from products.event_definitions.backend.models.schema import (SchemaPropertyGroupProperty,)from products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetric+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.warehouse_sources.backend.models.credential import get_or_create_datawarehouse_credentialfrom products.warehouse_sources.backend.models.table import DataWarehouseTablediff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.pyindex e98e6c70efba..17f1d21cc7c0 100644--- a/posthog/hogql/database/schema/test/test_system_tables.py+++ b/posthog/hogql/database/schema/test/test_system_tables.py@@ -14,7 +14,6 @@ from posthog.models import (Annotation,Cohort,ExportedAsset,- FeatureFlag,Group,GroupTypeMapping,GroupUsageMetric,@@ -41,6 +40,7 @@ from products.early_access_features.backend.models import EarlyAccessFeaturefrom products.endpoints.backend.models import Endpoint, EndpointVersionfrom products.error_tracking.backend.models import ErrorTrackingIssue, ErrorTrackingSymbolSetfrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.llm_analytics.backend.models.review_queues import ReviewQueue, ReviewQueueItemfrom products.llm_analytics.backend.models.score_definitions import ScoreDefinitionfrom products.llm_analytics.backend.models.trace_reviews import TraceReview, TraceReviewScorediff --git a/posthog/hogql_queries/experiments/test/experiment_query_runner/base.py b/posthog/hogql_queries/experiments/test/experiment_query_runner/base.pyindex 186389b38dd7..03707d669b6b 100644--- a/posthog/hogql_queries/experiments/test/experiment_query_runner/base.py+++ b/posthog/hogql_queries/experiments/test/experiment_query_runner/base.py@@ -10,7 +10,6 @@ from posthog.clickhouse.client.execute import sync_executefrom posthog.clickhouse.preaggregation.experiment_exposures_sql import TRUNCATE_EXPERIMENT_EXPOSURES_TABLE_SQLfrom posthog.clickhouse.preaggregation.experiment_metric_events_sql import TRUNCATE_EXPERIMENT_METRIC_EVENTS_TABLE_SQLfrom posthog.hogql_queries.experiments.experiment_query_runner import MIN_PRECOMPUTATION_DURATION_SECONDS-from posthog.models.feature_flag.feature_flag import FeatureFlagfrom posthog.models.team.extensions import get_or_create_team_extensionfrom products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob@@ -18,6 +17,7 @@ from products.data_tools.backend.models.join import DataWarehouseJoinfrom products.data_warehouse.backend.test.utils import create_data_warehouse_table_from_csvfrom products.experiments.backend.models.experiment import Experimentfrom products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig+from products.feature_flags.backend.models.feature_flag import FeatureFlagTEST_BUCKET = "test_storage_bucket-posthog.hogql.experiments.queryrunner"diff --git a/posthog/hogql_queries/experiments/test/experiment_query_runner/test_experiment_exposures_query_runner.py b/posthog/hogql_queries/experiments/test/experiment_query_runner/test_experiment_exposures_query_runner.pyindex 5a4ac312d96e..a7615dab5440 100644--- a/posthog/hogql_queries/experiments/test/experiment_query_runner/test_experiment_exposures_query_runner.py+++ b/posthog/hogql_queries/experiments/test/experiment_query_runner/test_experiment_exposures_query_runner.py@@ -15,10 +15,10 @@ from posthog.hogql_queries.experiments import MULTIPLE_VARIANT_KEYfrom posthog.hogql_queries.experiments.experiment_exposures_query_runner import ExperimentExposuresQueryRunnerfrom posthog.hogql_queries.experiments.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTestfrom posthog.hogql_queries.experiments.test.experiment_query_runner.utils import create_standard_group_test_events-from posthog.models.feature_flag import FeatureFlagfrom posthog.test.test_journeys import journeys_forfrom products.actions.backend.models.action import Action+from products.feature_flags.backend.models.feature_flag import FeatureFlag@override_settings(IN_UNIT_TESTING=True)diff --git a/posthog/hogql_queries/experiments/test/experiment_query_runner/test_retention_metric.py b/posthog/hogql_queries/experiments/test/experiment_query_runner/test_retention_metric.pyindex 5f49021e2549..4c6e3cbe8397 100644--- a/posthog/hogql_queries/experiments/test/experiment_query_runner/test_retention_metric.py+++ b/posthog/hogql_queries/experiments/test/experiment_query_runner/test_retention_metric.py@@ -20,9 +20,10 @@ from posthog.schema import (from posthog.hogql_queries.experiments.experiment_query_runner import ExperimentQueryRunnerfrom posthog.hogql_queries.experiments.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTest-from posthog.models import FeatureFlagfrom posthog.test.test_journeys import journeys_for+from products.feature_flags.backend.models.feature_flag import FeatureFlag+@override_settings(IN_UNIT_TESTING=True)class TestExperimentRetentionMetric(ExperimentQueryRunnerBaseTest):diff --git a/posthog/hogql_queries/experiments/test/experiment_query_runner/utils.py b/posthog/hogql_queries/experiments/test/experiment_query_runner/utils.pyindex 848671abb884..a6f14879bdf6 100644--- a/posthog/hogql_queries/experiments/test/experiment_query_runner/utils.py+++ b/posthog/hogql_queries/experiments/test/experiment_query_runner/utils.py@@ -2,12 +2,13 @@ from datetime import datetime, timedeltafrom posthog.test.base import _create_event, _create_person-from posthog.models.feature_flag.feature_flag import FeatureFlagfrom posthog.models.filters.utils import GroupTypeIndexfrom posthog.models.group.util import create_groupfrom posthog.models.group_type_mapping import GroupTypeMappingfrom posthog.models.team.team import Team+from products.feature_flags.backend.models.feature_flag import FeatureFlag+def create_standard_group_test_events(team: Team, feature_flag: FeatureFlag):group_type_index: GroupTypeIndex = 0diff --git a/posthog/hogql_queries/experiments/test/test_experiment_funnels_query_runner.py b/posthog/hogql_queries/experiments/test/test_experiment_funnels_query_runner.pyindex 5924ea6d4be3..826f1fb30bf1 100644--- a/posthog/hogql_queries/experiments/test/test_experiment_funnels_query_runner.py+++ b/posthog/hogql_queries/experiments/test/test_experiment_funnels_query_runner.py@@ -30,10 +30,10 @@ from posthog.schema import (from posthog.constants import ExperimentNoResultsErrorKeysfrom posthog.hogql_queries.experiments.experiment_funnels_query_runner import ExperimentFunnelsQueryRunner-from posthog.models.feature_flag.feature_flag import FeatureFlagfrom posthog.test.test_journeys import journeys_forfrom products.experiments.backend.models.experiment import Experiment, ExperimentHoldout+from products.feature_flags.backend.models.feature_flag import FeatureFlagclass TestExperimentFunnelsQueryRunner(ClickhouseTestMixin, APIBaseTest):diff --git a/posthog/hogql_queries/experiments/test/test_experiment_trends_query_runner.py b/posthog/hogql_queries/experiments/test/test_experiment_trends_query_runner.pyindex 32c3f33f72d5..edc96c71e055 100644--- a/posthog/hogql_queries/experiments/test/test_experiment_trends_query_runner.py+++ b/posthog/hogql_queries/experiments/test/test_experiment_trends_query_runner.py@@ -34,13 +34,13 @@ from posthog.constants import ExperimentNoResultsErrorKeysfrom posthog.hogql_queries.experiments.experiment_trends_query_runner import ExperimentTrendsQueryRunnerfrom posthog.hogql_queries.experiments.types import ExperimentMetricTypefrom posthog.models.cohort.cohort import Cohort-from posthog.models.feature_flag.feature_flag import FeatureFlagfrom posthog.models.group.util import create_groupfrom posthog.test.test_journeys import journeys_forfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.actions.backend.models.action import Actionfrom products.experiments.backend.models.experiment import Experiment, ExperimentHoldout+from products.feature_flags.backend.models.feature_flag import FeatureFlag@override_settings(IN_UNIT_TESTING=True)diff --git a/posthog/hogql_queries/experiments/test/test_stats_config.py b/posthog/hogql_queries/experiments/test/test_stats_config.pyindex feda75893c8d..0d4e9c648469 100644--- a/posthog/hogql_queries/experiments/test/test_stats_config.py+++ b/posthog/hogql_queries/experiments/test/test_stats_config.py@@ -20,9 +20,9 @@ from posthog.hogql_queries.experiments.utils import (get_frequentist_experiment_result,split_baseline_and_test_variants,)-from posthog.models.feature_flag.feature_flag import FeatureFlagfrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagINSUFFICIENT_DATA_CASES = [("very_small_sample", {"control": (1, 0.5, 0.25), "test": (1, 0.3, 0.09)}),diff --git a/posthog/management/commands/analyze_flags_cache_sizes.py b/posthog/management/commands/analyze_flags_cache_sizes.pyindex 9cdef968fdbe..b9e688b1b7f0 100644--- a/posthog/management/commands/analyze_flags_cache_sizes.py+++ b/posthog/management/commands/analyze_flags_cache_sizes.py@@ -7,12 +7,13 @@ import jsonimport statisticsfrom posthog.management.commands._base_hypercache_command import BaseHyperCacheCommand-from posthog.models.feature_flag.flags_cache import (+from posthog.models.team import Team++from products.feature_flags.backend.flags_cache import (FLAGS_HYPERCACHE_MANAGEMENT_CONFIG,_get_feature_flags_for_service,_get_feature_flags_for_teams_batch,)-from posthog.models.team import Teamclass Command(BaseHyperCacheCommand):diff --git a/posthog/management/commands/fix_invalid_flag_property_types.py b/posthog/management/commands/fix_invalid_flag_property_types.pyindex 4ada29c2e869..5e1fe8f43e01 100644--- a/posthog/management/commands/fix_invalid_flag_property_types.py+++ b/posthog/management/commands/fix_invalid_flag_property_types.py@@ -1,6 +1,6 @@from django.core.management.base import BaseCommand-from posthog.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.feature_flag import FeatureFlag# Valid property types for feature flags (from validate_filters in api/feature_flag.py)VALID_PROPERTY_TYPES = {"person", "cohort", "group", "flag"}diff --git a/posthog/management/commands/generate_random_product_tours.py b/posthog/management/commands/generate_random_product_tours.pyindex d3fe6dd37cbe..d06b6724c71b 100644--- a/posthog/management/commands/generate_random_product_tours.py+++ b/posthog/management/commands/generate_random_product_tours.py@@ -13,10 +13,11 @@ from nanoid import generatefrom posthog.clickhouse.client import sync_executefrom posthog.constants import PRODUCT_TOUR_TARGETING_FLAG_PREFIX-from posthog.models import FeatureFlag, Team, User+from posthog.models import Team, Userfrom posthog.models.event.sql import BULK_INSERT_EVENT_SQLfrom posthog.models.person.person import Person, PersonDistinctId+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_tours.backend.models import ProductTour# Sample step content for generating realistic toursdiff --git a/posthog/management/commands/sync_feature_flags.py b/posthog/management/commands/sync_feature_flags.pyindex a803f0ba4837..6c0b91ec221a 100644--- a/posthog/management/commands/sync_feature_flags.py+++ b/posthog/management/commands/sync_feature_flags.py@@ -5,7 +5,9 @@ from typing import castfrom django.core.management.base import BaseCommand-from posthog.models import FeatureFlag, Team, User+from posthog.models import Team, User++from products.feature_flags.backend.models.feature_flag import FeatureFlag# These flags won't be enabled when syncing feature flags# Turn these on for flags that heavily change the behavior and that you wouldn't likediff --git a/posthog/management/commands/sync_feature_flags_from_api.py b/posthog/management/commands/sync_feature_flags_from_api.pyindex 48abbfa2f410..c1f9fdfb98a1 100644--- a/posthog/management/commands/sync_feature_flags_from_api.py+++ b/posthog/management/commands/sync_feature_flags_from_api.py@@ -5,9 +5,11 @@ from django.core.management.base import BaseCommandimport requests-from posthog.models import FeatureFlag, Project, User+from posthog.models import Project, Userfrom posthog.ph_client import PH_US_API_KEY+from products.feature_flags.backend.models.feature_flag import FeatureFlag+def _build_filters(flag_data: dict) -> dict:# /flags?v=2 only exposes the single variant the distinct_id evaluated to,diff --git a/posthog/management/commands/test/test_base_hypercache_command.py b/posthog/management/commands/test/test_base_hypercache_command.pyindex 2baba77d60c2..115928422238 100644--- a/posthog/management/commands/test/test_base_hypercache_command.py+++ b/posthog/management/commands/test/test_base_hypercache_command.py@@ -968,7 +968,8 @@ class TestFlagVerifyCommandScoping(BaseTest):def test_includes_teams_with_only_soft_deleted_flags(self):"""Teams where all flags are soft-deleted are still included in scope."""from posthog.management.commands.verify_flags_cache import Command as VerifyFlagsCommand- from posthog.models.feature_flag.feature_flag import FeatureFlag++ from products.feature_flags.backend.models.feature_flag import FeatureFlagFeatureFlag.objects.create(team=self.team,@@ -998,7 +999,8 @@ class TestFlagVerifyCommandScoping(BaseTest):"""verify_flag_definitions_cache uses identical scoping logic."""from posthog.management.commands.verify_flag_definitions_cache import Command as VerifyFlagDefinitionsCommandfrom posthog.models import Team as TeamModel- from posthog.models.feature_flag.feature_flag import FeatureFlag++ from products.feature_flags.backend.models.feature_flag import FeatureFlagteam_with_flag = TeamModel.objects.create(organization=self.organization, name="Has Flag")team_no_flags = TeamModel.objects.create(organization=self.organization, name="No Flags")diff --git a/posthog/management/commands/verify_flag_definitions_cache.py b/posthog/management/commands/verify_flag_definitions_cache.pyindex c64e438ba15b..471b8fe3a0cd 100644--- a/posthog/management/commands/verify_flag_definitions_cache.py+++ b/posthog/management/commands/verify_flag_definitions_cache.py@@ -25,12 +25,13 @@ Usage:from typing import Any, overridefrom posthog.management.commands._base_hypercache_command import BaseHyperCacheCommand-from posthog.models.feature_flag.local_evaluation import (+from posthog.models.team import Team++from products.feature_flags.backend.local_evaluation import (FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG,verify_team_flag_definitions,)-from posthog.models.team import Teamclass Command(BaseHyperCacheCommand):diff --git a/posthog/management/commands/verify_flags_cache.py b/posthog/management/commands/verify_flags_cache.pyindex 702ca7cf215e..2ad49c668cb3 100644--- a/posthog/management/commands/verify_flags_cache.py+++ b/posthog/management/commands/verify_flags_cache.py@@ -29,7 +29,8 @@ Usage:from typing import overridefrom posthog.management.commands._base_hypercache_command import BaseHyperCacheCommand-from posthog.models.feature_flag.flags_cache import FLAGS_HYPERCACHE_MANAGEMENT_CONFIG, verify_team_flags++from products.feature_flags.backend.flags_cache import FLAGS_HYPERCACHE_MANAGEMENT_CONFIG, verify_team_flagsclass Command(BaseHyperCacheCommand):diff --git a/posthog/management/commands/warm_flag_definitions_cache.py b/posthog/management/commands/warm_flag_definitions_cache.pyindex dd0990686a3f..a3e43ec57c60 100644--- a/posthog/management/commands/warm_flag_definitions_cache.py+++ b/posthog/management/commands/warm_flag_definitions_cache.py@@ -19,7 +19,8 @@ Usage:"""from posthog.management.commands._base_hypercache_command import BaseHyperCacheCommand-from posthog.models.feature_flag.local_evaluation import (++from products.feature_flags.backend.local_evaluation import (FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG,)diff --git a/posthog/management/commands/warm_flags_cache.py b/posthog/management/commands/warm_flags_cache.pyindex ed5812cd3183..19972f5c6066 100644--- a/posthog/management/commands/warm_flags_cache.py+++ b/posthog/management/commands/warm_flags_cache.py@@ -16,7 +16,8 @@ Usage:"""from posthog.management.commands._base_hypercache_command import BaseHyperCacheCommand-from posthog.models.feature_flag.flags_cache import FLAGS_HYPERCACHE_MANAGEMENT_CONFIG++from products.feature_flags.backend.flags_cache import FLAGS_HYPERCACHE_MANAGEMENT_CONFIGclass Command(BaseHyperCacheCommand):diff --git a/posthog/middleware.py b/posthog/middleware.pyindex 50ba35c259d8..9254378b9992 100644--- a/posthog/middleware.py+++ b/posthog/middleware.py@@ -40,7 +40,7 @@ from posthog.event_usage import get_event_source, get_mcp_properties, sanitize_hfrom posthog.geoip import get_geoip_propertiesfrom posthog.helpers.impersonation import get_original_user_from_sessionfrom posthog.helpers.user_devices import set_known_device_cookie-from posthog.models import Cohort, FeatureFlag, Insight, Team, User+from posthog.models import Cohort, Insight, Team, Userfrom posthog.models.activity_logging.utils import (ACTIVITY_LOG_CLIENT_HEADER,ACTIVITY_LOG_CLIENT_MAX_LENGTH,@@ -54,6 +54,7 @@ from posthog.utils import _is_valid_ip_addressfrom products.actions.backend.models.action import Actionfrom products.dashboards.backend.models.dashboard import Dashboard+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebookfrom .auth import PersonalAPIKeyAuthenticationdiff --git a/posthog/migrations/1115_featureflag_filters_groups_default.py b/posthog/migrations/1115_featureflag_filters_groups_default.pyindex d71349e579ba..3846e765bd0b 100644--- a/posthog/migrations/1115_featureflag_filters_groups_default.py+++ b/posthog/migrations/1115_featureflag_filters_groups_default.py@@ -2,7 +2,7 @@from django.db import migrations, models-import posthog.models.feature_flag.feature_flag+import products.feature_flags.backend.models.feature_flagclass Migration(migrations.Migration):@@ -15,7 +15,7 @@ class Migration(migrations.Migration):migrations.AlterField(model_name="featureflag",name="filters",- field=models.JSONField(default=posthog.models.feature_flag.feature_flag.default_filters),+ field=models.JSONField(default=products.feature_flags.backend.models.feature_flag.default_filters),),],database_operations=[],diff --git a/posthog/migrations/1152_fix_device_bucketing_persist_across_auth.py b/posthog/migrations/1152_fix_device_bucketing_persist_across_auth.pyindex d4c8fa93dc88..c0f113c1415d 100644--- a/posthog/migrations/1152_fix_device_bucketing_persist_across_auth.py+++ b/posthog/migrations/1152_fix_device_bucketing_persist_across_auth.py@@ -81,7 +81,7 @@ def _invalidate_flag_caches(team_ids):"""Mirror the post_save receivers in flags_cache.py and local_evaluation.pyso flag evaluation services pick up the new state — bulk_update bypassesthose signals."""- from posthog.tasks.feature_flags import update_team_flags_cache, update_team_service_flags_cache+ from products.feature_flags.backend.tasks import update_team_flags_cache, update_team_service_flags_cachefor team_id in team_ids:update_team_flags_cache.delay(team_id)diff --git a/posthog/migrations/1182_migrate_feature_flags_models.py b/posthog/migrations/1182_migrate_feature_flags_models.pynew file mode 100644index 000000000000..2ad19a1c777d--- /dev/null+++ b/posthog/migrations/1182_migrate_feature_flags_models.py@@ -0,0 +1,183 @@+# Generated by Django 5.2.13 on 2026-05-20 15:38++import django.db.models.deletion+from django.db import migrations, models++MOVED_MODELS = [+ "evaluationcontext",+ "featureflag",+ "featureflagdashboards",+ "featureflagevaluationcontext",+ "featureflaghashkeyoverride",+ "featureflagoverride",+ "scheduledchange",+ "teamdefaultevaluationcontext",+]+++def update_content_type(apps, schema_editor):+ ContentType = apps.get_model("contenttypes", "ContentType")+ for model in MOVED_MODELS:+ # On fresh DBs, post_migrate may have already created the new (feature_flags, model)+ # ContentType row before this RunPython runs. Drop the stale (posthog, model) row+ # in that case so the unique constraint on (app_label, model) doesn't fire.+ old = ContentType.objects.filter(app_label="posthog", model=model).first()+ if old is None:+ continue+ new_exists = ContentType.objects.filter(app_label="feature_flags", model=model).exists()+ if new_exists:+ old.delete()+ else:+ old.app_label = "feature_flags"+ old.save()+++def reverse_content_type(apps, schema_editor):+ ContentType = apps.get_model("contenttypes", "ContentType")+ for model in MOVED_MODELS:+ new = ContentType.objects.filter(app_label="feature_flags", model=model).first()+ if new is None:+ continue+ old_exists = ContentType.objects.filter(app_label="posthog", model=model).exists()+ if old_exists:+ new.delete()+ else:+ new.app_label = "posthog"+ new.save()+++class Migration(migrations.Migration):+ dependencies = [+ ("early_access_features", "0006_migrate_feature_flags_models"),+ ("ee", "0045_migrate_feature_flags_models"),+ ("experiments", "0015_migrate_feature_flags_models"),+ ("feature_flags", "0002_migrate_feature_flags_models"),+ ("posthog", "1181_taggeditem_endpoint_unique_constraint"),+ ("product_tours", "0007_migrate_feature_flags_models"),+ ("surveys", "0004_migrate_feature_flags_models"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ database_operations=[+ migrations.RunPython(update_content_type, reverse_content_type),+ ],+ state_operations=[+ migrations.RemoveField(+ model_name="teamdefaultevaluationcontext",+ name="evaluation_context",+ ),+ migrations.RemoveField(+ model_name="featureflagevaluationcontext",+ name="evaluation_context",+ ),+ migrations.RemoveField(+ model_name="featureflag",+ name="analytics_dashboards",+ ),+ migrations.RemoveField(+ model_name="featureflag",+ name="created_by",+ ),+ migrations.RemoveField(+ model_name="featureflag",+ name="last_modified_by",+ ),+ migrations.RemoveField(+ model_name="featureflag",+ name="team",+ ),+ migrations.RemoveField(+ model_name="featureflag",+ name="usage_dashboard",+ ),+ migrations.RemoveField(+ model_name="featureflagoverride",+ name="feature_flag",+ ),+ migrations.AlterField(+ model_name="taggeditem",+ name="feature_flag",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="tagged_items",+ to="feature_flags.featureflag",+ ),+ ),+ migrations.RemoveField(+ model_name="featureflagdashboards",+ name="feature_flag",+ ),+ migrations.RemoveField(+ model_name="featureflagevaluationcontext",+ name="feature_flag",+ ),+ migrations.RemoveField(+ model_name="featureflagdashboards",+ name="dashboard",+ ),+ migrations.AlterUniqueTogether(+ name="featureflagevaluationcontext",+ unique_together=None,+ ),+ migrations.RemoveField(+ model_name="featureflagoverride",+ name="team",+ ),+ migrations.RemoveField(+ model_name="featureflagoverride",+ name="user",+ ),+ migrations.RemoveField(+ model_name="scheduledchange",+ name="created_by",+ ),+ migrations.RemoveField(+ model_name="scheduledchange",+ name="team",+ ),+ migrations.AlterUniqueTogether(+ name="teamdefaultevaluationcontext",+ unique_together=None,+ ),+ migrations.RemoveField(+ model_name="teamdefaultevaluationcontext",+ name="team",+ ),+ migrations.RemoveField(+ model_name="featureflaghashkeyoverride",+ name="person",+ ),+ migrations.RemoveField(+ model_name="featureflaghashkeyoverride",+ name="team",+ ),+ migrations.DeleteModel(+ name="EvaluationContext",+ ),+ migrations.DeleteModel(+ name="FeatureFlag",+ ),+ migrations.DeleteModel(+ name="FeatureFlagEvaluationContext",+ ),+ migrations.DeleteModel(+ name="FeatureFlagDashboards",+ ),+ migrations.DeleteModel(+ name="FeatureFlagOverride",+ ),+ migrations.DeleteModel(+ name="ScheduledChange",+ ),+ migrations.DeleteModel(+ name="TeamDefaultEvaluationContext",+ ),+ migrations.DeleteModel(+ name="FeatureFlagHashKeyOverride",+ ),+ ],+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex ae8d0b2f7601..d4a743cad995 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1181_taggeditem_endpoint_unique_constraint+1182_migrate_feature_flags_modelsdiff --git a/posthog/models/__init__.py b/posthog/models/__init__.pyindex c18c3bff237d..354f41ec5fe6 100644--- a/posthog/models/__init__.py+++ b/posthog/models/__init__.py@@ -29,7 +29,6 @@ from ..ducklake.models import DuckgresServer, DuckLakeBackfill, DuckLakeCatalogfrom .element import Elementfrom .element_group import ElementGroupfrom .entity import Entity-from .evaluation_context import EvaluationContext, FeatureFlagEvaluationContext, TeamDefaultEvaluationContextfrom .event.event import Eventfrom .event_buffer import EventBuffer@@ -40,7 +39,6 @@ from products.event_definitions.backend.models import EventPropertyfrom .role_external_reference import RoleExternalReferencefrom .exported_asset import ExportedAssetfrom .exported_recording import ExportedRecording-from .feature_flag import FeatureFlagfrom .file_system.file_system import FileSystemfrom .file_system.file_system_view_log import FileSystemViewLogfrom .filters import Filter, RetentionFilter@@ -78,7 +76,6 @@ from .proxy_record import ProxyRecordfrom .quick_filter import QuickFilterfrom .remote_config import RemoteConfigfrom .resource_transfer.resource_transfer import ResourceTransfer-from .scheduled_change import ScheduledChangefrom products.event_definitions.backend.models import EventSchema, SchemaPropertyGroup, SchemaPropertyGroupPropertyfrom .share_password import SharePasswordfrom .sharing_configuration import SharingConfiguration@@ -141,9 +138,6 @@ __all__ = ["Element","ElementGroup","Entity",- "EvaluationContext",- "FeatureFlagEvaluationContext",- "TeamDefaultEvaluationContext","Event","EventBuffer","EventDefinition",@@ -151,7 +145,6 @@ __all__ = ["RoleExternalReference","ExportedAsset","ExportedRecording",- "FeatureFlag","FileSystem","FileSystemViewLog","Filter",@@ -235,6 +228,8 @@ __all__ = ["UserGroupMembership","UserIntegration","UserPushToken",+ "DataWarehouseTable",+ "WebAnalyticsFilterPreset","ScheduledChange","Comment",# Deprecated models here for backwards compatibilitydiff --git a/posthog/models/feature_flag/__init__.py b/posthog/models/feature_flag/__init__.pydeleted file mode 100644index 760238fd1142..000000000000--- a/posthog/models/feature_flag/__init__.py+++ /dev/null@@ -1,9 +0,0 @@-# ruff: noqa: F401, I001--from .feature_flag import (- FeatureFlag,- FeatureFlagDashboards,- get_feature_flags_for_team_in_cache,- set_feature_flags_for_team_in_cache,-)-from .user_blast_radius import BlastRadiusResult, get_user_blast_radiusdiff --git a/posthog/models/file_system/test/test_file_system.py b/posthog/models/file_system/test/test_file_system.pyindex 324d50957fb3..c3383285ffe7 100644--- a/posthog/models/file_system/test/test_file_system.py+++ b/posthog/models/file_system/test/test_file_system.py@@ -1,11 +1,12 @@from django.test import TestCase-from posthog.models import FeatureFlag, Insight, Organization, Team, User+from posthog.models import Insight, Organization, Team, Userfrom posthog.models.file_system.file_system import FileSystem, escape_path, join_path, split_pathfrom posthog.models.file_system.unfiled_file_saver import save_unfiled_filesfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebookdiff --git a/posthog/models/file_system/test/test_file_system_mixin.py b/posthog/models/file_system/test/test_file_system_mixin.pyindex b9980fafe9cb..91ab599d52a7 100644--- a/posthog/models/file_system/test/test_file_system_mixin.py+++ b/posthog/models/file_system/test/test_file_system_mixin.py@@ -1,9 +1,10 @@from django.test import TestCase-from posthog.models import FeatureFlag, FileSystem, Insight, Organization, Team, User+from posthog.models import FileSystem, Insight, Organization, Team, Userfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notebooks.backend.models import Notebookdiff --git a/posthog/models/file_system/unfiled_file_saver.py b/posthog/models/file_system/unfiled_file_saver.pyindex ed09692bef11..cb6b4ce6e5fc 100644--- a/posthog/models/file_system/unfiled_file_saver.py+++ b/posthog/models/file_system/unfiled_file_saver.py@@ -5,7 +5,6 @@ from typing import Optionalfrom django.utils import timezonefrom posthog.models.cohort import Cohort-from posthog.models.feature_flag import FeatureFlagfrom posthog.models.file_system.file_system import FileSystem, escape_path, split_pathfrom posthog.models.file_system.file_system_mixin import FileSystemSyncMixinfrom posthog.models.hog_functions.hog_function import HogFunction@@ -18,6 +17,7 @@ from products.actions.backend.models.action import Actionfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.links.backend.models import Linkfrom products.notebooks.backend.models import Notebookfrom products.surveys.backend.models import Surveydiff --git a/posthog/models/product_intent/product_intent.py b/posthog/models/product_intent/product_intent.pyindex 02e122496f5f..df1cc067dad2 100644--- a/posthog/models/product_intent/product_intent.py+++ b/posthog/models/product_intent/product_intent.py@@ -13,7 +13,6 @@ from rest_framework import serializersfrom posthog.schema import ProductIntentContext, ProductKeyfrom posthog.exceptions_capture import capture_exception-from posthog.models.feature_flag.feature_flag import FeatureFlagfrom posthog.models.hog_flow.hog_flow import HogFlowfrom posthog.models.insight import Insightfrom posthog.models.team.team import Team@@ -27,6 +26,7 @@ from products.dashboards.backend.models.dashboard import Dashboardfrom products.error_tracking.backend.models import ErrorTrackingIssuefrom products.event_definitions.backend.models.event_definition import EventDefinitionfrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_tours.backend.models import ProductTourfrom products.surveys.backend.models import Surveydiff --git a/posthog/models/remote_config.py b/posthog/models/remote_config.pyindex cf416dfe2286..ea6ed598652c 100644--- a/posthog/models/remote_config.py+++ b/posthog/models/remote_config.py@@ -15,7 +15,6 @@ from prometheus_client import Counterfrom posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIASfrom posthog.database_healthcheck import DATABASE_FOR_FLAG_MATCHINGfrom posthog.exceptions_capture import capture_exception-from posthog.models.feature_flag.feature_flag import FeatureFlagfrom posthog.models.hog_functions.hog_function import HogFunctionfrom posthog.models.js_snippet_versioning import DEFAULT_SNIPPET_VERSIONfrom posthog.models.plugin import PluginConfig@@ -26,6 +25,7 @@ from posthog.models.utils import UUIDTModel, execute_with_timeoutfrom posthog.storage.hypercache import HyperCache, HyperCacheStoreMissingfrom products.error_tracking.backend.models import ErrorTrackingSuppressionRule+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_tours.backend.models import ProductTourfrom products.surveys.backend.models import Survey@@ -195,11 +195,11 @@ class RemoteConfig(UUIDTModel):@tracer.start_as_current_span("RemoteConfig.build_config")def build_config(self):- from posthog.models.feature_flag import FeatureFlagfrom posthog.models.team import Teamfrom posthog.plugins.site import get_decide_site_appsfrom products.error_tracking.backend.remote_config import build_error_tracking_config+ from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.surveys.backend.api.survey import get_surveys_opt_in, get_surveys_response# NOTE: It is important this is changed carefully. This is what the SDK will load in place of "decide" so the formatdiff --git a/posthog/models/resource_transfer/visitors/feature_flag.py b/posthog/models/resource_transfer/visitors/feature_flag.pyindex 90d124b17756..dbeb33912df0 100644--- a/posthog/models/resource_transfer/visitors/feature_flag.py+++ b/posthog/models/resource_transfer/visitors/feature_flag.py@@ -37,7 +37,7 @@ class FeatureFlagVisitor():@classmethoddef get_model(cls) -> type[models.Model]:- from posthog.models.feature_flag import FeatureFlag+ from products.feature_flags.backend.models.feature_flag import FeatureFlagreturn FeatureFlagdiff --git a/posthog/models/resource_transfer/visitors/feature_flag_filters.py b/posthog/models/resource_transfer/visitors/feature_flag_filters.pyindex 671113d6056c..30bd5544b76a 100644--- a/posthog/models/resource_transfer/visitors/feature_flag_filters.py+++ b/posthog/models/resource_transfer/visitors/feature_flag_filters.py@@ -1,4 +1,4 @@-"""Cohort, action, and holdout references inside :class:`posthog.models.feature_flag.FeatureFlag` ``filters`` JSON."""+"""Cohort, action, and holdout references inside :class:`products.feature_flags.backend.models.feature_flag.FeatureFlag` ``filters`` JSON."""from __future__ import annotationsdiff --git a/posthog/models/scoping/test_manager.py b/posthog/models/scoping/test_manager.pyindex 8eb0dfd2d6a3..7d437642826b 100644--- a/posthog/models/scoping/test_manager.py+++ b/posthog/models/scoping/test_manager.py@@ -1,11 +1,12 @@import pytestfrom posthog.test.base import BaseTest-from posthog.models.feature_flag import FeatureFlagfrom posthog.models.scoping import team_scope, unscopedfrom posthog.models.scoping.manager import TeamScopedManager, TeamScopeErrorfrom posthog.models.team import Team+from products.feature_flags.backend.models.feature_flag import FeatureFlag+class TestTeamScopedManager(BaseTest):def _make_manager(self) -> TeamScopedManager[FeatureFlag]:diff --git a/posthog/models/tagged_item.py b/posthog/models/tagged_item.pyindex a0d88ca4f698..4ad1fc113466 100644--- a/posthog/models/tagged_item.py+++ b/posthog/models/tagged_item.py@@ -73,7 +73,7 @@ class TaggedItem(ModelActivityMixin, UUIDTModel):related_name="tagged_items",)feature_flag = models.ForeignKey(- "FeatureFlag",+ "feature_flags.FeatureFlag",on_delete=models.CASCADE,null=True,blank=True,diff --git a/posthog/models/team/util.py b/posthog/models/team/util.pyindex 3f01c619941a..79a495a211d4 100644--- a/posthog/models/team/util.py+++ b/posthog/models/team/util.py@@ -27,13 +27,13 @@ def delete_bulky_postgres_data(team_ids: list[int]):"Efficiently delete large tables for teams from postgres. Using normal CASCADE delete here can time out"from posthog.models.cohort import Cohort- from posthog.models.feature_flag.feature_flag import FeatureFlagHashKeyOverridefrom posthog.models.file_system.file_system_view_log import FileSystemViewLogfrom posthog.models.insight_caching_state import InsightCachingStatefrom products.data_modeling.backend.models import Edge, Nodefrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.error_tracking.backend.models import ErrorTrackingIssueFingerprintV2+ from products.feature_flags.backend.models.feature_flag import FeatureFlagHashKeyOverride# Delete data modeling nodes and edges first to not block Team deletion.# Team cascades to DataWarehouseSavedQuery, but it has PROTECT on delete.diff --git a/posthog/models/test/test_product_intent.py b/posthog/models/test/test_product_intent.pyindex f7e58c603610..a8030e2d82d9 100644--- a/posthog/models/test/test_product_intent.py+++ b/posthog/models/test/test_product_intent.py@@ -11,7 +11,6 @@ from parameterized import parameterizedfrom posthog.schema import ProductIntentContext, ProductKey-from posthog.models.feature_flag import FeatureFlagfrom posthog.models.file_system.user_product_list import UserProductListfrom posthog.models.hog_flow.hog_flow import HogFlowfrom posthog.models.insight import Insight@@ -30,6 +29,7 @@ from posthog.utils import get_instance_realmfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.event_definitions.backend.models.event_definition import EventDefinitionfrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.surveys.backend.models import Surveydiff --git a/posthog/models/test/test_remote_config.py b/posthog/models/test/test_remote_config.pyindex a772634d94ff..8c8c3a0ab522 100644--- a/posthog/models/test/test_remote_config.py+++ b/posthog/models/test/test_remote_config.py@@ -10,11 +10,11 @@ from django.utils import timezonefrom parameterized import parameterized-from posthog.models.feature_flag.feature_flag import FeatureFlagfrom posthog.models.project import Projectfrom posthog.models.remote_config import RemoteConfigfrom products.actions.backend.models.action import Action+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.surveys.backend.models import SurveyCONFIG_REFRESH_QUERY_COUNT = 6diff --git a/posthog/models/test/test_scheduled_change.py b/posthog/models/test/test_scheduled_change.pyindex 0891b83bc9ca..63e59e974a34 100644--- a/posthog/models/test/test_scheduled_change.py+++ b/posthog/models/test/test_scheduled_change.py@@ -2,7 +2,7 @@ import jsonfrom posthog.test.base import BaseTest-from posthog.models import ScheduledChange+from products.feature_flags.backend.models.scheduled_change import ScheduledChangeclass TestScheduledChange(BaseTest):diff --git a/posthog/person_db_router.py b/posthog/person_db_router.pyindex 6b9e0f915510..eecf3b4f490d 100644--- a/posthog/person_db_router.py+++ b/posthog/person_db_router.py@@ -43,7 +43,10 @@ class PersonDBRouter:A router to control all database operations on models in the persons database."""- PERSONS_APP_LABEL = "posthog" # Assuming all models are in the 'posthog' app+ # Apps whose models can live in the persons DB. FeatureFlagHashKeyOverride+ # was historically in the `posthog` app; it moved to `feature_flags` when the+ # FF models were extracted, but the physical table still lives in persons_db.+ PERSONS_APP_LABELS = {"posthog", "feature_flags"}def db_for_read(self, model, **hints):"""@@ -70,10 +73,10 @@ class PersonDBRouter:by default, as Django doesn't support cross-database relations natively.You might need to adjust this based on specific foreign keys (e.g., Person -> Team)."""- obj1_in_persons_db = obj1._meta.app_label == self.PERSONS_APP_LABEL and self.is_persons_model(+ obj1_in_persons_db = obj1._meta.app_label in self.PERSONS_APP_LABELS and self.is_persons_model(obj1._meta.app_label, obj1._meta.model_name)- obj2_in_persons_db = obj2._meta.app_label == self.PERSONS_APP_LABEL and self.is_persons_model(+ obj2_in_persons_db = obj2._meta.app_label in self.PERSONS_APP_LABELS and self.is_persons_model(obj2._meta.app_label, obj2._meta.model_name)@@ -133,5 +136,6 @@ class PersonDBRouter:def is_persons_model(self, app_label, model_name):# only route posthog app models, not auth.Group (there is a name clash between posthog_group- # and Django's auth_group- return app_label == "posthog" and model_name in PERSONS_DB_MODELS+ # and Django's auth_group. featureflaghashkeyoverride moved to the feature_flags app but the+ # physical table still lives in persons_db.+ return app_label in self.PERSONS_APP_LABELS and model_name in PERSONS_DB_MODELSdiff --git a/posthog/rbac/test/test_user_access_control.py b/posthog/rbac/test/test_user_access_control.pyindex 3e6b4c57c6c6..6ae294d564c2 100644--- a/posthog/rbac/test/test_user_access_control.py+++ b/posthog/rbac/test/test_user_access_control.py@@ -1020,7 +1020,7 @@ class TestUserAccessControlSpecificAccessLevelForObject(BaseUserAccessControlTesdef test_feature_flag_specific_access_control(self):"""Test feature flag-specific access controls"""- from posthog.models.feature_flag import FeatureFlag+ from products.feature_flags.backend.models.feature_flag import FeatureFlagfeature_flag = FeatureFlag.objects.create(team=self.team, created_by=self.other_user)diff --git a/posthog/tasks/__init__.py b/posthog/tasks/__init__.pyindex a60088f9741a..72028afcbecc 100644--- a/posthog/tasks/__init__.py+++ b/posthog/tasks/__init__.py@@ -9,7 +9,6 @@ from . import (early_access_feature,email,exporter,- feature_flags,health_checks,hog_flows,hog_functions,@@ -39,7 +38,6 @@ __all__ = ["early_access_feature","email","exporter",- "feature_flags","health_checks","hog_flows","hog_functions",diff --git a/posthog/tasks/hypercache_verification.py b/posthog/tasks/hypercache_verification.pyindex 455b2fe0d323..ada0890b6052 100644--- a/posthog/tasks/hypercache_verification.py+++ b/posthog/tasks/hypercache_verification.py@@ -20,14 +20,15 @@ import structlogfrom celery import shared_taskfrom posthog.exceptions_capture import capture_exception-from posthog.models.feature_flag.local_evaluation import (+from posthog.storage.hypercache_manager import HyperCacheManagementConfig+from posthog.storage.hypercache_verifier import _run_verification_for_cache+from posthog.tasks.utils import CeleryQueue, PushGatewayTask++from products.feature_flags.backend.local_evaluation import (FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG,verify_team_flag_definitions,)-from posthog.storage.hypercache_manager import HyperCacheManagementConfig-from posthog.storage.hypercache_verifier import _run_verification_for_cache-from posthog.tasks.utils import CeleryQueue, PushGatewayTasklogger = structlog.get_logger(__name__)@@ -118,7 +119,7 @@ def _run_cache_verification(cache_type: CacheType, chunk_size: int) -> None:# Import cache-specific config and verify functionif cache_type == "flags":- from posthog.models.feature_flag.flags_cache import (+ from products.feature_flags.backend.flags_cache import (FLAGS_HYPERCACHE_MANAGEMENT_CONFIG as config,verify_team_flags as verify_fn,)diff --git a/posthog/tasks/process_scheduled_changes.py b/posthog/tasks/process_scheduled_changes.pyindex d3815fc6d102..f0df533817dc 100644--- a/posthog/tasks/process_scheduled_changes.py+++ b/posthog/tasks/process_scheduled_changes.py@@ -15,7 +15,9 @@ from dateutil.relativedelta import relativedeltafrom prometheus_client import Counterfrom posthog.exceptions_capture import capture_exception-from posthog.models import FeatureFlag, ScheduledChange++from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.scheduled_change import ScheduledChangelogger = structlog.get_logger(__name__)diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 727bbf12c04d..13283cd5c923 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -16,13 +16,6 @@ from posthog.tasks.email import (send_hog_functions_daily_digest,send_matview_failure_digest,)-from posthog.tasks.feature_flags import (- cleanup_stale_flag_definitions_expiry_tracking_task,- cleanup_stale_flags_expiry_tracking_task,- compute_feature_flag_metrics,- refresh_expiring_flag_definitions_cache_entries,- refresh_expiring_flags_cache_entries,-)from posthog.tasks.hypercache_verification import (verify_and_fix_flag_definitions_cache_task,verify_and_fix_flag_definitions_without_cohorts_cache_task,@@ -78,6 +71,13 @@ from posthog.utils import get_crontab, get_instance_regionfrom products.conversations.backend.tasks import wake_snoozed_ticketsfrom products.data_modeling.backend.tasks.cleanup_test_saved_queries import cleanup_expired_test_saved_queriesfrom products.endpoints.backend.tasks import deactivate_stale_materializations+from products.feature_flags.backend.tasks import (+ cleanup_stale_flag_definitions_expiry_tracking_task,+ cleanup_stale_flags_expiry_tracking_task,+ compute_feature_flag_metrics,+ refresh_expiring_flag_definitions_cache_entries,+ refresh_expiring_flags_cache_entries,+)from products.logs.backend.tasks import logs_alert_events_cleanup_taskTWENTY_FOUR_HOURS = 24 * 60 * 60diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.pyindex 6448d5903e60..e1ff1fad604e 100644--- a/posthog/tasks/tasks.py+++ b/posthog/tasks/tasks.py@@ -859,7 +859,7 @@ def sync_insight_caching_state(@shared_task(ignore_result=True)def calculate_decide_usage() -> None:- from posthog.models.feature_flag.flag_analytics import (+ from products.feature_flags.backend.flag_analytics import (capture_usage_for_all_teams as capture_decide_usage_for_all_teams,)@@ -874,7 +874,7 @@ def calculate_decide_usage() -> None:def find_flags_with_enriched_analytics() -> None:from datetime import datetime, timedelta- from posthog.models.feature_flag.flag_analytics import find_flags_with_enriched_analytics+ from products.feature_flags.backend.flag_analytics import find_flags_with_enriched_analyticsend = datetime.now()begin = end - timedelta(hours=12)@@ -1338,7 +1338,8 @@ def sync_feature_flag_last_called(self: PushGatewayTask) -> None:from django.core.cache import cachefrom posthog.clickhouse.client import sync_execute- from posthog.models.feature_flag.feature_flag import FeatureFlag++ from products.feature_flags.backend.models.feature_flag import FeatureFlagFEATURE_FLAG_LAST_CALLED_SYNC_KEY = "posthog:feature_flag_last_called_sync:last_timestamp"LOCK_KEY = "posthog:feature_flag_last_called_sync:lock"diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex da563b1f6d09..7089c7a4d4ae 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -58,13 +58,6 @@'posthog.tasks.email.send_two_factor_auth_enabled_email','posthog.tasks.email.send_two_factor_reset_email','posthog.tasks.exporter.export_asset',- 'posthog.tasks.feature_flags.cleanup_stale_flag_definitions_expiry_tracking_task',- 'posthog.tasks.feature_flags.cleanup_stale_flags_expiry_tracking_task',- 'posthog.tasks.feature_flags.compute_feature_flag_metrics',- 'posthog.tasks.feature_flags.refresh_expiring_flag_definitions_cache_entries',- 'posthog.tasks.feature_flags.refresh_expiring_flags_cache_entries',- 'posthog.tasks.feature_flags.update_team_flags_cache',- 'posthog.tasks.feature_flags.update_team_service_flags_cache','posthog.tasks.health_checks.evaluate_health_check_for_team','posthog.tasks.hog_flows.refresh_affected_hog_flows','posthog.tasks.hog_functions.refresh_affected_hog_functions',diff --git a/posthog/tasks/test/test_calculate_cohort.py b/posthog/tasks/test/test_calculate_cohort.pyindex d22fb17e4029..5f5365f59cd8 100644--- a/posthog/tasks/test/test_calculate_cohort.py+++ b/posthog/tasks/test/test_calculate_cohort.py@@ -1106,7 +1106,7 @@ class TestCohortCalculationTasks(APIBaseTest):with (patch("posthog.models.cohort.dependencies._on_cohort_changed") as mock_dep_cache,- patch("posthog.tasks.feature_flags.update_team_flags_cache") as mock_flags_cache,+ patch("products.feature_flags.backend.tasks.update_team_flags_cache") as mock_flags_cache,patch("posthog.tasks.hog_functions.refresh_affected_hog_functions") as mock_hog_refresh,):cohort._safe_save_cohort_state(team_id=self.team.pk, processing_error=None)diff --git a/posthog/tasks/test/test_early_access_feature.py b/posthog/tasks/test/test_early_access_feature.pyindex 9a966de8c7f3..529abeb7affe 100644--- a/posthog/tasks/test/test_early_access_feature.py+++ b/posthog/tasks/test/test_early_access_feature.py@@ -3,12 +3,12 @@ from unittest.mock import MagicMock, patchfrom posthog.hogql.constants import DEFAULT_RETURNED_ROWS-from posthog.models.feature_flag.feature_flag import FeatureFlagfrom posthog.models.person.person import Personfrom posthog.models.team import Teamfrom posthog.tasks.early_access_feature import send_events_for_early_access_feature_stage_changefrom products.early_access_features.backend.models import EarlyAccessFeature+from products.feature_flags.backend.models.feature_flag import FeatureFlagclass TestSendEventsForEarlyAccessFeatureStageChange(APIBaseTest):diff --git a/posthog/tasks/test/test_hypercache_verification.py b/posthog/tasks/test/test_hypercache_verification.pyindex 3e0d9c24983f..82a942a0cc03 100644--- a/posthog/tasks/test/test_hypercache_verification.py+++ b/posthog/tasks/test/test_hypercache_verification.py@@ -191,7 +191,7 @@ class TestVerifyAndFixFlagDefinitionsCacheTask(PushGatewayTaskTestMixin, TestCas_metric: str,mock_run_verification: MagicMock,) -> None:- from posthog.models.feature_flag.local_evaluation import verify_team_flag_definitions+ from products.feature_flags.backend.local_evaluation import verify_team_flag_definitionsmock_run_verification.return_value = MagicMock()diff --git a/posthog/tasks/test/test_process_scheduled_changes.py b/posthog/tasks/test/test_process_scheduled_changes.pyindex e2391df0db04..5004d6bef5c1 100644--- a/posthog/tasks/test/test_process_scheduled_changes.py+++ b/posthog/tasks/test/test_process_scheduled_changes.py@@ -7,11 +7,14 @@ from posthog.test.base import APIBaseTest, QueryMatchingTest, snapshot_postgres_from parameterized import parameterized-from posthog.models import FeatureFlag, Organization, ScheduledChange+from posthog.models import Organizationfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.team import Teamfrom posthog.tasks.process_scheduled_changes import process_scheduled_changes+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.scheduled_change import ScheduledChange+class TestProcessScheduledChanges(APIBaseTest, QueryMatchingTest):def test_schedule_feature_flag_set_active(self) -> None:diff --git a/posthog/tasks/test/test_pushgateway_task.py b/posthog/tasks/test/test_pushgateway_task.pyindex 086fc586c502..ba53156d599d 100644--- a/posthog/tasks/test/test_pushgateway_task.py+++ b/posthog/tasks/test/test_pushgateway_task.py@@ -93,7 +93,7 @@ class TestPushGatewayTask:def test_task_name_extracted_correctly(self, mock_push_context: MagicMock, mock_registry: CollectorRegistry) -> None:- @shared_task(bind=True, base=PushGatewayTask, name="posthog.tasks.feature_flags.my_complex_task")+ @shared_task(bind=True, base=PushGatewayTask, name="products.feature_flags.backend.tasks.my_complex_task")def my_complex_task(self: Any) -> str:return "done"diff --git a/posthog/tasks/test/test_stop_surveys_reached_target.py b/posthog/tasks/test/test_stop_surveys_reached_target.pyindex ea7808697937..bbf5bede9fdf 100644--- a/posthog/tasks/test/test_stop_surveys_reached_target.py+++ b/posthog/tasks/test/test_stop_surveys_reached_target.py@@ -9,9 +9,10 @@ from django.utils.timezone import nowfrom dateutil.relativedelta import relativedelta-from posthog.models import FeatureFlag, Organization, Team, User+from posthog.models import Organization, Team, Userfrom posthog.tasks.stop_surveys_reached_target import stop_surveys_reached_target+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.surveys.backend.models import Surveydiff --git a/posthog/tasks/test/test_update_survey_adaptive_sampling.py b/posthog/tasks/test/test_update_survey_adaptive_sampling.pyindex ff2fce99a611..b344f849a8ba 100644--- a/posthog/tasks/test/test_update_survey_adaptive_sampling.py+++ b/posthog/tasks/test/test_update_survey_adaptive_sampling.py@@ -7,9 +7,9 @@ from unittest.mock import MagicMock, patchfrom django.utils import timezone-from posthog.models import FeatureFlagfrom posthog.tasks.update_survey_adaptive_sampling import update_survey_adaptive_sampling+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.surveys.backend.models import Surveydiff --git a/posthog/tasks/test/test_update_survey_iteration.py b/posthog/tasks/test/test_update_survey_iteration.pyindex ff006060a402..8cb5047e7cf8 100644--- a/posthog/tasks/test/test_update_survey_iteration.py+++ b/posthog/tasks/test/test_update_survey_iteration.py@@ -5,9 +5,10 @@ from posthog.test.base import ClickhouseTestMixinfrom django.test import TestCasefrom django.utils.timezone import now-from posthog.models import FeatureFlag, Organization, Team, User+from posthog.models import Organization, Team, Userfrom posthog.tasks.update_survey_iteration import update_survey_iteration+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.surveys.backend.models import Surveydiff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.pyindex 6e5da006cd81..954306d34176 100644--- a/posthog/tasks/test/test_usage_report.py+++ b/posthog/tasks/test/test_usage_report.py@@ -40,7 +40,6 @@ from posthog.hogql_queries.events_query_runner import EventsQueryRunnerfrom posthog.models import Organization, Plugin, Teamfrom posthog.models.app_metrics2.sql import TRUNCATE_APP_METRICS2_TABLE_SQLfrom posthog.models.event.util import create_event-from posthog.models.feature_flag import FeatureFlagfrom posthog.models.group.util import create_groupfrom posthog.models.plugin import PluginConfigfrom posthog.models.sharing_configuration import SharingConfiguration@@ -66,6 +65,7 @@ from products.dashboards.backend.models.dashboard import Dashboardfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.data_warehouse.backend.types import ExternalDataSourceTypefrom products.error_tracking.backend.models import ErrorTrackingIssue+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcediff --git a/posthog/tasks/update_survey_iteration.py b/posthog/tasks/update_survey_iteration.pyindex 97ec7cb10bc2..97f2de15f414 100644--- a/posthog/tasks/update_survey_iteration.py+++ b/posthog/tasks/update_survey_iteration.py@@ -1,8 +1,7 @@from datetime import datefrom typing import Any-from posthog.models import FeatureFlag-+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.surveys.backend.models import Surveydiff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.pyindex 4c9693623f81..fe1e2c20e7c7 100644--- a/posthog/tasks/usage_report.py+++ b/posthog/tasks/usage_report.py@@ -34,7 +34,6 @@ from posthog.constants import FlagRequestTypefrom posthog.exceptions_capture import capture_exceptionfrom posthog.logging.timing import timed_logfrom posthog.models import BatchExport, GroupTypeMapping, OrganizationMembership, User-from posthog.models.feature_flag import FeatureFlagfrom posthog.models.hog_functions.hog_function import HogFunction, HogFunctionTypefrom posthog.models.organization import Organizationfrom posthog.models.plugin import PluginConfig@@ -50,6 +49,7 @@ from posthog.utils import get_helm_info_env, get_instance_realm, get_instance_refrom products.dashboards.backend.models.dashboard import Dashboardfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.error_tracking.backend.facade import api as error_tracking_api+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.surveys.backend.models import Surveyfrom products.surveys.backend.util import (SurveyEventProperties,diff --git a/posthog/temporal/experiments/test_backfill.py b/posthog/temporal/experiments/test_backfill.pyindex c1febf278b83..5e503ba73142 100644--- a/posthog/temporal/experiments/test_backfill.py+++ b/posthog/temporal/experiments/test_backfill.py@@ -8,7 +8,6 @@ from unittest.mock import MagicMock, patchfrom posthog.schema import ExperimentQueryResponse, ExperimentStatsBaseValidated, ExperimentVariantResultFrequentistfrom posthog.models import Organization, Team, User-from posthog.models.feature_flag import FeatureFlagfrom posthog.temporal.experiments.activities import _backfill_experiment_metric_syncfrom products.experiments.backend.models.experiment import (@@ -16,6 +15,7 @@ from products.experiments.backend.models.experiment import (ExperimentMetricResult,ExperimentTimeseriesRecalculation,)+from products.feature_flags.backend.models.feature_flag import FeatureFlag@pytest.mark.django_dbdiff --git a/posthog/temporal/experiments/test_recalculation_time_filter.py b/posthog/temporal/experiments/test_recalculation_time_filter.pyindex b6c77f6c72ac..9e6a6f72a304 100644--- a/posthog/temporal/experiments/test_recalculation_time_filter.py+++ b/posthog/temporal/experiments/test_recalculation_time_filter.py@@ -6,12 +6,12 @@ import pytestfrom unittest.mock import patchfrom posthog.models import Organization, Team, User-from posthog.models.feature_flag import FeatureFlagfrom posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.temporal.experiments.activities import _get_experiment_regular_metrics_for_hour_syncfrom products.experiments.backend.models.experiment import Experimentfrom products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig+from products.feature_flags.backend.models.feature_flag import FeatureFlagdef _create_running_experiment(team, user, flag_key, metrics=None):diff --git a/posthog/temporal/experiments/test_significance_transition.py b/posthog/temporal/experiments/test_significance_transition.pyindex 235c16a39bbb..281acd4b04ea 100644--- a/posthog/temporal/experiments/test_significance_transition.py+++ b/posthog/temporal/experiments/test_significance_transition.py@@ -7,10 +7,10 @@ from unittest.mock import MagicMock, patchfrom parameterized import parameterized-from posthog.models.feature_flag import FeatureFlagfrom posthog.temporal.experiments.utils import check_significance_transitionfrom products.experiments.backend.models.experiment import Experiment, ExperimentMetricResult+from products.feature_flags.backend.models.feature_flag import FeatureFlagMETRIC_DICT = {"uuid": "metric-123",diff --git a/posthog/temporal/usage_report/queries.py b/posthog/temporal/usage_report/queries.pyindex 937613b3bd03..497e40f008a7 100644--- a/posthog/temporal/usage_report/queries.py+++ b/posthog/temporal/usage_report/queries.py@@ -47,7 +47,6 @@ from django.db.models import Countfrom posthog.constants import FlagRequestTypefrom posthog.models import GroupTypeMapping-from posthog.models.feature_flag import FeatureFlagfrom posthog.tasks.usage_report import (get_all_event_metrics_in_period,get_teams_with_active_batch_exports_in_period,@@ -87,6 +86,7 @@ from posthog.tasks.usage_report import (from products.dashboards.backend.models.dashboard import Dashboardfrom products.error_tracking.backend.facade import api as error_tracking_api+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.surveys.backend.models import Survey# ---- Postgres ORM / API helpers ---------------------------------------------diff --git a/posthog/temporal/weekly_digest/queries.py b/posthog/temporal/weekly_digest/queries.pyindex c7c1a4ba79ca..eef086b4679a 100644--- a/posthog/temporal/weekly_digest/queries.py+++ b/posthog/temporal/weekly_digest/queries.py@@ -4,7 +4,6 @@ from django.db.models import Count, Q, QuerySetfrom posthog.helpers.session_recording_playlist_templates import DEFAULT_PLAYLIST_NAMESfrom posthog.models import Organization-from posthog.models.feature_flag import FeatureFlagfrom posthog.models.file_system.user_product_list import UserProductListfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team import Team@@ -14,6 +13,7 @@ from posthog.sync import database_sync_to_asyncfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.event_definitions.backend.models.event_definition import EventDefinitionfrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.surveys.backend.models import Surveyfrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcediff --git a/posthog/test/activity_logging/test_feature_flag_activity_logging.py b/posthog/test/activity_logging/test_feature_flag_activity_logging.pyindex 592174dee87b..afc181407692 100644--- a/posthog/test/activity_logging/test_feature_flag_activity_logging.py+++ b/posthog/test/activity_logging/test_feature_flag_activity_logging.py@@ -4,9 +4,10 @@ from posthog.test.base import APIBaseTestfrom dateutil import parser-from posthog.models import FeatureFlagfrom posthog.models.activity_logging.activity_log import Change, changes_between+from products.feature_flags.backend.models.feature_flag import FeatureFlag+class TestChangesBetweenFeatureFlags(APIBaseTest):def test_comparing_two_nothings_results_in_no_changes(self) -> None:diff --git a/posthog/test/test_feature_flag_analytics.py b/posthog/test/test_feature_flag_analytics.pyindex 5b97b986578c..23f33f7f7bb6 100644--- a/posthog/test/test_feature_flag_analytics.py+++ b/posthog/test/test_feature_flag_analytics.py@@ -18,10 +18,11 @@ from unittest.mock import MagicMock, patchfrom django.core.cache import cachefrom posthog import redis-from posthog.api.feature_flag import _create_usage_dashboardfrom posthog.constants import FlagRequestType-from posthog.models.feature_flag.feature_flag import FeatureFlag-from posthog.models.feature_flag.flag_analytics import (+from posthog.models.team.team import Team++from products.feature_flags.backend.api.feature_flag import _create_usage_dashboard+from products.feature_flags.backend.flag_analytics import (SDK_LIBRARIES,_extract_sdk_breakdown_from_redis,_flag_key_filter_sql,@@ -33,7 +34,7 @@ from posthog.models.feature_flag.flag_analytics import (get_team_request_library_key,increment_request_count,)-from posthog.models.team.team import Team+from products.feature_flags.backend.models.feature_flag import FeatureFlagclass TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):@@ -50,7 +51,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):r.delete(key)return super().setUp()- @patch("posthog.models.feature_flag.flag_analytics.CACHE_BUCKET_SIZE", 10)+ @patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)def test_increment_request_count_adds_requests_to_appropriate_buckets(self):team_id = 3other_team_id = 1243@@ -85,7 +86,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):)self.assertEqual(client.hgetall(f"posthog:decide_requests:other"), {})- @patch("posthog.models.feature_flag.flag_analytics.CACHE_BUCKET_SIZE", 10)+ @patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)def test_capture_team_decide_usage(self):mock_capture = MagicMock()team_id = 3@@ -169,7 +170,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):},)- @patch("posthog.models.feature_flag.flag_analytics.CACHE_BUCKET_SIZE", 10)+ @patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)def test_no_token_loses_capture_team_decide_usage_data(self):mock_capture = MagicMock()team_id = 3@@ -232,7 +233,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):},)- @patch("posthog.models.feature_flag.flag_analytics.CACHE_BUCKET_SIZE", 10)+ @patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)def test_efficient_querying_of_team_decide_usage_data(self):mock_capture = MagicMock()team_id = 3901@@ -305,7 +306,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):@pytest.mark.skip(reason="This works locally, but causes issues in CI because the freeze_time applies to threads as well in unrelated tests, causing timeouts.")- @patch("posthog.models.feature_flag.flag_analytics.CACHE_BUCKET_SIZE", 10)+ @patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)def test_no_interference_between_different_types_of_new_incoming_increments(self):# we want freezetime to apply to threads too.# However, the list can't be empty, so we need to add something.@@ -406,7 +407,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):@pytest.mark.skip(reason="This works locally, but causes issues in CI because the freeze_time applies to threads as well in unrelated tests, causing timeouts.")- @patch("posthog.models.feature_flag.flag_analytics.CACHE_BUCKET_SIZE", 10)+ @patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)def test_locking_works_for_capture_team_decide_usage(self):# we want freezetime to apply to threads too.# However, the list can't be empty, so we need to add something.@@ -497,7 +498,7 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):@pytest.mark.skip(reason="This works locally, but causes issues in CI because the freeze_time applies to threads as well in unrelated tests, causing timeouts.")- @patch("posthog.models.feature_flag.flag_analytics.CACHE_BUCKET_SIZE", 10)+ @patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)def test_locking_in_redis_doesnt_block_new_incoming_increments(self):# we want freezetime to apply to threads too.# However, the list can't be empty, so we need to add something.@@ -618,7 +619,7 @@ class TestSdkBreakdown(BaseTest):]self.assertEqual(SDK_LIBRARIES, expected_libraries)- @patch("posthog.models.feature_flag.flag_analytics.CACHE_BUCKET_SIZE", 10)+ @patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)def test_extract_sdk_breakdown_from_redis_empty(self):client = redis.get_client()team_id = 999@@ -627,7 +628,7 @@ class TestSdkBreakdown(BaseTest):result = _extract_sdk_breakdown_from_redis(client, team_id, FlagRequestType.DECIDE)self.assertEqual(result, {})- @patch("posthog.models.feature_flag.flag_analytics.CACHE_BUCKET_SIZE", 10)+ @patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)def test_extract_sdk_breakdown_from_redis_with_data(self):client = redis.get_client()team_id = 888@@ -661,7 +662,7 @@ class TestSdkBreakdown(BaseTest):{b"165192619": b"5"},)- @patch("posthog.models.feature_flag.flag_analytics.CACHE_BUCKET_SIZE", 10)+ @patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)def test_capture_team_decide_usage_includes_sdk_breakdown(self):mock_capture = MagicMock()team_id = 777@@ -707,7 +708,7 @@ class TestSdkBreakdown(BaseTest):},)- @patch("posthog.models.feature_flag.flag_analytics.CACHE_BUCKET_SIZE", 10)+ @patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)def test_capture_team_decide_usage_without_sdk_breakdown(self):mock_capture = MagicMock()team_id = 666@@ -746,7 +747,7 @@ class TestSdkBreakdown(BaseTest):},)- @patch("posthog.models.feature_flag.flag_analytics.CACHE_BUCKET_SIZE", 10)+ @patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)def test_capture_local_evaluation_usage_includes_sdk_breakdown(self):mock_capture = MagicMock()team_id = 555@@ -789,7 +790,7 @@ class TestSdkBreakdown(BaseTest):},)- @patch("posthog.models.feature_flag.flag_analytics.CACHE_BUCKET_SIZE", 10)+ @patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)def test_extract_sdk_breakdown_uses_pipelining_for_all_sdks(self):"""Verify that SDK breakdown extraction works correctly with many SDKs.@@ -836,7 +837,7 @@ class TestSdkBreakdown(BaseTest):remaining = client.hgetall(f"posthog:decide_requests:sdk:{team_id}:{sdk}")self.assertEqual(remaining, {b"165192619": b"1"}, f"SDK {sdk} should only have bucket 2 remaining")- @patch("posthog.models.feature_flag.flag_analytics.CACHE_BUCKET_SIZE", 10)+ @patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)def test_extract_sdk_breakdown_handles_single_bucket_gracefully(self):"""Verify that SDKs with only one bucket (still being filled) are not extracted.@@ -1036,7 +1037,7 @@ class TestCrossProjectEvaluations(ClickhouseTestMixin, APIBaseTest):def test_returns_none_when_clickhouse_fails(self):with patch(- "posthog.models.feature_flag.flag_analytics.sync_execute",+ "products.feature_flags.backend.flag_analytics.sync_execute",side_effect=RuntimeError("boom"),):assert get_evaluations_7d_by_team("my_flag", [self.team.id, 99]) is None@@ -1049,7 +1050,7 @@ class TestCachedCrossProjectEvaluations(ClickhouseTestMixin, APIBaseTest):def test_cached_returns_same_result_on_second_call(self):with patch(- "posthog.models.feature_flag.flag_analytics.get_evaluations_7d_by_team",+ "products.feature_flags.backend.flag_analytics.get_evaluations_7d_by_team",return_value={self.team.id: 5},) as spy:first = get_cached_evaluations_7d_by_team("my_flag", [self.team.id])@@ -1061,7 +1062,7 @@ class TestCachedCrossProjectEvaluations(ClickhouseTestMixin, APIBaseTest):def test_failure_results_are_not_cached(self):with patch(- "posthog.models.feature_flag.flag_analytics.get_evaluations_7d_by_team",+ "products.feature_flags.backend.flag_analytics.get_evaluations_7d_by_team",side_effect=[None, {self.team.id: 7}],) as spy:first = get_cached_evaluations_7d_by_team("my_flag", [self.team.id])@@ -1078,7 +1079,7 @@ class TestCachedCrossProjectEvaluations(ClickhouseTestMixin, APIBaseTest):class TestFlagKeyFilterSQL(BaseTest):def test_falls_back_to_json_extract_when_not_materialized(self):with patch(- "posthog.models.feature_flag.flag_analytics.get_materialized_column_for_property",+ "products.feature_flags.backend.flag_analytics.get_materialized_column_for_property",return_value=None,):sql = _flag_key_filter_sql()@@ -1088,7 +1089,7 @@ class TestFlagKeyFilterSQL(BaseTest):fake_column = MagicMock()fake_column.name = "mat_$feature_flag"with patch(- "posthog.models.feature_flag.flag_analytics.get_materialized_column_for_property",+ "products.feature_flags.backend.flag_analytics.get_materialized_column_for_property",return_value=fake_column,):sql = _flag_key_filter_sql()diff --git a/posthog/test/test_flags_redis_cache.py b/posthog/test/test_flags_redis_cache.pyindex 84bff8907068..80a8b4a8523a 100644--- a/posthog/test/test_flags_redis_cache.py+++ b/posthog/test/test_flags_redis_cache.py@@ -14,8 +14,8 @@ from django.core.cache import cachefrom django.test import override_settingsfrom posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIAS, write_flags_to_cache-from posthog.models import FeatureFlag-from posthog.models.feature_flag import set_feature_flags_for_team_in_cache++from products.feature_flags.backend.models.feature_flag import FeatureFlag, set_feature_flags_for_team_in_cacheclass TestFlagsRedisCache(BaseTest):diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.pyindex 9bb96b2721b7..0f8161637b4b 100644--- a/posthog/test/test_middleware.py+++ b/posthog/test/test_middleware.py@@ -26,7 +26,7 @@ from social_core.exceptions import AuthCanceled, AuthFailed, AuthMissingParametefrom posthog.api.test.test_organization import create_organizationfrom posthog.api.test.test_team import create_teamfrom posthog.middleware import per_request_logging_context_middleware-from posthog.models import Cohort, FeatureFlag, Insight+from posthog.models import Cohort, Insightfrom posthog.models.organization import Organizationfrom posthog.models.team import Teamfrom posthog.models.user import User@@ -34,6 +34,7 @@ from posthog.settings import SITE_URLfrom products.actions.backend.models.action import Actionfrom products.dashboards.backend.models.dashboard import Dashboard+from products.feature_flags.backend.models.feature_flag import FeatureFlagdef _social_auth_backend() -> BaseAuth:diff --git a/posthog/test/test_rate_limit.py b/posthog/test/test_rate_limit.pyindex 1e7df4c92604..80a5b43aaabf 100644--- a/posthog/test/test_rate_limit.py+++ b/posthog/test/test_rate_limit.py@@ -13,7 +13,6 @@ from parameterized import parameterizedfrom rest_framework import statusfrom posthog import models, rate_limit-from posthog.api.feature_flag import LocalEvaluationThrottle, RemoteConfigThrottlefrom posthog.api.test.test_team import create_teamfrom posthog.api.test.test_user import create_userfrom posthog.models import Team@@ -30,6 +29,8 @@ from posthog.rate_limit import (get_route_from_path,)+from products.feature_flags.backend.api.feature_flag import LocalEvaluationThrottle, RemoteConfigThrottle+class TestUserAPI(APIBaseTest):def setUp(self):@@ -649,7 +650,7 @@ class TestUserAPI(APIBaseTest):mock_request = Mock()with (- patch("posthog.api.feature_flag.LOCAL_EVAL_RATE_LIMITS", {}),+ patch("products.feature_flags.backend.api.feature_flag.LOCAL_EVAL_RATE_LIMITS", {}),patch.object(throttle, "safely_get_team_id_from_view", return_value=123),patch.object(throttle.__class__.__bases__[0], "allow_request", return_value=True),):@@ -667,7 +668,7 @@ class TestUserAPI(APIBaseTest):mock_request = Mock()with (- patch("posthog.api.feature_flag.LOCAL_EVAL_RATE_LIMITS", {}),+ patch("products.feature_flags.backend.api.feature_flag.LOCAL_EVAL_RATE_LIMITS", {}),patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True),patch.object(throttle, "safely_get_team_id_from_view", return_value=123),patch.object(throttle.__class__.__bases__[0], "allow_request", return_value=True),@@ -702,7 +703,7 @@ class TestUserAPI(APIBaseTest):mock_request = Mock()with (- patch("posthog.api.feature_flag.LOCAL_EVAL_RATE_LIMITS", {123: "1200/minute"}),+ patch("products.feature_flags.backend.api.feature_flag.LOCAL_EVAL_RATE_LIMITS", {123: "1200/minute"}),patch.object(throttle, "safely_get_team_id_from_view", return_value=123),patch.object(throttle.__class__.__bases__[0], "allow_request", return_value=True),):@@ -722,7 +723,7 @@ class TestUserAPI(APIBaseTest):mock_request = Mock()with (- patch("posthog.api.feature_flag.REMOTE_CONFIG_RATE_LIMITS", {}),+ patch("products.feature_flags.backend.api.feature_flag.REMOTE_CONFIG_RATE_LIMITS", {}),patch.object(throttle, "safely_get_team_id_from_view", return_value=123),patch.object(throttle.__class__.__bases__[0], "allow_request", return_value=True),):@@ -740,7 +741,7 @@ class TestUserAPI(APIBaseTest):mock_request = Mock()with (- patch("posthog.api.feature_flag.REMOTE_CONFIG_RATE_LIMITS", {}),+ patch("products.feature_flags.backend.api.feature_flag.REMOTE_CONFIG_RATE_LIMITS", {}),patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True),patch.object(throttle, "safely_get_team_id_from_view", return_value=123),patch.object(throttle.__class__.__bases__[0], "allow_request", return_value=True),@@ -775,7 +776,7 @@ class TestUserAPI(APIBaseTest):mock_request = Mock()with (- patch("posthog.api.feature_flag.REMOTE_CONFIG_RATE_LIMITS", {123: "1200/minute"}),+ patch("products.feature_flags.backend.api.feature_flag.REMOTE_CONFIG_RATE_LIMITS", {123: "1200/minute"}),patch.object(throttle, "safely_get_team_id_from_view", return_value=123),patch.object(throttle.__class__.__bases__[0], "allow_request", return_value=True),):diff --git a/products/actions/backend/api/test/test_action.py b/products/actions/backend/api/test/test_action.pyindex 4760f1edd386..e04e55bf1ddc 100644--- a/products/actions/backend/api/test/test_action.py+++ b/products/actions/backend/api/test/test_action.py@@ -500,9 +500,8 @@ class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert data[0]["name"] == "Legacy insight"def test_references_returns_experiment_using_action(self):- from posthog.models.feature_flag import FeatureFlag-from products.experiments.backend.models.experiment import Experiment+ from products.feature_flags.backend.models.feature_flag import FeatureFlagaction = Action.objects.create(team=self.team, name="test action", steps_json=[{"event": "$pageview"}])flag = FeatureFlag.objects.create(team=self.team, key="exp-flag", created_by=self.user)@@ -600,9 +599,8 @@ class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert response.json() == []def test_references_does_not_return_deleted_experiments(self):- from posthog.models.feature_flag import FeatureFlag-from products.experiments.backend.models.experiment import Experiment+ from products.feature_flags.backend.models.feature_flag import FeatureFlagaction = Action.objects.create(team=self.team, name="test action", steps_json=[{"event": "$pageview"}])flag = FeatureFlag.objects.create(team=self.team, key="deleted-exp-flag", created_by=self.user)@@ -754,9 +752,8 @@ class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert counts[action_without_refs.id] == 0def test_include_reference_count_counts_across_all_resource_types(self):- from posthog.models.feature_flag import FeatureFlag-from products.experiments.backend.models.experiment import Experiment+ from products.feature_flags.backend.models.feature_flag import FeatureFlagaction = Action.objects.create(team=self.team, name="widely used action", steps_json=[{"event": "$pageview"}])diff --git a/products/early_access_features/backend/api.py b/products/early_access_features/backend/api.pyindex c8eccf74f0c4..2232e081e727 100644--- a/products/early_access_features/backend/api.py+++ b/products/early_access_features/backend/api.py@@ -12,22 +12,23 @@ from rest_framework.response import Responsefrom posthog.schema import ProductKey-from posthog.api.feature_flag import (- FeatureFlagSerializer,- MinimalFeatureFlagSerializer,- warn_if_missing_feature_flag_write_scope,-)from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import get_tokenfrom posthog.cdp.internal_events import InternalEventEvent, InternalEventPerson, produce_internal_eventfrom posthog.exceptions import generate_exception_response-from posthog.models.feature_flag.feature_flag import FeatureFlagfrom posthog.models.team.team import Teamfrom posthog.models.utils import uuid7from posthog.tasks.early_access_feature import send_events_for_early_access_feature_stage_changefrom posthog.utils_cors import cors_response+from products.feature_flags.backend.api.feature_flag import (+ FeatureFlagSerializer,+ MinimalFeatureFlagSerializer,+ warn_if_missing_feature_flag_write_scope,+)+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from .models import EarlyAccessFeaturelogger = structlog.get_logger(__name__)diff --git a/products/early_access_features/backend/migrations/0006_migrate_feature_flags_models.py b/products/early_access_features/backend/migrations/0006_migrate_feature_flags_models.pynew file mode 100644index 000000000000..f4862fa1f070--- /dev/null+++ b/products/early_access_features/backend/migrations/0006_migrate_feature_flags_models.py@@ -0,0 +1,31 @@+# Generated by Django 5.2.13 on 2026-05-20 15:38++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("early_access_features", "0005_clear_concept_super_groups"),+ ("feature_flags", "0002_migrate_feature_flags_models"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AlterField(+ model_name="earlyaccessfeature",+ name="feature_flag",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.PROTECT,+ related_name="features",+ related_query_name="feature",+ to="feature_flags.featureflag",+ ),+ ),+ ],+ database_operations=[],+ ),+ ]diff --git a/products/early_access_features/backend/migrations/max_migration.txt b/products/early_access_features/backend/migrations/max_migration.txtindex 61716557c0a1..83c91681da3a 100644--- a/products/early_access_features/backend/migrations/max_migration.txt+++ b/products/early_access_features/backend/migrations/max_migration.txt@@ -1 +1 @@-0005_clear_concept_super_groups\ No newline at end of file+0006_migrate_feature_flags_modelsdiff --git a/products/early_access_features/backend/models.py b/products/early_access_features/backend/models.pyindex 63649aab0eee..28f0a3e83d18 100644--- a/products/early_access_features/backend/models.py+++ b/products/early_access_features/backend/models.py@@ -35,7 +35,7 @@ class EarlyAccessFeature(FileSystemSyncMixin, RootTeamMixin, UUIDTModel):related_query_name="feature",)feature_flag = models.ForeignKey(- "posthog.FeatureFlag",+ "feature_flags.FeatureFlag",null=True,blank=True,on_delete=models.PROTECT,diff --git a/products/early_access_features/backend/test/test_early_access_feature.py b/products/early_access_features/backend/test/test_early_access_feature.pyindex 6277bde650a2..9f866a216b08 100644--- a/products/early_access_features/backend/test/test_early_access_feature.py+++ b/products/early_access_features/backend/test/test_early_access_feature.py@@ -11,10 +11,11 @@ from parameterized import parameterizedfrom rest_framework import statusfrom posthog.api.test.test_personal_api_keys import PersonalAPIKeysBaseTest-from posthog.models import FeatureFlag, Person+from posthog.models import Personfrom posthog.models.team.team_caching import set_team_in_cachefrom products.early_access_features.backend.models import EarlyAccessFeature+from products.feature_flags.backend.models.feature_flag import FeatureFlagclass TestEarlyAccessFeatureSiteAppTemplate(unittest.TestCase):@@ -789,7 +790,7 @@ class TestEarlyAccessFeature(APIBaseTest):assert {"custom": "data", "number": 42} in payloadsassert {} in payloads- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_creation_context_is_set_to_early_access_features(self, mock_report_user_action):response = self.client.post(f"/api/projects/{self.team.id}/early_access_feature/",diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex be6827f95f50..381260d3f14a 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -20,13 +20,10 @@ from rest_framework.exceptions import ValidationErrorfrom posthog.schema import ActionsNode, ExperimentEventExposureConfig, ExperimentFunnelMetric, ExperimentMetricfrom posthog.api.cohort import CohortSerializer-from posthog.api.feature_flag import FeatureFlagSerializerfrom posthog.event_usage import EventSource, report_user_actionfrom posthog.hogql_queries.experiments.experiment_metric_fingerprint import compute_metric_fingerprintfrom posthog.hogql_queries.experiments.funnel_validation import FunnelDWValidatorfrom posthog.models.cohort import Cohort-from posthog.models.evaluation_context import FeatureFlagEvaluationContext-from posthog.models.feature_flag.feature_flag import FeatureFlagfrom posthog.models.filters.filter import Filterfrom posthog.models.signals import mute_selected_signalsfrom posthog.models.team.extensions import get_or_create_team_extension@@ -45,6 +42,9 @@ from products.experiments.backend.models.experiment import (holdout_filters_for_flag,)from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig+from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer+from products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContext+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.notifications.backend.facade.api import (NotificationData,NotificationType,diff --git a/products/experiments/backend/max_tools.py b/products/experiments/backend/max_tools.pyindex af18212e0dd3..2f3cb00c11b5 100644--- a/products/experiments/backend/max_tools.py+++ b/products/experiments/backend/max_tools.py@@ -11,7 +11,6 @@ from posthog.schema import MaxExperimentMetricResultfrom posthog.clickhouse.query_tagging import Product, tags_contextfrom posthog.event_usage import EventSourcefrom posthog.hogql_queries.experiments.utils import get_experiment_stats_method-from posthog.models import FeatureFlagfrom posthog.session_recordings.session_recording_api import list_recordings_from_queryfrom posthog.session_recordings.utils import filter_from_params_to_queryfrom posthog.sync import database_sync_to_async@@ -19,6 +18,7 @@ from posthog.sync import database_sync_to_asyncfrom products.experiments.backend.experiment_service import ExperimentServicefrom products.experiments.backend.experiment_summary_data_service import ExperimentSummaryDataServicefrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.hogai.context.experiment.context import ExperimentContextfrom ee.hogai.tool import MaxTooldiff --git a/products/experiments/backend/migrations/0015_migrate_feature_flags_models.py b/products/experiments/backend/migrations/0015_migrate_feature_flags_models.pynew file mode 100644index 000000000000..acd97860afe8--- /dev/null+++ b/products/experiments/backend/migrations/0015_migrate_feature_flags_models.py@@ -0,0 +1,27 @@+# Generated by Django 5.2.13 on 2026-05-20 15:38++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("experiments", "0014_teamexperimentsconfig_default_cuped_lookback_days"),+ ("feature_flags", "0002_migrate_feature_flags_models"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AlterField(+ model_name="experiment",+ name="feature_flag",+ field=models.ForeignKey(+ on_delete=django.db.models.deletion.RESTRICT,+ to="feature_flags.featureflag",+ ),+ ),+ ],+ database_operations=[],+ ),+ ]diff --git a/products/experiments/backend/migrations/max_migration.txt b/products/experiments/backend/migrations/max_migration.txtindex 28aee939a655..8d04f1dfe060 100644--- a/products/experiments/backend/migrations/max_migration.txt+++ b/products/experiments/backend/migrations/max_migration.txt@@ -1 +1 @@-0014_teamexperimentsconfig_default_cuped_lookback_days+0015_migrate_feature_flags_modelsdiff --git a/products/experiments/backend/models/experiment.py b/products/experiments/backend/models/experiment.pyindex 79420060dafe..0306151fcfa6 100644--- a/products/experiments/backend/models/experiment.py+++ b/products/experiments/backend/models/experiment.py@@ -44,7 +44,7 @@ class Experiment(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.secondary_metrics = models.JSONField(default=list, null=True, blank=True)created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True)- feature_flag = models.ForeignKey("posthog.FeatureFlag", blank=False, on_delete=models.RESTRICT)+ feature_flag = models.ForeignKey("feature_flags.FeatureFlag", blank=False, on_delete=models.RESTRICT)exposure_cohort = models.ForeignKey("posthog.Cohort", on_delete=models.SET_NULL, null=True, blank=True)holdout = models.ForeignKey("ExperimentHoldout", on_delete=models.SET_NULL, null=True, blank=True)diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex fecf1809ae31..801cadfc103c 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -20,7 +20,6 @@ from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.api.shared import UserBasicSerializerfrom posthog.hogql_queries.experiments.experiment_metric_fingerprint import compute_metric_fingerprintfrom posthog.hogql_queries.experiments.utils import get_experiment_stats_method-from posthog.models.feature_flag import FeatureFlagfrom posthog.models.llm_prompt import LLMPromptfrom posthog.models.team.team import Teamfrom posthog.rbac.user_access_control import UserAccessControlSerializerMixin@@ -30,6 +29,7 @@ from products.experiments.backend.facade.contracts import CreateExperimentInputfrom products.experiments.backend.llm_metric_templates import TEMPLATE_NAMESfrom products.experiments.backend.metric_utils import refresh_action_names_in_metricfrom products.experiments.backend.models.experiment import Experiment, ExperimentHoldout+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.clickhouse.views.experiment_holdouts import ExperimentHoldoutSerializerfrom ee.clickhouse.views.experiment_saved_metrics import ExperimentToSavedMetricSerializer@@ -290,7 +290,7 @@ class ExperimentSerializer(UserAccessControlSerializerMixin, serializers.ModelSe@extend_schema_field(OpenApiTypes.OBJECT)def get_feature_flag(self, obj):- from posthog.api.feature_flag import MinimalFeatureFlagSerializer+ from products.feature_flags.backend.api.feature_flag import MinimalFeatureFlagSerializerreturn MinimalFeatureFlagSerializer(obj.feature_flag).data if obj.feature_flag else Nonediff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex 4bc8abbf37e2..27529770599d 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -24,14 +24,11 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.api.cohort import CohortSerializer-from posthog.api.feature_flag import FeatureFlagSerializerfrom posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import actionfrom posthog.approvals.mixins import ApprovalHandlingMixinfrom posthog.models.activity_logging.activity_log import Detail, changes_between, log_activity-from posthog.models.evaluation_context import FeatureFlagEvaluationContext-from posthog.models.feature_flag import FeatureFlagfrom posthog.models.filters.filter import Filterfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.signals import model_activity_signal, mutable_receiver@@ -58,6 +55,9 @@ from products.experiments.backend.presentation.serializers import (ExperimentSerializer,ShipVariantSerializer,)+from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer+from products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContext+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_tours.backend.models import ProductTourfrom products.surveys.backend.models import Surveydiff --git a/products/experiments/backend/test/test_api.py b/products/experiments/backend/test/test_api.pyindex fd6ec746e3d3..64fc1576233f 100644--- a/products/experiments/backend/test/test_api.py+++ b/products/experiments/backend/test/test_api.py@@ -12,11 +12,10 @@ import pytestfrom posthog.test.base import BaseTestfrom unittest.mock import patch-from posthog.models.feature_flag.feature_flag import FeatureFlag as FeatureFlagModel-from products.experiments.backend.facade.api import create_experimentfrom products.experiments.backend.facade.contracts import CreateExperimentInput, Experimentfrom products.experiments.backend.models.experiment import Experiment as ExperimentModel+from products.feature_flags.backend.models.feature_flag import FeatureFlag as FeatureFlagModelclass TestCreateExperiment(BaseTest):diff --git a/products/experiments/backend/test/test_create_from_prompt.py b/products/experiments/backend/test/test_create_from_prompt.pyindex 3bc3b011a22b..e14dcc2b12e8 100644--- a/products/experiments/backend/test/test_create_from_prompt.py+++ b/products/experiments/backend/test/test_create_from_prompt.py@@ -6,11 +6,11 @@ from unittest.mock import patchfrom parameterized import parameterizedfrom rest_framework import status-from posthog.models.feature_flag import FeatureFlagfrom posthog.models.llm_prompt import LLMPromptfrom products.experiments.backend.llm_metric_templates import TEMPLATE_NAMESfrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.api.test.base import APILicensedTestdiff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.pyindex 182ae9f1fe3a..250433c04439 100644--- a/products/experiments/backend/test/test_experiment_service.py+++ b/products/experiments/backend/test/test_experiment_service.py@@ -16,10 +16,8 @@ from rest_framework.test import APIRequestFactoryfrom posthog.schema import EventsNode, ExperimentMetric-from posthog.api.feature_flag import FeatureFlagSerializer-from posthog.models import FeatureFlag, Team+from posthog.models import Teamfrom posthog.models.cohort import Cohort-from posthog.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContextfrom posthog.models.team.extensions import get_or_create_team_extensionfrom products.actions.backend.models.action import Action@@ -33,6 +31,9 @@ from products.experiments.backend.models.experiment import (ExperimentTimeseriesRecalculation,)from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig+from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer+from products.feature_flags.backend.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext+from products.feature_flags.backend.models.feature_flag import FeatureFlag# Note that we use allow_unknown_events here since allowing it was the behavior before validating itdiff --git a/products/experiments/backend/test/test_experiment_summary_tool.py b/products/experiments/backend/test/test_experiment_summary_tool.pyindex 31bb74de450d..3142c139b1e0 100644--- a/products/experiments/backend/test/test_experiment_summary_tool.py+++ b/products/experiments/backend/test/test_experiment_summary_tool.py@@ -20,7 +20,6 @@ from posthog.schema import (from posthog.hogql.constants import LimitContextfrom posthog.hogql_queries.query_runner import ExecutionMode-from posthog.models.feature_flag.feature_flag import FeatureFlagfrom products.experiments.backend.experiment_summary_data_service import (ExperimentSummaryDataService,@@ -31,6 +30,7 @@ from products.experiments.backend.experiment_summary_data_service import ()from products.experiments.backend.metric_utils import get_default_metric_titlefrom products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetric+from products.feature_flags.backend.models.feature_flag import FeatureFlag@override_settings(IN_UNIT_TESTING=True)diff --git a/products/experiments/backend/test/test_facade.py b/products/experiments/backend/test/test_facade.pyindex db774de11d19..7edbe7331e57 100644--- a/products/experiments/backend/test/test_facade.py+++ b/products/experiments/backend/test/test_facade.py@@ -62,9 +62,7 @@ class TestCreateExperiment(APIBaseTest):result = create_experiment(team=self.team, user=self.user, input_dto=input_dto)assert result.name == "Test Experiment"-- # Verify feature flag has correct variants- from posthog.models.feature_flag import FeatureFlag+ from products.feature_flags.backend.models.feature_flag import FeatureFlagflag = FeatureFlag.objects.get(id=result.feature_flag_id)assert len(flag.variants) == 2diff --git a/products/experiments/backend/test/test_max_tools.py b/products/experiments/backend/test/test_max_tools.pyindex 6a68e3aca38a..d1bb20f06f78 100644--- a/products/experiments/backend/test/test_max_tools.py+++ b/products/experiments/backend/test/test_max_tools.py@@ -8,10 +8,10 @@ from posthog.schema import ()from posthog.event_usage import EventSource-from posthog.models import FeatureFlagfrom products.experiments.backend.max_tools import CreateExperimentTool, ExperimentSummaryToolfrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.hogai.utils.types import AssistantStatediff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex eb7609a7ecec..4e3c6c725fe9 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -14,7 +14,6 @@ from rest_framework import statusfrom posthog.models import Organization, Teamfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.cohort.cohort import Cohort-from posthog.models.feature_flag import FeatureFlag, get_feature_flags_for_team_in_cachefrom posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.user import Userfrom posthog.test.test_journeys import journeys_for@@ -24,6 +23,7 @@ from products.event_definitions.backend.models.event_definition import EventDefifrom products.experiments.backend.models.experiment import Experiment, ExperimentHoldout, ExperimentSavedMetricfrom products.experiments.backend.models.team_experiments_config import TeamExperimentsConfigfrom products.experiments.backend.models.web_experiment import WebExperiment+from products.feature_flags.backend.models.feature_flag import FeatureFlag, get_feature_flags_for_team_in_cachefrom ee.api.test.base import APILicensedTestfrom ee.clickhouse.views.experiment_saved_metrics import ExperimentToSavedMetricSerializerdiff --git a/products/experiments/backend/test/test_session_replay_summary_tool.py b/products/experiments/backend/test/test_session_replay_summary_tool.pyindex b534b6397d20..8b2f75f94992 100644--- a/products/experiments/backend/test/test_session_replay_summary_tool.py+++ b/products/experiments/backend/test/test_session_replay_summary_tool.py@@ -4,11 +4,11 @@ from freezegun import freeze_timefrom posthog.test.base import APIBaseTestfrom unittest.mock import patch-from posthog.models import FeatureFlagfrom posthog.session_recordings.models.session_recording import SessionRecordingfrom products.experiments.backend.max_tools import SessionReplaySummaryToolfrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.hogai.utils.types import AssistantStatediff --git a/posthog/admin/admins/feature_flag_admin.py b/products/feature_flags/backend/admin.pysimilarity index 92%rename from posthog/admin/admins/feature_flag_admin.pyrename to products/feature_flags/backend/admin.pyindex 176ecbefc18c..3624c7937d67 100644--- a/posthog/admin/admins/feature_flag_admin.py+++ b/products/feature_flags/backend/admin.py@@ -2,7 +2,7 @@ from django.contrib import adminfrom django.urls import reversefrom django.utils.html import format_html-from posthog.models import FeatureFlag+from products.feature_flags.backend.models.feature_flag import FeatureFlag@admin.register(FeatureFlag)diff --git a/posthog/feature_flags/__init__.py b/products/feature_flags/backend/api/__init__.pysimilarity index 100%rename from posthog/feature_flags/__init__.pyrename to products/feature_flags/backend/api/__init__.pydiff --git a/posthog/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pysimilarity index 99%rename from posthog/api/feature_flag.pyrename to products/feature_flags/backend/api/feature_flag.pyindex 6ad1376a5c10..fde762e00ba9 100644--- a/posthog/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -58,33 +58,13 @@ from posthog.helpers.encrypted_flag_payloads import (encrypt_flag_payloads,get_decrypted_flag_payloads_protected,)-from posthog.models import FeatureFlag, Team+from posthog.models import Teamfrom posthog.models.activity_logging.activity_log import Detail, changes_between, load_activity, log_activityfrom posthog.models.activity_logging.activity_page import ActivityLogPaginatedResponseSerializer, activity_page_responsefrom posthog.models.activity_logging.model_activity import ImpersonatedContext, is_impersonated_sessionfrom posthog.models.cohort import Cohortfrom posthog.models.cohort.cohort import CohortTypefrom posthog.models.cohort.util import get_all_cohort_dependencies-from posthog.models.evaluation_context import normalize_context_name-from posthog.models.feature_flag import (- FeatureFlagDashboards,- get_user_blast_radius,- set_feature_flags_for_team_in_cache,-)-from posthog.models.feature_flag.flag_analytics import increment_request_count-from posthog.models.feature_flag.flag_status import FeatureFlagStatusChecker-from posthog.models.feature_flag.local_evaluation import (- DATABASE_FOR_LOCAL_EVALUATION,- _get_flag_properties_from_filters,- get_flags_response_if_none_match,-)-from posthog.models.feature_flag.types import PropertyFilterType-from posthog.models.feature_flag.version_history import (- VersionHistoryIncomplete,- VersionNotFound,- reconstruct_flag_at_timestamp,- reconstruct_flag_at_version,-)from posthog.models.person.point_in_time_properties import (build_person_properties_at_time,get_person_and_distinct_ids_for_identifier,@@ -102,6 +82,27 @@ from posthog.views import format_bytesfrom products.dashboards.backend.api.dashboard import Dashboardfrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.flag_analytics import increment_request_count+from products.feature_flags.backend.flag_status import FeatureFlagStatusChecker+from products.feature_flags.backend.local_evaluation import (+ DATABASE_FOR_LOCAL_EVALUATION,+ _get_flag_properties_from_filters,+ get_flags_response_if_none_match,+)+from products.feature_flags.backend.models.evaluation_context import normalize_context_name+from products.feature_flags.backend.models.feature_flag import (+ FeatureFlag,+ FeatureFlagDashboards,+ set_feature_flags_for_team_in_cache,+)+from products.feature_flags.backend.types import PropertyFilterType+from products.feature_flags.backend.user_blast_radius import get_user_blast_radius+from products.feature_flags.backend.version_history import (+ VersionHistoryIncomplete,+ VersionNotFound,+ reconstruct_flag_at_timestamp,+ reconstruct_flag_at_version,+)from products.product_tours.backend.models import ProductTourfrom products.surveys.backend.models import Survey@@ -612,7 +613,10 @@ class EvaluationContextSerializerMixin(serializers.Serializer):if not self._is_evaluation_contexts_feature_enabled():return- from posthog.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext+ from products.feature_flags.backend.models.evaluation_context import (+ EvaluationContext,+ FeatureFlagEvaluationContext,+ )seen: set[str] = set()deduped_names: list[str] = []@@ -2342,7 +2346,7 @@ class MinimalFeatureFlagSerializer(serializers.ModelSerializer):):return [ec.evaluation_context.name for ec in feature_flag.flag_evaluation_contexts.all()]- from posthog.models.evaluation_context import FeatureFlagEvaluationContext+ from products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContextreturn list(FeatureFlagEvaluationContext.objects.filter(feature_flag=feature_flag)@@ -2536,7 +2540,7 @@ class FeatureFlagViewSet(def safely_get_queryset(self, queryset) -> QuerySet:from django.db.models import Exists, OuterRef- from posthog.models.evaluation_context import FeatureFlagEvaluationContext+ from products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContext# Always prefetch experiment_set since it's used in both list and retrievequeryset = queryset.prefetch_related(@@ -3057,11 +3061,12 @@ class FeatureFlagViewSet(from django.utils import timezonefrom posthog.models.activity_logging.activity_log import LogActivityEntry, bulk_log_activity- from posthog.models.feature_flag.feature_flag import set_feature_flags_for_team_in_cachefrom posthog.rbac.user_access_control import access_level_satisfied_for_resource- from posthog.tasks.feature_flags import update_team_flags_cache, update_team_service_flags_cachefrom posthog.tasks.remote_config import update_team_remote_config+ from products.feature_flags.backend.models.feature_flag import set_feature_flags_for_team_in_cache+ from products.feature_flags.backend.tasks import update_team_flags_cache, update_team_service_flags_cache+filters = request.data.get("filters", {})explicit_ids = request.data.get("ids", [])diff --git a/posthog/api/flag_value.py b/products/feature_flags/backend/api/flag_value.pysimilarity index 97%rename from posthog/api/flag_value.pyrename to products/feature_flags/backend/api/flag_value.pyindex db953f8f0922..75a4f176be0a 100644--- a/posthog/api/flag_value.py+++ b/products/feature_flags/backend/api/flag_value.py@@ -5,7 +5,8 @@ from rest_framework.permissions import IsAuthenticatedfrom posthog.api.mixins import validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.models import FeatureFlag++from products.feature_flags.backend.models.feature_flag import FeatureFlagclass FlagValueQuerySerializer(serializers.Serializer):diff --git a/posthog/api/organization_feature_flag.py b/products/feature_flags/backend/api/organization_feature_flag.pysimilarity index 98%rename from posthog/api/organization_feature_flag.pyrename to products/feature_flags/backend/api/organization_feature_flag.pyindex aa74f2aedaf8..ae6fd857bc23 100644--- a/posthog/api/organization_feature_flag.py+++ b/products/feature_flags/backend/api/organization_feature_flag.py@@ -9,18 +9,20 @@ from rest_framework.response import Responsefrom posthog.api.cohort import CohortSerializerfrom posthog.api.documentation import _FallbackSerializer, extend_schema-from posthog.api.feature_flag import FeatureFlagSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import actionfrom posthog.helpers.encrypted_flag_payloads import get_decrypted_flag_payloads-from posthog.models import FeatureFlag, Team+from posthog.models import Teamfrom posthog.models.cohort import Cohort, CohortOrEmpty-from posthog.models.feature_flag.flag_analytics import get_cached_evaluations_7d_by_teamfrom posthog.models.filters.filter import Filter-from posthog.models.scheduled_change import ScheduledChangefrom posthog.user_permissions import UserPermissions+from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer+from products.feature_flags.backend.flag_analytics import get_cached_evaluations_7d_by_team+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.scheduled_change import ScheduledChange+class CopyFlagsRequestSerializer(serializers.Serializer):feature_flag_key = serializers.CharField(required=True, help_text="Key of the feature flag to copy")diff --git a/posthog/api/scheduled_change.py b/products/feature_flags/backend/api/scheduled_change.pysimilarity index 97%rename from posthog/api/scheduled_change.pyrename to products/feature_flags/backend/api/scheduled_change.pyindex fed358579991..e73b2f742cac 100644--- a/posthog/api/scheduled_change.py+++ b/products/feature_flags/backend/api/scheduled_change.py@@ -5,10 +5,11 @@ from drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, extend_schemafrom rest_framework import serializers, viewsets-from posthog.api.feature_flag import CanEditFeatureFlagfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializer-from posthog.models import ScheduledChange++from products.feature_flags.backend.api.feature_flag import CanEditFeatureFlag+from products.feature_flags.backend.models.scheduled_change import ScheduledChangeclass ScheduledChangeSerializer(serializers.ModelSerializer):@@ -186,8 +187,7 @@ class ScheduledChangeSerializer(serializers.ModelSerializer):"""Raise ValidationError unless the request user can edit the target record."""if model_name != "FeatureFlag" or not record_id:return-- from posthog.models import FeatureFlag+ from products.feature_flags.backend.models.feature_flag import FeatureFlagtry:feature_flag = FeatureFlag.objects.get(id=record_id, team_id=team_id)diff --git a/posthog/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambrsimilarity index 98%rename from posthog/api/test/__snapshots__/test_feature_flag.ambrrename to products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambrindex e6bfa863e068..7b4f81c799ca 100644--- a/posthog/api/test/__snapshots__/test_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr@@ -98,31 +98,6 @@use_hive_partitioning=0'''# ----# name: TestBlastRadius.test_user_blast_radius_with_group_key_property.3- '''- /* user_id:0 request:_snapshot_ */- SELECT count(DISTINCT groups.key) AS `count(DISTINCT groups.key)`- FROM- (SELECT tupleElement(argMax(tuple(groups.team_id), toTimeZone(groups._timestamp, 'UTC')), 1) AS team_id,- groups.group_type_index AS index,- groups.group_key AS key- FROM groups- WHERE equals(groups.team_id, 99999)- GROUP BY groups.group_type_index,- groups.group_key) AS groups- WHERE and(ifNull(equals(groups.team_id, 99999), 0), ifNull(equals(groups.index, 0), 0), ifNull(ilike(groups.key, '%org:%'), 0))- LIMIT 100 SETTINGS readonly=2,- max_execution_time=60,- allow_experimental_object_type=1,- max_ast_elements=4000000,- max_expanded_ast_elements=4000000,- max_bytes_before_external_group_by=0,- transform_null_in=1,- optimize_min_equality_disjunction_chain_length=4294967295,- allow_experimental_join_condition=1,- use_hive_partitioning=0- '''-# ---# name: TestBlastRadius.test_user_blast_radius_with_groups'''/* user_id:0 request:_snapshot_ */@@ -158,18 +133,6 @@AND group_type_index = 0'''# ----# name: TestBlastRadius.test_user_blast_radius_with_groups.2- '''- /* user_id:0 request:_snapshot_ */- SELECT count(1)- FROM- (SELECT id- FROM person- WHERE team_id = 99999- GROUP BY id- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)- '''-# ---# name: TestBlastRadius.test_user_blast_radius_with_groups_multiple_queries'''/* user_id:0 request:_snapshot_ */@@ -205,18 +168,6 @@AND group_type_index = 0'''# ----# name: TestBlastRadius.test_user_blast_radius_with_groups_multiple_queries.2- '''- /* user_id:0 request:_snapshot_ */- SELECT count(1)- FROM- (SELECT id- FROM person- WHERE team_id = 99999- GROUP BY id- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)- '''-# ---# name: TestBlastRadius.test_user_blast_radius_with_multiple_precalculated_cohorts'''diff --git a/posthog/api/test/__snapshots__/test_organization_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambrsimilarity index 100%rename from posthog/api/test/__snapshots__/test_organization_feature_flag.ambrrename to products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambrdiff --git a/posthog/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pysimilarity index 98%rename from posthog/api/test/test_feature_flag.pyrename to products/feature_flags/backend/api/test/test_feature_flag.pyindex 2a5c41b32d1a..e76604645b40 100644--- a/posthog/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -25,15 +25,11 @@ from rest_framework.relations import ManyRelatedFieldfrom posthog import redisfrom posthog.api.cohort import get_cohort_actors_for_feature_flag-from posthog.api.feature_flag import FeatureFlagSerializer, extract_etag_from_headerfrom posthog.constants import AvailableFeaturefrom posthog.helpers.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUE, get_decrypted_flag_payload-from posthog.models import FeatureFlag, GroupTypeMapping, Insight, TaggedItem, User+from posthog.models import GroupTypeMapping, Insight, TaggedItem, Userfrom posthog.models.cohort import Cohortfrom posthog.models.cohort.cohort import CohortType-from posthog.models.feature_flag import FeatureFlagDashboards, get_feature_flags_for_team_in_cache-from posthog.models.feature_flag.feature_flag import FeatureFlagHashKeyOverride-from posthog.models.feature_flag.flag_status import FeatureFlagStatusfrom posthog.models.group.group import Groupfrom posthog.models.group.util import create_groupfrom posthog.models.organization import Organization, OrganizationMembership@@ -47,6 +43,14 @@ from posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer, extract_etag_from_header+from products.feature_flags.backend.flag_status import FeatureFlagStatus+from products.feature_flags.backend.models.feature_flag import (+ FeatureFlag,+ FeatureFlagDashboards,+ FeatureFlagHashKeyOverride,+ get_feature_flags_for_team_in_cache,+)from products.product_tours.backend.models import ProductTourfrom products.surveys.backend.models import Survey@@ -515,7 +519,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):existing_flag.refresh_from_db()self.assertEqual(existing_flag.name, "Beta feature 3")- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_group_type_index_feature_flag(self, mock_report_user_action):feature_flag = self.client.post(f"/api/projects/{self.team.id}/feature_flags/",@@ -746,7 +750,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertIn(expected_type, response.json()["detail"])@freeze_time("2021-08-25T22:09:14.252Z")- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_create_feature_flag(self, mock_report_user_action):response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/",@@ -804,7 +808,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(instance.created_by, self.user)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_create_minimal_feature_flag(self, mock_report_user_action):response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/",@@ -841,7 +845,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):request=ANY,)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_create_remote_config_flag_defaults_to_100_percent_rollout(self, mock_report_user_action):"""Test that remote config flags default to 100% rollout in various scenarios."""test_cases = [@@ -901,7 +905,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):instance = FeatureFlag.objects.get(id=response_data["id"])self.assertEqual(instance.filters["groups"][0]["rollout_percentage"], 100)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_create_encrypted_payloads_requires_remote_configuration(self, mock_report_user_action):response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/",@@ -917,7 +921,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertIn("remote configuration", response.json()["detail"])- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_create_encrypted_payloads_with_remote_configuration_succeeds(self, mock_report_user_action):response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/",@@ -932,7 +936,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):)self.assertEqual(response.status_code, status.HTTP_201_CREATED)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_update_remote_config_flag_to_non_remote_with_encrypted_payloads_fails(self, mock_report_user_action):response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/",@@ -956,7 +960,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertIn("remote configuration", response.json()["detail"])- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_update_non_remote_flag_to_encrypted_payloads_fails(self, mock_report_user_action):response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/",@@ -979,7 +983,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertIn("remote configuration", response.json()["detail"])- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_create_feature_flag_with_analytics_dashboards(self, mock_report_user_action):dashboard = Dashboard.objects.create(team=self.team, name="private dashboard", created_by=self.user)response = self.client.post(@@ -997,7 +1001,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(instance.key, "feature-with-analytics-dashboards")self.assertEqual(instance.analytics_dashboards.all()[0].id, dashboard.pk)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_create_feature_flag_rejects_dashboard_from_other_team(self, mock_report_user_action):other_team = Team.objects.create(organization=self.organization, api_token="token_other", name="Other Team")other_dashboard = Dashboard.objects.create(team=other_team, name="other team dashboard", created_by=self.user)@@ -1014,7 +1018,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.json()["attr"], "analytics_dashboards")self.assertIn("does not exist", response.json()["detail"])- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_update_feature_flag_rejects_dashboard_from_other_team(self, mock_report_user_action):flag = FeatureFlag.objects.create(team=self.team,@@ -1051,7 +1055,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):analytics_field = cast(ManyRelatedField, fields["analytics_dashboards"])self.assertEqual(analytics_field.child_relation.get_queryset().count(), 0)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_create_feature_flag_with_evaluation_runtime(self, mock_report_user_action):# Test creating a feature flag with different evaluation_runtime values@@ -1094,7 +1098,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.status_code, status.HTTP_201_CREATED)self.assertEqual(response.json()["evaluation_runtime"], "all")- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_update_feature_flag_evaluation_runtime(self, mock_report_user_action):# Create a flag with default evaluation_runtimeresponse = self.client.post(@@ -1119,7 +1123,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):instance = FeatureFlag.objects.get(id=flag_id)self.assertEqual(instance.evaluation_runtime, "server")- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_create_multivariate_feature_flag(self, mock_report_user_action):response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/",@@ -1418,7 +1422,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):"Filters are not valid (variant override does not exist)",)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_updating_feature_flag(self, mock_report_user_action):with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:response = self.client.post(@@ -1556,7 +1560,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):],)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_updating_feature_flag_partial(self, mock_report_user_action):# Test that we can update a feature flag with only some of the fields# And the unchanged fields are not updated@@ -1605,7 +1609,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.json()["name"], "Updated name")self.assertEqual(response.json()["filters"]["groups"][0]["rollout_percentage"], 100)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_updating_feature_flag_with_different_user(self, mock_report_user_action):with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:# Create flag with original user@@ -1638,7 +1642,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(feature_flag.created_by, original_user)self.assertEqual(feature_flag.last_modified_by, different_user)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_updating_feature_flag_fails_concurrency_check_when_version_outdated(self, mock_report_user_action):with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:# Create flag with original user: version 0@@ -1720,7 +1724,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(feature_flag.name, "Another Updated name")self.assertEqual(feature_flag.last_modified_by, different_user)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_updating_feature_flag_does_not_fail_concurrency_check_when_changing_different_fields(self, mock_report_user_action):@@ -1834,7 +1838,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(feature_flag.last_modified_by, original_user)self.assertEqual(response.json()["filters"]["groups"][0]["rollout_percentage"], 45)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_updating_feature_flag_does_not_fail_when_version_not_in_request(self, mock_report_user_action):with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:response = self.client.post(@@ -2299,7 +2303,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):conflicts = serializer._get_conflicting_changes(feature_flag, validated_data, original_flag)self.assertEqual(conflicts, ["name", "filters"])- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_updating_feature_flag_treats_null_version_as_zero(self, mock_report_user_action):with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:response = self.client.post(@@ -2325,7 +2329,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(feature_flag.version, 1)self.assertEqual(feature_flag.name, "Updated name")- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_updating_feature_flag_key(self, mock_report_user_action):with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:response = self.client.post(@@ -2509,7 +2513,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):"a-new-feature-flag-key",)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_updating_feature_flag_key_does_not_update_insight_with_changed_description(self, mock_report_user_action):with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:response = self.client.post(@@ -2598,7 +2602,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):"a-new-feature-flag-key",)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_updating_feature_flag_key_does_not_update_insight_with_changed_filter(self, mock_report_user_action):with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:response = self.client.post(@@ -2687,7 +2691,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):"a-new-feature-flag-key",)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_updating_feature_flag_key_does_not_update_insight_with_removed_filter(self, mock_report_user_action):with freeze_time("2021-08-25T22:09:14.252Z") as frozen_datetime:response = self.client.post(@@ -3350,119 +3354,6 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):team=self.team, key="56397-delete-flag", deleted=True).exists()- @parameterized.expand(- [- ("create",),- ("rename",),- ]- )- def test_reuses_key_held_by_legacy_soft_deleted_flag_with_soft_deleted_experiment(self, mode: str):- # Legacy tombstone holds the key with a soft-deleted experiment FK- # blocking hard-delete. Reusing the key should rename the tombstone,- # not raise the old "delete the experiment" error.- legacy_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="ghost-key")- exp = Experiment.objects.create(team=self.team, created_by=self.user, feature_flag=legacy_flag)- exp.deleted = True- exp.save()- # Bypass API so soft-delete rename doesn't fire — mimics historical data.- FeatureFlag.objects_including_soft_deleted.filter(pk=legacy_flag.pk).update(deleted=True)-- if mode == "create":- response = self.client.post(- f"/api/projects/{self.team.id}/feature_flags/",- {"name": "Ghost", "key": "ghost-key"},- )- assert response.status_code == 201, response.content- assert response.json()["key"] == "ghost-key"- else:- other = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="ghost-key-v2")- response = self.client.patch(- f"/api/projects/{self.team.id}/feature_flags/{other.id}/",- {"key": "ghost-key"},- )- assert response.status_code == 200, response.content- other.refresh_from_db()- assert other.key == "ghost-key"-- # Tombstone is renamed; experiment FK still resolves.- legacy_flag = FeatureFlag.objects_including_soft_deleted.get(pk=legacy_flag.pk)- assert legacy_flag.deleted is True- assert legacy_flag.key == f"ghost-key:deleted:{legacy_flag.id}"- exp.refresh_from_db()- assert exp.feature_flag_id == legacy_flag.id-- @parameterized.expand(- [- ("create",),- ("rename",),- ]- )- def test_reuse_key_with_inconsistent_soft_deleted_flag_referenced_by_active_experiment(self, mode: str):- # If a tombstone is still referenced by an active experiment (invariant- # violation), renaming it would silently break the experiment. Error out.- legacy_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="inconsistent-key")- exp = Experiment.objects.create(team=self.team, created_by=self.user, feature_flag=legacy_flag)- FeatureFlag.objects_including_soft_deleted.filter(pk=legacy_flag.pk).update(deleted=True)-- if mode == "create":- response = self.client.post(- f"/api/projects/{self.team.id}/feature_flags/",- {"name": "Inconsistent", "key": "inconsistent-key"},- )- else:- other = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="inconsistent-key-v2")- response = self.client.patch(- f"/api/projects/{self.team.id}/feature_flags/{other.id}/",- {"key": "inconsistent-key"},- )-- assert response.status_code == 400- assert f"active experiment(s) with ID(s): {exp.id}" in response.json()["detail"]- assert "inconsistent-key" in response.json()["detail"]-- # Tombstone was not mutated.- legacy_flag.refresh_from_db()- assert legacy_flag.key == "inconsistent-key"-- @parameterized.expand(- [- ("create",),- ("rename",),- ]- )- def test_reuse_key_with_inconsistent_soft_deleted_flag_referenced_by_eaf(self, mode: str):- # EarlyAccessFeature.feature_flag uses on_delete=PROTECT (sibling of- # RESTRICT). A tombstone with an EAF must surface the same defensive- # error, not a 500.- legacy_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="eaf-key")- EarlyAccessFeature.objects.create(- team=self.team,- name="EAF",- description="",- stage="alpha",- feature_flag=legacy_flag,- )- FeatureFlag.objects_including_soft_deleted.filter(pk=legacy_flag.pk).update(deleted=True)-- if mode == "create":- response = self.client.post(- f"/api/projects/{self.team.id}/feature_flags/",- {"name": "EAF Reuse", "key": "eaf-key"},- )- else:- other = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="eaf-key-v2")- response = self.client.patch(- f"/api/projects/{self.team.id}/feature_flags/{other.id}/",- {"key": "eaf-key"},- )-- assert response.status_code == 400- assert "early access feature(s)" in response.json()["detail"]- assert "eaf-key" in response.json()["detail"]-- legacy_flag.refresh_from_db()- assert legacy_flag.key == "eaf-key"-def test_soft_delete_flag_blocked_with_active_experiment(self):flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="flag2")exp = Experiment.objects.create(team=self.team, created_by=self.user, feature_flag=flag)@@ -3678,7 +3569,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):# targeting_flag and internal_targeting_flag should be excluded# (they're survey-specific and filtered out from the main list)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_create_feature_flag_usage_dashboard(self, mock_report_user_action):response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/",@@ -4057,7 +3948,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):)@freeze_time("2021-08-25T22:09:14.252Z")- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_dashboard_enrichment_fails_if_already_enriched(self, mock_report_user_action):response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/",@@ -4094,7 +3985,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):{"error": "Usage dashboard already has enriched data", "success": False},)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_dashboard_enrichment_fails_if_no_enriched_data(self, mock_report_user_action):response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/",@@ -4123,7 +4014,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):},)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_local_evaluation_for_invalid_cohorts(self, mock_report_user_action):FeatureFlag.objects.all().delete()@@ -4326,7 +4217,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):assert str(cohort_valid.pk) in response_data["cohorts"]assert str(cohort_with_nested_invalid.pk) in response_data["cohorts"]- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_local_evaluation_for_cohorts_with_variant_overrides(self, mock_report_user_action):FeatureFlag.objects.all().delete()@@ -4459,7 +4350,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):sorted_flags[0].items(),)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_local_evaluation_for_static_cohorts(self, mock_report_user_action):FeatureFlag.objects.all().delete()@@ -4578,7 +4469,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):{},)- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_local_evaluation_for_arbitrary_cohorts(self, mock_report_user_action):FeatureFlag.objects.all().delete()@@ -4838,7 +4729,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):sorted_flags[1].items(),)- @patch("posthog.models.feature_flag.flag_analytics.CACHE_BUCKET_SIZE", 10)+ @patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)def test_local_evaluation_billing_analytics(self):FeatureFlag.objects.all().delete()@@ -4902,7 +4793,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):{b"165192618": b"6"},)- @patch("posthog.models.feature_flag.flag_analytics.CACHE_BUCKET_SIZE", 10)+ @patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)def test_local_evaluation_billing_analytics_for_regular_feature_flag_list(self):FeatureFlag.objects.all().delete()@@ -5550,7 +5441,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):),])- @patch("posthog.api.feature_flag.posthoganalytics.feature_enabled")+ @patch("products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled")def test_behavioral_cohort_flag_validation(self,_name,@@ -5674,7 +5565,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):),])- @patch("posthog.api.feature_flag.posthoganalytics.feature_enabled")+ @patch("products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled")def test_mixed_aggregation_types_across_condition_sets(self, _name, mixed_targeting_enabled, expected_status, mock_feature_enabled):@@ -5718,7 +5609,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):else:self.assertIn("Mixed aggregation types", response.json()["detail"])- @patch("posthog.api.feature_flag.posthoganalytics.feature_enabled")+ @patch("products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled")def test_mixed_aggregation_round_trip(self, mock_feature_enabled):mock_feature_enabled.return_value = True@@ -5755,7 +5646,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):("flag_disabled", False, status.HTTP_400_BAD_REQUEST),])- @patch("posthog.api.feature_flag.posthoganalytics.feature_enabled")+ @patch("products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled")def test_mixed_aggregation_with_properties(self, _name, mixed_targeting_enabled, expected_status, mock_feature_enabled):@@ -5812,7 +5703,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):("flag_disabled", False, status.HTTP_400_BAD_REQUEST),])- @patch("posthog.api.feature_flag.posthoganalytics.feature_enabled")+ @patch("products.feature_flags.backend.api.feature_flag.posthoganalytics.feature_enabled")def test_patch_uniform_flag_to_mixed(self, _name, mixed_targeting_enabled, expected_status, mock_feature_enabled):mock_feature_enabled.return_value = mixed_targeting_enabled@@ -6927,7 +6818,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):assert flags is not Noneself.assertEqual(len(flags), 0)- @patch("posthog.api.feature_flag.LocalEvaluationThrottle.rate", new="7/minute")+ @patch("products.feature_flags.backend.api.feature_flag.LocalEvaluationThrottle.rate", new="7/minute")@patch("posthog.rate_limit.BurstRateThrottle.rate", new="5/minute")@patch("posthog.rate_limit.statsd.incr")@patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)@@ -7152,488 +7043,260 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):response.json().items(),)- def test_cant_create_flag_with_invalid_regex(self):+ def test_feature_flag_includes_cohort_names(self):+ cohort = Cohort.objects.create(+ team=self.team,+ name="test_cohort",+ groups=[{"properties": [{"key": "email", "value": "@posthog.com", "type": "person"}]}],+ )response = self.client.post(- f"/api/projects/{self.team.id}/feature_flags",+ f"/api/projects/{self.team.id}/feature_flags/",{- "name": "Beta feature",- "key": "beta-x",+ "name": "Alpha feature",+ "key": "alpha-feature","filters": {- "groups": [- {- "rollout_percentage": 65,- "properties": [- {- "key": "email",- "type": "person",- "value": "[unclosed",- "operator": "regex",- }- ],- }- ]+ "groups": [{"properties": [{"key": "id", "type": "cohort", "value": cohort.pk}]}],},},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)++ # Get the flag+ response = self.client.get(+ f"/api/projects/{self.team.id}/feature_flags/{response.json()['id']}/",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(+ response.json()["filters"]["groups"][0]["properties"][0],+ {+ "key": "id",+ "type": "cohort",+ "value": cohort.pk,+ "cohort_name": "test_cohort",+ },+ )++ def test_feature_flag_includes_group_key_names(self):+ GroupTypeMapping.objects.create(+ team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0+ )+ Group.objects.create(+ team=self.team,+ group_key="org-uuid-1",+ group_type_index=0,+ group_properties={"name": "Acme Corp"},+ version=0,+ )+ Group.objects.create(+ team=self.team,+ group_key="org-uuid-2",+ group_type_index=0,+ group_properties={"name": "Widget Inc"},+ version=0,)- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(response.json()["detail"], "groups[0].properties[0].value: invalid regex pattern")- def test_cant_create_flag_with_invalid_not_regex(self):response = self.client.post(- f"/api/projects/{self.team.id}/feature_flags",+ f"/api/projects/{self.team.id}/feature_flags/",{- "name": "Beta feature",- "key": "beta-x",+ "name": "Group flag",+ "key": "group-flag","filters": {+ "aggregation_group_type_index": 0,"groups": [{- "rollout_percentage": 65,"properties": [{- "key": "email",+ "key": "$group_key","type": "group",+ "value": ["org-uuid-1", "org-uuid-2"],+ "operator": "exact","group_type_index": 0,- "value": "(unclosed",- "operator": "not_regex",}- ],+ ]}],},},+ format="json",)- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(response.json()["detail"], "groups[0].properties[0].value: invalid regex pattern")+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)- def test_patch_non_filter_field_skips_regex_validation(self):- flag = FeatureFlag.objects.create(+ response = self.client.get(+ f"/api/projects/{self.team.id}/feature_flags/{response.json()['id']}/",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ prop = response.json()["filters"]["groups"][0]["properties"][0]+ self.assertEqual(prop["key"], "$group_key")+ self.assertEqual(+ prop["group_key_names"],+ {"org-uuid-1": "Acme Corp", "org-uuid-2": "Widget Inc"},+ )++ def test_create_feature_flag_in_specific_folder(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ data={+ "key": "my-test-flag-in-folder",+ "name": "Test Flag in Folder",+ "filters": {"groups": [{"properties": [], "rollout_percentage": 50}]},+ "_create_in_folder": "Special Folder/Flags",+ },+ format="json",+ )+ assert response.status_code == 201, response.json()+ flag_id = response.json()["id"]+ assert flag_id is not None++ from posthog.models.file_system.file_system import FileSystem++ fs_entry = FileSystem.objects.filter(team=self.team, ref=str(flag_id), type="feature_flag").first()+ assert fs_entry, "No FileSystem entry found for this feature flag."+ assert "Special Folder/Flags" in fs_entry.path, (+ f"Expected 'Special Folder/Flags' in path, got: '{fs_entry.path}'"+ )++ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")+ def test_updating_feature_flag_key_updates_super_groups(self, mock_report_user_action):+ # Create a feature flag with super_groups+ feature_flag = FeatureFlag.objects.create(team=self.team,created_by=self.user,- key="flag-with-lookbehind",+ key="old-key",+ name="Test Flag",filters={- "groups": [+ "groups": [{"properties": [], "rollout_percentage": 0}],+ "super_groups": [{- "rollout_percentage": 100,"properties": [{- "key": "email",+ "key": "$feature_enrollment/old-key","type": "person",- "value": "(?<!a{2,5})b",- "operator": "regex",+ "value": ["true"],+ "operator": "exact",}],+ "rollout_percentage": 100,}- ]+ ],},)++ # Update the feature flag keyresponse = self.client.patch(- f"/api/projects/{self.team.id}/feature_flags/{flag.id}",- {"active": False},+ f"/api/projects/{self.team.id}/feature_flags/{feature_flag.id}",+ {"key": "new-key"},+ format="json",)+self.assertEqual(response.status_code, status.HTTP_200_OK)- @parameterized.expand(- [- (- "unchanged_invalid_regex_accepted",- "(?<!a{2,5})b",- "(?<!a{2,5})b",- status.HTTP_200_OK,- ),- (- "valid_to_invalid_regex_rejected",- "^valid$",- "[unclosed",- status.HTTP_400_BAD_REQUEST,- ),- (- "different_invalid_regex_rejected",- "[unclosed",- "(unbalanced",- status.HTTP_400_BAD_REQUEST,- ),- ]- )- def test_patch_flag_regex_validation(self, _name, existing_pattern, new_pattern, expected_status):- flag = FeatureFlag.objects.create(+ # Refresh the feature flag from the database+ feature_flag.refresh_from_db()++ # Verify the super_groups were updated+ self.assertEqual(+ feature_flag.filters["super_groups"][0]["properties"][0]["key"],+ "$feature_enrollment/new-key",+ )++ # Verify the old key is not present+ self.assertNotIn("$feature_enrollment/old-key", str(feature_flag.filters))++ def test_feature_flag_experiment_set(self):+ # Create a feature flag+ feature_flag = FeatureFlag.objects.create(team=self.team,created_by=self.user,- key="flag-regex-test",- filters={- "groups": [- {- "rollout_percentage": 100,- "properties": [- {- "key": "email",- "type": "person",- "value": existing_pattern,- "operator": "regex",- }- ],- }- ]- },+ key="test-flag",+ name="Test Flag",+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},)- response = self.client.patch(- f"/api/projects/{self.team.id}/feature_flags/{flag.id}",- {- "filters": {- "groups": [- {- "rollout_percentage": 100,- "properties": [- {- "key": "email",- "type": "person",- "value": new_pattern,- "operator": "regex",- }- ],- }- ]- }- },++ # Initially, experiment_set should be empty+ response = self.client.get(f"/api/projects/@current/feature_flags/{feature_flag.id}")+ assert response.status_code == 200+ assert response.json()["experiment_set"] == []++ # Create an active experiment linked to the flag+ experiment = Experiment.objects.create(+ team=self.team,+ created_by=self.user,+ name="Test Experiment",+ feature_flag=feature_flag,+ start_date=datetime(2024, 1, 1, 12, 0, 0, tzinfo=UTC),)- self.assertEqual(response.status_code, expected_status)- if expected_status == status.HTTP_400_BAD_REQUEST:- self.assertEqual(response.json()["detail"], "groups[0].properties[0].value: invalid regex pattern")- def test_cant_create_flag_with_non_string_regex_value(self):- response = self.client.post(- f"/api/projects/{self.team.id}/feature_flags",- {- "name": "Beta feature",- "key": "beta-x",- "filters": {- "groups": [- {- "rollout_percentage": 65,- "properties": [- {- "key": "email",- "type": "person",- "value": 123,- "operator": "regex",- }- ],- }- ]- },- },+ # experiment_set should now include the experiment ID+ response = self.client.get(f"/api/projects/@current/feature_flags/{feature_flag.id}")+ assert response.status_code == 200+ assert response.json()["experiment_set"] == [experiment.id]++ # Create a deleted experiment - should not be included+ experiment2 = Experiment.objects.create(+ team=self.team,+ created_by=self.user,+ name="Another Experiment",+ feature_flag=feature_flag,+ start_date=datetime(2024, 1, 1, 12, 1, 0, tzinfo=UTC),)- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(response.json()["detail"], "Invalid value for operator regex: 123")- def test_can_create_flag_with_valid_regex(self):+ # experiment_set should include both experiments+ response = self.client.get(f"/api/projects/@current/feature_flags/{feature_flag.id}")+ assert response.status_code == 200+ assert response.json()["experiment_set"] == [experiment.id, experiment2.id]++ # Delete the active experiments+ experiment.deleted = True+ experiment.save()+ experiment2.deleted = True+ experiment2.save()++ # experiment_set should now be empty again+ response = self.client.get(f"/api/projects/@current/feature_flags/{feature_flag.id}")+ assert response.status_code == 200+ assert response.json()["experiment_set"] == []++ def test_bulk_keys_valid_ids(self):+ """Test that valid IDs return correct key mapping"""+ # Create test flags+ flag1 = FeatureFlag.objects.create(key="test-flag-1", name="Test Flag 1", team=self.team, created_by=self.user)+ flag2 = FeatureFlag.objects.create(key="test-flag-2", name="Test Flag 2", team=self.team, created_by=self.user)+ flag3 = FeatureFlag.objects.create(key="test-flag-3", name="Test Flag 3", team=self.team, created_by=self.user)+response = self.client.post(- f"/api/projects/{self.team.id}/feature_flags",- {- "name": "Beta feature",- "key": "beta-x",- "filters": {- "groups": [- {- "rollout_percentage": 65,- "properties": [- {- "key": "email",- "type": "person",- "value": "^[a-z]+@posthog\\.com$",- "operator": "regex",- }- ],- }- ]- },- },+ f"/api/projects/@current/feature_flags/bulk_keys/",+ {"ids": [flag1.id, flag2.id, flag3.id]},+ format="json",)- self.assertEqual(response.status_code, status.HTTP_201_CREATED)- saved = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{response.json()['id']}").json()- self.assertEqual(saved["filters"]["groups"][0]["properties"][0]["value"], "^[a-z]+@posthog\\.com$")- @parameterized.expand(- [- ("python_valid_pg_invalid_persons", "person", None, "2.3.9{0-9}{1}"),- ("python_valid_pg_invalid_groups", "group", 1, "2.3.9{0-9}{1 ef}"),- ]- )- def test_can_create_flag_with_postgres_incompatible_regex(self, _name, prop_type, group_type_index, pattern):- if prop_type == "group":- create_group_type_mapping_without_created_at(- team=self.team,- project_id=self.team.project_id,- group_type="xyz",- group_type_index=group_type_index,- )- prop = {"key": "email", "type": prop_type, "value": pattern, "operator": "regex"}- if group_type_index is not None:- prop["group_type_index"] = group_type_index- filters: dict = {"groups": [{"rollout_percentage": 65, "properties": [prop]}]}- if group_type_index is not None:- filters["aggregation_group_type_index"] = group_type_index+ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ assert "keys" in data+ assert data["keys"] == {+ str(flag1.id): "test-flag-1",+ str(flag2.id): "test-flag-2",+ str(flag3.id): "test-flag-3",+ }++ def test_bulk_keys_empty_list(self):+ """Test that empty ID list returns empty keys object"""response = self.client.post(- f"/api/projects/{self.team.id}/feature_flags",- {"name": "Beta feature", "key": f"beta-{prop_type}", "filters": filters},+ f"/api/projects/@current/feature_flags/bulk_keys/",+ {"ids": []},+ format="json",)- self.assertEqual(response.status_code, status.HTTP_201_CREATED)- saved = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{response.json()['id']}").json()- self.assertEqual(saved["filters"]["groups"][0]["properties"][0]["value"], pattern)- def test_feature_flag_includes_cohort_names(self):- cohort = Cohort.objects.create(- team=self.team,- name="test_cohort",- groups=[{"properties": [{"key": "email", "value": "@posthog.com", "type": "person"}]}],- )+ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ assert data == {"keys": {}}++ def test_bulk_keys_invalid_ids(self):+ """Test that invalid IDs (non-integers) return error"""response = self.client.post(- f"/api/projects/{self.team.id}/feature_flags/",- {- "name": "Alpha feature",- "key": "alpha-feature",- "filters": {- "groups": [{"properties": [{"key": "id", "type": "cohort", "value": cohort.pk}]}],- },- },- format="json",- )- self.assertEqual(response.status_code, status.HTTP_201_CREATED)-- # Get the flag- response = self.client.get(- f"/api/projects/{self.team.id}/feature_flags/{response.json()['id']}/",- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(- response.json()["filters"]["groups"][0]["properties"][0],- {- "key": "id",- "type": "cohort",- "value": cohort.pk,- "cohort_name": "test_cohort",- },- )-- def test_feature_flag_includes_group_key_names(self):- GroupTypeMapping.objects.create(- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0- )- Group.objects.create(- team=self.team,- group_key="org-uuid-1",- group_type_index=0,- group_properties={"name": "Acme Corp"},- version=0,- )- Group.objects.create(- team=self.team,- group_key="org-uuid-2",- group_type_index=0,- group_properties={"name": "Widget Inc"},- version=0,- )-- response = self.client.post(- f"/api/projects/{self.team.id}/feature_flags/",- {- "name": "Group flag",- "key": "group-flag",- "filters": {- "aggregation_group_type_index": 0,- "groups": [- {- "properties": [- {- "key": "$group_key",- "type": "group",- "value": ["org-uuid-1", "org-uuid-2"],- "operator": "exact",- "group_type_index": 0,- }- ]- }- ],- },- },- format="json",- )- self.assertEqual(response.status_code, status.HTTP_201_CREATED)-- response = self.client.get(- f"/api/projects/{self.team.id}/feature_flags/{response.json()['id']}/",- )- self.assertEqual(response.status_code, status.HTTP_200_OK)-- prop = response.json()["filters"]["groups"][0]["properties"][0]- self.assertEqual(prop["key"], "$group_key")- self.assertEqual(- prop["group_key_names"],- {"org-uuid-1": "Acme Corp", "org-uuid-2": "Widget Inc"},- )-- def test_create_feature_flag_in_specific_folder(self):- response = self.client.post(- f"/api/projects/{self.team.id}/feature_flags/",- data={- "key": "my-test-flag-in-folder",- "name": "Test Flag in Folder",- "filters": {"groups": [{"properties": [], "rollout_percentage": 50}]},- "_create_in_folder": "Special Folder/Flags",- },- format="json",- )- assert response.status_code == 201, response.json()- flag_id = response.json()["id"]- assert flag_id is not None-- from posthog.models.file_system.file_system import FileSystem-- fs_entry = FileSystem.objects.filter(team=self.team, ref=str(flag_id), type="feature_flag").first()- assert fs_entry, "No FileSystem entry found for this feature flag."- assert "Special Folder/Flags" in fs_entry.path, (- f"Expected 'Special Folder/Flags' in path, got: '{fs_entry.path}'"- )-- @patch("posthog.api.feature_flag.report_user_action")- def test_updating_feature_flag_key_updates_super_groups(self, mock_report_user_action):- # Create a feature flag with super_groups- feature_flag = FeatureFlag.objects.create(- team=self.team,- created_by=self.user,- key="old-key",- name="Test Flag",- filters={- "groups": [{"properties": [], "rollout_percentage": 0}],- "super_groups": [- {- "properties": [- {- "key": "$feature_enrollment/old-key",- "type": "person",- "value": ["true"],- "operator": "exact",- }- ],- "rollout_percentage": 100,- }- ],- },- )-- # Update the feature flag key- response = self.client.patch(- f"/api/projects/{self.team.id}/feature_flags/{feature_flag.id}",- {"key": "new-key"},- format="json",- )-- self.assertEqual(response.status_code, status.HTTP_200_OK)-- # Refresh the feature flag from the database- feature_flag.refresh_from_db()-- # Verify the super_groups were updated- self.assertEqual(- feature_flag.filters["super_groups"][0]["properties"][0]["key"],- "$feature_enrollment/new-key",- )-- # Verify the old key is not present- self.assertNotIn("$feature_enrollment/old-key", str(feature_flag.filters))-- def test_feature_flag_experiment_set(self):- # Create a feature flag- feature_flag = FeatureFlag.objects.create(- team=self.team,- created_by=self.user,- key="test-flag",- name="Test Flag",- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},- )-- # Initially, experiment_set should be empty- response = self.client.get(f"/api/projects/@current/feature_flags/{feature_flag.id}")- assert response.status_code == 200- assert response.json()["experiment_set"] == []-- # Create an active experiment linked to the flag- experiment = Experiment.objects.create(- team=self.team,- created_by=self.user,- name="Test Experiment",- feature_flag=feature_flag,- start_date=datetime(2024, 1, 1, 12, 0, 0, tzinfo=UTC),- )-- # experiment_set should now include the experiment ID- response = self.client.get(f"/api/projects/@current/feature_flags/{feature_flag.id}")- assert response.status_code == 200- assert response.json()["experiment_set"] == [experiment.id]-- # Create a deleted experiment - should not be included- experiment2 = Experiment.objects.create(- team=self.team,- created_by=self.user,- name="Another Experiment",- feature_flag=feature_flag,- start_date=datetime(2024, 1, 1, 12, 1, 0, tzinfo=UTC),- )-- # experiment_set should include both experiments- response = self.client.get(f"/api/projects/@current/feature_flags/{feature_flag.id}")- assert response.status_code == 200- assert response.json()["experiment_set"] == [experiment.id, experiment2.id]-- # Delete the active experiments- experiment.deleted = True- experiment.save()- experiment2.deleted = True- experiment2.save()-- # experiment_set should now be empty again- response = self.client.get(f"/api/projects/@current/feature_flags/{feature_flag.id}")- assert response.status_code == 200- assert response.json()["experiment_set"] == []-- def test_bulk_keys_valid_ids(self):- """Test that valid IDs return correct key mapping"""- # Create test flags- flag1 = FeatureFlag.objects.create(key="test-flag-1", name="Test Flag 1", team=self.team, created_by=self.user)- flag2 = FeatureFlag.objects.create(key="test-flag-2", name="Test Flag 2", team=self.team, created_by=self.user)- flag3 = FeatureFlag.objects.create(key="test-flag-3", name="Test Flag 3", team=self.team, created_by=self.user)-- response = self.client.post(- f"/api/projects/@current/feature_flags/bulk_keys/",- {"ids": [flag1.id, flag2.id, flag3.id]},- format="json",- )-- assert response.status_code == status.HTTP_200_OK- data = response.json()- assert "keys" in data- assert data["keys"] == {- str(flag1.id): "test-flag-1",- str(flag2.id): "test-flag-2",- str(flag3.id): "test-flag-3",- }-- def test_bulk_keys_empty_list(self):- """Test that empty ID list returns empty keys object"""- response = self.client.post(- f"/api/projects/@current/feature_flags/bulk_keys/",- {"ids": []},- format="json",- )-- assert response.status_code == status.HTTP_200_OK- data = response.json()- assert data == {"keys": {}}-- def test_bulk_keys_invalid_ids(self):- """Test that invalid IDs (non-integers) return error"""- response = self.client.post(- f"/api/projects/@current/feature_flags/bulk_keys/",- {"ids": ["invalid", "not-a-number"]},+ f"/api/projects/@current/feature_flags/bulk_keys/",+ {"ids": ["invalid", "not-a-number"]},format="json",)@@ -7753,107 +7416,29 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):assert "keys" in dataassert data["keys"] == {str(flag1.id): "test-flag-1"}- def test_bulk_keys_works_with_personal_api_key(self):- """Once enabled as MCP tool with feature_flag:read scope, PAT requests must succeed."""- flag = FeatureFlag.objects.create(+ def test_local_evaluation_caching_basic(self):+ """Test basic caching functionality for local_evaluation endpoint."""+ # Clear any existing flags for this team to avoid interference+ FeatureFlag.objects.filter(team=self.team).delete()++ FeatureFlag.objects.create(team=self.team,created_by=self.user,- key="pat-scope-test",- filters={"groups": [{"rollout_percentage": 100, "properties": []}]},+ key="test-flag",+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},)+personal_api_key = generate_random_token_personal()PersonalAPIKey.objects.create(- label="X",- user=self.user,- scopes=["feature_flag:read"],- secure_value=hash_key_value(personal_api_key),+ label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key))- self.client.logout()- response = self.client.post(- f"/api/projects/{self.team.id}/feature_flags/bulk_keys/",- {"ids": [flag.id]},- format="json",- headers={"authorization": f"Bearer {personal_api_key}"},- )- assert response.status_code == status.HTTP_200_OK, response.json()- assert response.json() == {"keys": {str(flag.id): "pat-scope-test"}}-- def test_bulk_update_tags_works_with_personal_api_key(self):- """Same scope-config bug on bulk_update_tags; same fix in tagged_item.py."""- flag = FeatureFlag.objects.create(- team=self.team,- created_by=self.user,- key="pat-tag-test",- filters={"groups": [{"rollout_percentage": 100, "properties": []}]},- )- personal_api_key = generate_random_token_personal()- PersonalAPIKey.objects.create(- label="X",- user=self.user,- scopes=["feature_flag:write"],- secure_value=hash_key_value(personal_api_key),- )- self.client.logout()- response = self.client.post(- f"/api/projects/{self.team.id}/feature_flags/bulk_update_tags/",- {"ids": [flag.id], "action": "add", "tags": ["foo"]},- format="json",- headers={"authorization": f"Bearer {personal_api_key}"},- )- assert response.status_code == status.HTTP_200_OK, response.json()- # Pin the body so a regression that grants the PAT scope but loses the- # mutation (broken preload_object_access_controls, wrong scope_object,- # etc.) can't stay green: the endpoint returns 200 with the flag in- # `skipped` rather than a non-2xx status when ACLs drop it.- body = response.json()- assert body["updated"] == [{"id": flag.id, "tags": ["foo"]}]- assert body["skipped"] == []-- # Lives in the feature-flag test file (instead of test_insight.py) so the- # full bulk-ops PAT regression story — positive feature-flag cases and the- # negative cross-resource block — stays adjacent for reviewers of #57885.- def test_feature_flag_write_pat_cannot_mutate_insight_tags(self):- """A feature_flag:write PAT must not reach Insight.bulk_update_tags via the shared mixin."""- insight = Insight.objects.create(team=self.team, name="x", created_by=self.user)- personal_api_key = generate_random_token_personal()- PersonalAPIKey.objects.create(- label="X",- user=self.user,- scopes=["feature_flag:write"],- secure_value=hash_key_value(personal_api_key),- )- self.client.logout()- response = self.client.post(- f"/api/projects/{self.team.id}/insights/bulk_update_tags/",- {"ids": [insight.id], "action": "add", "tags": ["foo"]},- format="json",- headers={"authorization": f"Bearer {personal_api_key}"},- )- assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()-- def test_local_evaluation_caching_basic(self):- """Test basic caching functionality for local_evaluation endpoint."""- # Clear any existing flags for this team to avoid interference- FeatureFlag.objects.filter(team=self.team).delete()-- FeatureFlag.objects.create(- team=self.team,- created_by=self.user,- key="test-flag",- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},- )-- personal_api_key = generate_random_token_personal()- PersonalAPIKey.objects.create(- label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)- )-- # Clear both Redis and S3 caches- from posthog.models.feature_flag.local_evaluation import clear_flag_definition_caches-- clear_flag_definition_caches(self.team)-- # First request should miss cache and populate it++ # Clear both Redis and S3 caches+ from products.feature_flags.backend.local_evaluation import clear_flag_definition_caches++ clear_flag_definition_caches(self.team)++ # First request should miss cache and populate itself.client.logout()response = self.client.get(f"/api/feature_flag/local_evaluation",@@ -8225,7 +7810,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):@patch("django.db.transaction.on_commit", side_effect=lambda func: func())def test_local_evaluation_cache_invalidation_on_feature_flag_delete(self, mock_on_commit):"""Test that cache invalidates when FeatureFlag is deleted."""- from posthog.models.feature_flag.local_evaluation import (+ from products.feature_flags.backend.local_evaluation import (flag_definitions_hypercache,flag_definitions_without_cohorts_hypercache,)@@ -8300,7 +7885,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):@patch("django.db.transaction.on_commit", side_effect=lambda func: func())def test_local_evaluation_cache_invalidation_on_cohort_delete(self, mock_on_commit):"""Test that cache invalidates when Cohort is deleted."""- from posthog.models.feature_flag.local_evaluation import (+ from products.feature_flags.backend.local_evaluation import (flag_definitions_hypercache,flag_definitions_without_cohorts_hypercache,)@@ -8362,7 +7947,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):# Verify response changed from the original cached versionself.assertNotEqual(data["cohorts"], updated_data.get("cohorts", {}))- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_create_feature_flag_without_usage_dashboard(self, mock_report_user_action):response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/",@@ -8392,7 +7977,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key))- from posthog.models.feature_flag.local_evaluation import clear_flag_definition_caches+ from products.feature_flags.backend.local_evaluation import clear_flag_definition_cachesclear_flag_definition_caches(self.team)@@ -8423,7 +8008,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key))- from posthog.models.feature_flag.local_evaluation import clear_flag_definition_caches+ from products.feature_flags.backend.local_evaluation import clear_flag_definition_cachesclear_flag_definition_caches(self.team)@@ -8463,7 +8048,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key))- from posthog.models.feature_flag.local_evaluation import clear_flag_definition_caches+ from products.feature_flags.backend.local_evaluation import clear_flag_definition_cachesclear_flag_definition_caches(self.team)@@ -8497,7 +8082,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key))- from posthog.models.feature_flag.local_evaluation import clear_flag_definition_caches+ from products.feature_flags.backend.local_evaluation import clear_flag_definition_cachesclear_flag_definition_caches(self.team)@@ -8552,7 +8137,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key))- from posthog.models.feature_flag.local_evaluation import clear_flag_definition_caches+ from products.feature_flags.backend.local_evaluation import clear_flag_definition_cachesclear_flag_definition_caches(self.team)@@ -8602,7 +8187,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key))- from posthog.models.feature_flag.local_evaluation import clear_flag_definition_caches+ from products.feature_flags.backend.local_evaluation import clear_flag_definition_cachesclear_flag_definition_caches(self.team)@@ -8647,7 +8232,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key))- from posthog.models.feature_flag.local_evaluation import clear_flag_definition_caches+ from products.feature_flags.backend.local_evaluation import clear_flag_definition_cachesclear_flag_definition_caches(self.team)@@ -8687,7 +8272,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key))- from posthog.models.feature_flag.local_evaluation import clear_flag_definition_caches+ from products.feature_flags.backend.local_evaluation import clear_flag_definition_cachesclear_flag_definition_caches(self.team)@@ -8717,7 +8302,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.headers["ETag"], etag)def test_local_evaluation_secret_key_in_body_counter_not_incremented_for_header_auth(self):- from posthog.api.feature_flag import LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTER+ from products.feature_flags.backend.api.feature_flag import LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTERself.team.secret_api_token = "phs_testtokenforheaderauth"self.team.save()@@ -8741,7 +8326,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTER._value.get(), before)def test_local_evaluation_secret_key_in_body_counter_incremented_for_body_auth(self):- from posthog.api.feature_flag import LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTER+ from products.feature_flags.backend.api.feature_flag import LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTERself.team.secret_api_token = "phs_testtokenforbodyauth"self.team.save()@@ -8767,7 +8352,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTER._value.get(), before + 1)def test_local_evaluation_secret_key_in_body_counter_not_incremented_when_header_wins(self):- from posthog.api.feature_flag import LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTER+ from products.feature_flags.backend.api.feature_flag import LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTERself.team.secret_api_token = "phs_testtokenforheaderwins"self.team.save()@@ -8791,186 +8376,605 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):content_type="application/json",headers={"authorization": f"Bearer {self.team.secret_api_token}"},)- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTER._value.get(), before)+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(LOCAL_EVALUATION_SECRET_KEY_IN_BODY_COUNTER._value.get(), before)++ @parameterized.expand(+ [+ ("header", "header"),+ ("body", "body"),+ ("query_string", "query_string"),+ ]+ )+ def test_local_evaluation_personal_api_key_source_counter(self, name, source):+ from products.feature_flags.backend.api.feature_flag import LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER++ FeatureFlag.objects.filter(team=self.team).delete()+ FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key="test-flag",+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )++ personal_api_key = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)+ )++ self.client.logout()+ before = LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER.labels(source=source)._value.get()++ url = f"/api/feature_flag/local_evaluation?token={self.team.api_token}"+ if source == "header":+ response = self.client.get(+ url,+ headers={"authorization": f"Bearer {personal_api_key}"},+ )+ elif source == "body":+ response = self.client.generic( # type: ignore[assignment]+ "GET",+ url,+ data=json.dumps({"personal_api_key": personal_api_key}),+ content_type="application/json",+ )+ else:+ response = self.client.get(+ f"{url}&personal_api_key={personal_api_key}",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(+ LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER.labels(source=source)._value.get(),+ before + 1,+ )++ def test_local_evaluation_personal_api_key_source_counter_not_incremented_for_secret_key(self):+ from products.feature_flags.backend.api.feature_flag import LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER++ self.team.secret_api_token = "phs_testtokenforpaksource"+ self.team.save()++ FeatureFlag.objects.filter(team=self.team).delete()+ FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key="test-flag",+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )++ self.client.logout()+ before_header = LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER.labels(source="header")._value.get()+ before_body = LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER.labels(source="body")._value.get()++ response = self.client.get(+ f"/api/feature_flag/local_evaluation?token={self.team.api_token}",+ headers={"authorization": f"Bearer {self.team.secret_api_token}"},+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(+ LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER.labels(source="header")._value.get(), before_header+ )+ self.assertEqual(+ LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER.labels(source="body")._value.get(), before_body+ )++ def test_feature_flag_detail_actions_respect_access_control(self) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()++ user2 = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)++ flag = FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ name="secret flag",+ key="secret-flag",+ )+ AccessControl.objects.create(resource="feature_flag", resource_id=flag.id, team=self.team, access_level="none")++ self.client.force_login(user2)++ retrieve_response = self.client.get(f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/")+ self.assertEqual(retrieve_response.status_code, status.HTTP_403_FORBIDDEN)++ activity_response = self.client.get(f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/activity/")+ self.assertEqual(activity_response.status_code, status.HTTP_403_FORBIDDEN)++ status_response = self.client.get(f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/status/")+ self.assertEqual(status_response.status_code, status.HTTP_403_FORBIDDEN)++ def test_org_admin_can_list_flag_with_default_none_after_grantee_removed(self) -> None:+ # Regression: a flag with a team-wide "none" default plus a single explicit+ # editor grant becomes invisible to everyone once the grantee is removed+ # from the org (their AccessControl row cascade-deletes). Org admins should+ # still be able to find such orphaned flags in the list endpoint.+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()++ creator = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)+ grantee = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)+ grantee_membership = grantee.organization_memberships.get(organization=self.organization)++ flag = FeatureFlag.objects.create(+ team=self.team,+ created_by=creator,+ name="orphaned flag",+ key="orphaned-flag",+ )+ # Team-wide "no access" default for this flag+ AccessControl.objects.create(resource="feature_flag", resource_id=flag.id, team=self.team, access_level="none")+ # Single explicit editor grant for the grantee+ AccessControl.objects.create(+ resource="feature_flag",+ resource_id=flag.id,+ team=self.team,+ organization_member=grantee_membership,+ access_level="editor",+ )++ # self.user is the org admin via APIBaseTest setup+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()++ # Remove the grantee from the org -> cascade deletes their explicit grant+ grantee_membership.delete()++ # Org admin must still see the flag in the list (it's an orphaned flag now)+ list_response = self.client.get(f"/api/projects/{self.team.pk}/feature_flags/")+ self.assertEqual(list_response.status_code, status.HTTP_200_OK)+ keys = [f["key"] for f in list_response.json()["results"]]+ self.assertIn("orphaned-flag", keys)++ def test_member_still_blocked_from_listing_default_none_flag(self) -> None:+ # Counterpart to the test above: non-admin members without an explicit+ # grant must still be filtered out by the per-object "none" default.+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()++ other = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)++ flag = FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ name="blocked flag",+ key="blocked-flag",+ )+ AccessControl.objects.create(resource="feature_flag", resource_id=flag.id, team=self.team, access_level="none")++ self.client.force_login(other)+ list_response = self.client.get(f"/api/projects/{self.team.pk}/feature_flags/")+ self.assertEqual(list_response.status_code, status.HTTP_200_OK)+ keys = [f["key"] for f in list_response.json()["results"]]+ self.assertNotIn("blocked-flag", keys)++ @parameterized.expand(+ [+ ("create",),+ ("rename",),+ ]+ )+ def test_reuses_key_held_by_legacy_soft_deleted_flag_with_soft_deleted_experiment(self, mode: str):+ # Legacy tombstone holds the key with a soft-deleted experiment FK+ # blocking hard-delete. Reusing the key should rename the tombstone,+ # not raise the old "delete the experiment" error.+ legacy_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="ghost-key")+ exp = Experiment.objects.create(team=self.team, created_by=self.user, feature_flag=legacy_flag)+ exp.deleted = True+ exp.save()+ # Bypass API so soft-delete rename doesn't fire — mimics historical data.+ FeatureFlag.objects_including_soft_deleted.filter(pk=legacy_flag.pk).update(deleted=True)++ if mode == "create":+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ {"name": "Ghost", "key": "ghost-key"},+ )+ assert response.status_code == 201, response.content+ assert response.json()["key"] == "ghost-key"+ else:+ other = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="ghost-key-v2")+ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{other.id}/",+ {"key": "ghost-key"},+ )+ assert response.status_code == 200, response.content+ other.refresh_from_db()+ assert other.key == "ghost-key"++ # Tombstone is renamed; experiment FK still resolves.+ legacy_flag = FeatureFlag.objects_including_soft_deleted.get(pk=legacy_flag.pk)+ assert legacy_flag.deleted is True+ assert legacy_flag.key == f"ghost-key:deleted:{legacy_flag.id}"+ exp.refresh_from_db()+ assert exp.feature_flag_id == legacy_flag.id++ @parameterized.expand(+ [+ ("create",),+ ("rename",),+ ]+ )+ def test_reuse_key_with_inconsistent_soft_deleted_flag_referenced_by_active_experiment(self, mode: str):+ # If a tombstone is still referenced by an active experiment (invariant+ # violation), renaming it would silently break the experiment. Error out.+ legacy_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="inconsistent-key")+ exp = Experiment.objects.create(team=self.team, created_by=self.user, feature_flag=legacy_flag)+ FeatureFlag.objects_including_soft_deleted.filter(pk=legacy_flag.pk).update(deleted=True)++ if mode == "create":+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ {"name": "Inconsistent", "key": "inconsistent-key"},+ )+ else:+ other = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="inconsistent-key-v2")+ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{other.id}/",+ {"key": "inconsistent-key"},+ )++ assert response.status_code == 400+ assert f"active experiment(s) with ID(s): {exp.id}" in response.json()["detail"]+ assert "inconsistent-key" in response.json()["detail"]++ # Tombstone was not mutated.+ legacy_flag.refresh_from_db()+ assert legacy_flag.key == "inconsistent-key"++ @parameterized.expand(+ [+ ("create",),+ ("rename",),+ ]+ )+ def test_reuse_key_with_inconsistent_soft_deleted_flag_referenced_by_eaf(self, mode: str):+ # EarlyAccessFeature.feature_flag uses on_delete=PROTECT (sibling of+ # RESTRICT). A tombstone with an EAF must surface the same defensive+ # error, not a 500.+ legacy_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="eaf-key")+ EarlyAccessFeature.objects.create(+ team=self.team,+ name="EAF",+ description="",+ stage="alpha",+ feature_flag=legacy_flag,+ )+ FeatureFlag.objects_including_soft_deleted.filter(pk=legacy_flag.pk).update(deleted=True)++ if mode == "create":+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/",+ {"name": "EAF Reuse", "key": "eaf-key"},+ )+ else:+ other = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="eaf-key-v2")+ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{other.id}/",+ {"key": "eaf-key"},+ )++ assert response.status_code == 400+ assert "early access feature(s)" in response.json()["detail"]+ assert "eaf-key" in response.json()["detail"]++ legacy_flag.refresh_from_db()+ assert legacy_flag.key == "eaf-key"++ def test_cant_create_flag_with_invalid_regex(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags",+ {+ "name": "Beta feature",+ "key": "beta-x",+ "filters": {+ "groups": [+ {+ "rollout_percentage": 65,+ "properties": [+ {+ "key": "email",+ "type": "person",+ "value": "[unclosed",+ "operator": "regex",+ }+ ],+ }+ ]+ },+ },+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["detail"], "groups[0].properties[0].value: invalid regex pattern")++ def test_cant_create_flag_with_invalid_not_regex(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags",+ {+ "name": "Beta feature",+ "key": "beta-x",+ "filters": {+ "groups": [+ {+ "rollout_percentage": 65,+ "properties": [+ {+ "key": "email",+ "type": "group",+ "group_type_index": 0,+ "value": "(unclosed",+ "operator": "not_regex",+ }+ ],+ }+ ],+ },+ },+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["detail"], "groups[0].properties[0].value: invalid regex pattern")++ def test_patch_non_filter_field_skips_regex_validation(self):+ flag = FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key="flag-with-lookbehind",+ filters={+ "groups": [+ {+ "rollout_percentage": 100,+ "properties": [+ {+ "key": "email",+ "type": "person",+ "value": "(?<!a{2,5})b",+ "operator": "regex",+ }+ ],+ }+ ]+ },+ )+ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}",+ {"active": False},+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ @parameterized.expand(+ [+ (+ "unchanged_invalid_regex_accepted",+ "(?<!a{2,5})b",+ "(?<!a{2,5})b",+ status.HTTP_200_OK,+ ),+ (+ "valid_to_invalid_regex_rejected",+ "^valid$",+ "[unclosed",+ status.HTTP_400_BAD_REQUEST,+ ),+ (+ "different_invalid_regex_rejected",+ "[unclosed",+ "(unbalanced",+ status.HTTP_400_BAD_REQUEST,+ ),+ ]+ )+ def test_patch_flag_regex_validation(self, _name, existing_pattern, new_pattern, expected_status):+ flag = FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key="flag-regex-test",+ filters={+ "groups": [+ {+ "rollout_percentage": 100,+ "properties": [+ {+ "key": "email",+ "type": "person",+ "value": existing_pattern,+ "operator": "regex",+ }+ ],+ }+ ]+ },+ )+ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}",+ {+ "filters": {+ "groups": [+ {+ "rollout_percentage": 100,+ "properties": [+ {+ "key": "email",+ "type": "person",+ "value": new_pattern,+ "operator": "regex",+ }+ ],+ }+ ]+ }+ },+ )+ self.assertEqual(response.status_code, expected_status)+ if expected_status == status.HTTP_400_BAD_REQUEST:+ self.assertEqual(response.json()["detail"], "groups[0].properties[0].value: invalid regex pattern")++ def test_cant_create_flag_with_non_string_regex_value(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags",+ {+ "name": "Beta feature",+ "key": "beta-x",+ "filters": {+ "groups": [+ {+ "rollout_percentage": 65,+ "properties": [+ {+ "key": "email",+ "type": "person",+ "value": 123,+ "operator": "regex",+ }+ ],+ }+ ]+ },+ },+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["detail"], "Invalid value for operator regex: 123")++ def test_can_create_flag_with_valid_regex(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags",+ {+ "name": "Beta feature",+ "key": "beta-x",+ "filters": {+ "groups": [+ {+ "rollout_percentage": 65,+ "properties": [+ {+ "key": "email",+ "type": "person",+ "value": "^[a-z]+@posthog\\.com$",+ "operator": "regex",+ }+ ],+ }+ ]+ },+ },+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ saved = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{response.json()['id']}").json()+ self.assertEqual(saved["filters"]["groups"][0]["properties"][0]["value"], "^[a-z]+@posthog\\.com$")@parameterized.expand([- ("header", "header"),- ("body", "body"),- ("query_string", "query_string"),+ ("python_valid_pg_invalid_persons", "person", None, "2.3.9{0-9}{1}"),+ ("python_valid_pg_invalid_groups", "group", 1, "2.3.9{0-9}{1 ef}"),])- def test_local_evaluation_personal_api_key_source_counter(self, name, source):- from posthog.api.feature_flag import LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER+ def test_can_create_flag_with_postgres_incompatible_regex(self, _name, prop_type, group_type_index, pattern):+ if prop_type == "group":+ create_group_type_mapping_without_created_at(+ team=self.team,+ project_id=self.team.project_id,+ group_type="xyz",+ group_type_index=group_type_index,+ )+ prop = {"key": "email", "type": prop_type, "value": pattern, "operator": "regex"}+ if group_type_index is not None:+ prop["group_type_index"] = group_type_index+ filters: dict = {"groups": [{"rollout_percentage": 65, "properties": [prop]}]}+ if group_type_index is not None:+ filters["aggregation_group_type_index"] = group_type_index+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags",+ {"name": "Beta feature", "key": f"beta-{prop_type}", "filters": filters},+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ saved = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{response.json()['id']}").json()+ self.assertEqual(saved["filters"]["groups"][0]["properties"][0]["value"], pattern)- FeatureFlag.objects.filter(team=self.team).delete()- FeatureFlag.objects.create(+ def test_bulk_keys_works_with_personal_api_key(self):+ """Once enabled as MCP tool with feature_flag:read scope, PAT requests must succeed."""+ flag = FeatureFlag.objects.create(team=self.team,created_by=self.user,- key="test-flag",- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ key="pat-scope-test",+ filters={"groups": [{"rollout_percentage": 100, "properties": []}]},)-personal_api_key = generate_random_token_personal()PersonalAPIKey.objects.create(- label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)- )-- self.client.logout()- before = LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER.labels(source=source)._value.get()-- url = f"/api/feature_flag/local_evaluation?token={self.team.api_token}"- if source == "header":- response = self.client.get(- url,- headers={"authorization": f"Bearer {personal_api_key}"},- )- elif source == "body":- response = self.client.generic( # type: ignore[assignment]- "GET",- url,- data=json.dumps({"personal_api_key": personal_api_key}),- content_type="application/json",- )- else:- response = self.client.get(- f"{url}&personal_api_key={personal_api_key}",- )-- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(- LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER.labels(source=source)._value.get(),- before + 1,- )-- def test_local_evaluation_personal_api_key_source_counter_not_incremented_for_secret_key(self):- from posthog.api.feature_flag import LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER-- self.team.secret_api_token = "phs_testtokenforpaksource"- self.team.save()-- FeatureFlag.objects.filter(team=self.team).delete()- FeatureFlag.objects.create(- team=self.team,- created_by=self.user,- key="test-flag",- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ label="X",+ user=self.user,+ scopes=["feature_flag:read"],+ secure_value=hash_key_value(personal_api_key),)-self.client.logout()- before_header = LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER.labels(source="header")._value.get()- before_body = LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER.labels(source="body")._value.get()-- response = self.client.get(- f"/api/feature_flag/local_evaluation?token={self.team.api_token}",- headers={"authorization": f"Bearer {self.team.secret_api_token}"},- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(- LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER.labels(source="header")._value.get(), before_header- )- self.assertEqual(- LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER.labels(source="body")._value.get(), before_body+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/bulk_keys/",+ {"ids": [flag.id]},+ format="json",+ headers={"authorization": f"Bearer {personal_api_key}"},)+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json() == {"keys": {str(flag.id): "pat-scope-test"}}- def test_feature_flag_detail_actions_respect_access_control(self) -> None:- self.organization.available_product_features = [- {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},- {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},- ]- self.organization.save()-- user2 = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)-+ def test_bulk_update_tags_works_with_personal_api_key(self):+ """Same scope-config bug on bulk_update_tags; same fix in tagged_item.py."""flag = FeatureFlag.objects.create(team=self.team,created_by=self.user,- name="secret flag",- key="secret-flag",+ key="pat-tag-test",+ filters={"groups": [{"rollout_percentage": 100, "properties": []}]},)- AccessControl.objects.create(resource="feature_flag", resource_id=flag.id, team=self.team, access_level="none")-- self.client.force_login(user2)-- retrieve_response = self.client.get(f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/")- self.assertEqual(retrieve_response.status_code, status.HTTP_403_FORBIDDEN)-- activity_response = self.client.get(f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/activity/")- self.assertEqual(activity_response.status_code, status.HTTP_403_FORBIDDEN)-- status_response = self.client.get(f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/status/")- self.assertEqual(status_response.status_code, status.HTTP_403_FORBIDDEN)-- def test_org_admin_can_list_flag_with_default_none_after_grantee_removed(self) -> None:- # Regression: a flag with a team-wide "none" default plus a single explicit- # editor grant becomes invisible to everyone once the grantee is removed- # from the org (their AccessControl row cascade-deletes). Org admins should- # still be able to find such orphaned flags in the list endpoint.- self.organization.available_product_features = [- {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},- {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},- ]- self.organization.save()-- creator = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)- grantee = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)- grantee_membership = grantee.organization_memberships.get(organization=self.organization)-- flag = FeatureFlag.objects.create(- team=self.team,- created_by=creator,- name="orphaned flag",- key="orphaned-flag",+ personal_api_key = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="X",+ user=self.user,+ scopes=["feature_flag:write"],+ secure_value=hash_key_value(personal_api_key),)- # Team-wide "no access" default for this flag- AccessControl.objects.create(resource="feature_flag", resource_id=flag.id, team=self.team, access_level="none")- # Single explicit editor grant for the grantee- AccessControl.objects.create(- resource="feature_flag",- resource_id=flag.id,- team=self.team,- organization_member=grantee_membership,- access_level="editor",+ self.client.logout()+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/bulk_update_tags/",+ {"ids": [flag.id], "action": "add", "tags": ["foo"]},+ format="json",+ headers={"authorization": f"Bearer {personal_api_key}"},)+ assert response.status_code == status.HTTP_200_OK, response.json()+ # Pin the body so a regression that grants the PAT scope but loses the+ # mutation (broken preload_object_access_controls, wrong scope_object,+ # etc.) can't stay green: the endpoint returns 200 with the flag in+ # `skipped` rather than a non-2xx status when ACLs drop it.+ body = response.json()+ assert body["updated"] == [{"id": flag.id, "tags": ["foo"]}]+ assert body["skipped"] == []- # self.user is the org admin via APIBaseTest setup- self.organization_membership.level = OrganizationMembership.Level.ADMIN- self.organization_membership.save()-- # Remove the grantee from the org -> cascade deletes their explicit grant- grantee_membership.delete()-- # Org admin must still see the flag in the list (it's an orphaned flag now)- list_response = self.client.get(f"/api/projects/{self.team.pk}/feature_flags/")- self.assertEqual(list_response.status_code, status.HTTP_200_OK)- keys = [f["key"] for f in list_response.json()["results"]]- self.assertIn("orphaned-flag", keys)-- def test_member_still_blocked_from_listing_default_none_flag(self) -> None:- # Counterpart to the test above: non-admin members without an explicit- # grant must still be filtered out by the per-object "none" default.- self.organization.available_product_features = [- {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},- {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},- ]- self.organization.save()-- other = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)-- flag = FeatureFlag.objects.create(- team=self.team,- created_by=self.user,- name="blocked flag",- key="blocked-flag",+ # Lives in the feature-flag test file (instead of test_insight.py) so the+ # full bulk-ops PAT regression story — positive feature-flag cases and the+ # negative cross-resource block — stays adjacent for reviewers of #57885.+ def test_feature_flag_write_pat_cannot_mutate_insight_tags(self):+ """A feature_flag:write PAT must not reach Insight.bulk_update_tags via the shared mixin."""+ insight = Insight.objects.create(team=self.team, name="x", created_by=self.user)+ personal_api_key = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="X",+ user=self.user,+ scopes=["feature_flag:write"],+ secure_value=hash_key_value(personal_api_key),)- AccessControl.objects.create(resource="feature_flag", resource_id=flag.id, team=self.team, access_level="none")-- self.client.force_login(other)- list_response = self.client.get(f"/api/projects/{self.team.pk}/feature_flags/")- self.assertEqual(list_response.status_code, status.HTTP_200_OK)- keys = [f["key"] for f in list_response.json()["results"]]- self.assertNotIn("blocked-flag", keys)+ self.client.logout()+ response = self.client.post(+ f"/api/projects/{self.team.id}/insights/bulk_update_tags/",+ {"ids": [insight.id], "action": "add", "tags": ["foo"]},+ format="json",+ headers={"authorization": f"Bearer {personal_api_key}"},+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()def test_member_still_blocked_from_bulk_keys_default_none_flag(self) -> None:# bulk_keys must not leak keys for flags the user has been explicitly@@ -9322,7 +9326,7 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):response = self.client.get(f"/api/cohort/{cohort.pk}/persons")self.assertEqual(len(response.json()["results"]), 0, response)- @patch("posthog.tasks.feature_flags.update_team_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_flags_cache")@patch("django.db.transaction.on_commit", side_effect=lambda func: func())def test_creating_static_cohort_with_experience_continuity_flag(self, mock_on_commit, mock_update_cache):FeatureFlag.objects.create(@@ -9384,7 +9388,7 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):response = self.client.get(f"/api/cohort/{cohort.pk}/persons")self.assertEqual(len(response.json()["results"]), 1, response)- @patch("posthog.tasks.feature_flags.update_team_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_flags_cache")@patch("django.db.transaction.on_commit", side_effect=lambda func: func())def test_creating_static_cohort_iterator(self, mock_on_commit, mock_update_cache):FeatureFlag.objects.create(@@ -9453,7 +9457,7 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):response = self.client.get(f"/api/cohort/{cohort.pk}/persons")self.assertEqual(len(response.json()["results"]), 3, response)- @patch("posthog.tasks.feature_flags.update_team_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_flags_cache")@patch("django.db.transaction.on_commit", side_effect=lambda func: func())def test_creating_static_cohort_with_default_person_properties_adjustment(self, mock_on_commit, mock_update_cache):FeatureFlag.objects.create(@@ -9547,7 +9551,7 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(cohort2.name, "some cohort2")self.assertEqual(cohort2.count, 2)- @patch("posthog.tasks.feature_flags.update_team_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_flags_cache")@patch("django.db.transaction.on_commit", side_effect=lambda func: func())def test_creating_static_cohort_with_cohort_flag_adds_cohort_props_as_default_too(self, mock_on_commit, mock_update_cache@@ -11413,7 +11417,7 @@ class TestFeatureFlagEvaluationContexts(APIBaseTest):self.assertEqual(tag_names, ["app", "docs", "marketing"])# Check that evaluation contexts are created (using new model)- from posthog.models.evaluation_context import FeatureFlagEvaluationContext+ from products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContexteval_contexts = FeatureFlagEvaluationContext.objects.filter(feature_flag=flag)self.assertEqual(eval_contexts.count(), 2)@@ -11440,7 +11444,7 @@ class TestFeatureFlagEvaluationContexts(APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_200_OK)- from posthog.models.evaluation_context import FeatureFlagEvaluationContext+ from products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContexteval_contexts = FeatureFlagEvaluationContext.objects.filter(feature_flag=flag)self.assertEqual(eval_contexts.count(), 1)@@ -11482,7 +11486,7 @@ class TestFeatureFlagEvaluationContexts(APIBaseTest):format="json",)- from posthog.models.evaluation_context import FeatureFlagEvaluationContext+ from products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContextself.assertEqual(FeatureFlagEvaluationContext.objects.filter(feature_flag=flag).count(), 2)@@ -11505,8 +11509,11 @@ class TestFeatureFlagEvaluationContexts(APIBaseTest):@pytest.mark.eedef test_evaluation_contexts_in_minimal_serializer(self):- from posthog.api.feature_flag import MinimalFeatureFlagSerializer- from posthog.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext+ from products.feature_flags.backend.api.feature_flag import MinimalFeatureFlagSerializer+ from products.feature_flags.backend.models.evaluation_context import (+ EvaluationContext,+ FeatureFlagEvaluationContext,+ )flag = FeatureFlag.objects.create(team=self.team,@@ -11606,8 +11613,11 @@ class TestFeatureFlagEvaluationContexts(APIBaseTest):@pytest.mark.eedef test_evaluation_contexts_in_cache(self):- from posthog.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext- from posthog.models.feature_flag import set_feature_flags_for_team_in_cache+ from products.feature_flags.backend.models.evaluation_context import (+ EvaluationContext,+ FeatureFlagEvaluationContext,+ )+ from products.feature_flags.backend.models.feature_flag import set_feature_flags_for_team_in_cacheflag = FeatureFlag.objects.create(team=self.team,@@ -11638,7 +11648,10 @@ class TestFeatureFlagEvaluationContexts(APIBaseTest):@pytest.mark.eedef test_evaluation_contexts_cache_invalidation(self):- from posthog.models.feature_flag import get_feature_flags_for_team_in_cache, set_feature_flags_for_team_in_cache+ from products.feature_flags.backend.models.feature_flag import (+ get_feature_flags_for_team_in_cache,+ set_feature_flags_for_team_in_cache,+ )flag = FeatureFlag.objects.create(team=self.team,@@ -13027,8 +13040,12 @@ class TestFeatureFlagBulkDelete(APIBaseTest):# Mock on_commit to execute callbacks immediately (Django test transactions don't commit)# Patch at source module since the import happens inside the function- with patch("posthog.api.feature_flag.transaction.on_commit", side_effect=lambda fn: fn()):- with patch("posthog.models.feature_flag.feature_flag.set_feature_flags_for_team_in_cache") as mock_cache:+ with patch(+ "products.feature_flags.backend.api.feature_flag.transaction.on_commit", side_effect=lambda fn: fn()+ ):+ with patch(+ "products.feature_flags.backend.models.feature_flag.set_feature_flags_for_team_in_cache"+ ) as mock_cache:response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/bulk_delete/",{"ids": [f.id for f in flags]},@@ -13421,8 +13438,8 @@ class TestFeatureFlagVersions(APIBaseTest):class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):- @patch("posthog.api.feature_flag.get_flags_from_service")- @patch("posthog.api.feature_flag.get_person_and_distinct_ids_for_identifier")+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")+ @patch("products.feature_flags.backend.api.feature_flag.get_person_and_distinct_ids_for_identifier")@override_settings(INTERNAL_REQUEST_TOKEN="test-token")def test_test_evaluation_happy_path(self, mock_get_person, mock_get_flags):"""Test successful evaluation of a feature flag."""@@ -13478,8 +13495,8 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):self.assertEqual(data["evaluation_distinct_id"], "test-user")self.assertEqual(mock_get_flags.call_args.kwargs["distinct_id"], "test-user")- @patch("posthog.api.feature_flag.get_flags_from_service")- @patch("posthog.api.feature_flag.get_person_and_distinct_ids_for_identifier")+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")+ @patch("products.feature_flags.backend.api.feature_flag.get_person_and_distinct_ids_for_identifier")@override_settings(INTERNAL_REQUEST_TOKEN="test-token")def test_test_evaluation_with_person_id_uses_smallest_distinct_id(self, mock_get_person, mock_get_flags):"""When the caller passes person_id (no distinct_id), bucketing must@@ -13519,7 +13536,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):# ...but the response must NOT leak it back to the caller.self.assertIsNone(response.json()["evaluation_distinct_id"])- @patch("posthog.api.feature_flag.get_flags_from_service")+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")@override_settings(INTERNAL_REQUEST_TOKEN="test-token")def test_test_evaluation_with_timestamp(self, mock_get_flags):"""Historical evaluation must drive the Rust call with reconstructed@@ -13547,7 +13564,9 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):}}- with patch("posthog.api.feature_flag.build_person_properties_at_time") as mock_build_props:+ with patch(+ "products.feature_flags.backend.api.feature_flag.build_person_properties_at_time"+ ) as mock_build_props:mock_build_props.return_value = {"email": "[email protected]"}# Use a recent timestamp that's after flag creation@@ -13619,7 +13638,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)self.assertEqual(response.json()["detail"], "Person not found for distinct_id: nonexistent-user")- @patch("posthog.api.feature_flag.get_flags_from_service")+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")@override_settings(INTERNAL_REQUEST_TOKEN="")def test_test_evaluation_missing_internal_token_error(self, mock_get_flags):"""Test 500 when INTERNAL_REQUEST_TOKEN is not set."""@@ -13635,7 +13654,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)self.assertEqual(response.json()["error"], "Internal request token not configured")- @patch("posthog.api.feature_flag.get_flags_from_service")+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")@override_settings(INTERNAL_REQUEST_TOKEN="test-token")def test_test_evaluation_historical_missing_conditions_502(self, mock_get_flags):"""Test 502 when historical evaluation returns no conditions (misconfigured token)."""@@ -13655,7 +13674,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):}}- with patch("posthog.api.feature_flag.build_person_properties_at_time", return_value={}):+ with patch("products.feature_flags.backend.api.feature_flag.build_person_properties_at_time", return_value={}):# Use a recent timestamp that's after flag creationfrom datetime import datetime@@ -13670,7 +13689,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.status_code, status.HTTP_502_BAD_GATEWAY)self.assertEqual(response.json()["error"], "Historical evaluation unavailable. Check service configuration.")- @patch("posthog.api.feature_flag.get_flags_from_service")+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")@override_settings(INTERNAL_REQUEST_TOKEN="test-token")def test_test_evaluation_current_missing_conditions_200(self, mock_get_flags):"""Test 200 when current evaluation returns no conditions (no 502 for current evaluation)."""@@ -13702,7 +13721,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):# Verify the response is still validself.assertIn("result", response.json())- @patch("posthog.api.feature_flag.build_person_properties_at_time")+ @patch("products.feature_flags.backend.api.feature_flag.build_person_properties_at_time")def test_test_evaluation_build_properties_failure(self, mock_build_props):"""Test 500 when build_person_properties_at_time raises exception."""flag = FeatureFlag.objects.create(team=self.team, key="test-flag")@@ -13720,7 +13739,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)self.assertEqual(response.json()["error"], "Failed to build person properties at specified timestamp.")- @patch("posthog.api.feature_flag.get_flags_from_service")+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")@override_settings(INTERNAL_REQUEST_TOKEN="test-token")def test_test_evaluation_filters_person_properties(self, mock_get_flags):"""Test that person_properties are filtered to only flag-referenced keys."""@@ -13768,7 +13787,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):# Should only include 'email' since that's referenced in the flag, not 'name' or 'age'self.assertEqual(data["person_properties"], {"email": "[email protected]"})- @patch("posthog.api.feature_flag.get_flags_from_service")+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")@override_settings(INTERNAL_REQUEST_TOKEN="test-token")def test_test_evaluation_unexpected_response_type(self, mock_get_flags):"""Test 502 when flag service returns unexpected response format."""@@ -13821,7 +13840,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.status_code, 400)- @patch("posthog.api.feature_flag.get_flags_from_service")+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")@override_settings(INTERNAL_REQUEST_TOKEN="test-token")def test_test_evaluation_build_properties_value_error_no_leak(self, mock_get_flags):"""Test that ValueError from build_person_properties_at_time doesn't leak sensitive information."""@@ -13848,7 +13867,9 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):Person.objects.create(team=self.team, distinct_ids=["test-user"])- with patch("posthog.api.feature_flag.build_person_properties_at_time") as mock_build_props:+ with patch(+ "products.feature_flags.backend.api.feature_flag.build_person_properties_at_time"+ ) as mock_build_props:# Mock build_person_properties_at_time to raise ValueError with sensitive informationmock_build_props.side_effect = ValueError("naive datetime: /secret/path/user123")@@ -13875,7 +13896,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):# Verify the mock was calledmock_build_props.assert_called_once()- @patch("posthog.api.feature_flag.get_flags_from_service")+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")@override_settings(INTERNAL_REQUEST_TOKEN="test-token")def test_test_evaluation_reconstruct_flag_value_error_no_leak(self, mock_get_flags):"""Test that ValueError from reconstruct_flag_at_timestamp doesn't leak sensitive information."""@@ -13899,7 +13920,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):}}- with patch("posthog.api.feature_flag.reconstruct_flag_at_timestamp") as mock_reconstruct:+ with patch("products.feature_flags.backend.api.feature_flag.reconstruct_flag_at_timestamp") as mock_reconstruct:# Mock reconstruct_flag_at_timestamp to raise ValueError with sensitive informationmock_reconstruct.side_effect = ValueError("timestamp must be timezone-aware: /secret/config/token")@@ -13928,7 +13949,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):class TestFeatureFlagEvaluationReasons(APIBaseTest, ClickhouseTestMixin):- @patch("posthog.api.feature_flag.get_flags_from_service")+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")def test_evaluation_reasons_passes_runtime_all(self, mock_get_flags):"""The Person → Feature flags tab must bypass Rust's header-basedruntime detection — otherwise flags whose evaluation_runtime is@@ -13943,29 +13964,6 @@ class TestFeatureFlagEvaluationReasons(APIBaseTest, ClickhouseTestMixin):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(mock_get_flags.call_args.kwargs["evaluation_runtime"], "all")- @parameterized.expand(- [- ("evaluation_reasons", "evaluation_reasons/", {"distinct_id": "user-1"}, False),- ("my_flags", "my_flags/", {}, True),- ]- )- @patch("posthog.api.feature_flag.get_flags_from_service")- def test_internal_handler_forwards_internal_request_token(- self, _name, endpoint, params, needs_flag, mock_get_flags- ):- """The in-app Django handlers (my_flags, evaluation_reasons) are not- customer SDK traffic — they must forward INTERNAL_REQUEST_TOKEN so the- Rust service skips the per-team billing limiter."""- if needs_flag:- FeatureFlag.objects.create(team=self.team, key="my-flag", created_by=self.user)- mock_get_flags.return_value = {"flags": {}}-- with self.settings(INTERNAL_REQUEST_TOKEN="test-internal-token"):- response = self.client.get(f"/api/projects/{self.team.pk}/feature_flags/{endpoint}", params)-- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(mock_get_flags.call_args.kwargs["internal_request_token"], "test-internal-token")-@parameterized.expand([("all",),@@ -13973,7 +13971,7 @@ class TestFeatureFlagEvaluationReasons(APIBaseTest, ClickhouseTestMixin):("server",),])- @patch("posthog.api.feature_flag.get_flags_from_service")+ @patch("products.feature_flags.backend.api.feature_flag.get_flags_from_service")def test_evaluation_reasons_surfaces_flag_for_runtime(self, runtime, mock_get_flags):"""Each stored runtime must round-trip through evaluation_reasons withits evaluation.reason intact — this is the shapediff --git a/posthog/api/test/test_feature_flag_default_evaluation_contexts.py b/products/feature_flags/backend/api/test/test_feature_flag_default_evaluation_contexts.pysimilarity index 97%rename from posthog/api/test/test_feature_flag_default_evaluation_contexts.pyrename to products/feature_flags/backend/api/test/test_feature_flag_default_evaluation_contexts.pyindex 76af795b6114..26ebdcf6d99d 100644--- a/posthog/api/test/test_feature_flag_default_evaluation_contexts.py+++ b/products/feature_flags/backend/api/test/test_feature_flag_default_evaluation_contexts.py@@ -3,8 +3,8 @@ from unittest.mock import patchfrom rest_framework import status-from posthog.models import FeatureFlag-from posthog.models.evaluation_context import EvaluationContext, TeamDefaultEvaluationContext+from products.feature_flags.backend.models.evaluation_context import EvaluationContext, TeamDefaultEvaluationContext+from products.feature_flags.backend.models.feature_flag import FeatureFlagclass TestFeatureFlagDefaultEnvironments(APIBaseTest):diff --git a/posthog/api/test/test_feature_flag_dependency_deletion.py b/products/feature_flags/backend/api/test/test_feature_flag_dependency_deletion.pysimilarity index 99%rename from posthog/api/test/test_feature_flag_dependency_deletion.pyrename to products/feature_flags/backend/api/test/test_feature_flag_dependency_deletion.pyindex c0569bbfafe2..8ff94a8b8e66 100644--- a/posthog/api/test/test_feature_flag_dependency_deletion.py+++ b/products/feature_flags/backend/api/test/test_feature_flag_dependency_deletion.py@@ -6,7 +6,7 @@ from posthog.test.base import APIBaseTestfrom rest_framework import status-from posthog.models import FeatureFlag+from products.feature_flags.backend.models.feature_flag import FeatureFlagclass TestFeatureFlagDependencyDeletion(APIBaseTest):diff --git a/posthog/api/test/test_feature_flag_dependency_disabling.py b/products/feature_flags/backend/api/test/test_feature_flag_dependency_disabling.pysimilarity index 99%rename from posthog/api/test/test_feature_flag_dependency_disabling.pyrename to products/feature_flags/backend/api/test/test_feature_flag_dependency_disabling.pyindex 19897f8cf5ce..1e4c9516a50f 100644--- a/posthog/api/test/test_feature_flag_dependency_disabling.py+++ b/products/feature_flags/backend/api/test/test_feature_flag_dependency_disabling.py@@ -6,7 +6,7 @@ from posthog.test.base import APIBaseTestfrom rest_framework import status-from posthog.models import FeatureFlag+from products.feature_flags.backend.models.feature_flag import FeatureFlagclass TestFeatureFlagDependencyDisabling(APIBaseTest):diff --git a/posthog/api/test/test_feature_flag_require_evaluation_tags.py b/products/feature_flags/backend/api/test/test_feature_flag_require_evaluation_tags.pysimilarity index 98%rename from posthog/api/test/test_feature_flag_require_evaluation_tags.pyrename to products/feature_flags/backend/api/test/test_feature_flag_require_evaluation_tags.pyindex bae7b157c0c7..65a7e09eda97 100644--- a/posthog/api/test/test_feature_flag_require_evaluation_tags.py+++ b/products/feature_flags/backend/api/test/test_feature_flag_require_evaluation_tags.py@@ -3,8 +3,8 @@ from unittest.mock import patchfrom rest_framework import status-from posthog.models import FeatureFlag-from posthog.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext+from products.feature_flags.backend.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext+from products.feature_flags.backend.models.feature_flag import FeatureFlagclass TestFeatureFlagRequireEvaluationTags(APIBaseTest):diff --git a/posthog/api/test/test_feature_flag_utils.py b/products/feature_flags/backend/api/test/test_feature_flag_utils.pysimilarity index 100%rename from posthog/api/test/test_feature_flag_utils.pyrename to products/feature_flags/backend/api/test/test_feature_flag_utils.pydiff --git a/posthog/api/test/test_organization_feature_flag.py b/products/feature_flags/backend/api/test/test_organization_feature_flag.pysimilarity index 99%rename from posthog/api/test/test_organization_feature_flag.pyrename to products/feature_flags/backend/api/test/test_organization_feature_flag.pyindex d84612632001..fc14e806b38e 100644--- a/posthog/api/test/test_organization_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_organization_feature_flag.py@@ -17,18 +17,18 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status-from posthog.models import FeatureFlagfrom posthog.models.cohort import Cohortfrom posthog.models.cohort.util import sort_cohorts_topologicallyfrom posthog.models.organization import Organizationfrom posthog.models.personal_api_key import PersonalAPIKey-from posthog.models.scheduled_change import ScheduledChangefrom posthog.models.team.team import Teamfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom products.dashboards.backend.api.dashboard import Dashboardfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.scheduled_change import ScheduledChangefrom products.surveys.backend.models import Survey@@ -1367,7 +1367,7 @@ class TestOrganizationFeatureFlagCopySchedules(APIBaseTest):}with patch(- "posthog.api.organization_feature_flag.OrganizationFeatureFlagView._copy_feature_flag_schedules"+ "products.feature_flags.backend.api.organization_feature_flag.OrganizationFeatureFlagView._copy_feature_flag_schedules") as mock_copy:mock_copy.side_effect = Exception("Database error")response = self.client.post(url, data)@@ -1471,7 +1471,7 @@ class TestOrganizationFeatureFlagEvaluations(ClickhouseTestMixin, APIBaseTest):def test_clickhouse_failure_returns_null_evaluations(self):with patch(- "posthog.api.organization_feature_flag.get_cached_evaluations_7d_by_team",+ "products.feature_flags.backend.api.organization_feature_flag.get_cached_evaluations_7d_by_team",return_value=None,):body = self.client.get(self._url("shared_flag")).json()diff --git a/posthog/api/test/test_scheduled_change.py b/products/feature_flags/backend/api/test/test_scheduled_change.pysimilarity index 95%rename from posthog/api/test/test_scheduled_change.pyrename to products/feature_flags/backend/api/test/test_scheduled_change.pyindex ddc2b7bfc5ca..ea119ea4512a 100644--- a/posthog/api/test/test_scheduled_change.py+++ b/products/feature_flags/backend/api/test/test_scheduled_change.py@@ -6,8 +6,9 @@ from unittest.mock import patchfrom parameterized import parameterizedfrom rest_framework import serializers, status-from posthog.api.scheduled_change import ScheduledChangeSerializer-from posthog.models import FeatureFlag, ScheduledChange+from products.feature_flags.backend.api.scheduled_change import ScheduledChangeSerializer+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.scheduled_change import ScheduledChangeclass TestScheduledChange(APIBaseTest):@@ -51,7 +52,10 @@ class TestScheduledChange(APIBaseTest):payload = {"operation": "update_status", "value": False}# Mock the permission check to return False- with patch("posthog.api.scheduled_change.CanEditFeatureFlag.has_object_permission", return_value=False):+ with patch(+ "products.feature_flags.backend.api.scheduled_change.CanEditFeatureFlag.has_object_permission",+ return_value=False,+ ):response = self.client.post(f"/api/projects/{self.team.id}/scheduled_changes/",data={@@ -78,7 +82,10 @@ class TestScheduledChange(APIBaseTest):payload = {"operation": "update_status", "value": False}# Mock the permission check to return True- with patch("posthog.api.scheduled_change.CanEditFeatureFlag.has_object_permission", return_value=True):+ with patch(+ "products.feature_flags.backend.api.scheduled_change.CanEditFeatureFlag.has_object_permission",+ return_value=True,+ ):response = self.client.post(f"/api/projects/{self.team.id}/scheduled_changes/",data={@@ -487,7 +494,10 @@ class TestScheduledChange(APIBaseTest):created_by=self.user,)- with patch("posthog.api.scheduled_change.CanEditFeatureFlag.has_object_permission", return_value=True):+ with patch(+ "products.feature_flags.backend.api.scheduled_change.CanEditFeatureFlag.has_object_permission",+ return_value=True,+ ):response = self.client.patch(f"/api/projects/{self.team.id}/scheduled_changes/{scheduled_change.id}/",data={"payload": {"operation": "update_status", "value": True}},@@ -524,7 +534,8 @@ class TestScheduledChange(APIBaseTest):new_payload = {"operation": "update_status", "value": True}with patch(- "posthog.api.scheduled_change.CanEditFeatureFlag.has_object_permission", return_value=has_permission+ "products.feature_flags.backend.api.scheduled_change.CanEditFeatureFlag.has_object_permission",+ return_value=has_permission,):response = self.client.patch(f"/api/projects/{self.team.id}/scheduled_changes/{scheduled_change.id}/",@@ -564,7 +575,10 @@ class TestScheduledChange(APIBaseTest):created_by=self.user,)- with patch("posthog.api.scheduled_change.CanEditFeatureFlag.has_object_permission", return_value=True):+ with patch(+ "products.feature_flags.backend.api.scheduled_change.CanEditFeatureFlag.has_object_permission",+ return_value=True,+ ):response = self.client.patch(f"/api/projects/{self.team.id}/scheduled_changes/{scheduled_change.id}/",data=patch_body,diff --git a/products/feature_flags/backend/apps.py b/products/feature_flags/backend/apps.pyindex 92cb35f1ab55..d13bbcbc667c 100644--- a/products/feature_flags/backend/apps.py+++ b/products/feature_flags/backend/apps.py@@ -2,6 +2,9 @@ from django.apps import AppConfigclass FeatureFlagsConfig(AppConfig):- default_auto_field = "django.db.models.BigAutoField"+ # AutoField (INT4) matches the legacy posthog app default so existing+ # posthog_featureflag.id columns stay compatible with the Rust feature-flags+ # service which decodes id as i32.+ default_auto_field = "django.db.models.AutoField"name = "products.feature_flags.backend"label = "feature_flags"diff --git a/posthog/models/feature_flag/flag_analytics.py b/products/feature_flags/backend/flag_analytics.pysimilarity index 99%rename from posthog/models/feature_flag/flag_analytics.pyrename to products/feature_flags/backend/flag_analytics.pyindex e9ba71ed33a9..3b2a5083d836 100644--- a/posthog/models/feature_flag/flag_analytics.py+++ b/products/feature_flags/backend/flag_analytics.py@@ -13,9 +13,10 @@ from posthog.constants import FlagRequestTypefrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.dashboard_templates import add_enriched_insights_to_feature_flag_dashboardfrom posthog.models import Team-from posthog.models.feature_flag.feature_flag import FeatureFlagfrom posthog.redis import get_client, redis+from products.feature_flags.backend.models.feature_flag import FeatureFlag+if TYPE_CHECKING:from posthoganalytics import Posthogdiff --git a/posthog/models/feature_flag/flag_matching.py b/products/feature_flags/backend/flag_matching.pysimilarity index 99%rename from posthog/models/feature_flag/flag_matching.pyrename to products/feature_flags/backend/flag_matching.pyindex 9298a03b8510..1f4a4904bd86 100644--- a/posthog/models/feature_flag/flag_matching.py+++ b/products/feature_flags/backend/flag_matching.py@@ -35,7 +35,7 @@ from posthog.models.utils import execute_with_timeoutfrom posthog.person_db_router import PERSONS_DB_FOR_READ, PERSONS_DB_FOR_WRITEfrom posthog.queries.base import match_property, properties_to_Q, sanitize_property_key-from .feature_flag import FeatureFlag, FeatureFlagHashKeyOverride+from .models.feature_flag import FeatureFlag, FeatureFlagHashKeyOverridelogger = structlog.get_logger(__name__)diff --git a/posthog/models/feature_flag/flag_status.py b/products/feature_flags/backend/flag_status.pysimilarity index 99%rename from posthog/models/feature_flag/flag_status.pyrename to products/feature_flags/backend/flag_status.pyindex 7facd9ef74cc..a4a6b19c92f4 100644--- a/posthog/models/feature_flag/flag_status.py+++ b/products/feature_flags/backend/flag_status.py@@ -5,7 +5,7 @@ import structlogfrom posthog.date_util import thirty_days_ago-from .feature_flag import FeatureFlag+from .models.feature_flag import FeatureFlaglogger = structlog.get_logger(__name__)diff --git a/posthog/models/feature_flag/flags_cache.py b/products/feature_flags/backend/flags_cache.pysimilarity index 97%rename from posthog/models/feature_flag/flags_cache.pyrename to products/feature_flags/backend/flags_cache.pyindex 6e1a9d89358f..cc74dc792c68 100644--- a/posthog/models/feature_flag/flags_cache.py+++ b/products/feature_flags/backend/flags_cache.py@@ -22,7 +22,7 @@ Configuration:- Miss TTL: 1 day (configurable via FLAGS_CACHE_MISS_TTL env var)Manual operations:- from posthog.models.feature_flag.flags_cache import clear_flags_cache+ from products.feature_flags.backend.flags_cache import clear_flags_cacheclear_flags_cache(team_id)"""@@ -47,9 +47,6 @@ from posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIASfrom posthog.metrics import TOMBSTONE_COUNTERfrom posthog.models.cohort.cohort import Cohortfrom posthog.models.cohort.dependencies import extract_cohort_dependencies-from posthog.models.evaluation_context import FeatureFlagEvaluationContext-from posthog.models.feature_flag import FeatureFlag-from posthog.models.feature_flag.feature_flag import get_feature_flags, serialize_feature_flagsfrom posthog.models.team import Teamfrom posthog.storage.cache_expiry_manager import (cleanup_stale_expiry_tracking as cleanup_generic,@@ -62,6 +59,9 @@ from posthog.storage.hypercache_manager import (get_cache_stats as get_cache_stats_generic,)+from products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContext+from products.feature_flags.backend.models.feature_flag import FeatureFlag, get_feature_flags, serialize_feature_flags+logger = structlog.get_logger(__name__)# Sorted set key for tracking cache expirations@@ -173,6 +173,7 @@ def _load_cohorts_with_deps(seed_ids: set[int], **team_filter: Any) -> dict[int,breakdepth += 1newly_loaded: list[Cohort] = []+ # nosemgrep: idor-lookup-without-team — team scope is enforced via **team_filter kwargs (team_id or team__project_id__in passed by caller).for cohort in Cohort.objects.filter(pk__in=ids_to_load, deleted=False, **team_filter):loaded[cohort.pk] = cohortnewly_loaded.append(cohort)@@ -858,7 +859,7 @@ def feature_flag_changed_flags_cache(sender, instance: "FeatureFlag", **kwargs):if not settings.FLAGS_REDIS_URL:return- from posthog.tasks.feature_flags import update_team_service_flags_cache+ from products.feature_flags.backend.tasks import update_team_service_flags_cache# Defer task execution until after the transaction commits to avoid race conditions# Note: Metric tracking happens in the task itself to capture actual success/failure result@@ -876,7 +877,7 @@ def team_created_flags_cache(sender, instance: "Team", created: bool, **kwargs):if not created or not settings.FLAGS_REDIS_URL:return- from posthog.tasks.feature_flags import update_team_service_flags_cache+ from products.feature_flags.backend.tasks import update_team_service_flags_cache# Defer task execution until after the transaction commits# Note: Metric tracking happens in the task itself to capture actual success/failure result@@ -912,7 +913,7 @@ def evaluation_context_changed_flags_cache(sender, instance: "FeatureFlagEvaluatif not settings.FLAGS_REDIS_URL:return- from posthog.tasks.feature_flags import update_team_service_flags_cache+ from products.feature_flags.backend.tasks import update_team_service_flags_cacheteam_id = instance.feature_flag.team_idtransaction.on_commit(lambda: update_team_service_flags_cache.delay(team_id))@@ -935,6 +936,6 @@ def cohort_changed_flags_cache(sender, instance: "Cohort", **kwargs):if update_fields is not None and frozenset(update_fields) <= _COHORT_RECALCULATION_FIELDS:return- from posthog.tasks.feature_flags import update_team_service_flags_cache+ from products.feature_flags.backend.tasks import update_team_service_flags_cachetransaction.on_commit(lambda: update_team_service_flags_cache.delay(instance.team_id))diff --git a/posthog/models/feature_flag/local_evaluation.py b/products/feature_flags/backend/local_evaluation.pysimilarity index 97%rename from posthog/models/feature_flag/local_evaluation.pyrename to products/feature_flags/backend/local_evaluation.pyindex ce506315e7e2..8dd43999626d 100644--- a/posthog/models/feature_flag/local_evaluation.py+++ b/products/feature_flags/backend/local_evaluation.py@@ -38,15 +38,15 @@ from prometheus_client import Counterfrom posthog.models.cohort.cohort import Cohort, CohortOrEmpty, is_cohort_recalculation_only_savefrom posthog.models.cohort.util import get_nested_cohort_ids-from posthog.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext-from posthog.models.feature_flag import FeatureFlag-from posthog.models.feature_flag.flags_cache import _compare_flag_fields, get_teams_with_flags_queryset-from posthog.models.feature_flag.types import FlagFilters, FlagProperty, PropertyFilterTypefrom posthog.models.team import Teamfrom posthog.person_db_router import PERSONS_DB_FOR_READfrom posthog.storage.hypercache import HyperCache, emit_cache_sync_metricsfrom posthog.storage.hypercache_manager import HyperCacheManagementConfig+from products.feature_flags.backend.flags_cache import _compare_flag_fields, get_teams_with_flags_queryset+from products.feature_flags.backend.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.types import FlagFilters, FlagProperty, PropertyFilterTypefrom products.surveys.backend.models import Surveylogger = structlog.get_logger(__name__)@@ -502,7 +502,7 @@ def _get_flags_response_for_local_evaluation_batch(query each regardless of team count), then iterates the materialized flaglist with itertools.groupby to process one team at a time."""- from posthog.api.feature_flag import MinimalFeatureFlagSerializer+ from products.feature_flags.backend.api.feature_flag import MinimalFeatureFlagSerializerif not teams:return {}@@ -556,11 +556,13 @@ def _get_flags_response_for_local_evaluation_batch(while ids_to_load:newly_loaded: list[Cohort] = []- for cohort in (+ cohort_qs = (+ # nosemgrep: idor-lookup-without-team — team scope is enforced via team__project_id__in.Cohort.objects.db_manager(DATABASE_FOR_LOCAL_EVALUATION).filter(pk__in=ids_to_load, team__project_id__in=project_ids, deleted=False, is_static=False).select_related("team")- ):+ )+ for cohort in cohort_qs:cohorts_by_project[cohort.team.project_id][cohort.pk] = cohortloaded_ids.add(cohort.pk)newly_loaded.append(cohort)@@ -854,7 +856,7 @@ def verify_team_flag_definitions(@receiver(post_save, sender=FeatureFlag)@receiver(post_delete, sender=FeatureFlag)def feature_flag_changed(sender, instance: "FeatureFlag", **kwargs):- from posthog.tasks.feature_flags import update_team_flags_cache+ from products.feature_flags.backend.tasks import update_team_flags_cache# Defer task execution until after the transaction commitstransaction.on_commit(lambda: update_team_flags_cache.delay(instance.team_id))@@ -866,7 +868,7 @@ def cohort_changed(sender, instance: "Cohort", **kwargs):if is_cohort_recalculation_only_save(kwargs):return- from posthog.tasks.feature_flags import update_team_flags_cache+ from products.feature_flags.backend.tasks import update_team_flags_cachetransaction.on_commit(lambda: update_team_flags_cache.delay(instance.team_id))@@ -874,7 +876,7 @@ def cohort_changed(sender, instance: "Cohort", **kwargs):@receiver(post_save, sender=FeatureFlagEvaluationContext)@receiver(post_delete, sender=FeatureFlagEvaluationContext)def evaluation_context_changed(sender, instance: "FeatureFlagEvaluationContext", **kwargs):- from posthog.tasks.feature_flags import update_team_flags_cache+ from products.feature_flags.backend.tasks import update_team_flags_cacheteam_id = instance.feature_flag.team_idtransaction.on_commit(lambda: update_team_flags_cache.delay(team_id))@@ -887,6 +889,6 @@ def evaluation_context_name_changed(sender, instance: "EvaluationContext", creatif created:return # New contexts can't be referenced by any flags yet- from posthog.tasks.feature_flags import update_team_flags_cache+ from products.feature_flags.backend.tasks import update_team_flags_cachetransaction.on_commit(lambda: update_team_flags_cache.delay(instance.team_id))diff --git a/products/feature_flags/backend/max_tools.py b/products/feature_flags/backend/max_tools.pyindex 054dc0cb02dd..e90b83838112 100644--- a/products/feature_flags/backend/max_tools.py+++ b/products/feature_flags/backend/max_tools.py@@ -7,13 +7,14 @@ from rest_framework.exceptions import ValidationErrorfrom posthog.schema import FeatureFlagGroupType-from posthog.api.feature_flag import FeatureFlagSerializerfrom posthog.exceptions_capture import capture_exception-from posthog.models import FeatureFlagfrom posthog.rbac.user_access_control import AccessControlLevelfrom posthog.scopes import APIScopeObjectfrom posthog.sync import database_sync_to_async+from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from ee.hogai.tool import MaxTooldiff --git a/products/feature_flags/backend/migrations/0002_migrate_feature_flags_models.py b/products/feature_flags/backend/migrations/0002_migrate_feature_flags_models.pynew file mode 100644index 000000000000..1f04f4f315ef--- /dev/null+++ b/products/feature_flags/backend/migrations/0002_migrate_feature_flags_models.py@@ -0,0 +1,437 @@+# Generated by Django 5.2.13 on 2026-05-20 15:38++import django.utils.timezone+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.models.utils++import products.feature_flags.backend.models.feature_flag+++class Migration(migrations.Migration):+ dependencies = [+ ("dashboards", "0001_migrate_dashboards_models"),+ ("feature_flags", "0001_team_feature_flag_defaults_config"),+ ("posthog", "1163_alter_batchexportrun_batch_export_and_more"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.CreateModel(+ name="FeatureFlagHashKeyOverride",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ ("feature_flag_key", models.CharField(max_length=400)),+ ("hash_key", models.CharField(max_length=400)),+ ],+ options={+ "db_table": "posthog_featureflaghashkeyoverride",+ "managed": False,+ },+ ),+ migrations.CreateModel(+ name="EvaluationContext",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("name", models.CharField(max_length=255)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "team",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="evaluation_context_set",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "posthog_evaluationcontext",+ "unique_together": {("team", "name")},+ },+ ),+ migrations.CreateModel(+ name="FeatureFlag",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ ("key", models.CharField(max_length=400)),+ ("name", models.TextField(blank=True)),+ (+ "filters",+ models.JSONField(+ default=products.feature_flags.backend.models.feature_flag.default_filters+ ),+ ),+ ("rollout_percentage", models.IntegerField(blank=True, null=True)),+ ("created_at", models.DateTimeField(default=django.utils.timezone.now)),+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),+ ("deleted", models.BooleanField(default=False)),+ ("active", models.BooleanField(default=True)),+ ("version", models.IntegerField(default=1, null=True)),+ ("rollback_conditions", models.JSONField(blank=True, null=True)),+ ("performed_rollback", models.BooleanField(blank=True, null=True)),+ (+ "ensure_experience_continuity",+ models.BooleanField(blank=True, default=False, null=True),+ ),+ (+ "has_enriched_analytics",+ models.BooleanField(blank=True, default=False, null=True),+ ),+ (+ "is_remote_configuration",+ models.BooleanField(blank=True, default=False, null=True),+ ),+ (+ "has_encrypted_payloads",+ models.BooleanField(blank=True, default=False, null=True),+ ),+ (+ "evaluation_runtime",+ models.CharField(+ blank=True,+ choices=[+ ("server", "Server"),+ ("client", "Client"),+ ("all", "All"),+ ],+ default="all",+ help_text="Specifies where this feature flag should be evaluated",+ max_length=10,+ null=True,+ ),+ ),+ (+ "bucketing_identifier",+ models.CharField(+ blank=True,+ choices=[+ ("distinct_id", "User ID (default)"),+ ("device_id", "Device ID"),+ ],+ default="distinct_id",+ help_text="Identifier used for bucketing users into rollout and variants",+ max_length=50,+ null=True,+ ),+ ),+ (+ "last_called_at",+ models.DateTimeField(+ blank=True,+ help_text="Last time this feature flag was called (from $feature_flag_called events)",+ null=True,+ ),+ ),+ (+ "created_by",+ models.ForeignKey(+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "last_modified_by",+ models.ForeignKey(+ db_index=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="updated_feature_flags",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),+ ),+ (+ "usage_dashboard",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to="dashboards.dashboard",+ ),+ ),+ ],+ options={+ "db_table": "posthog_featureflag",+ },+ ),+ migrations.CreateModel(+ name="FeatureFlagDashboards",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True, null=True)),+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),+ (+ "dashboard",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ to="dashboards.dashboard",+ ),+ ),+ (+ "feature_flag",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ to="feature_flags.featureflag",+ ),+ ),+ ],+ options={+ "db_table": "posthog_featureflagdashboards",+ },+ ),+ migrations.AddField(+ model_name="featureflag",+ name="analytics_dashboards",+ field=models.ManyToManyField(+ related_name="analytics_dashboards",+ related_query_name="analytics_dashboard",+ through="feature_flags.FeatureFlagDashboards",+ to="dashboards.dashboard",+ ),+ ),+ migrations.CreateModel(+ name="FeatureFlagEvaluationContext",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "evaluation_context",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="feature_flags",+ to="feature_flags.evaluationcontext",+ ),+ ),+ (+ "feature_flag",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="flag_evaluation_contexts",+ to="feature_flags.featureflag",+ ),+ ),+ ],+ options={+ "db_table": "posthog_featureflagevaluationcontext",+ },+ ),+ migrations.CreateModel(+ name="FeatureFlagOverride",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ ("override_value", models.JSONField()),+ (+ "feature_flag",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ to="feature_flags.featureflag",+ ),+ ),+ (+ "team",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),+ ),+ (+ "user",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ ],+ options={+ "db_table": "posthog_featureflagoverride",+ },+ ),+ migrations.CreateModel(+ name="ScheduledChange",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ ("record_id", models.CharField(max_length=200)),+ (+ "model_name",+ models.CharField(choices=[("FeatureFlag", "feature flag")], max_length=100),+ ),+ ("payload", models.JSONField(default=dict)),+ ("scheduled_at", models.DateTimeField()),+ ("executed_at", models.DateTimeField(blank=True, null=True)),+ ("failure_reason", models.TextField(blank=True, null=True)),+ ("failure_count", models.IntegerField(default=0)),+ ("is_recurring", models.BooleanField(default=False)),+ (+ "recurrence_interval",+ models.CharField(+ blank=True,+ choices=[+ ("daily", "daily"),+ ("weekly", "weekly"),+ ("monthly", "monthly"),+ ("yearly", "yearly"),+ ],+ max_length=20,+ null=True,+ ),+ ),+ ("last_executed_at", models.DateTimeField(blank=True, null=True)),+ (+ "cron_expression",+ models.CharField(blank=True, max_length=100, null=True),+ ),+ ("end_date", models.DateTimeField(blank=True, null=True)),+ ("timezone", models.CharField(blank=True, max_length=240, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "created_by",+ models.ForeignKey(+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),+ ),+ ],+ options={+ "db_table": "posthog_scheduledchange",+ },+ ),+ migrations.CreateModel(+ name="TeamDefaultEvaluationContext",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "evaluation_context",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="team_defaults",+ to="feature_flags.evaluationcontext",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="default_evaluation_context_set",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "posthog_teamdefaultevaluationcontext",+ },+ ),+ migrations.AddConstraint(+ model_name="featureflagdashboards",+ constraint=models.UniqueConstraint(+ fields=("feature_flag", "dashboard"),+ name="unique feature flag for a dashboard",+ ),+ ),+ migrations.AddConstraint(+ model_name="featureflag",+ constraint=models.UniqueConstraint(fields=("team", "key"), name="unique key for team"),+ ),+ migrations.AlterUniqueTogether(+ name="featureflagevaluationcontext",+ unique_together={("feature_flag", "evaluation_context")},+ ),+ migrations.AddConstraint(+ model_name="featureflagoverride",+ constraint=models.UniqueConstraint(+ fields=("user", "feature_flag", "team"),+ name="unique feature flag for a user/team combo",+ ),+ ),+ migrations.AddIndex(+ model_name="scheduledchange",+ index=models.Index(+ fields=["scheduled_at", "executed_at"],+ name="posthog_sch_schedul_c3687e_idx",+ ),+ ),+ migrations.AlterUniqueTogether(+ name="teamdefaultevaluationcontext",+ unique_together={("team", "evaluation_context")},+ ),+ ],+ database_operations=[+ # No database operations - table already exists with this name+ ],+ ),+ ]diff --git a/products/feature_flags/backend/migrations/max_migration.txt b/products/feature_flags/backend/migrations/max_migration.txtindex 4aa2861bf3bf..ba97bd43605d 100644--- a/products/feature_flags/backend/migrations/max_migration.txt+++ b/products/feature_flags/backend/migrations/max_migration.txt@@ -1 +1 @@-0001_team_feature_flag_defaults_config+0002_migrate_feature_flags_modelsdiff --git a/posthog/models/evaluation_context.py b/products/feature_flags/backend/models/evaluation_context.pysimilarity index 83%rename from posthog/models/evaluation_context.pyrename to products/feature_flags/backend/models/evaluation_context.pyindex 06adf0dd1084..d7a2908c6f68 100644--- a/posthog/models/evaluation_context.py+++ b/products/feature_flags/backend/models/evaluation_context.py@@ -30,6 +30,7 @@ class EvaluationContext(UUIDModel):class Meta:unique_together = [["team", "name"]]+ db_table = "posthog_evaluationcontext"def __str__(self) -> str:return f"{self.team_id}:{self.name}"@@ -44,15 +45,16 @@ class FeatureFlagEvaluationContext(UUIDModel):"""feature_flag = models.ForeignKey(- "posthog.FeatureFlag", on_delete=models.CASCADE, related_name="flag_evaluation_contexts"+ "feature_flags.FeatureFlag", on_delete=models.CASCADE, related_name="flag_evaluation_contexts")evaluation_context = models.ForeignKey(- "posthog.EvaluationContext", on_delete=models.CASCADE, related_name="feature_flags"+ "feature_flags.EvaluationContext", on_delete=models.CASCADE, related_name="feature_flags")created_at = models.DateTimeField(auto_now_add=True)class Meta:unique_together = [["feature_flag", "evaluation_context"]]+ db_table = "posthog_featureflagevaluationcontext"def __str__(self) -> str:return f"{self.feature_flag.key} - {self.evaluation_context.name}"@@ -65,12 +67,13 @@ class TeamDefaultEvaluationContext(UUIDModel):team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="default_evaluation_context_set")evaluation_context = models.ForeignKey(- "posthog.EvaluationContext", on_delete=models.CASCADE, related_name="team_defaults"+ "feature_flags.EvaluationContext", on_delete=models.CASCADE, related_name="team_defaults")created_at = models.DateTimeField(auto_now_add=True)class Meta:unique_together = [["team", "evaluation_context"]]+ db_table = "posthog_teamdefaultevaluationcontext"def __str__(self) -> str:return f"{self.team.name} - {self.evaluation_context.name}"diff --git a/posthog/models/feature_flag/feature_flag.py b/products/feature_flags/backend/models/feature_flag.pysimilarity index 97%rename from posthog/models/feature_flag/feature_flag.pyrename to products/feature_flags/backend/models/feature_flag.pyindex 1b3b706877be..db9c43edd1fa 100644--- a/posthog/models/feature_flag/feature_flag.py+++ b/products/feature_flags/backend/models/feature_flag.py@@ -54,8 +54,8 @@ class FeatureFlag(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models# DEPRECATED: rollout percentage now lives in filters["groups"][N]["rollout_percentage"]rollout_percentage = deprecate_field(models.IntegerField(null=True, blank=True))- team = models.ForeignKey("Team", on_delete=models.CASCADE)- created_by = models.ForeignKey("User", on_delete=models.SET_NULL, null=True)+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)+ created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True)created_at = models.DateTimeField(default=timezone.now)updated_at = models.DateTimeField(null=True, auto_now=True)deleted = models.BooleanField(default=False)@@ -63,7 +63,7 @@ class FeatureFlag(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, modelsversion = models.IntegerField(default=1, null=True)last_modified_by = models.ForeignKey(- "User",+ "posthog.User",on_delete=models.SET_NULL,null=True,related_name="updated_feature_flags",@@ -129,6 +129,7 @@ class FeatureFlag(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, modelsclass Meta:constraints = [models.UniqueConstraint(fields=["team", "key"], name="unique key for team")]+ db_table = "posthog_featureflag"def __str__(self):return f"{self.key} ({self.pk})"@@ -445,7 +446,7 @@ class FeatureFlag(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, modelsuser: Optional[AbstractBaseUser] = None,scheduled_change_id: Optional[int] = None,):- from posthog.api.feature_flag import FeatureFlagSerializer+ from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializerif "operation" not in payload or "value" not in payload:raise Exception("Invalid payload")@@ -542,8 +543,8 @@ class FeatureFlagHashKeyOverride(models.Model):# DO_NOTHING: Person/Team deletion handled manually via FeatureFlagHashKeyOverride.objects.filter(...).delete()# in delete_bulky_postgres_data(). Django CASCADE doesn't work across separate databases.# db_constraint=False: No database FK constraint - FeatureFlagHashKeyOverride may live in separate database- person = models.ForeignKey("Person", on_delete=models.DO_NOTHING, db_constraint=False)- team = models.ForeignKey("Team", on_delete=models.DO_NOTHING, db_constraint=False)+ person = models.ForeignKey("posthog.Person", on_delete=models.DO_NOTHING, db_constraint=False)+ team = models.ForeignKey("posthog.Team", on_delete=models.DO_NOTHING, db_constraint=False)hash_key = models.CharField(max_length=400)class Meta:@@ -555,14 +556,15 @@ class FeatureFlagHashKeyOverride(models.Model):name="Unique hash_key for a user/team/feature_flag combo",)]+ db_table = "posthog_featureflaghashkeyoverride"# DEPRECATED: This model is no longer used, but it's not deleted to avoid downtimeclass FeatureFlagOverride(models.Model):feature_flag = models.ForeignKey("FeatureFlag", on_delete=models.CASCADE)- user = models.ForeignKey("User", on_delete=models.CASCADE)+ user = models.ForeignKey("posthog.User", on_delete=models.CASCADE)override_value = models.JSONField()- team = models.ForeignKey("Team", on_delete=models.CASCADE)+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)class Meta:constraints = [@@ -571,6 +573,7 @@ class FeatureFlagOverride(models.Model):name="unique feature flag for a user/team combo",)]+ db_table = "posthog_featureflagoverride"def get_feature_flags(@@ -651,7 +654,7 @@ def serialize_feature_flags(flags: list[FeatureFlag]) -> list[dict[str, Any]]:Returns:List of serialized flag dictionaries"""- from posthog.api.feature_flag import MinimalFeatureFlagSerializer+ from products.feature_flags.backend.api.feature_flag import MinimalFeatureFlagSerializerserialized_data = MinimalFeatureFlagSerializer(flags, many=True).datareturn list(serialized_data)@@ -720,3 +723,4 @@ class FeatureFlagDashboards(models.Model):name="unique feature flag for a dashboard",)]+ db_table = "posthog_featureflagdashboards"diff --git a/posthog/models/scheduled_change.py b/products/feature_flags/backend/models/scheduled_change.pysimilarity index 94%rename from posthog/models/scheduled_change.pyrename to products/feature_flags/backend/models/scheduled_change.pyindex c90c5cda3c1c..2caaf97d7485 100644--- a/posthog/models/scheduled_change.py+++ b/products/feature_flags/backend/models/scheduled_change.py@@ -22,7 +22,7 @@ class ScheduledChange(RootTeamMixin, models.Model):ADD_RELEASE_CONDITION = "add_release_condition", "add_release_condition"UPDATE_VARIANTS = "update_variants", "update_variants"- id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")+ id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")record_id = models.CharField(max_length=200)model_name = models.CharField(max_length=100, choices=AllowedModels)payload = models.JSONField(default=dict)@@ -51,15 +51,16 @@ class ScheduledChange(RootTeamMixin, models.Model):# UTC-wall-clock interpretation to avoid retroactively shifting any live schedule.timezone = models.CharField(max_length=240, null=True, blank=True)- team = models.ForeignKey("Team", on_delete=models.CASCADE)+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)created_at = models.DateTimeField(auto_now_add=True)- created_by = models.ForeignKey("User", on_delete=models.SET_NULL, null=True)+ created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True)updated_at = models.DateTimeField(auto_now=True)class Meta:indexes = [models.Index(fields=["scheduled_at", "executed_at"]),]+ db_table = "posthog_scheduledchange"@propertydef formatted_failure_reason(self) -> str:diff --git a/products/feature_flags/backend/models/team_feature_flag_defaults_config.py b/products/feature_flags/backend/models/team_feature_flag_defaults_config.pyindex a17d357f4fec..d3253aaad066 100644--- a/products/feature_flags/backend/models/team_feature_flag_defaults_config.py+++ b/products/feature_flags/backend/models/team_feature_flag_defaults_config.py@@ -2,14 +2,13 @@ import loggingfrom django.db import models-from posthog.models import Teamfrom posthog.models.team.extensions import register_team_extension_signallogger = logging.getLogger(__name__)class TeamFeatureFlagDefaultsConfig(models.Model):- team = models.OneToOneField(Team, on_delete=models.CASCADE, primary_key=True)+ team = models.OneToOneField("posthog.Team", on_delete=models.CASCADE, primary_key=True)enabled = models.BooleanField(default=False)diff --git a/posthog/feature_flags/sdk_cache_provider.py b/products/feature_flags/backend/sdk_cache_provider.pysimilarity index 96%rename from posthog/feature_flags/sdk_cache_provider.pyrename to products/feature_flags/backend/sdk_cache_provider.pyindex 9d5a1cad7892..3aa6abdf6ebc 100644--- a/posthog/feature_flags/sdk_cache_provider.py+++ b/products/feature_flags/backend/sdk_cache_provider.py@@ -35,7 +35,7 @@ class HyperCacheFlagProvider:calls skip the import entirely."""if self._hypercache is None:- from posthog.models.feature_flag.local_evaluation import flag_definitions_hypercache+ from products.feature_flags.backend.local_evaluation import flag_definitions_hypercacheself._hypercache = flag_definitions_hypercachereturn self._hypercachediff --git a/posthog/tasks/feature_flags.py b/products/feature_flags/backend/tasks.pysimilarity index 98%rename from posthog/tasks/feature_flags.pyrename to products/feature_flags/backend/tasks.pyindex 6799945553c5..b363b4663c83 100644--- a/posthog/tasks/feature_flags.py+++ b/products/feature_flags/backend/tasks.py@@ -8,22 +8,23 @@ import structlogfrom celery import shared_taskfrom prometheus_client import Gauge-from posthog.models.feature_flag.feature_flag import FeatureFlag-from posthog.models.feature_flag.flags_cache import (+from posthog.models.team import Team+from posthog.scoping_audit import skip_team_scope_audit+from posthog.storage.hypercache_manager import HYPERCACHE_SIGNAL_UPDATE_COUNTER+from posthog.tasks.utils import CeleryQueue, PushGatewayTask++from products.feature_flags.backend.flags_cache import (cleanup_stale_expiry_tracking,get_cache_stats,refresh_expiring_flags_caches,update_flags_cache,)-from posthog.models.feature_flag.local_evaluation import (+from products.feature_flags.backend.local_evaluation import (FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG,update_flag_caches,)-from posthog.models.team import Team-from posthog.scoping_audit import skip_team_scope_audit-from posthog.storage.hypercache_manager import HYPERCACHE_SIGNAL_UPDATE_COUNTER-from posthog.tasks.utils import CeleryQueue, PushGatewayTask+from products.feature_flags.backend.models.feature_flag import FeatureFlaglogger = structlog.get_logger(__name__)diff --git a/posthog/models/feature_flag/test/test_feature_flag_manager.py b/products/feature_flags/backend/test/test_feature_flag_manager.pysimilarity index 93%rename from posthog/models/feature_flag/test/test_feature_flag_manager.pyrename to products/feature_flags/backend/test/test_feature_flag_manager.pyindex 70ec5f7d8309..b3d6ffab9ed9 100644--- a/posthog/models/feature_flag/test/test_feature_flag_manager.py+++ b/products/feature_flags/backend/test/test_feature_flag_manager.py@@ -1,6 +1,6 @@from posthog.test.base import BaseTest-from posthog.models import FeatureFlag+from products.feature_flags.backend.models.feature_flag import FeatureFlagclass TestFeatureFlagManager(BaseTest):diff --git a/posthog/tasks/test/test_feature_flag_metrics.py b/products/feature_flags/backend/test/test_feature_flag_metrics.pysimilarity index 97%rename from posthog/tasks/test/test_feature_flag_metrics.pyrename to products/feature_flags/backend/test/test_feature_flag_metrics.pyindex d4a7254eedce..d0f188319210 100644--- a/posthog/tasks/test/test_feature_flag_metrics.py+++ b/products/feature_flags/backend/test/test_feature_flag_metrics.py@@ -3,9 +3,11 @@ from unittest.mock import MagicMock, patchfrom prometheus_client import CollectorRegistry-from posthog.models import FeatureFlag, Team+from posthog.models import Teamfrom posthog.models.organization import Organization-from posthog.tasks.feature_flags import compute_feature_flag_metrics++from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.tasks import compute_feature_flag_metricsclass TestComputeFeatureFlagMetrics(BaseTest):@@ -18,7 +20,7 @@ class TestComputeFeatureFlagMetrics(BaseTest):self.patcher = patch("posthog.tasks.utils.pushed_metrics_registry", return_value=self.mock_context)self.patcher.start()self.settings_patcher = patch(- "posthog.tasks.feature_flags.settings.PROM_PUSHGATEWAY_ADDRESS", "http://localhost:9091"+ "products.feature_flags.backend.tasks.settings.PROM_PUSHGATEWAY_ADDRESS", "http://localhost:9091")self.settings_patcher.start()@@ -417,7 +419,7 @@ class TestComputeFeatureFlagMetrics(BaseTest):filters={"groups": []},)- with patch("posthog.tasks.feature_flags.settings") as mock_settings:+ with patch("products.feature_flags.backend.tasks.settings") as mock_settings:mock_settings.PROM_PUSHGATEWAY_ADDRESS = ""compute_feature_flag_metrics()diff --git a/posthog/tasks/test/test_feature_flag_sync.py b/products/feature_flags/backend/test/test_feature_flag_sync.pysimilarity index 99%rename from posthog/tasks/test/test_feature_flag_sync.pyrename to products/feature_flags/backend/test/test_feature_flag_sync.pyindex a00a2bb7e022..c667dc89e6b1 100644--- a/posthog/tasks/test/test_feature_flag_sync.py+++ b/products/feature_flags/backend/test/test_feature_flag_sync.py@@ -9,9 +9,10 @@ from django.test import override_settingsfrom django.utils import timezone as tzfrom posthog.errors import CH_TRANSIENT_ERRORS, CHQueryErrorTooManyBytes-from posthog.models import FeatureFlagfrom posthog.tasks.tasks import sync_feature_flag_last_called+from products.feature_flags.backend.models.feature_flag import FeatureFlag+def mock_redis_client() -> Mock:"""Mock Redis client with in-memory storage"""diff --git a/posthog/tasks/test/test_flag_definitions_cache_tasks.py b/products/feature_flags/backend/test/test_flag_definitions_cache_tasks.pysimilarity index 97%rename from posthog/tasks/test/test_flag_definitions_cache_tasks.pyrename to products/feature_flags/backend/test/test_flag_definitions_cache_tasks.pyindex 77410848e9b3..0d7c4c78ea24 100644--- a/posthog/tasks/test/test_flag_definitions_cache_tasks.py+++ b/products/feature_flags/backend/test/test_flag_definitions_cache_tasks.py@@ -2,11 +2,12 @@ from unittest.mock import MagicMock, patchfrom django.test import TestCase-from posthog.tasks.feature_flags import (+from posthog.tasks.test.utils import PushGatewayTaskTestMixin++from products.feature_flags.backend.tasks import (cleanup_stale_flag_definitions_expiry_tracking_task,refresh_expiring_flag_definitions_cache_entries,)-from posthog.tasks.test.utils import PushGatewayTaskTestMixinclass TestRefreshExpiringFlagDefinitionsCacheEntries(PushGatewayTaskTestMixin, TestCase):diff --git a/posthog/models/feature_flag/test/test_flags_cache.py b/products/feature_flags/backend/test/test_flags_cache.pysimilarity index 96%rename from posthog/models/feature_flag/test/test_flags_cache.pyrename to products/feature_flags/backend/test/test_flags_cache.pyindex 4bb72af1d771..6819f231d45d 100644--- a/posthog/models/feature_flag/test/test_flags_cache.py+++ b/products/feature_flags/backend/test/test_flags_cache.py@@ -22,10 +22,10 @@ from django.test import override_settingsfrom parameterized import parameterized-from posthog.models import FeatureFlag, Team+from posthog.models import Teamfrom posthog.models.cohort.cohort import Cohort-from posthog.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext-from posthog.models.feature_flag.flags_cache import (++from products.feature_flags.backend.flags_cache import (_compute_flag_dependencies,_extract_cohort_ids_from_flag_filters,_extract_direct_dependency_ids,@@ -40,6 +40,8 @@ from posthog.models.feature_flag.flags_cache import (get_teams_with_flags_queryset,update_flags_cache,)+from products.feature_flags.backend.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext+from products.feature_flags.backend.models.feature_flag import FeatureFlag@override_settings(FLAGS_REDIS_URL="redis://test")@@ -541,7 +543,7 @@ class TestServiceFlagsSignals(BaseTest):super().setUp()clear_flags_cache(self.team, kinds=["redis", "s3"])- @patch("posthog.tasks.feature_flags.update_team_service_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())def test_signal_fired_on_flag_create(self, mock_task):"""Test that signal fires when a flag is created."""@@ -555,7 +557,7 @@ class TestServiceFlagsSignals(BaseTest):# Signal should trigger the Celery taskmock_task.delay.assert_called_once_with(self.team.id)- @patch("posthog.tasks.feature_flags.update_team_service_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())def test_signal_fired_on_flag_update(self, mock_task):"""Test that signal fires when a flag is updated."""@@ -576,7 +578,7 @@ class TestServiceFlagsSignals(BaseTest):# Signal should trigger the Celery taskmock_task.delay.assert_called_once_with(self.team.id)- @patch("posthog.tasks.feature_flags.update_team_service_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())def test_signal_fired_on_flag_delete(self, mock_task):"""Test that signal fires when a flag is deleted."""@@ -596,7 +598,7 @@ class TestServiceFlagsSignals(BaseTest):# Signal should trigger the Celery taskmock_task.delay.assert_called_once_with(self.team.id)- @patch("posthog.tasks.feature_flags.update_team_service_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())def test_signal_fired_on_team_create(self, mock_task):"""Test that signal fires when a team is created."""@@ -643,7 +645,7 @@ class TestServiceFlagsCeleryTasks(BaseTest):def test_update_team_service_flags_cache_task(self):"""Test the Celery task that updates service flags cache."""- from posthog.tasks.feature_flags import update_team_service_flags_cache+ from products.feature_flags.backend.tasks import update_team_service_flags_cache# Create a flagFeatureFlag.objects.create(@@ -664,7 +666,7 @@ class TestServiceFlagsCeleryTasks(BaseTest):def test_update_team_service_flags_cache_task_team_not_found(self):"""Test the Celery task handles missing team gracefully."""- from posthog.tasks.feature_flags import update_team_service_flags_cache+ from products.feature_flags.backend.tasks import update_team_service_flags_cache# Run task with non-existent team ID# Should not raise an exception@@ -1122,7 +1124,7 @@ class TestCacheStats(BaseTest):@patch("posthog.storage.hypercache_manager.get_client")def test_get_cache_stats_basic(self, mock_get_client):"""Test basic cache stats gathering with Redis pipelining."""- from posthog.models.feature_flag.flags_cache import get_cache_stats+ from products.feature_flags.backend.flags_cache import get_cache_stats# Mock Redis client with pipelining supportmock_redis = MagicMock()@@ -1175,7 +1177,7 @@ class TestGetTeamsWithExpiringCaches(BaseTest):@patch("posthog.storage.cache_expiry_manager.time")def test_returns_teams_with_expiring_ttl(self, mock_time, mock_get_client):"""Teams with expiration timestamp < threshold should be returned."""- from posthog.models.feature_flag.flags_cache import (+ from products.feature_flags.backend.flags_cache import (FLAGS_CACHE_EXPIRY_SORTED_SET,get_teams_with_expiring_flags_caches,)@@ -1217,7 +1219,7 @@ class TestGetTeamsWithExpiringCaches(BaseTest):@patch("posthog.storage.cache_expiry_manager.time")def test_skips_teams_with_fresh_ttl(self, mock_time, mock_get_client):"""Teams with expiration timestamp > threshold should not be returned."""- from posthog.models.feature_flag.flags_cache import get_teams_with_expiring_flags_caches+ from products.feature_flags.backend.flags_cache import get_teams_with_expiring_flags_caches# Mock Redis sorted set returning empty (no teams expiring soon)mock_time.time.return_value = 1000000@@ -1233,7 +1235,7 @@ class TestGetTeamsWithExpiringCaches(BaseTest):@patch("posthog.storage.cache_expiry_manager.get_client")def test_returns_empty_when_no_expiring_caches(self, mock_get_client):"""Should return empty list when sorted set is empty."""- from posthog.models.feature_flag.flags_cache import get_teams_with_expiring_flags_caches+ from products.feature_flags.backend.flags_cache import get_teams_with_expiring_flags_caches# Mock Redis to return empty sorted setmock_redis = MagicMock()@@ -1251,7 +1253,7 @@ class TestGetTeamsWithExpiringCaches(BaseTest):This is a regression test for a bug where cache_expiry_manager was usingthe default Redis database (0) instead of the dedicated flags cache database (1)."""- from posthog.models.feature_flag.flags_cache import (+ from products.feature_flags.backend.flags_cache import (FLAGS_HYPERCACHE_MANAGEMENT_CONFIG,get_teams_with_expiring_caches,)@@ -1271,10 +1273,10 @@ class TestGetTeamsWithExpiringCaches(BaseTest):class TestBatchOperations(BaseTest):"""Test batch operations for flags cache."""- @patch("posthog.models.feature_flag.flags_cache.refresh_expiring_caches")+ @patch("products.feature_flags.backend.flags_cache.refresh_expiring_caches")def test_refresh_expiring_caches(self, mock_refresh):"""Test refreshing expiring caches calls generic function."""- from posthog.models.feature_flag.flags_cache import (+ from products.feature_flags.backend.flags_cache import (FLAGS_HYPERCACHE_MANAGEMENT_CONFIG,refresh_expiring_flags_caches,)@@ -1293,7 +1295,10 @@ class TestBatchOperations(BaseTest):@patch("posthog.storage.cache_expiry_manager.get_client")def test_cleanup_stale_expiry_tracking(self, mock_get_client):"""Test cleaning up stale expiry tracking entries."""- from posthog.models.feature_flag.flags_cache import FLAGS_CACHE_EXPIRY_SORTED_SET, cleanup_stale_expiry_tracking+ from products.feature_flags.backend.flags_cache import (+ FLAGS_CACHE_EXPIRY_SORTED_SET,+ cleanup_stale_expiry_tracking,+ )team1 = self.team# Create a team that will be deleted@@ -1326,11 +1331,12 @@ class TestBatchOperations(BaseTest):@patch("posthog.storage.hypercache.time")def test_warm_without_stagger_tracks_expiry_with_default_ttl(self, mock_time, mock_get_client):"""Test that expiry tracking happens even when stagger_ttl=False (uses batch path)."""- from posthog.models.feature_flag.flags_cache import (+ from posthog.storage.hypercache_manager import warm_caches++ from products.feature_flags.backend.flags_cache import (FLAGS_CACHE_EXPIRY_SORTED_SET,FLAGS_HYPERCACHE_MANAGEMENT_CONFIG,)- from posthog.storage.hypercache_manager import warm_caches# Create a flag so batch loading succeedsFeatureFlag.objects.create(@@ -1574,7 +1580,7 @@ class TestManagementCommands(BaseTest):# Comprehensive tests for analyze_flags_cache_sizes- @patch("posthog.models.feature_flag.flags_cache._get_feature_flags_for_teams_batch")+ @patch("products.feature_flags.backend.flags_cache._get_feature_flags_for_teams_batch")def test_analyze_percentile_calculation(self, mock_batch_get_flags):"""Test that percentile calculation is accurate."""from io import StringIO@@ -1673,7 +1679,7 @@ class TestManagementCommands(BaseTest):self.assertIn("FLAG FIELD SIZE ANALYSIS", output)self.assertIn("Largest flag fields", output)- @patch("posthog.models.feature_flag.flags_cache._get_feature_flags_for_teams_batch")+ @patch("products.feature_flags.backend.flags_cache._get_feature_flags_for_teams_batch")def test_analyze_compression_ratio(self, mock_batch_get_flags):"""Test that compression ratios are calculated correctly."""from io import StringIO@@ -1754,7 +1760,7 @@ class TestManagementCommands(BaseTest):# Mock the hypercache's set_cache_value to failwith patch(- "posthog.models.feature_flag.flags_cache.flags_hypercache.set_cache_value", side_effect=failing_set_cache+ "products.feature_flags.backend.flags_cache.flags_hypercache.set_cache_value", side_effect=failing_set_cache):out = StringIO()call_command("warm_flags_cache", stdout=out)@@ -1785,7 +1791,7 @@ class TestManagementCommands(BaseTest):# Should show TTL range in outputself.assertIn("TTL range: 3-10 days", output)- @patch("posthog.models.feature_flag.flags_cache.update_flags_cache")+ @patch("products.feature_flags.backend.flags_cache.update_flags_cache")def test_warm_missing_team_ids_warning(self, mock_update):"""Test that warming with non-existent team IDs shows warning."""from io import StringIO@@ -1811,7 +1817,7 @@ class TestManagementCommands(BaseTest):from django.core.management import call_command- from posthog.models.feature_flag.flags_cache import clear_flags_cache+ from products.feature_flags.backend.flags_cache import clear_flags_cache# Clear any cache from previous testsclear_flags_cache(self.team, kinds=["redis", "s3"])@@ -1841,7 +1847,7 @@ class TestManagementCommands(BaseTest):from django.core.management import call_command- from posthog.models.feature_flag.flags_cache import update_flags_cache+ from products.feature_flags.backend.flags_cache import update_flags_cache# Create a real flagflag = FeatureFlag.objects.create(@@ -1867,8 +1873,11 @@ class TestManagementCommands(BaseTest):def test_verify_cache_detects_evaluation_context_rename(self):"""Test that verification detects when an evaluation context is renamed."""- from posthog.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext- from posthog.models.feature_flag.flags_cache import update_flags_cache, verify_team_flags+ from products.feature_flags.backend.flags_cache import update_flags_cache, verify_team_flags+ from products.feature_flags.backend.models.evaluation_context import (+ EvaluationContext,+ FeatureFlagEvaluationContext,+ )flag = FeatureFlag.objects.create(team=self.team,@@ -1925,7 +1934,7 @@ class TestManagementCommands(BaseTest):cache must be ignored (otherwise a benign serializer field removalrewrites every team's cache), but a key the DB has and the cachedoesn't is a real divergence and must still be flagged."""- from posthog.models.feature_flag.flags_cache import update_flags_cache, verify_team_flags+ from products.feature_flags.backend.flags_cache import update_flags_cache, verify_team_flagsFeatureFlag.objects.create(team=self.team,@@ -1951,7 +1960,7 @@ class TestManagementCommands(BaseTest):def test_verify_miss_includes_db_data(self):"""Test that cache miss result includes db_data for direct cache write."""- from posthog.models.feature_flag.flags_cache import clear_flags_cache, verify_team_flags+ from products.feature_flags.backend.flags_cache import clear_flags_cache, verify_team_flagsFeatureFlag.objects.create(team=self.team,@@ -1970,7 +1979,7 @@ class TestManagementCommands(BaseTest):self.assertIn("flags", result["db_data"])def test_verify_detects_missing_evaluation_metadata(self):- from posthog.models.feature_flag.flags_cache import update_flags_cache, verify_team_flags+ from products.feature_flags.backend.flags_cache import update_flags_cache, verify_team_flagsFeatureFlag.objects.create(team=self.team,@@ -1999,7 +2008,7 @@ class TestManagementCommands(BaseTest):"""Without an etag, the Rust in-memory cache bypasses every request viathe etag_missing branch. The verifier must surface this as a countedmismatch so the regression class cannot recur silently."""- from posthog.models.feature_flag.flags_cache import update_flags_cache, verify_team_flags+ from products.feature_flags.backend.flags_cache import update_flags_cache, verify_team_flagsFeatureFlag.objects.create(team=self.team,@@ -2027,7 +2036,7 @@ class TestManagementCommands(BaseTest):drifted cached flags, MISSING_ETAG is reported, not DATA_MISMATCH. Therepair path writes db_data back and corrects both, so this is purelyabout which signal surfaces first."""- from posthog.models.feature_flag.flags_cache import update_flags_cache, verify_team_flags+ from products.feature_flags.backend.flags_cache import update_flags_cache, verify_team_flagsflag = FeatureFlag.objects.create(team=self.team,@@ -2056,7 +2065,7 @@ class TestManagementCommands(BaseTest):teams every 30 minutes — exactly the load this PR is trying to reduce."""from unittest.mock import patch- from posthog.models.feature_flag.flags_cache import update_flags_cache, verify_team_flags+ from products.feature_flags.backend.flags_cache import update_flags_cache, verify_team_flagsFeatureFlag.objects.create(team=self.team,@@ -2099,7 +2108,7 @@ class TestManagementCommands(BaseTest):)# Make the hypercache update fail by mocking update_cache- with patch("posthog.models.feature_flag.flags_cache.flags_hypercache.update_cache", return_value=False):+ with patch("products.feature_flags.backend.flags_cache.flags_hypercache.update_cache", return_value=False):out = StringIO()call_command("verify_flags_cache", f"--team-ids={self.team.id}", "--fix", stdout=out)@@ -2107,8 +2116,8 @@ class TestManagementCommands(BaseTest):self.assertIn("Failed to fix", output)self.assertIn("Cache fixes failed: 1", output)- @patch("posthog.models.feature_flag.flags_cache.get_flags_from_cache")- @patch("posthog.models.feature_flag.flags_cache._get_feature_flags_for_teams_batch")+ @patch("products.feature_flags.backend.flags_cache.get_flags_from_cache")+ @patch("products.feature_flags.backend.flags_cache._get_feature_flags_for_teams_batch")def test_verify_with_sample(self, mock_batch_get_flags, mock_get_cache):"""Test verify command with --sample parameter."""from io import StringIO@@ -2141,7 +2150,7 @@ class TestManagementCommands(BaseTest):from django.core.management import call_command- from posthog.models.feature_flag.flags_cache import update_flags_cache+ from products.feature_flags.backend.flags_cache import update_flags_cache# Create a real flagFeatureFlag.objects.create(@@ -2168,7 +2177,7 @@ class TestManagementCommands(BaseTest):from django.core.management import call_command- from posthog.models.feature_flag.flags_cache import clear_flags_cache+ from products.feature_flags.backend.flags_cache import clear_flags_cache# Delete any existing flags for this team from previous testsFeatureFlag.objects.filter(team=self.team).delete()@@ -2188,7 +2197,7 @@ class TestManagementCommands(BaseTest):self.assertIn("CACHE_MISS", output)self.assertIn("Cache misses:", output)- @patch("posthog.models.feature_flag.flags_cache._get_feature_flags_for_teams_batch")+ @patch("products.feature_flags.backend.flags_cache._get_feature_flags_for_teams_batch")def test_analyze_batch_load_fallback(self, mock_batch_get_flags):"""Test analyze command falls back gracefully when batch load fails."""from io import StringIO@@ -2222,7 +2231,7 @@ class TestManagementCommands(BaseTest):from django.core.management import call_command- from posthog.models.feature_flag.flags_cache import FLAGS_HYPERCACHE_MANAGEMENT_CONFIG+ from products.feature_flags.backend.flags_cache import FLAGS_HYPERCACHE_MANAGEMENT_CONFIG# Create a flag for the teamFeatureFlag.objects.create(@@ -3346,7 +3355,7 @@ class TestSerializeCohort(BaseTest):@override_settings(FLAGS_REDIS_URL="redis://test")class TestCohortChangedFlagsCacheSignal(BaseTest):@patch("django.db.transaction.on_commit", lambda fn: fn())- @patch("posthog.tasks.feature_flags.update_team_service_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")def test_fires_on_cohort_definition_change(self, mock_task):cohort = Cohort.objects.create(team=self.team, name="test")mock_task.reset_mock()@@ -3362,7 +3371,7 @@ class TestCohortChangedFlagsCacheSignal(BaseTest):])@patch("django.db.transaction.on_commit", lambda fn: fn())- @patch("posthog.tasks.feature_flags.update_team_service_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")def test_skips_recalculation_only_save(self, _name, field, value, mock_task):cohort = Cohort.objects.create(team=self.team, name="test")mock_task.reset_mock()@@ -3371,7 +3380,7 @@ class TestCohortChangedFlagsCacheSignal(BaseTest):mock_task.delay.assert_not_called()@patch("django.db.transaction.on_commit", lambda fn: fn())- @patch("posthog.tasks.feature_flags.update_team_service_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")def test_skips_cohort_type_only_save(self, mock_task):cohort = Cohort.objects.create(team=self.team, name="test")mock_task.reset_mock()@@ -3380,7 +3389,7 @@ class TestCohortChangedFlagsCacheSignal(BaseTest):mock_task.delay.assert_not_called()@patch("django.db.transaction.on_commit", lambda fn: fn())- @patch("posthog.tasks.feature_flags.update_team_service_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")def test_fires_on_mixed_recalculation_and_definition_fields(self, mock_task):cohort = Cohort.objects.create(team=self.team, name="test")mock_task.reset_mock()@@ -3390,7 +3399,7 @@ class TestCohortChangedFlagsCacheSignal(BaseTest):mock_task.delay.assert_called_with(self.team.id)@patch("django.db.transaction.on_commit", lambda fn: fn())- @patch("posthog.tasks.feature_flags.update_team_service_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")def test_fires_on_cohort_delete(self, mock_task):cohort = Cohort.objects.create(team=self.team, name="test")mock_task.reset_mock()@@ -3399,7 +3408,7 @@ class TestCohortChangedFlagsCacheSignal(BaseTest):@override_settings(FLAGS_REDIS_URL=None)@patch("django.db.transaction.on_commit", lambda fn: fn())- @patch("posthog.tasks.feature_flags.update_team_service_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")def test_skips_when_no_flags_redis_url(self, mock_task):cohort = Cohort.objects.create(team=self.team, name="test")mock_task.reset_mock()diff --git a/posthog/models/feature_flag/test/test_local_evaluation.py b/products/feature_flags/backend/test/test_local_evaluation.pysimilarity index 97%rename from posthog/models/feature_flag/test/test_local_evaluation.pyrename to products/feature_flags/backend/test/test_local_evaluation.pyindex ec049044a2a1..fa403ff3cb99 100644--- a/posthog/models/feature_flag/test/test_local_evaluation.py+++ b/products/feature_flags/backend/test/test_local_evaluation.py@@ -7,8 +7,13 @@ from django.test import override_settingsfrom parameterized import parameterizedfrom posthog.models.cohort.cohort import Cohort-from posthog.models.feature_flag.feature_flag import FeatureFlag-from posthog.models.feature_flag.local_evaluation import (+from posthog.models.group_type_mapping import GroupTypeMapping+from posthog.models.project import Project+from posthog.models.tag import Tag+from posthog.models.team.team import Team+from posthog.test.test_utils import create_group_type_mapping_without_created_at++from products.feature_flags.backend.local_evaluation import (FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG,_extract_cohort_ids_from_filters,@@ -24,12 +29,7 @@ from posthog.models.feature_flag.local_evaluation import (update_flag_definitions_cache,verify_team_flag_definitions,)-from posthog.models.group_type_mapping import GroupTypeMapping-from posthog.models.project import Project-from posthog.models.tag import Tag-from posthog.models.team.team import Team-from posthog.test.test_utils import create_group_type_mapping_without_created_at-+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.surveys.backend.models import Survey@@ -213,11 +213,14 @@ class TestLocalEvaluationCache(BaseTest):class TestLocalEvaluationSignals(BaseTest):- @patch("posthog.tasks.feature_flags.update_team_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())def test_signal_fired_on_evaluation_context_association_create(self, mock_task):"""Creating a FeatureFlagEvaluationContext fires the cache update signal."""- from posthog.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext+ from products.feature_flags.backend.models.evaluation_context import (+ EvaluationContext,+ FeatureFlagEvaluationContext,+ )flag = FeatureFlag.objects.create(team=self.team,@@ -235,11 +238,14 @@ class TestLocalEvaluationSignals(BaseTest):mock_task.delay.assert_called_once_with(self.team.id)- @patch("posthog.tasks.feature_flags.update_team_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())def test_signal_fired_on_evaluation_context_association_delete(self, mock_task):"""Deleting a FeatureFlagEvaluationContext fires the cache update signal."""- from posthog.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext+ from products.feature_flags.backend.models.evaluation_context import (+ EvaluationContext,+ FeatureFlagEvaluationContext,+ )flag = FeatureFlag.objects.create(team=self.team,@@ -256,14 +262,14 @@ class TestLocalEvaluationSignals(BaseTest):mock_task.delay.assert_called_once_with(self.team.id)- @patch("posthog.tasks.feature_flags.update_team_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())def test_signal_not_fired_on_evaluation_context_create(self, mock_task):"""Creating an EvaluationContext does NOT fire the cache update signal.New contexts can't be referenced by any flags yet, so invalidation is a no-op."""- from posthog.models.evaluation_context import EvaluationContext+ from products.feature_flags.backend.models.evaluation_context import EvaluationContextFeatureFlag.objects.create(team=self.team,@@ -278,14 +284,17 @@ class TestLocalEvaluationSignals(BaseTest):mock_task.delay.assert_not_called()- @patch("posthog.tasks.feature_flags.update_team_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())def test_signal_fired_on_evaluation_context_rename(self, mock_task):"""Renaming an EvaluationContext fires the cache update signal.Flags referencing the context need to pick up the new name."""- from posthog.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext+ from products.feature_flags.backend.models.evaluation_context import (+ EvaluationContext,+ FeatureFlagEvaluationContext,+ )flag = FeatureFlag.objects.create(team=self.team,@@ -303,7 +312,7 @@ class TestLocalEvaluationSignals(BaseTest):mock_task.delay.assert_called_once_with(self.team.id)- @patch("posthog.tasks.feature_flags.update_team_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())def test_tag_rename_does_not_fire_signal(self, mock_task):"""Tag renames no longer affect evaluation contexts, so no cache invalidation needed."""@@ -437,7 +446,7 @@ class TestSurveyFlagExclusion(BaseTest):assert regular_flag.key in flag_keysassert survey_flag.key not in flag_keys- @patch("posthog.tasks.feature_flags.update_team_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())def test_flag_cache_invalidated_on_survey_change(self, mock_task):"""Creating/deleting a survey should invalidate the flag cache."""@@ -464,7 +473,7 @@ class TestSurveyFlagExclusion(BaseTest):mock_task.delay.assert_called_with(self.team.id)- @patch("posthog.tasks.feature_flags.update_team_flags_cache")+ @patch("products.feature_flags.backend.tasks.update_team_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())def test_flag_cache_invalidated_on_survey_update(self, mock_task):"""Updating a survey should invalidate the flag cache."""diff --git a/products/feature_flags/backend/test/test_max_tools.py b/products/feature_flags/backend/test/test_max_tools.pyindex 93e12455a776..10a0e4a1dae7 100644--- a/products/feature_flags/backend/test/test_max_tools.py+++ b/products/feature_flags/backend/test/test_max_tools.py@@ -4,7 +4,6 @@ from parameterized import parameterizedfrom posthog.schema import FeatureFlagGroupType, GroupPropertyFilter, PersonPropertyFilter, PropertyOperator-from posthog.models import FeatureFlagfrom posthog.models.group_type_mapping import GroupTypeMappingfrom products.feature_flags.backend.max_tools import (@@ -12,6 +11,7 @@ from products.feature_flags.backend.max_tools import (FeatureFlagCreationSchema,MultivariateVariant,)+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.hogai.utils.types import AssistantStatediff --git a/posthog/feature_flags/test_sdk_cache_provider.py b/products/feature_flags/backend/test/test_sdk_cache_provider.pysimilarity index 95%rename from posthog/feature_flags/test_sdk_cache_provider.pyrename to products/feature_flags/backend/test/test_sdk_cache_provider.pyindex 4bb14ef3eae2..a27719902a59 100644--- a/posthog/feature_flags/test_sdk_cache_provider.py+++ b/products/feature_flags/backend/test/test_sdk_cache_provider.py@@ -5,7 +5,7 @@ from django.test import SimpleTestCasefrom parameterized import parameterizedfrom posthoganalytics.client import Client-from posthog.feature_flags.sdk_cache_provider import HyperCacheFlagProvider+from products.feature_flags.backend.sdk_cache_provider import HyperCacheFlagProviderclass TestHyperCacheFlagProvider(SimpleTestCase):@@ -47,7 +47,7 @@ class TestHyperCacheFlagProvider(SimpleTestCase):("exception", None, Exception("Redis connection failed"), None),])- @patch("posthog.models.feature_flag.local_evaluation.flag_definitions_hypercache")+ @patch("products.feature_flags.backend.local_evaluation.flag_definitions_hypercache")def test_get_flag_definitions(self, _name, cache_return, side_effect, expected, mock_hypercache):# Reset cached reference so the mock is picked upself.provider._hypercache = None@@ -65,13 +65,13 @@ class TestHyperCacheFlagProvider(SimpleTestCase):assert result == expected@patch(- "posthog.feature_flags.sdk_cache_provider.HyperCacheFlagProvider._get_hypercache",+ "products.feature_flags.backend.sdk_cache_provider.HyperCacheFlagProvider._get_hypercache",side_effect=ImportError("circular import"),)def test_get_flag_definitions_returns_none_on_circular_import(self, _mock):assert self.provider.get_flag_definitions() is None- @patch("posthog.models.feature_flag.local_evaluation.flag_definitions_hypercache")+ @patch("products.feature_flags.backend.local_evaluation.flag_definitions_hypercache")def test_caches_hypercache_reference(self, mock_hypercache):self.provider._hypercache = Nonemock_hypercache.get_from_cache.return_value = Nonediff --git a/posthog/models/feature_flag/test/test_version_history.py b/products/feature_flags/backend/test/test_version_history.pysimilarity index 99%rename from posthog/models/feature_flag/test/test_version_history.pyrename to products/feature_flags/backend/test/test_version_history.pyindex 654c3e6d29c3..f05eeaecbfa7 100644--- a/posthog/models/feature_flag/test/test_version_history.py+++ b/products/feature_flags/backend/test/test_version_history.py@@ -5,8 +5,9 @@ from posthog.test.base import BaseTestfrom parameterized import parameterizedfrom posthog.models.activity_logging.activity_log import Change, ChangeAction, Detail, log_activity-from posthog.models.feature_flag.feature_flag import FeatureFlag-from posthog.models.feature_flag.version_history import (++from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.version_history import (RECONSTRUCTABLE_FIELDS,VersionHistoryIncomplete,VersionNotFound,diff --git a/posthog/models/feature_flag/types.py b/products/feature_flags/backend/types.pysimilarity index 100%rename from posthog/models/feature_flag/types.pyrename to products/feature_flags/backend/types.pydiff --git a/posthog/models/feature_flag/user_blast_radius.py b/products/feature_flags/backend/user_blast_radius.pysimilarity index 100%rename from posthog/models/feature_flag/user_blast_radius.pyrename to products/feature_flags/backend/user_blast_radius.pydiff --git a/posthog/models/feature_flag/version_history.py b/products/feature_flags/backend/version_history.pysimilarity index 99%rename from posthog/models/feature_flag/version_history.pyrename to products/feature_flags/backend/version_history.pyindex 5d7c5c7360f8..9bd69618aa86 100644--- a/posthog/models/feature_flag/version_history.py+++ b/products/feature_flags/backend/version_history.py@@ -4,7 +4,8 @@ from typing import Anyfrom django.utils import timezonefrom posthog.models.activity_logging.activity_log import ActivityLog, common_field_exclusions, field_exclusions-from posthog.models.feature_flag.feature_flag import FeatureFlag++from products.feature_flags.backend.models.feature_flag import FeatureFlagclass VersionNotFound(Exception):diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.tsindex 11275be1f858..25f821b8c473 100644--- a/products/feature_flags/frontend/generated/api.schemas.ts+++ b/products/feature_flags/frontend/generated/api.schemas.ts@@ -1174,6 +1174,15 @@ export interface UserBlastRadiusResponseApi {total: number}+export interface FlagValueItemApi {+ name: unknown+}++export interface FlagValueResponseApi {+ results: FlagValueItemApi[]+ refreshing: boolean+}+/*** * `FeatureFlag` - feature flag*/@@ -1433,6 +1442,13 @@ export type FeatureFlagsMyFlagsRetrieveParams = {groups?: string}+export type FlagValueValuesRetrieveParams = {+ /**+ * The flag ID+ */+ key?: string+}+export type ScheduledChangesListParams = {/*** Number of results to return per page.diff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.tsindex 62f4f552b93e..c283190f3973 100644--- a/products/feature_flags/frontend/generated/api.ts+++ b/products/feature_flags/frontend/generated/api.ts@@ -31,6 +31,8 @@ import type {FeatureFlagsListParams,FeatureFlagsLocalEvaluationRetrieveParams,FeatureFlagsMyFlagsRetrieveParams,+ FlagValueResponseApi,+ FlagValueValuesRetrieveParams,LocalEvaluationResponseApi,MyFlagsResponseApi,PaginatedFeatureFlagListApi,@@ -697,6 +699,42 @@ export const featureFlagsUserBlastRadiusCreate = async (})}+export const getFlagValueValuesRetrieveUrl = (projectId: string, params?: FlagValueValuesRetrieveParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString())+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/flag_value/values/?${stringifiedParams}`+ : `/api/projects/${projectId}/flag_value/values/`+}++/**+ * Get possible values for a feature flag.++Query parameters:+- key: The flag ID (required)+Returns:++- Array of objects with 'name' field containing possible values+ */+export const flagValueValuesRetrieve = async (+ projectId: string,+ params?: FlagValueValuesRetrieveParams,+ options?: RequestInit+): Promise<FlagValueResponseApi> => {+ return apiMutator<FlagValueResponseApi>(getFlagValueValuesRetrieveUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getScheduledChangesListUrl = (projectId: string, params?: ScheduledChangesListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yamlindex 608566e45437..8f962a6fbcd3 100644--- a/products/feature_flags/mcp/tools.yaml+++ b/products/feature_flags/mcp/tools.yaml@@ -302,6 +302,9 @@ tools:feature-flags-versions-retrieve:operation: feature_flags_versions_retrieveenabled: false+ flag-value-values-retrieve:+ operation: flag_value_values_retrieve+ enabled: falseorg-feature-flags-retrieve:operation: org_feature_flags_retrieveenabled: falsediff --git a/products/posthog_ai/scripts/audit_constants/__init__.py b/products/posthog_ai/scripts/audit_constants/__init__.pyindex 1d0828d88a69..e61918948d2d 100644--- a/products/posthog_ai/scripts/audit_constants/__init__.py+++ b/products/posthog_ai/scripts/audit_constants/__init__.py@@ -5,7 +5,7 @@ def audit_constants() -> dict[str, object]:"""Return audit-related constants for experiment/flag audit skills.Values sourced from:- - staleness_days: posthog.models.feature_flag.flag_status (timedelta(days=30))+ - staleness_days: products.feature_flags.backend.flag_status (timedelta(days=30))- variant_sum_target: rollout percentages must sum to 100These are hardcoded rather than imported because experiment_service triggersdiff --git a/products/product_tours/backend/api/product_tour.py b/products/product_tours/backend/api/product_tour.pyindex d049a7b7c9c6..1df500af3e58 100644--- a/products/product_tours/backend/api/product_tour.py+++ b/products/product_tours/backend/api/product_tour.py@@ -22,7 +22,6 @@ from rest_framework.decorators import actionfrom rest_framework.request import Requestfrom rest_framework.response import Response-from posthog.api.feature_flag import FeatureFlagSerializer, MinimalFeatureFlagSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import get_token@@ -43,6 +42,7 @@ from posthog.models.user import Userfrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom posthog.utils_cors import cors_response+from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer, MinimalFeatureFlagSerializerfrom products.product_tours.backend.constants import ProductTourEventName, ProductTourPersonPropertiesfrom products.product_tours.backend.generate_tour_content import ContentGenerationResult, generate_with_geminifrom products.product_tours.backend.models import ProductTour@@ -229,7 +229,7 @@ class ProductTourSerializerCreateUpdateOnly(serializers.ModelSerializer):return valuedef validate(self, data):- from posthog.models.feature_flag import FeatureFlag+ from products.feature_flags.backend.models.feature_flag import FeatureFlag# For partial updates (PATCH), fall back to the instance's existing# linked_flag_id when the field wasn't included in the request.diff --git a/products/product_tours/backend/api/test/test_product_tour.py b/products/product_tours/backend/api/test/test_product_tour.pyindex b782fa78fb0e..4a57d3d79c1f 100644--- a/products/product_tours/backend/api/test/test_product_tour.py+++ b/products/product_tours/backend/api/test/test_product_tour.py@@ -6,9 +6,9 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status-from posthog.models.feature_flag import FeatureFlagfrom posthog.models.team.team import Team+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_tours.backend.api.product_tour import get_product_tours_responsefrom products.product_tours.backend.constants import ProductTourEventName, ProductTourPersonPropertiesfrom products.product_tours.backend.models import ProductTourdiff --git a/products/product_tours/backend/api/test/test_product_tour_draft.py b/products/product_tours/backend/api/test/test_product_tour_draft.pyindex 8c9394e2f893..ca8468676099 100644--- a/products/product_tours/backend/api/test/test_product_tour_draft.py+++ b/products/product_tours/backend/api/test/test_product_tour_draft.py@@ -6,8 +6,7 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status-from posthog.models.feature_flag import FeatureFlag-+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_tours.backend.models import ProductTourdiff --git a/products/product_tours/backend/migrations/0007_migrate_feature_flags_models.py b/products/product_tours/backend/migrations/0007_migrate_feature_flags_models.pynew file mode 100644index 000000000000..1bec3ff2d376--- /dev/null+++ b/products/product_tours/backend/migrations/0007_migrate_feature_flags_models.py@@ -0,0 +1,44 @@+# Generated by Django 5.2.13 on 2026-05-20 15:38++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("feature_flags", "0002_migrate_feature_flags_models"),+ ("product_tours", "0006_alter_producttour_linked_surveys"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AlterField(+ model_name="producttour",+ name="internal_targeting_flag",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="product_tours_internal_targeting_flag",+ related_query_name="product_tour_internal_targeting_flag",+ to="feature_flags.featureflag",+ ),+ ),+ migrations.AlterField(+ model_name="producttour",+ name="linked_flag",+ field=models.ForeignKey(+ blank=True,+ db_index=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="product_tours_linked_flag",+ related_query_name="product_tour_linked_flag",+ to="feature_flags.featureflag",+ ),+ ),+ ],+ database_operations=[],+ ),+ ]diff --git a/products/product_tours/backend/migrations/max_migration.txt b/products/product_tours/backend/migrations/max_migration.txtindex 3a575e32d558..38261dd9b38e 100644--- a/products/product_tours/backend/migrations/max_migration.txt+++ b/products/product_tours/backend/migrations/max_migration.txt@@ -1 +1 @@-0006_alter_producttour_linked_surveys+0007_migrate_feature_flags_modelsdiff --git a/products/product_tours/backend/models.py b/products/product_tours/backend/models.pyindex 511ae3af6ef2..3a56a983515b 100644--- a/products/product_tours/backend/models.py+++ b/products/product_tours/backend/models.py@@ -28,7 +28,7 @@ class ProductTour(models.Model):description = models.TextField(blank=True, default="")internal_targeting_flag = models.ForeignKey(- "posthog.FeatureFlag",+ "feature_flags.FeatureFlag",null=True,blank=True,on_delete=models.SET_NULL,@@ -37,7 +37,7 @@ class ProductTour(models.Model):)linked_flag = models.ForeignKey(- "posthog.FeatureFlag",+ "feature_flags.FeatureFlag",null=True,blank=True,on_delete=models.SET_NULL,diff --git a/products/ruff.toml b/products/ruff.tomlindex 62795c9e794b..d41a23e02998 100644--- a/products/ruff.toml+++ b/products/ruff.toml@@ -31,6 +31,7 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]"endpoints/backend/**" = ["ANN"]"error_tracking/backend/**" = ["ANN"]"experiments/backend/**" = ["ANN"]+"feature_flags/backend/**" = ["ANN"]"llm_analytics/backend/**" = ["ANN"]"logs/backend/**" = ["ANN"]"marketing_analytics/backend/**" = ["ANN"]diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.pyindex 92bb14a5f389..a29c3bc6a017 100644--- a/products/surveys/backend/api/survey.py+++ b/products/surveys/backend/api/survey.py@@ -42,12 +42,6 @@ from rest_framework.response import Responsefrom posthog.schema import ProductKeyfrom posthog.api.documentation import FeatureFlagFiltersSchemaSerializer-from posthog.api.feature_flag import (- BEHAVIOURAL_COHORT_FOUND_ERROR_CODE,- FeatureFlagSerializer,- MinimalFeatureFlagSerializer,- warn_if_missing_feature_flag_write_scope,-)from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import action@@ -66,7 +60,6 @@ from posthog.helpers.trigram_search import (from posthog.models import Insightfrom posthog.models.activity_logging.activity_log import Change, Detail, changes_between, load_activity, log_activityfrom posthog.models.activity_logging.activity_page import activity_page_response-from posthog.models.feature_flag import FeatureFlagfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.models.utils import UUIDT@@ -76,6 +69,13 @@ from posthog.utils_cors import cors_responsefrom products.actions.backend.api.action import ActionSerializer, ActionStepJSONSerializerfrom products.actions.backend.models.action import Action+from products.feature_flags.backend.api.feature_flag import (+ BEHAVIOURAL_COHORT_FOUND_ERROR_CODE,+ FeatureFlagSerializer,+ MinimalFeatureFlagSerializer,+ warn_if_missing_feature_flag_write_scope,+)+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.surveys.backend.models import MAX_ITERATION_COUNT, Survey, SurveyResponseArchive, ensure_question_idsfrom products.surveys.backend.summarization import fetch_responses, format_as_markdown, summarize_responsesfrom products.surveys.backend.translation import generate_survey_translationdiff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.pyindex 48f9caee793b..6461e9e5b3c1 100644--- a/products/surveys/backend/api/test/test_survey.py+++ b/products/surveys/backend/api/test/test_survey.py@@ -24,11 +24,12 @@ from rest_framework import statusfrom posthog.api.test.test_personal_api_keys import PersonalAPIKeysBaseTestfrom posthog.constants import AvailableFeature-from posthog.models import FeatureFlag, Insight, Person, Team+from posthog.models import Insight, Person, Teamfrom posthog.models.cohort.cohort import Cohortfrom posthog.models.organization import Organization, OrganizationMembershipfrom products.actions.backend.models.action import Action+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_tours.backend.models import ProductTourfrom products.surveys.backend.api.survey import nh3_clean_with_allow_listfrom products.surveys.backend.models import MAX_ITERATION_COUNT, Survey, SurveyResponseArchive@@ -896,7 +897,7 @@ class TestSurvey(APIBaseTest):assert "choices" not in translationsassert translations["question"] == "¿Qué piensas?"- @patch("posthog.api.feature_flag.report_user_action")+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_creation_context_is_set_to_surveys(self, mock_report_user_action):response = self.client.post(f"/api/projects/{self.team.id}/surveys/",diff --git a/products/surveys/backend/migrations/0004_migrate_feature_flags_models.py b/products/surveys/backend/migrations/0004_migrate_feature_flags_models.pynew file mode 100644index 000000000000..cd516e79201c--- /dev/null+++ b/products/surveys/backend/migrations/0004_migrate_feature_flags_models.py@@ -0,0 +1,67 @@+# Generated by Django 5.2.13 on 2026-05-20 15:38++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("feature_flags", "0002_migrate_feature_flags_models"),+ ("surveys", "0003_survey_base_language_alter_survey_questions"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AlterField(+ model_name="survey",+ name="internal_response_sampling_flag",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="surveys_internal_response_sampling_flag",+ related_query_name="surveys_internal_response_sampling_flag",+ to="feature_flags.featureflag",+ ),+ ),+ migrations.AlterField(+ model_name="survey",+ name="internal_targeting_flag",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="surveys_internal_targeting_flag",+ related_query_name="survey_internal_targeting_flag",+ to="feature_flags.featureflag",+ ),+ ),+ migrations.AlterField(+ model_name="survey",+ name="linked_flag",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="surveys_linked_flag",+ related_query_name="survey_linked_flag",+ to="feature_flags.featureflag",+ ),+ ),+ migrations.AlterField(+ model_name="survey",+ name="targeting_flag",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="surveys_targeting_flag",+ related_query_name="survey_targeting_flag",+ to="feature_flags.featureflag",+ ),+ ),+ ],+ database_operations=[],+ ),+ ]diff --git a/products/surveys/backend/migrations/max_migration.txt b/products/surveys/backend/migrations/max_migration.txtindex d4e7bc2fc1da..9b337fbc2f53 100644--- a/products/surveys/backend/migrations/max_migration.txt+++ b/products/surveys/backend/migrations/max_migration.txt@@ -1 +1 @@-0003_survey_base_language_alter_survey_questions+0004_migrate_feature_flags_modelsdiff --git a/products/surveys/backend/models.py b/products/surveys/backend/models.pyindex c1b36d76e019..b2871cbf122c 100644--- a/products/surveys/backend/models.py+++ b/products/surveys/backend/models.py@@ -58,7 +58,7 @@ class Survey(FileSystemSyncMixin, RootTeamMixin, UUIDTModel):name = models.CharField(max_length=400)description = models.TextField(blank=True)linked_flag = models.ForeignKey(- "posthog.FeatureFlag",+ "feature_flags.FeatureFlag",null=True,blank=True,on_delete=models.SET_NULL,@@ -66,7 +66,7 @@ class Survey(FileSystemSyncMixin, RootTeamMixin, UUIDTModel):related_query_name="survey_linked_flag",)targeting_flag = models.ForeignKey(- "posthog.FeatureFlag",+ "feature_flags.FeatureFlag",null=True,blank=True,on_delete=models.SET_NULL,@@ -84,7 +84,7 @@ class Survey(FileSystemSyncMixin, RootTeamMixin, UUIDTModel):db_constraint=True,)internal_targeting_flag = models.ForeignKey(- "posthog.FeatureFlag",+ "feature_flags.FeatureFlag",null=True,blank=True,on_delete=models.SET_NULL,@@ -92,7 +92,7 @@ class Survey(FileSystemSyncMixin, RootTeamMixin, UUIDTModel):related_query_name="survey_internal_targeting_flag",)internal_response_sampling_flag = models.ForeignKey(- "posthog.FeatureFlag",+ "feature_flags.FeatureFlag",null=True,blank=True,on_delete=models.SET_NULL,@@ -482,9 +482,10 @@ surveys_hypercache = HyperCache(@receiver(post_save, sender=Survey)@receiver(post_delete, sender=Survey)def survey_changed(sender, instance: "Survey", **kwargs):- from posthog.tasks.feature_flags import update_team_flags_cachefrom posthog.tasks.surveys import update_team_surveys_cache+ from products.feature_flags.backend.tasks import update_team_flags_cache+# Defer task execution until after the transaction commits# Update both survey cache and flag cache since survey-linked flags are# excluded from local evaluation (GitHub issue #43631)diff --git a/products/surveys/backend/test_max_tools.py b/products/surveys/backend/test_max_tools.pyindex 0ff67e68f096..8193f464549d 100644--- a/products/surveys/backend/test_max_tools.py+++ b/products/surveys/backend/test_max_tools.py@@ -11,8 +11,9 @@ from asgiref.sync import sync_to_asyncfrom langchain_core.runnables import RunnableConfigfrom parameterized import parameterized-from posthog.models import FeatureFlag, Insight+from posthog.models import Insight+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.surveys.backend.models import Surveyfrom .max_tools import CreateSurveyTool, EditSurveyTool, SimpleSurveyQuestion, SurveyAnalysisTooldiff --git a/products/tasks/backend/management/commands/setup_background_agents.py b/products/tasks/backend/management/commands/setup_background_agents.pyindex 15a976871e85..d65f7541ce53 100644--- a/products/tasks/backend/management/commands/setup_background_agents.py+++ b/products/tasks/backend/management/commands/setup_background_agents.py@@ -10,9 +10,10 @@ from django.conf import settingsfrom django.core.management.base import BaseCommand, CommandErrorfrom posthog.models import OAuthApplication, Team-from posthog.models.feature_flag import FeatureFlagfrom posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV+from products.feature_flags.backend.models.feature_flag import FeatureFlag+AUTO_FILL_KEYS = ["OIDC_RSA_PRIVATE_KEY","SANDBOX_JWT_PRIVATE_KEY",diff --git a/products/tasks/scripts/run_agent_in_docker.py b/products/tasks/scripts/run_agent_in_docker.pyindex e4e55ac10c1a..5a3d262e2cc5 100755--- a/products/tasks/scripts/run_agent_in_docker.py+++ b/products/tasks/scripts/run_agent_in_docker.py@@ -24,9 +24,10 @@ django.setup()from django.db import transaction-from posthog.models import FeatureFlag, Integration, PersonalAPIKey, Team, User+from posthog.models import Integration, PersonalAPIKey, Team, Userfrom posthog.models.utils import generate_random_token_personal, hash_key_value+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.tasks.backend.models import Task, TaskRunfrom products.tasks.backend.services.docker_sandbox import DockerSandboxfrom products.tasks.backend.services.sandbox import SandboxConfig, SandboxTemplatediff --git a/tach.toml b/tach.tomlindex 71d1880c990a..0c1cf3423bbd 100644--- a/tach.toml+++ b/tach.toml@@ -115,6 +115,7 @@ path = "products.actions"depends_on = ["posthog","products.experiments",+ "products.feature_flags",]layer = "modules"@@ -239,7 +240,7 @@ layer = "modules"[[modules]]path = "products.early_access_features"depends_on = [- "posthog",+ "posthog", "products.feature_flags",]layer = "modules"@@ -278,7 +279,7 @@ depends_on = ["products.event_definitions","products.notifications","products.product_tours",- "products.surveys",+ "products.surveys", "products.feature_flags",]layer = "modules"@@ -286,7 +287,7 @@ layer = "modules"path = "products.feature_flags"depends_on = ["ee",- "posthog",+ "posthog", "products.surveys", "products.dashboards", "products.early_access_features", "products.product_tours", "products.experiments",]layer = "modules"@@ -432,7 +433,7 @@ layer = "modules"path = "products.product_tours"depends_on = ["posthog",- "products.surveys",+ "products.surveys", "products.feature_flags",]layer = "modules"@@ -490,7 +491,7 @@ depends_on = ["ee","posthog","products.actions",- "products.product_tours",+ "products.product_tours", "products.feature_flags",]layer = "modules"@@ -505,7 +506,7 @@ depends_on = ["products.mcp_store","products.posthog_ai","products.signals",- "products.slack_app",+ "products.slack_app", "products.feature_flags",]layer = "modules"