: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(approvals): extract approvals into its own product (#66197)
Paul D'Ambraca94a6c45544
diff --git a/.github/CODEOWNERS-soft b/.github/CODEOWNERS-softindex 3574f801b6d8..1a110a2b99c8 100644--- a/.github/CODEOWNERS-soft+++ b/.github/CODEOWNERS-soft@@ -142,7 +142,6 @@ frontend/src/scenes/audit-logs/ @PostHog/team-platform-featuresfrontend/src/scenes/activity/ @PostHog/team-platform-featuresposthog/models/activity_logging/ @PostHog/team-platform-featuresfrontend/src/scenes/approvals/ @PostHog/team-platform-features-posthog/approvals/ @PostHog/team-platform-featuresfrontend/src/scenes/resource-transfer/ @PostHog/team-platform-featuresposthog/api/resource_transfer.py @PostHog/team-platform-featuresposthog/models/resource_transfer/ @PostHog/team-platform-featuresdiff --git a/.semgrep/rules/idor-team-scoped-models.py b/.semgrep/rules/idor-team-scoped-models.pyindex 7b40a86c196f..1b917f903bf9 100644--- a/.semgrep/rules/idor-team-scoped-models.py+++ b/.semgrep/rules/idor-team-scoped-models.py@@ -1,5 +1,6 @@from django.shortcuts import get_object_or_404-from posthog.models import ChangeRequest, Notebook+from posthog.models import Notebook+from products.approvals.backend.models import ChangeRequestfrom products.cohorts.backend.models.cohort import Cohortfrom products.product_analytics.backend.models.insight import Insightfrom products.actions.backend.models.action import Actiondiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 24033dda2915..d10d356f16c8 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2696,6 +2696,8 @@ importers:products/annotations: {}+ products/approvals: {}+products/batch_exports: {}products/business_knowledge:diff --git a/posthog/api/rest_router.py b/posthog/api/rest_router.pyindex 0e5dd64442b8..5ebabf3a08d9 100644--- a/posthog/api/rest_router.py+++ b/posthog/api/rest_router.py@@ -15,7 +15,6 @@ from posthog.api.query_performance_proxy import QueryPerformanceProxyViewSetfrom posthog.api.routing import DefaultRouterPlusPlus, RouterRegistryfrom posthog.api.sdk_health import SdkHealthViewSetfrom posthog.api.wizard import http as wizard-from posthog.approvals import api as approval_apifrom posthog.settings import EE_AVAILABLEfrom ee.api.quota_limits import QuotaLimitsViewSet@@ -598,20 +597,6 @@ register_legacy_dual_route_team_nested_viewset(projects_router.register(r"js-snippet", JsSnippetViewSet, "project_js_snippet", ["team_id"])-register_legacy_dual_route_team_nested_viewset(- r"change_requests",- approval_api.ChangeRequestViewSet,- "project_change_requests",- ["team_id"],-)--register_legacy_dual_route_team_nested_viewset(- r"approval_policies",- approval_api.ApprovalPolicyViewSet,- "project_approval_policies",- ["team_id"],-)-register_legacy_dual_route_team_nested_viewset(r"core_events",CoreEventViewSet,diff --git a/posthog/api/test/test_personal_api_keys.py b/posthog/api/test/test_personal_api_keys.pyindex cb96bafd78f1..3cd25f9b8091 100644--- a/posthog/api/test/test_personal_api_keys.py+++ b/posthog/api/test/test_personal_api_keys.py@@ -821,7 +821,7 @@ class TestPersonalAPIKeysWithApprovalsScope(PersonalAPIKeysBaseTest):assert response.json()["detail"] == "API key missing required scope 'approvals:read'"def _create_change_request(self):- from posthog.approvals.models import ChangeRequest, ChangeRequestState+ from products.approvals.backend.models import ChangeRequest, ChangeRequestStatereturn ChangeRequest.objects.create(team=self.team,diff --git a/posthog/migrations/1239_migrate_approvals_models.py b/posthog/migrations/1239_migrate_approvals_models.pynew file mode 100644index 000000000000..580eba27da76--- /dev/null+++ b/posthog/migrations/1239_migrate_approvals_models.py@@ -0,0 +1,95 @@+from django.db import migrations++MODELS_TO_MOVE = ("changerequest", "approvalpolicy", "approval")+++def _move_content_types(apps, schema_editor, from_label, to_label):+ """Move ContentTypes between apps, handling duplicates idempotently."""+ db_alias = schema_editor.connection.alias+ ContentType = apps.get_model("contenttypes", "ContentType")+ Permission = apps.get_model("auth", "Permission")++ for model_name in MODELS_TO_MOVE:+ source = ContentType.objects.using(db_alias).filter(app_label=from_label, model=model_name).first()+ target = ContentType.objects.using(db_alias).filter(app_label=to_label, model=model_name).first()++ if source and target:+ Permission.objects.using(db_alias).filter(content_type=source).update(content_type=target)+ source.delete(using=db_alias)+ elif source:+ source.app_label = to_label+ source.save(using=db_alias)+++def update_content_types(apps, schema_editor):+ _move_content_types(apps, schema_editor, "posthog", "approvals")+++def reverse_content_types(apps, schema_editor):+ _move_content_types(apps, schema_editor, "approvals", "posthog")+++class Migration(migrations.Migration):+ dependencies = [+ ("approvals", "0001_migrate_approvals_models"),+ ("posthog", "1238_ducklakebackfill_earliest_event_date"),+ ]++ # State-only move: the approval models now live in the `approvals` app+ # (products/approvals/backend). database_operations is empty — the physical tables are+ # untouched; products/approvals/backend/migrations/0001_migrate_approvals_models.py+ # recreates them in ORM state under the `approvals` app. The RunPython below repoints+ # existing django_content_type / auth_permission rows from the posthog label to approvals.+ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AlterUniqueTogether(+ name="approvalpolicy",+ unique_together=None,+ ),+ migrations.RemoveField(+ model_name="approvalpolicy",+ name="bypass_roles",+ ),+ migrations.RemoveField(+ model_name="approvalpolicy",+ name="created_by",+ ),+ migrations.RemoveField(+ model_name="approvalpolicy",+ name="organization",+ ),+ migrations.RemoveField(+ model_name="approvalpolicy",+ name="team",+ ),+ migrations.RemoveField(+ model_name="changerequest",+ name="applied_by",+ ),+ migrations.RemoveField(+ model_name="changerequest",+ name="created_by",+ ),+ migrations.RemoveField(+ model_name="changerequest",+ name="organization",+ ),+ migrations.RemoveField(+ model_name="changerequest",+ name="team",+ ),+ migrations.DeleteModel(+ name="Approval",+ ),+ migrations.DeleteModel(+ name="ApprovalPolicy",+ ),+ migrations.DeleteModel(+ name="ChangeRequest",+ ),+ ],+ database_operations=[],+ ),+ migrations.RunPython(update_content_types, reverse_content_types),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 664ecbdbfbed..379e354ae555 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1238_ducklakebackfill_earliest_event_date+1239_migrate_approvals_modelsdiff --git a/posthog/models/__init__.py b/posthog/models/__init__.pyindex f3ea3c5f075f..07dc14d23531 100644--- a/posthog/models/__init__.py+++ b/posthog/models/__init__.py@@ -85,12 +85,7 @@ from .oauth import (OAuthRefreshToken,)-from ..approvals.models import Approval, ApprovalPolicy, ChangeRequest-__all__ = [- "Approval",- "ApprovalPolicy",- "ChangeRequest","ActivityLog","AsyncDeletion","AsyncMigration",diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 195575fccbb1..09f0780ac6ad 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -95,6 +95,7 @@ PRODUCTS_APPS = ["products.cohorts.backend.apps.CohortsConfig","products.growth.backend.apps.GrowthConfig","products.reminders.backend.apps.RemindersConfig",+ "products.approvals.backend.apps.ApprovalsConfig",]INSTALLED_APPS = [diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex b713c9c9e23d..9c56c57e2644 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -7,7 +7,6 @@ from celery import Celeryfrom celery.canvas import Signaturefrom celery.schedules import crontab-from posthog.approvals.tasks import expire_old_change_requests, validate_pending_change_requestsfrom posthog.caching.warming import schedule_warming_for_teams_taskfrom posthog.clickhouse.client.execute_async import QueryStatusManagerfrom posthog.tasks.ai_observability_usage_report import send_ai_observability_usage_reports@@ -73,6 +72,7 @@ from posthog.tasks.team_llm_gateway_policy import refresh_expiring_llm_gateway_pfrom posthog.tasks.team_metadata import cleanup_stale_expiry_tracking_task, refresh_expiring_team_metadata_cache_entriesfrom posthog.utils import get_crontab, get_instance_region+from products.approvals.backend.tasks import expire_old_change_requests, validate_pending_change_requestsfrom products.conversations.backend.tasks import (flush_pending_email_replies,poll_teams_shared_channels,diff --git a/posthog/approvals/__init__.py b/products/approvals/__init__.pysimilarity index 100%rename from posthog/approvals/__init__.pyrename to products/approvals/__init__.pydiff --git a/posthog/approvals/tests/__init__.py b/products/approvals/backend/__init__.pysimilarity index 100%rename from posthog/approvals/tests/__init__.pyrename to products/approvals/backend/__init__.pydiff --git a/posthog/approvals/actions/__init__.py b/products/approvals/backend/actions/__init__.pysimilarity index 100%rename from posthog/approvals/actions/__init__.pyrename to products/approvals/backend/actions/__init__.pydiff --git a/posthog/approvals/actions/base.py b/products/approvals/backend/actions/base.pysimilarity index 100%rename from posthog/approvals/actions/base.pyrename to products/approvals/backend/actions/base.pydiff --git a/posthog/approvals/actions/feature_flags.py b/products/approvals/backend/actions/feature_flags.pysimilarity index 99%rename from posthog/approvals/actions/feature_flags.pyrename to products/approvals/backend/actions/feature_flags.pyindex 49e5f44716b4..3bd6a9d02e99 100644--- a/posthog/approvals/actions/feature_flags.py+++ b/products/approvals/backend/actions/feature_flags.py@@ -3,9 +3,8 @@ from typing import Any, Optionalfrom django.db import transaction-from posthog.approvals.actions.base import BaseAction-from posthog.approvals.exceptions import ApplyFailed, PreconditionFailed-+from products.approvals.backend.actions.base import BaseAction+from products.approvals.backend.exceptions import ApplyFailed, PreconditionFailedfrom products.feature_flags.backend.api.feature_flag import FeatureFlagSerializerfrom products.feature_flags.backend.models.feature_flag import FeatureFlagdiff --git a/posthog/approvals/actions/registry.py b/products/approvals/backend/actions/registry.pysimilarity index 82%rename from posthog/approvals/actions/registry.pyrename to products/approvals/backend/actions/registry.pyindex acfc9572ff87..e5612a413df5 100644--- a/posthog/approvals/actions/registry.py+++ b/products/approvals/backend/actions/registry.py@@ -1,12 +1,12 @@from typing import Optional-from posthog.approvals.actions.base import BaseAction+from products.approvals.backend.actions.base import BaseActionACTION_REGISTRY: dict[str, type[BaseAction]] = {}def register_actions():- from posthog.approvals.actions.feature_flags import (+ from products.approvals.backend.actions.feature_flags import (DisableFeatureFlagAction,EnableFeatureFlagAction,UpdateFeatureFlagAction,diff --git a/posthog/approvals/api.py b/products/approvals/backend/api.pysimilarity index 95%rename from posthog/approvals/api.pyrename to products/approvals/backend/api.pyindex 2185b80a3021..906b4b28b307 100644--- a/posthog/approvals/api.py+++ b/products/approvals/backend/api.py@@ -13,11 +13,6 @@ from rest_framework.response import Responsefrom rest_framework.serializers import BaseSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.approvals.exceptions import AlreadyVotedError, InvalidStateError, ReasonRequiredError-from posthog.approvals.models import ApprovalPolicy, ChangeRequest-from posthog.approvals.permissions import CanApprove, CanCancel-from posthog.approvals.serializers import ApprovalPolicySerializer, ChangeRequestSerializer-from posthog.approvals.services import ChangeRequestServicefrom posthog.constants import AvailableFeaturefrom posthog.models import Userfrom posthog.permissions import (@@ -26,6 +21,12 @@ from posthog.permissions import (PremiumFeaturePermission,)+from products.approvals.backend.exceptions import AlreadyVotedError, InvalidStateError, ReasonRequiredError+from products.approvals.backend.models import ApprovalPolicy, ChangeRequest+from products.approvals.backend.permissions import CanApprove, CanCancel+from products.approvals.backend.serializers import ApprovalPolicySerializer, ChangeRequestSerializer+from products.approvals.backend.services import ChangeRequestService+logger = logging.getLogger(__name__)diff --git a/products/approvals/backend/apps.py b/products/approvals/backend/apps.pynew file mode 100644index 000000000000..7c57c4cc1646--- /dev/null+++ b/products/approvals/backend/apps.py@@ -0,0 +1,7 @@+from django.apps import AppConfig+++class ApprovalsConfig(AppConfig):+ default_auto_field = "django.db.models.BigAutoField"+ name = "products.approvals.backend"+ label = "approvals"diff --git a/posthog/approvals/decorators.py b/products/approvals/backend/decorators.pysimilarity index 97%rename from posthog/approvals/decorators.pyrename to products/approvals/backend/decorators.pyindex 49d38e615bad..08b6a4801652 100644--- a/posthog/approvals/decorators.py+++ b/products/approvals/backend/decorators.py@@ -10,15 +10,16 @@ from rest_framework import statusfrom rest_framework.exceptions import APIException, PermissionDenied, ValidationErrorfrom rest_framework.response import Response-from posthog.approvals.actions.registry import get_action-from posthog.approvals.exceptions import ApprovalRequired-from posthog.approvals.models import ChangeRequest, ChangeRequestState-from posthog.approvals.notifications import send_approval_requested_notification-from posthog.approvals.policies import PolicyDecision, PolicyEngine-from posthog.approvals.serializers import ChangeRequestSerializerfrom posthog.constants import AvailableFeaturefrom posthog.event_usage import report_user_action+from products.approvals.backend.actions.registry import get_action+from products.approvals.backend.exceptions import ApprovalRequired+from products.approvals.backend.models import ChangeRequest, ChangeRequestState+from products.approvals.backend.notifications import send_approval_requested_notification+from products.approvals.backend.policies import PolicyDecision, PolicyEngine+from products.approvals.backend.serializers import ChangeRequestSerializer+logger = logging.getLogger(__name__)diff --git a/posthog/approvals/exceptions.py b/products/approvals/backend/exceptions.pysimilarity index 100%rename from posthog/approvals/exceptions.pyrename to products/approvals/backend/exceptions.pydiff --git a/products/approvals/backend/migrations/0001_migrate_approvals_models.py b/products/approvals/backend/migrations/0001_migrate_approvals_models.pynew file mode 100644index 000000000000..90446ce96643--- /dev/null+++ b/products/approvals/backend/migrations/0001_migrate_approvals_models.py@@ -0,0 +1,230 @@+# Generated by Django 5.2.14 on 2026-06-25 17:18++import datetime+from typing import Any++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ initial = True++ dependencies = [+ ("ee", "0050_migrate_replay_models"),+ ("posthog", "1238_ducklakebackfill_earliest_event_date"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ # State-only move from the `posthog` app. The physical tables already exist+ # (created under the posthog app), so database_operations is empty — this migration+ # only recreates the models in ORM state under the `approvals` app.+ database_operations: list[Any] = []++ state_operations = [+ migrations.CreateModel(+ name="ChangeRequest",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7, editable=False, primary_key=True, serialize=False+ ),+ ),+ ("action_key", models.CharField(max_length=128)),+ ("action_version", models.IntegerField(default=1)),+ ("resource_type", models.CharField(max_length=64)),+ ("resource_id", models.CharField(blank=True, max_length=128, null=True)),+ ("intent", models.JSONField()),+ ("intent_display", models.JSONField()),+ ("policy_snapshot", models.JSONField()),+ (+ "validation_status",+ models.CharField(+ choices=[+ ("valid", "Valid"),+ ("invalid", "Invalid"),+ ("expired", "Expired"),+ ("stale", "Stale (resource changed)"),+ ],+ default="valid",+ max_length=16,+ ),+ ),+ ("validation_errors", models.JSONField(blank=True, null=True)),+ ("validated_at", models.DateTimeField(blank=True, null=True)),+ (+ "state",+ models.CharField(+ choices=[+ ("pending", "Pending"),+ ("approved", "Approved (awaiting application)"),+ ("applied", "Applied"),+ ("rejected", "Rejected"),+ ("expired", "Expired"),+ ("failed", "Failed to apply"),+ ],+ default="pending",+ max_length=16,+ ),+ ),+ ("expires_at", models.DateTimeField()),+ ("applied_at", models.DateTimeField(blank=True, null=True)),+ ("apply_error", models.TextField(blank=True)),+ ("result_data", models.JSONField(blank=True, null=True)),+ (+ "applied_by",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="change_requests_applied",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "created_by",+ models.ForeignKey(+ blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL+ ),+ ),+ (+ "organization",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.organization"),+ ),+ ("team", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team")),+ ],+ options={+ "db_table": "posthog_changerequest",+ "ordering": ["-created_at"],+ },+ ),+ migrations.CreateModel(+ name="Approval",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7, editable=False, primary_key=True, serialize=False+ ),+ ),+ (+ "decision",+ models.CharField(choices=[("approved", "Approved"), ("rejected", "Rejected")], max_length=16),+ ),+ ("reason", models.TextField(blank=True)),+ (+ "created_by",+ models.ForeignKey(+ blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL+ ),+ ),+ (+ "change_request",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="approvals",+ to="approvals.changerequest",+ ),+ ),+ ],+ options={+ "db_table": "posthog_approval",+ },+ ),+ migrations.CreateModel(+ name="ApprovalPolicy",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7, editable=False, primary_key=True, serialize=False+ ),+ ),+ ("action_key", models.CharField(max_length=128)),+ ("conditions", models.JSONField(default=dict)),+ ("approver_config", models.JSONField()),+ ("allow_self_approve", models.BooleanField(default=False)),+ ("bypass_org_membership_levels", models.JSONField(default=list)),+ (+ "expires_after",+ models.DurationField(+ default=datetime.timedelta(days=14), help_text="Auto-expire change requests after this duration"+ ),+ ),+ ("enabled", models.BooleanField(default=True)),+ (+ "bypass_roles",+ models.ManyToManyField(+ blank=True,+ db_table="posthog_approvalpolicy_bypass_roles",+ related_name="bypass_policies",+ to="ee.role",+ ),+ ),+ (+ "created_by",+ models.ForeignKey(+ blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL+ ),+ ),+ (+ "organization",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.organization"),+ ),+ (+ "team",+ models.ForeignKey(+ blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to="posthog.team"+ ),+ ),+ ],+ options={+ "verbose_name_plural": "Approval policies",+ "db_table": "posthog_approvalpolicy",+ "indexes": [+ models.Index(fields=["action_key", "enabled"], name="posthog_app_action__871059_idx"),+ models.Index(fields=["organization", "enabled"], name="posthog_app_organiz_36e124_idx"),+ models.Index(fields=["team", "enabled"], name="posthog_app_team_id_9f077f_idx"),+ ],+ "unique_together": {("organization", "team", "action_key")},+ },+ ),+ migrations.AddIndex(+ model_name="changerequest",+ index=models.Index(fields=["team", "state"], name="posthog_cha_team_id_0a5974_idx"),+ ),+ migrations.AddIndex(+ model_name="changerequest",+ index=models.Index(fields=["action_key", "state"], name="posthog_cha_action__2d384d_idx"),+ ),+ migrations.AddIndex(+ model_name="changerequest",+ index=models.Index(fields=["expires_at"], name="posthog_cha_expires_0a6444_idx"),+ ),+ migrations.AddIndex(+ model_name="changerequest",+ index=models.Index(fields=["validation_status", "state"], name="posthog_cha_validat_24672f_idx"),+ ),+ migrations.AddIndex(+ model_name="approval",+ index=models.Index(fields=["change_request", "decision"], name="posthog_app_change__5af5e4_idx"),+ ),+ migrations.AlterUniqueTogether(+ name="approval",+ unique_together={("change_request", "created_by")},+ ),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(database_operations=database_operations, state_operations=state_operations)+ ]diff --git a/products/approvals/backend/migrations/__init__.py b/products/approvals/backend/migrations/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/approvals/backend/migrations/max_migration.txt b/products/approvals/backend/migrations/max_migration.txtnew file mode 100644index 000000000000..21e2fe39a8a9--- /dev/null+++ b/products/approvals/backend/migrations/max_migration.txt@@ -0,0 +1 @@+0001_migrate_approvals_modelsdiff --git a/posthog/approvals/mixins.py b/products/approvals/backend/mixins.pysimilarity index 89%rename from posthog/approvals/mixins.pyrename to products/approvals/backend/mixins.pyindex ceb458f10408..bc8766c9f3d1 100644--- a/posthog/approvals/mixins.py+++ b/products/approvals/backend/mixins.py@@ -1,8 +1,8 @@from rest_framework import statusfrom rest_framework.response import Response-from posthog.approvals.exceptions import ApprovalRequired-from posthog.approvals.serializers import ChangeRequestSerializer+from products.approvals.backend.exceptions import ApprovalRequired+from products.approvals.backend.serializers import ChangeRequestSerializerclass ApprovalHandlingMixin:diff --git a/posthog/approvals/models.py b/products/approvals/backend/models.pysimilarity index 91%rename from posthog/approvals/models.pyrename to products/approvals/backend/models.pyindex 64e8def99bf5..c993b8bbb3ee 100644--- a/posthog/approvals/models.py+++ b/products/approvals/backend/models.py@@ -6,8 +6,8 @@ from django.db import modelsfrom posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModelif TYPE_CHECKING:- from posthog.approvals.actions.base import BaseAction- from posthog.approvals.models import ApprovalPolicy as ApprovalPolicyType+ from products.approvals.backend.actions.base import BaseAction+ from products.approvals.backend.models import ApprovalPolicy as ApprovalPolicyTypeclass ChangeRequestState(models.TextChoices):@@ -71,7 +71,7 @@ class ChangeRequest(UUIDModel, CreatedMetaFields, UpdatedMetaFields):result_data = models.JSONField(null=True, blank=True)class Meta:- app_label = "posthog"+ db_table = "posthog_changerequest" # pinned to pre-move physical table name, do not renameindexes = [models.Index(fields=["team", "state"]),models.Index(fields=["action_key", "state"]),@@ -85,7 +85,7 @@ class ChangeRequest(UUIDModel, CreatedMetaFields, UpdatedMetaFields):def get_policy(self) -> Optional["ApprovalPolicyType"]:"""Get the matching approval policy for this change request."""- from posthog.approvals.policies import PolicyEngine+ from products.approvals.backend.policies import PolicyEnginereturn PolicyEngine().get_policy(self.action_key, self.team, self.organization)@@ -100,7 +100,7 @@ class ChangeRequest(UUIDModel, CreatedMetaFields, UpdatedMetaFields):def get_action_class(self) -> Optional[type["BaseAction"]]:"""Get the action class for this change request from the registry."""- from posthog.approvals.actions.registry import get_action+ from products.approvals.backend.actions.registry import get_actionreturn get_action(self.action_key)@@ -126,7 +126,7 @@ class Approval(UUIDModel, CreatedMetaFields, UpdatedMetaFields):reason = models.TextField(blank=True)class Meta:- app_label = "posthog"+ db_table = "posthog_approval" # pinned to pre-move physical table name, do not renameunique_together = [["change_request", "created_by"]]indexes = [models.Index(fields=["change_request", "decision"]),@@ -170,6 +170,7 @@ class ApprovalPolicy(UUIDModel, CreatedMetaFields, UpdatedMetaFields):"ee.Role",blank=True,related_name="bypass_policies",+ db_table="posthog_approvalpolicy_bypass_roles", # pinned to pre-move physical M2M table name, do not rename)expires_after = models.DurationField(@@ -182,7 +183,7 @@ class ApprovalPolicy(UUIDModel, CreatedMetaFields, UpdatedMetaFields):objects = ApprovalPolicyManager()class Meta:- app_label = "posthog"+ db_table = "posthog_approvalpolicy" # pinned to pre-move physical table name, do not renameunique_together = [["organization", "team", "action_key"]]indexes = [models.Index(fields=["action_key", "enabled"]),diff --git a/posthog/approvals/notifications.py b/products/approvals/backend/notifications.pysimilarity index 99%rename from posthog/approvals/notifications.pyrename to products/approvals/backend/notifications.pyindex 027d04b64611..f4e331e37fee 100644--- a/posthog/approvals/notifications.py+++ b/products/approvals/backend/notifications.py@@ -16,7 +16,7 @@ from products.notifications.backend.facade.api import (from products.notifications.backend.facade.enums import NotificationOnlyResourceTypeif TYPE_CHECKING:- from posthog.approvals.models import Approval, ChangeRequest+ from products.approvals.backend.models import Approval, ChangeRequestlogger = get_logger(__name__)diff --git a/posthog/approvals/permissions.py b/products/approvals/backend/permissions.pysimilarity index 97%rename from posthog/approvals/permissions.pyrename to products/approvals/backend/permissions.pyindex d36cc5854757..c084875f541f 100644--- a/posthog/approvals/permissions.py+++ b/products/approvals/backend/permissions.py@@ -11,7 +11,7 @@ class CanApprove(permissions.BasePermission):message = "You do not have permission to approve this change request"def has_object_permission(self, request, view, obj):- from posthog.approvals.models import ChangeRequestState+ from products.approvals.backend.models import ChangeRequestStateif obj.state != ChangeRequestState.PENDING:self.message = "Only pending change requests can be approved"diff --git a/posthog/approvals/policies.py b/products/approvals/backend/policies.pysimilarity index 98%rename from posthog/approvals/policies.pyrename to products/approvals/backend/policies.pyindex d71265c15159..3cd3440c8c6b 100644--- a/posthog/approvals/policies.py+++ b/products/approvals/backend/policies.py@@ -33,7 +33,7 @@ class PolicyEngine:1. Team-level policy (if team provided)2. Org-level policy"""- from posthog.approvals.models import ApprovalPolicy+ from products.approvals.backend.models import ApprovalPolicypolicy = None@@ -66,7 +66,7 @@ class PolicyEngine:Get all active policies for an action that match the given intent.Used for conflict detection."""- from posthog.approvals.models import ApprovalPolicy+ from products.approvals.backend.models import ApprovalPolicypolicies = []diff --git a/products/approvals/backend/routes.py b/products/approvals/backend/routes.pynew file mode 100644index 000000000000..f06f4df038e8--- /dev/null+++ b/products/approvals/backend/routes.py@@ -0,0 +1,18 @@+from posthog.api.routing import RouterRegistry++from products.approvals.backend import api as approval_api+++def register_routes(routers: RouterRegistry) -> None:+ routers.register_legacy_dual_route(+ r"change_requests",+ approval_api.ChangeRequestViewSet,+ "project_change_requests",+ ["team_id"],+ )+ routers.register_legacy_dual_route(+ r"approval_policies",+ approval_api.ApprovalPolicyViewSet,+ "project_approval_policies",+ ["team_id"],+ )diff --git a/posthog/approvals/serializers.py b/products/approvals/backend/serializers.pysimilarity index 98%rename from posthog/approvals/serializers.pyrename to products/approvals/backend/serializers.pyindex ab573afb0552..893e63509475 100644--- a/posthog/approvals/serializers.py+++ b/products/approvals/backend/serializers.py@@ -2,7 +2,8 @@ from drf_spectacular.utils import extend_schema_fieldfrom rest_framework import serializersfrom posthog.api.shared import UserBasicSerializer-from posthog.approvals.models import Approval, ApprovalPolicy, ChangeRequest++from products.approvals.backend.models import Approval, ApprovalPolicy, ChangeRequestclass ChangeRequestSerializer(serializers.ModelSerializer):diff --git a/posthog/approvals/services.py b/products/approvals/backend/services.pysimilarity index 97%rename from posthog/approvals/services.pyrename to products/approvals/backend/services.pyindex 3d317ebe2c21..4e75ca84fbc4 100644--- a/posthog/approvals/services.py+++ b/products/approvals/backend/services.py@@ -5,18 +5,22 @@ from typing import Any, Optionalfrom django.db import transactionfrom django.utils import timezone-from posthog.approvals.actions.registry import get_action-from posthog.approvals.exceptions import (+from posthog.event_usage import report_user_action+from posthog.models import User++from products.approvals.backend.actions.registry import get_action+from products.approvals.backend.exceptions import (AlreadyVotedError,ApplyFailed,InvalidStateError,PreconditionFailed,ReasonRequiredError,)-from posthog.approvals.models import Approval, ApprovalDecision, ChangeRequest, ChangeRequestState-from posthog.approvals.notifications import send_approval_applied_notification, send_approval_decision_notification-from posthog.event_usage import report_user_action-from posthog.models import User+from products.approvals.backend.models import Approval, ApprovalDecision, ChangeRequest, ChangeRequestState+from products.approvals.backend.notifications import (+ send_approval_applied_notification,+ send_approval_decision_notification,+)logger = logging.getLogger(__name__)diff --git a/posthog/approvals/tasks.py b/products/approvals/backend/tasks.pysimilarity index 90%rename from posthog/approvals/tasks.pyrename to products/approvals/backend/tasks.pyindex 1795b4983955..2e71c6ae3f3e 100644--- a/posthog/approvals/tasks.py+++ b/products/approvals/backend/tasks.py@@ -6,14 +6,17 @@ from django.utils import timezonefrom celery import shared_taskfrom structlog import get_logger-from posthog.approvals.models import ChangeRequest, ChangeRequestState, ValidationStatus-from posthog.approvals.notifications import send_approval_expired_notificationfrom posthog.scoping_audit import skip_team_scope_audit+from products.approvals.backend.models import ChangeRequest, ChangeRequestState, ValidationStatus+from products.approvals.backend.notifications import send_approval_expired_notification+logger = get_logger(__name__)-@shared_task(ignore_result=True)+# Pin the task name to its pre-move path so the beat schedule and any in-flight+# messages keep routing after the module moved out of posthog/approvals.+@shared_task(ignore_result=True, name="posthog.approvals.tasks.validate_pending_change_requests")@skip_team_scope_auditdef validate_pending_change_requests() -> dict[str, Any]:"""@@ -83,7 +86,7 @@ def validate_pending_change_requests() -> dict[str, Any]:return result-@shared_task(ignore_result=True)+@shared_task(ignore_result=True, name="posthog.approvals.tasks.expire_old_change_requests")@skip_team_scope_auditdef expire_old_change_requests() -> dict[str, Any]:"""diff --git a/products/approvals/backend/tests/__init__.py b/products/approvals/backend/tests/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/approvals/tests/test_approvals_api.py b/products/approvals/backend/tests/test_approvals_api.pysimilarity index 99%rename from posthog/approvals/tests/test_approvals_api.pyrename to products/approvals/backend/tests/test_approvals_api.pyindex 285677214619..33d719daef6d 100644--- a/posthog/approvals/tests/test_approvals_api.py+++ b/products/approvals/backend/tests/test_approvals_api.py@@ -8,7 +8,10 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status-from posthog.approvals.models import (+from posthog.constants import AvailableFeature+from posthog.models import User++from products.approvals.backend.models import (Approval,ApprovalDecision,ApprovalPolicy,@@ -16,9 +19,6 @@ from posthog.approvals.models import (ChangeRequestState,ValidationStatus,)-from posthog.constants import AvailableFeature-from posthog.models import User-from products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -204,7 +204,7 @@ class TestChangeRequestViewSet(APIBaseTest):assert response.json()["id"] == str(cr.id)assert response.json()["action_key"] == "feature_flag.enable"- @patch("posthog.approvals.services.apply_change_request")+ @patch("products.approvals.backend.services.apply_change_request")def test_approve_success(self, mock_apply):mock_apply.return_value = type("obj", (object,), {"id": 123, "version": 1})()cr = self._create_change_request()@@ -382,7 +382,7 @@ class TestChangeRequestViewSet(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert response.json()["can_approve"] is False- @patch("posthog.approvals.services.apply_change_request")+ @patch("products.approvals.backend.services.apply_change_request")def test_approve_succeeds_when_user_in_approver_role(self, mock_apply):from ee.models.rbac.role import Role, RoleMembershipdiff --git a/posthog/approvals/tests/test_notifications.py b/products/approvals/backend/tests/test_notifications.pysimilarity index 84%rename from posthog/approvals/tests/test_notifications.pyrename to products/approvals/backend/tests/test_notifications.pyindex 56464cddc050..3b811a73b2d7 100644--- a/posthog/approvals/tests/test_notifications.py+++ b/products/approvals/backend/tests/test_notifications.py@@ -5,8 +5,17 @@ from unittest.mock import MagicMock, patchfrom django.utils import timezone-from posthog.approvals.models import Approval, ApprovalDecision, ApprovalPolicy, ChangeRequest, ChangeRequestState-from posthog.approvals.notifications import (+from posthog.email import CUSTOMER_IO_TEMPLATE_ID_MAP+from posthog.models.instance_setting import override_instance_config++from products.approvals.backend.models import (+ Approval,+ ApprovalDecision,+ ApprovalPolicy,+ ChangeRequest,+ ChangeRequestState,+)+from products.approvals.backend.notifications import (_build_change_request_url,_send_approval_email,send_approval_applied_notification,@@ -14,8 +23,6 @@ from posthog.approvals.notifications import (send_approval_expired_notification,send_approval_requested_notification,)-from posthog.email import CUSTOMER_IO_TEMPLATE_ID_MAP-from posthog.models.instance_setting import override_instance_configclass TestApprovalNotifications(BaseTest):@@ -92,8 +99,8 @@ class TestBuildChangeRequestUrl(TestApprovalNotifications):class TestSendApprovalEmail(TestApprovalNotifications):- @patch("posthog.approvals.notifications.EmailMessage")- @patch("posthog.approvals.notifications.is_email_available")+ @patch("products.approvals.backend.notifications.EmailMessage")+ @patch("products.approvals.backend.notifications.is_email_available")def test_sends_email_when_available(self, mock_is_email_available, mock_email_message):mock_is_email_available.return_value = Truemock_message_instance = MagicMock()@@ -116,7 +123,7 @@ class TestSendApprovalEmail(TestApprovalNotifications):mock_message_instance.add_user_recipient.assert_called_once_with(self.approver)mock_message_instance.send.assert_called_once_with(send_async=True)- @patch("posthog.approvals.notifications.is_email_available")+ @patch("products.approvals.backend.notifications.is_email_available")def test_skips_when_email_not_available(self, mock_is_email_available):mock_is_email_available.return_value = False@@ -141,7 +148,7 @@ class TestSendApprovalEmail(TestApprovalNotifications):class TestSendApprovalRequestedNotification(TestApprovalNotifications):- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_sends_to_all_approvers(self, mock_send_email):send_approval_requested_notification(self.change_request)@@ -152,7 +159,7 @@ class TestSendApprovalRequestedNotification(TestApprovalNotifications):self.assertIn(self.approver, recipients)self.assertIn(self.approver2, recipients)- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_skips_when_no_policy(self, mock_send_email):self.policy.delete()@@ -160,7 +167,7 @@ class TestSendApprovalRequestedNotification(TestApprovalNotifications):mock_send_email.assert_not_called()- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_uses_correct_template(self, mock_send_email):send_approval_requested_notification(self.change_request)@@ -168,7 +175,7 @@ class TestSendApprovalRequestedNotification(TestApprovalNotifications):self.assertEqual(call_kwargs["template_name"], "approval_requested")self.assertIn("needs your sign-off", call_kwargs["subject"])- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_continues_on_individual_email_failure(self, mock_send_email):mock_send_email.side_effect = [Exception("Email failed"), None]@@ -178,8 +185,8 @@ class TestSendApprovalRequestedNotification(TestApprovalNotifications):class TestRealtimeDispatchOnRequested(TestApprovalNotifications):- @patch("posthog.approvals.notifications.create_notification")- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications.create_notification")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_dispatches_one_realtime_per_approver(self, _mock_email, mock_create_notification):send_approval_requested_notification(self.change_request)@@ -199,8 +206,8 @@ class TestRealtimeDispatchOnRequested(TestApprovalNotifications):expected_url = f"/project/{self.change_request.team.project_id}/approvals/{self.change_request.id}"self.assertEqual(first_data.source_url, expected_url)- @patch("posthog.approvals.notifications.create_notification")- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications.create_notification")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_body_falls_back_to_action_key_when_no_description(self, _mock_email, mock_create_notification):self.change_request.intent_display = {}self.change_request.save()@@ -210,8 +217,8 @@ class TestRealtimeDispatchOnRequested(TestApprovalNotifications):first_data = mock_create_notification.call_args_list[0].args[0]self.assertEqual(first_data.body, self.change_request.action_key)- @patch("posthog.approvals.notifications.create_notification")- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications.create_notification")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_no_realtime_dispatch_when_no_policy(self, _mock_email, mock_create_notification):self.policy.delete()@@ -219,14 +226,14 @@ class TestRealtimeDispatchOnRequested(TestApprovalNotifications):mock_create_notification.assert_not_called()- @patch("posthog.approvals.notifications.create_notification", side_effect=RuntimeError("boom"))- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications.create_notification", side_effect=RuntimeError("boom"))+ @patch("products.approvals.backend.notifications._send_approval_email")def test_realtime_failure_is_swallowed(self, _mock_email, _mock_create):# Should not raise — failure is logged and swallowed so email path is not impacted.send_approval_requested_notification(self.change_request)- @patch("posthog.approvals.notifications.create_notification")- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications.create_notification")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_failure_for_one_approver_does_not_block_others(self, _mock_email, mock_create_notification):mock_create_notification.side_effect = [RuntimeError("boom"), None]@@ -236,8 +243,8 @@ class TestRealtimeDispatchOnRequested(TestApprovalNotifications):target_ids = [call.args[0].target_id for call in mock_create_notification.call_args_list]self.assertEqual(set(target_ids), {str(self.approver.id), str(self.approver2.id)})- @patch("posthog.approvals.notifications.create_notification")- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications.create_notification")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_no_realtime_dispatch_when_no_approvers(self, _mock_email, mock_create_notification):self.policy.approver_config = {"users": [], "quorum": 1}self.policy.save()@@ -246,8 +253,8 @@ class TestRealtimeDispatchOnRequested(TestApprovalNotifications):mock_create_notification.assert_not_called()- @patch("posthog.approvals.notifications.create_notification")- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications.create_notification")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_email_failure_does_not_block_realtime(self, mock_email, mock_create_notification):mock_email.side_effect = RuntimeError("smtp down")@@ -257,7 +264,7 @@ class TestRealtimeDispatchOnRequested(TestApprovalNotifications):class TestSendApprovalDecisionNotification(TestApprovalNotifications):- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_sends_approval_notification(self, mock_send_email):approval = Approval.objects.create(change_request=self.change_request,@@ -274,7 +281,7 @@ class TestSendApprovalDecisionNotification(TestApprovalNotifications):self.assertEqual(call_kwargs["template_name"], "approval_approved")self.assertIn("approved your change", call_kwargs["subject"])- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_sends_rejection_notification(self, mock_send_email):approval = Approval.objects.create(change_request=self.change_request,@@ -290,7 +297,7 @@ class TestSendApprovalDecisionNotification(TestApprovalNotifications):self.assertEqual(call_kwargs["template_name"], "approval_rejected")self.assertEqual(call_kwargs["subject"], "Your change request was declined")- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_skips_when_no_requester(self, mock_send_email):self.change_request.created_by = Noneself.change_request.save()@@ -307,7 +314,7 @@ class TestSendApprovalDecisionNotification(TestApprovalNotifications):class TestSendApprovalExpiredNotification(TestApprovalNotifications):- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_sends_expired_notification(self, mock_send_email):send_approval_expired_notification(self.change_request)@@ -317,7 +324,7 @@ class TestSendApprovalExpiredNotification(TestApprovalNotifications):self.assertEqual(call_kwargs["template_name"], "approval_expired")self.assertEqual(call_kwargs["subject"], "Your change request timed out")- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_skips_when_no_requester(self, mock_send_email):self.change_request.created_by = Noneself.change_request.save()@@ -328,7 +335,7 @@ class TestSendApprovalExpiredNotification(TestApprovalNotifications):class TestSendApprovalAppliedNotification(TestApprovalNotifications):- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_sends_applied_notification(self, mock_send_email):send_approval_applied_notification(self.change_request)@@ -338,7 +345,7 @@ class TestSendApprovalAppliedNotification(TestApprovalNotifications):self.assertEqual(call_kwargs["template_name"], "approval_applied")self.assertEqual(call_kwargs["subject"], "Your change is live! 🎉")- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_skips_when_no_requester(self, mock_send_email):self.change_request.created_by = Noneself.change_request.save()@@ -349,7 +356,7 @@ class TestSendApprovalAppliedNotification(TestApprovalNotifications):class TestEmailTemplateRendering(TestApprovalNotifications):- @patch("posthog.approvals.notifications.is_email_available")+ @patch("products.approvals.backend.notifications.is_email_available")def test_approval_requested_template_renders(self, mock_is_email_available):mock_is_email_available.return_value = True@@ -370,7 +377,7 @@ class TestEmailTemplateRendering(TestApprovalNotifications):self.assertIn("needs your sign-off", message.html_body)self.assertIn("Test Team", message.html_body)- @patch("posthog.approvals.notifications.is_email_available")+ @patch("products.approvals.backend.notifications.is_email_available")def test_approval_approved_template_renders(self, mock_is_email_available):mock_is_email_available.return_value = True@@ -391,7 +398,7 @@ class TestEmailTemplateRendering(TestApprovalNotifications):self.assertIn("approved your change", message.html_body)self.assertIn("Test Team", message.html_body)- @patch("posthog.approvals.notifications.is_email_available")+ @patch("products.approvals.backend.notifications.is_email_available")def test_approval_rejected_template_renders(self, mock_is_email_available):mock_is_email_available.return_value = True@@ -412,7 +419,7 @@ class TestEmailTemplateRendering(TestApprovalNotifications):self.assertIn("wasn't approved", message.html_body)self.assertIn("Test Team", message.html_body)- @patch("posthog.approvals.notifications.is_email_available")+ @patch("products.approvals.backend.notifications.is_email_available")def test_approval_expired_template_renders(self, mock_is_email_available):mock_is_email_available.return_value = True@@ -432,7 +439,7 @@ class TestEmailTemplateRendering(TestApprovalNotifications):self.assertIn("expired", message.html_body)self.assertIn("Test Team", message.html_body)- @patch("posthog.approvals.notifications.is_email_available")+ @patch("products.approvals.backend.notifications.is_email_available")def test_approval_applied_template_renders(self, mock_is_email_available):mock_is_email_available.return_value = True@@ -452,7 +459,7 @@ class TestEmailTemplateRendering(TestApprovalNotifications):self.assertIn("is live", message.html_body)self.assertIn("Test Team", message.html_body)- @patch("posthog.approvals.notifications.is_email_available")+ @patch("products.approvals.backend.notifications.is_email_available")def test_templates_contain_cta_button(self, mock_is_email_available):mock_is_email_available.return_value = Truetemplates_with_cta = {@@ -484,8 +491,8 @@ class TestEmailTemplateRendering(TestApprovalNotifications):class TestRealtimeDispatchOnResolve(TestApprovalNotifications):- @patch("posthog.approvals.notifications.create_notification")- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications.create_notification")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_decision_approved_dispatches_realtime(self, _mock_email, mock_create_notification):approval = self._create_approval(self.change_request, decision="approved")@@ -498,8 +505,8 @@ class TestRealtimeDispatchOnResolve(TestApprovalNotifications):assert data.resource_type.value == "approval"assert data.source_url == f"/project/{self.team.project_id}/approvals/{self.change_request.id}"- @patch("posthog.approvals.notifications.create_notification")- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications.create_notification")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_decision_rejected_dispatches_realtime(self, _mock_email, mock_create_notification):approval = self._create_approval(self.change_request, decision="rejected")@@ -508,24 +515,24 @@ class TestRealtimeDispatchOnResolve(TestApprovalNotifications):data = mock_create_notification.call_args.args[0]assert "declined" in data.title.lower()- @patch("posthog.approvals.notifications.create_notification")- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications.create_notification")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_applied_dispatches_realtime(self, _mock_email, mock_create_notification):send_approval_applied_notification(self.change_request)data = mock_create_notification.call_args.args[0]assert "live" in data.title.lower()- @patch("posthog.approvals.notifications.create_notification")- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications.create_notification")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_expired_dispatches_realtime(self, _mock_email, mock_create_notification):send_approval_expired_notification(self.change_request)data = mock_create_notification.call_args.args[0]assert "expired" in data.title.lower()- @patch("posthog.approvals.notifications.create_notification")- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications.create_notification")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_skips_realtime_when_no_requester(self, _mock_email, mock_create_notification):self.change_request.created_by = Noneself.change_request.save()@@ -535,8 +542,8 @@ class TestRealtimeDispatchOnResolve(TestApprovalNotifications):mock_create_notification.assert_not_called()- @patch("posthog.approvals.notifications.create_notification")- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications.create_notification")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_email_failure_does_not_block_realtime(self, mock_email, mock_create_notification):mock_email.side_effect = RuntimeError("smtp down")@@ -544,16 +551,16 @@ class TestRealtimeDispatchOnResolve(TestApprovalNotifications):mock_create_notification.assert_called_once()- @patch("posthog.approvals.notifications.create_notification")- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications.create_notification")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_body_uses_intent_display_description(self, _mock_email, mock_create_notification):send_approval_applied_notification(self.change_request)data = mock_create_notification.call_args.args[0]assert data.body == "Update rollout to 50%"- @patch("posthog.approvals.notifications.create_notification")- @patch("posthog.approvals.notifications._send_approval_email")+ @patch("products.approvals.backend.notifications.create_notification")+ @patch("products.approvals.backend.notifications._send_approval_email")def test_body_falls_back_to_action_key_when_no_description(self, _mock_email, mock_create_notification):self.change_request.intent_display = {}self.change_request.save()diff --git a/posthog/approvals/tests/test_policy_engine.py b/products/approvals/backend/tests/test_policy_engine.pysimilarity index 99%rename from posthog/approvals/tests/test_policy_engine.pyrename to products/approvals/backend/tests/test_policy_engine.pyindex 6d6b2bd87d1c..1c28a4583b7e 100644--- a/posthog/approvals/tests/test_policy_engine.py+++ b/products/approvals/backend/tests/test_policy_engine.py@@ -4,10 +4,11 @@ from posthog.test.base import APIBaseTestfrom parameterized import parameterized-from posthog.approvals.models import ApprovalPolicy-from posthog.approvals.policies import PolicyEnginefrom posthog.models.organization import OrganizationMembership+from products.approvals.backend.models import ApprovalPolicy+from products.approvals.backend.policies import PolicyEngine+class TestPolicyEngineBypass(APIBaseTest):def _create_policy(diff --git a/posthog/approvals/tests/test_services.py b/products/approvals/backend/tests/test_services.pysimilarity index 89%rename from posthog/approvals/tests/test_services.pyrename to products/approvals/backend/tests/test_services.pyindex b0d43f73b2d2..b4a54e3d3a9c 100644--- a/posthog/approvals/tests/test_services.py+++ b/products/approvals/backend/tests/test_services.py@@ -7,9 +7,9 @@ from django.utils import timezonefrom parameterized import parameterized-from posthog.approvals.exceptions import InvalidStateError-from posthog.approvals.models import ChangeRequest, ChangeRequestState-from posthog.approvals.services import ChangeRequestService+from products.approvals.backend.exceptions import InvalidStateError+from products.approvals.backend.models import ChangeRequest, ChangeRequestState+from products.approvals.backend.services import ChangeRequestServiceclass TestApproveRejectRaceCondition(BaseTest):diff --git a/posthog/approvals/tests/test_tasks.py b/products/approvals/backend/tests/test_tasks.pysimilarity index 91%rename from posthog/approvals/tests/test_tasks.pyrename to products/approvals/backend/tests/test_tasks.pyindex 31ab902ea133..c9e0c5a0fef6 100644--- a/posthog/approvals/tests/test_tasks.py+++ b/products/approvals/backend/tests/test_tasks.py@@ -7,8 +7,8 @@ from django.utils import timezonefrom parameterized import parameterized-from posthog.approvals.models import ChangeRequest-from posthog.approvals.tasks import expire_old_change_requests, validate_pending_change_requests+from products.approvals.backend.models import ChangeRequest+from products.approvals.backend.tasks import expire_old_change_requests, validate_pending_change_requestsclass TestValidatePendingChangeRequests(BaseTest):@@ -49,7 +49,7 @@ class TestValidatePendingChangeRequests(BaseTest):self.assertEqual(result["checked_count"], 0)self.assertEqual(result["stale_count"], 0)- @patch("posthog.approvals.tasks.ChangeRequest.get_action_class")+ @patch("products.approvals.backend.tasks.ChangeRequest.get_action_class")def test_marks_stale_when_resource_changed(self, mock_get_action):mock_action = mock_get_action.return_valuemock_action.prepare_context.return_value = {}@@ -63,7 +63,7 @@ class TestValidatePendingChangeRequests(BaseTest):self.assertIsNotNone(self.change_request.validation_errors)self.assertIsNotNone(self.change_request.validated_at)- @patch("posthog.approvals.tasks.ChangeRequest.get_action_class")+ @patch("products.approvals.backend.tasks.ChangeRequest.get_action_class")def test_leaves_unchanged_when_not_stale(self, mock_get_action):mock_action = mock_get_action.return_valuemock_action.prepare_context.return_value = {}@@ -124,7 +124,7 @@ class TestExpireOldChangeRequests(BaseTest):self.expired_request.refresh_from_db()self.assertEqual(self.expired_request.state, expected_state)- @patch("posthog.approvals.tasks.send_approval_expired_notification")+ @patch("products.approvals.backend.tasks.send_approval_expired_notification")def test_expire_task_sends_notifications(self, mock_notification):expire_old_change_requests()diff --git a/posthog/approvals/tests/test_update_feature_flag_action.py b/products/approvals/backend/tests/test_update_feature_flag_action.pysimilarity index 94%rename from posthog/approvals/tests/test_update_feature_flag_action.pyrename to products/approvals/backend/tests/test_update_feature_flag_action.pyindex 3f062ad3d0c3..d3aa5592c807 100644--- a/posthog/approvals/tests/test_update_feature_flag_action.py+++ b/products/approvals/backend/tests/test_update_feature_flag_action.py@@ -5,10 +5,9 @@ from unittest.mock import MagicMock, patchfrom parameterized import parameterized-from posthog.approvals.actions.feature_flags import UpdateFeatureFlagAction-from posthog.approvals.models import ApprovalPolicy, ChangeRequest-from posthog.approvals.policies import PolicyEngine-+from products.approvals.backend.actions.feature_flags import UpdateFeatureFlagAction+from products.approvals.backend.models import ApprovalPolicy, ChangeRequest+from products.approvals.backend.policies import PolicyEnginefrom products.feature_flags.backend.models.feature_flag import FeatureFlagSINGLE_DICT_PATHS = {"holdout"}@@ -199,14 +198,14 @@ class TestCheckStaleness(APIBaseTest):intent = {"preconditions": {"version": stored_version}}context = {"instance": flag}- from posthog.approvals.actions.feature_flags import EnableFeatureFlagAction+ from products.approvals.backend.actions.feature_flags import EnableFeatureFlagActionresult = EnableFeatureFlagAction.check_staleness(intent, context)assert result is expected_staledef test_stale_when_no_instance_in_context(self):- from posthog.approvals.actions.feature_flags import EnableFeatureFlagAction+ from products.approvals.backend.actions.feature_flags import EnableFeatureFlagActionintent = {"preconditions": {"version": 1}}result = EnableFeatureFlagAction.check_staleness(intent, {})@@ -214,7 +213,7 @@ class TestCheckStaleness(APIBaseTest):assert result is Truedef test_not_stale_when_no_stored_version(self):- from posthog.approvals.actions.feature_flags import EnableFeatureFlagAction+ from products.approvals.backend.actions.feature_flags import EnableFeatureFlagActionflag = self._create_flag()intent: dict[str, Any] = {"preconditions": {}}@@ -248,7 +247,7 @@ class TestCheckStaleness(APIBaseTest):assert result is Truedef test_base_action_check_staleness_always_returns_false(self):- from posthog.approvals.actions.base import BaseAction+ from products.approvals.backend.actions.base import BaseActionresult = BaseAction.check_staleness({"preconditions": {"version": 1}}, {})@@ -387,7 +386,7 @@ class TestMultiPolicyConflictDetection(APIBaseTest):created_by=self.user,)- @patch("posthog.approvals.decorators._is_approvals_enabled", return_value=True)+ @patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)def test_single_policy_match_returns_normal_approval_flow(self, mock_enabled):flag = self._create_flag()self._create_policy(@@ -402,7 +401,7 @@ class TestMultiPolicyConflictDetection(APIBaseTest):assert response.status_code in [200, 409]- @patch("posthog.approvals.decorators._is_approvals_enabled", return_value=True)+ @patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)def test_matching_policy_returns_http_400(self, mock_enabled):flag = self._create_flag()self._create_policy(@@ -423,7 +422,7 @@ class TestMultiPolicyConflictDetection(APIBaseTest):class TestActionRegistrationAndIntegration(APIBaseTest):def test_update_feature_flag_action_registered_in_registry(self):- from posthog.approvals.actions.registry import ACTION_REGISTRY, register_actions+ from products.approvals.backend.actions.registry import ACTION_REGISTRY, register_actionsregister_actions()@@ -431,7 +430,7 @@ class TestActionRegistrationAndIntegration(APIBaseTest):assert ACTION_REGISTRY["feature_flag.update"] == UpdateFeatureFlagActiondef test_action_coexists_with_enable_disable_actions(self):- from posthog.approvals.actions.registry import ACTION_REGISTRY, register_actions+ from products.approvals.backend.actions.registry import ACTION_REGISTRY, register_actionsregister_actions()@@ -439,7 +438,7 @@ class TestActionRegistrationAndIntegration(APIBaseTest):assert "feature_flag.disable" in ACTION_REGISTRYassert "feature_flag.update" in ACTION_REGISTRY- @patch("posthog.approvals.decorators._is_approvals_enabled", return_value=True)+ @patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)def test_enable_disable_detected_before_update(self, mock_enabled):flag = FeatureFlag.objects.create(team=self.team,diff --git a/products/approvals/package.json b/products/approvals/package.jsonnew file mode 100644index 000000000000..29e5f52a6291--- /dev/null+++ b/products/approvals/package.json@@ -0,0 +1,7 @@+{+ "name": "@posthog/products-approvals",+ "scripts": {+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",+ "backend:lint": "ruff check --config ../../pyproject.toml backend && ruff format --config ../../pyproject.toml --check backend"+ }+}diff --git a/products/approvals/product.yaml b/products/approvals/product.yamlnew file mode 100644index 000000000000..eb73b6aaceb4--- /dev/null+++ b/products/approvals/product.yaml@@ -0,0 +1,3 @@+name: Approvals+owners:+ - team-feature-flagsdiff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex 3b2ccd0e798f..df83e032d20b 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -27,7 +27,6 @@ from posthog.schema import ()from posthog.api.cohort import CohortSerializer-from posthog.approvals.policies import PolicyEnginefrom posthog.event_usage import EventSource, report_user_actionfrom posthog.models.filters.filter import Filterfrom posthog.models.signals import mute_selected_signals@@ -38,6 +37,7 @@ from posthog.rbac.user_access_control import UserAccessControlfrom posthog.utils import str_to_boolfrom products.actions.backend.models.action import Action+from products.approvals.backend.policies import PolicyEnginefrom products.cohorts.backend.models.cohort import Cohortfrom products.experiments.backend.hogql_queries.base_query_utils import is_threshold_supported_mathfrom products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprintdiff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex 4f946e96a4ae..729f1ac524f1 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -28,7 +28,6 @@ from posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import action-from posthog.approvals.mixins import ApprovalHandlingMixinfrom posthog.auth import IDJagAccessTokenAuthentication, OAuthAccessTokenAuthentication, PersonalAPIKeyAuthenticationfrom posthog.models.filters.filter import Filterfrom posthog.models.organization import OrganizationMembership@@ -40,6 +39,7 @@ from posthog.temporal.common.client import sync_connectfrom posthog.temporal.experiments.models import ExperimentTimeseriesRecalculationWorkflowInputsfrom posthog.user_permissions import UserPermissions+from products.approvals.backend.mixins import ApprovalHandlingMixinfrom products.experiments.backend.experiment_service import ExperimentServicefrom products.experiments.backend.llm_metric_templates import build_template, list_templatesdiff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 75ad6f19c118..a6874419ddcc 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -36,8 +36,6 @@ from posthog.api.services.flags_service import get_flags_from_servicefrom posthog.api.shared import UserBasicSerializerfrom posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixinfrom posthog.api.utils import ClassicBehaviorBooleanFieldSerializer, ErrorResponseSerializer, action-from posthog.approvals.decorators import approval_gate-from posthog.approvals.mixins import ApprovalHandlingMixinfrom posthog.auth import (IDJagAccessTokenAuthentication,OAuthAccessTokenAuthentication,@@ -69,6 +67,8 @@ from posthog.settings.feature_flags import REMOTE_CONFIG_RATE_LIMITSfrom posthog.utils import is_valid_regexfrom posthog.views import format_bytes+from products.approvals.backend.decorators import approval_gate+from products.approvals.backend.mixins import ApprovalHandlingMixinfrom products.cohorts.backend.models.cohort import Cohort, CohortTypefrom products.cohorts.backend.models.util import get_all_cohort_dependenciesfrom products.dashboards.backend.api.dashboard import Dashboarddiff --git a/products/ruff.toml b/products/ruff.tomlindex 31677da02c9d..3b09f70990a7 100644--- a/products/ruff.toml+++ b/products/ruff.toml@@ -21,6 +21,7 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]"actions/backend/**" = ["ANN"]"alerts/backend/**" = ["ANN"]"annotations/backend/**" = ["ANN"]+"approvals/backend/**" = ["ANN"]"batch_exports/backend/**" = ["ANN"]"cdp/backend/**" = ["ANN"]"cohorts/backend/**" = ["ANN"]@@ -60,6 +61,7 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]"alerts/**" = ["PLC0415"]"analytics_platform/**" = ["PLC0415"]"annotations/**" = ["PLC0415"]+"approvals/**" = ["PLC0415"]"batch_exports/**" = ["PLC0415"]"business_knowledge/**" = ["PLC0415"]"cdp/**" = ["PLC0415"]diff --git a/tach.toml b/tach.tomlindex 1fdcabab3840..ec1f0ba12cfe 100644--- a/tach.toml+++ b/tach.toml@@ -71,6 +71,7 @@ depends_on = ["ee","products.access_control","products.analytics_platform",+ "products.approvals","products.batch_exports","products.business_knowledge","products.cdp",@@ -159,6 +160,16 @@ depends_on = []layer = "modules"+[[modules]]+path = "products.approvals"+depends_on = [+ "ee",+ "posthog",+ "products.feature_flags",+ "products.notifications",+]+layer = "modules"+[[modules]]path = "products.batch_exports"depends_on = [@@ -307,6 +318,7 @@ depends_on = ["ee","posthog","products.actions",+ "products.approvals","products.ai_observability","products.analytics_platform","products.data_tools",@@ -325,6 +337,7 @@ depends_on = ["products.cohorts","ee","posthog",+ "products.approvals","products.dashboards","products.early_access_features","products.experiments",