:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(approvals): scope flag approval policies by the product that owns the flag (#114053)
Yasen8d8e61d02494
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 7b22bdc3b955..fb1cdc749698 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -262,6 +262,7 @@ export const FEATURE_FLAGS = {AMPLITUDE_BATCH_IMPORT_OPTIONS: 'amplitude-batch-import-options', // owner: #team-ingestionANOMALY_ALERT_GUIDANCE_EXPERIMENT: 'anomaly-alert-guidance',APPROVALS: 'approvals', // owner: @yasen-posthog #team-platform-features+ APPROVALS_SCOPE_BY_FLAG_OWNER: 'approvals-scope-by-flag-owner', // owner: @yasen-posthog #team-platform-features, scopes approval policies by the product that owns the flagAUTORESEARCH: 'autoresearch', // owner: @andrewm4894 #team-platform-featuresAUTORESEARCH_REPORT_NOTEBOOK: 'autoresearch-report-notebook', // owner: @andrewm4894 #team-platform-features, gates the training run report notebookAVERAGE_PAGE_VIEW_COLUMN: 'average-page-view-column', // owner: @jordanm-posthog #team-web-analyticsdiff --git a/frontend/src/scenes/approvals/ApprovalDetail.tsx b/frontend/src/scenes/approvals/ApprovalDetail.tsxindex 4fd1df1558c3..d7b21dcc21a3 100644--- a/frontend/src/scenes/approvals/ApprovalDetail.tsx+++ b/frontend/src/scenes/approvals/ApprovalDetail.tsx@@ -110,7 +110,7 @@ function ApprovalDetail({ id }: ApprovalLogicProps): JSX.Element {<div className="mt-1">{(() => {const resourceUrl = getApprovalResourceUrl(- changeRequest.action_key,+ changeRequest.resource_type,changeRequest.resource_id)const name = getApprovalResourceName(diff --git a/frontend/src/scenes/approvals/approvalLogic.tsx b/frontend/src/scenes/approvals/approvalLogic.tsxindex 29f06d818130..a3f894e0db3f 100644--- a/frontend/src/scenes/approvals/approvalLogic.tsx+++ b/frontend/src/scenes/approvals/approvalLogic.tsx@@ -163,7 +163,7 @@ export const approvalLogic = kea<approvalLogicType>([listeners(({ actions, values, props }) => {const navigateAfterAction = (fullReload: boolean = false): void => {const cr = values.changeRequest- const resourceUrl = cr ? getApprovalResourceUrl(cr.action_key, cr.resource_id) : null+ const resourceUrl = cr ? getApprovalResourceUrl(cr.resource_type, cr.resource_id) : nullconst targetUrl = resourceUrl || urls.approvals()if (fullReload) {diff --git a/frontend/src/scenes/approvals/utils.ts b/frontend/src/scenes/approvals/utils.tsindex e332eee40536..cde8b58120ad 100644--- a/frontend/src/scenes/approvals/utils.ts+++ b/frontend/src/scenes/approvals/utils.ts@@ -3,8 +3,24 @@ export const ApprovalActionKey = {FEATURE_FLAG_ENABLE: 'feature_flag.enable',FEATURE_FLAG_DISABLE: 'feature_flag.disable',FEATURE_FLAG_UPDATE: 'feature_flag.update',+ EXPERIMENT_LAUNCH: 'experiment.launch',+ EXPERIMENT_PAUSE: 'experiment.pause',+ EXPERIMENT_UPDATE: 'experiment.update',} as const+// Actions whose policy can limit approval to some changes. Saving any other action drops its conditions.+export const CONDITIONAL_APPROVAL_ACTIONS: ReadonlySet<string> = new Set([+ ApprovalActionKey.FEATURE_FLAG_UPDATE,+ ApprovalActionKey.EXPERIMENT_UPDATE,+])++// Experiment actions govern an experiment's flag only once the organization scopes policies by flag owner.+export const EXPERIMENT_APPROVAL_ACTIONS: ReadonlySet<string> = new Set([+ ApprovalActionKey.EXPERIMENT_LAUNCH,+ ApprovalActionKey.EXPERIMENT_PAUSE,+ ApprovalActionKey.EXPERIMENT_UPDATE,+])+export type ApprovalActionKeyType = (typeof ApprovalActionKey)[keyof typeof ApprovalActionKey]export type ApprovalContext = 'feature_flag' | 'experiment'@@ -31,6 +47,18 @@ export const APPROVAL_ACTIONS: Record<string, ApprovalActionConfig> = {description: "change this feature flag's release conditions or rollout",contextDescriptions: { experiment: 'update this experiment' },},+ [ApprovalActionKey.EXPERIMENT_LAUNCH]: {+ label: 'Launch experiment',+ description: 'launch this experiment',+ },+ [ApprovalActionKey.EXPERIMENT_PAUSE]: {+ label: 'Pause experiment',+ description: 'pause this experiment',+ },+ [ApprovalActionKey.EXPERIMENT_UPDATE]: {+ label: 'Update experiment',+ description: "change this experiment's rollout or variant split, or ship a winning variant",+ },}export function getApprovalActionLabel(actionKey: string): string {@@ -57,12 +85,11 @@ const APPROVAL_RESOURCE_CONFIG: Record<string, { label: string; urlBuilder: (id:[ApprovalResourceType.FEATURE_FLAG]: { label: 'Feature flag', urlBuilder: (id) => `/feature-flags/${id}` },}-export function getApprovalResourceUrl(actionKey: string, resourceId: string | null): string | null {+export function getApprovalResourceUrl(resourceType: string, resourceId: string | null): string | null {if (!resourceId) {return null}- const prefix = actionKey.split('.')[0]- const config = APPROVAL_RESOURCE_CONFIG[prefix]+ const config = APPROVAL_RESOURCE_CONFIG[resourceType]return config ? config.urlBuilder(resourceId) : null}diff --git a/frontend/src/scenes/settings/organization/Approvals/ApprovalPolicies.tsx b/frontend/src/scenes/settings/organization/Approvals/ApprovalPolicies.tsxindex 28310657dba0..6116ea978e2f 100644--- a/frontend/src/scenes/settings/organization/Approvals/ApprovalPolicies.tsx+++ b/frontend/src/scenes/settings/organization/Approvals/ApprovalPolicies.tsx@@ -3,24 +3,33 @@ import { useEffect, useState } from 'react'import { IconInfo, IconX } from '@posthog/icons'import {+ LemonBanner,LemonButton,LemonInput,LemonInputSelect,LemonSelect,LemonSwitch,LemonTable,+ Link,Tooltip,} from '@posthog/lemon-ui'import { PayGateMini } from 'lib/components/PayGateMini/PayGateMini'import { useRestrictedArea } from 'lib/components/RestrictedArea'import { OrganizationMembershipLevel } from 'lib/constants'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { More } from 'lib/lemon-ui/LemonButton/More'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { LemonModal } from 'lib/lemon-ui/LemonModal'import { LemonTableColumn } from 'lib/lemon-ui/LemonTable'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'-import { APPROVAL_ACTIONS, ApprovalActionKey, getApprovalActionLabel } from 'scenes/approvals/utils'+import {+ APPROVAL_ACTIONS,+ ApprovalActionKey,+ CONDITIONAL_APPROVAL_ACTIONS,+ EXPERIMENT_APPROVAL_ACTIONS,+ getApprovalActionLabel,+} from 'scenes/approvals/utils'import { membersLogic } from 'scenes/organization/membersLogic'import { rolesLogic } from 'scenes/settings/organization/Permissions/Roles/rolesLogic'@@ -65,6 +74,7 @@ export function ApprovalPolicies(): JSX.Element {const [editingPolicy, setEditingPolicy] = useState<ApprovalPolicy | null>(null)const [isCreating, setIsCreating] = useState(false)const restrictionReason = useRestrictedArea({ minimumAccessLevel: OrganizationMembershipLevel.Admin })+ const scopedByFlagOwner = useFeatureFlag('APPROVALS_SCOPE_BY_FLAG_OWNER')useEffect(() => {loadPolicies()@@ -156,6 +166,25 @@ export function ApprovalPolicies(): JSX.Element {return (<PayGateMini feature={AvailableFeature.APPROVALS} featureDetail="approval-policies"><div className="space-y-4">+ {scopedByFlagOwner && (+ <LemonBanner type="info" dismissKey="approval-policies-experiment-split" alignItems="start">+ <div className="flex flex-col gap-1">+ <span className="font-semibold">Experiments now have their own approval policies</span>+ <p className="m-0">+ Launching, pausing, and changing the rollout or variant split of an experiment now+ follow the experiment policies. Feature flag policies cover the flags that no product+ manages, so flags that a survey, product tour, or early access feature manages no longer+ need approval. Surveys will get their own policies soon.{' '}+ <Link+ to="https://posthog.com/docs/settings/approvals#experiment-policies"+ target="_blank"+ >+ Learn how policies apply to each flag+ </Link>+ </p>+ </div>+ </LemonBanner>+ )}<div className="flex justify-end items-center"><LemonButton type="primary" onClick={() => setIsCreating(true)} disabledReason={restrictionReason}>Add policy@@ -185,7 +214,9 @@ function ApprovalPolicyModal({ policy, onClose }: { policy?: ApprovalPolicy; onCconst { loadAllMembers } = useActions(membersLogic)const { loadRoles } = useActions(rolesLogic)+ const scopedByFlagOwner = useFeatureFlag('APPROVALS_SCOPE_BY_FLAG_OWNER')const [actionKey, setActionKey] = useState(policy?.action_key || 'feature_flag.enable')+ const supportsConditions = CONDITIONAL_APPROVAL_ACTIONS.has(actionKey)const [quorum, setQuorum] = useState(policy?.approver_config?.quorum || 1)const [allowSelfApprove, setAllowSelfApprove] = useState(policy?.allow_self_approve || false)const [approverUserIds, setApproverUserIds] = useState<number[]>(policy?.approver_config?.users || [])@@ -241,7 +272,7 @@ function ApprovalPolicyModal({ policy, onClose }: { policy?: ApprovalPolicy; onC// Build conditions from rules (for now, just take the first rule)let conditions: Record<string, unknown> = {}- if (actionKey === ApprovalActionKey.FEATURE_FLAG_UPDATE && rules.length > 0) {+ if (supportsConditions && rules.length > 0) {const rule = rules[0]if (rule.type !== 'any_change' && rule.value === undefined) {lemonToast.error('Please specify a threshold value')@@ -322,18 +353,25 @@ function ApprovalPolicyModal({ policy, onClose }: { policy?: ApprovalPolicy; onCvalue={actionKey}onChange={(value) => {setActionKey(value)- if (value !== ApprovalActionKey.FEATURE_FLAG_UPDATE) {+ if (!CONDITIONAL_APPROVAL_ACTIONS.has(value)) {setRules([])}}}- options={Object.entries(APPROVAL_ACTIONS).map(([value, action]) => ({- label: action.label,- value,- }))}+ options={Object.entries(APPROVAL_ACTIONS)+ .filter(+ ([value]) =>+ scopedByFlagOwner ||+ value === policy?.action_key ||+ !EXPERIMENT_APPROVAL_ACTIONS.has(value)+ )+ .map(([value, action]) => ({+ label: action.label,+ value,+ }))}/></div>- {actionKey === ApprovalActionKey.FEATURE_FLAG_UPDATE && (+ {supportsConditions && (<div className="space-y-3"><div className="flex items-center gap-2"><label className="block text-sm font-medium">Require approval when</label>@@ -373,9 +411,9 @@ function ApprovalPolicyModal({ policy, onClose }: { policy?: ApprovalPolicy; onC)}<p className="text-xs text-secondary">- With no conditions, any change to a flag's rollout needs approval. So does any change to its- release conditions, unless an experiment, survey, product tour or early access feature- manages the flag.+ {actionKey === ApprovalActionKey.EXPERIMENT_UPDATE+ ? "With no conditions, any change to an experiment's rollout, variant split or holdout exclusion needs approval. Changes to its release conditions do not."+ : "With no conditions, any change to a flag's rollout needs approval. So does any change to its release conditions, unless an experiment, survey, product tour or early access feature manages the flag."}</p></div>)}diff --git a/frontend/src/scenes/settings/organization/Approvals/ChangeRequestsList.tsx b/frontend/src/scenes/settings/organization/Approvals/ChangeRequestsList.tsxindex b3fc2496ba8a..a2b202e6c558 100644--- a/frontend/src/scenes/settings/organization/Approvals/ChangeRequestsList.tsx+++ b/frontend/src/scenes/settings/organization/Approvals/ChangeRequestsList.tsx@@ -40,7 +40,7 @@ export function ChangeRequestsList(): JSX.Element {{title: 'Resource',render: function RenderResource(_, changeRequest) {- const resourceUrl = getApprovalResourceUrl(changeRequest.action_key, changeRequest.resource_id)+ const resourceUrl = getApprovalResourceUrl(changeRequest.resource_type, changeRequest.resource_id)const name = getApprovalResourceName(changeRequest.resource_type, changeRequest.intent)return resourceUrl && name ? <LemonTableLink to={resourceUrl} title={name} /> : name},diff --git a/products/approvals/backend/actions/base.py b/products/approvals/backend/actions/base.pyindex 2a563377f979..0e5860378526 100644--- a/products/approvals/backend/actions/base.py+++ b/products/approvals/backend/actions/base.py@@ -26,11 +26,19 @@ class BaseAction(ABC):intent_fields: Optional[list[str]] = None- # TODO(experiment-approval-policies): temporary. Action keys whose policy gates this action- # when it has no policy of its own, so a move to a new key leaves no window without approval.- # The fallback policy's conditions name the old action's fields, so they are not evaluated.+ # Action keys whose policy gates this action when it has no policy of its own.+ # The fallback policy's conditions name the other action's fields, so they are not evaluated.fallback_policy_action_keys: tuple[str, ...] = ()+ @classmethod+ def fallback_policy_action_keys_for(cls, organization) -> tuple[str, ...]:+ """The fallback keys to try for this organization, in order.++ A hook rather than the attribute, because which policy stands in for this action can+ depend on how far the organization has moved between families.+ """+ return cls.fallback_policy_action_keys+@classmethoddef _get_instance(cls, view, *args, **kwargs):if hasattr(view, "context") and "request" in view.context:diff --git a/products/approvals/backend/actions/experiment_holdouts.py b/products/approvals/backend/actions/experiment_holdouts.pyindex aa113b15789f..56bb33100003 100644--- a/products/approvals/backend/actions/experiment_holdouts.py+++ b/products/approvals/backend/actions/experiment_holdouts.py@@ -2,6 +2,7 @@ from typing import Any, Optionalfrom products.approvals.backend.actions.base import BaseActionfrom products.approvals.backend.exceptions import ApplyFailed, PreconditionFailed+from products.approvals.backend.ownership import scope_by_owner_enableddef _exclusion_percentage(filters: Any) -> Optional[float]:@@ -37,10 +38,24 @@ class ExperimentHoldoutActionBase(BaseAction):"""resource_type = "experiment_holdout"- # TODO(experiment-approval-policies): until experiment-owned flags leave `feature_flag.*`- # scope, an organization's flag policy still gates the flag writes a holdout change makes.fallback_policy_action_keys = ("feature_flag.update",)+ @classmethod+ def fallback_policy_action_keys_for(cls, organization) -> tuple[str, ...]:+ """Whichever policy gates the flag writes this holdout change makes, and only that one.++ The two are never both offered. While the organization has not moved to scoping by flag+ owner, its experiment policies are mirrors the sync refreshes hourly, so reading one would+ answer from an hour-old copy: a bypass an admin revoked on the flag policy would keep+ working here until the next run. Once the organization is rolled out+ (`scope_by_owner_enabled`), the mirror is the organization's own policy and the flag policy+ no longer governs an experiment's flags, so the experiment policy is the only right answer.+ An unknown rollout state reads as off here, while the sync reads it as rolled out and stops.+ """+ if scope_by_owner_enabled(organization):+ return ("experiment.update",)+ return cls.fallback_policy_action_keys+@classmethoddef _holdout(cls, view, *args, **kwargs):instance = cls._get_instance(view, *args, **kwargs)diff --git a/products/approvals/backend/actions/experiments.py b/products/approvals/backend/actions/experiments.pynew file mode 100644index 000000000000..9eb36012df7f--- /dev/null+++ b/products/approvals/backend/actions/experiments.py@@ -0,0 +1,79 @@+"""Approval actions for the flags an experiment owns.++An experiment drives its flag rather than being a separate resource to gate: launching writes+`active`, pausing clears it, and changing the split or shipping a winner rewrites the rollout.+Every one of those writes reaches `FeatureFlagSerializer`, so these actions gate the same writes+the `feature_flag.*` family gates and differ only in which flags they govern.++That is why they subclass the flag actions instead of restating them. Detection, intent, the+staleness checks and the apply path are the flag's; `owner_scope` is what makes this family see an+experiment's flags and the unowned family stop seeing them.++Gating the experiment endpoints instead would leave a hole. An experiment's flag edited through+the flags API matches neither family then: not `feature_flag.*`, which no longer covers it, and+not `experiment.*`, because no experiment endpoint was called.+"""++from typing import Any++from products.approvals.backend.actions.feature_flags import (+ DisableFeatureFlagAction,+ EnableFeatureFlagAction,+ UpdateFeatureFlagAction,+)+from products.feature_flags.backend.ownership import FLAG_OWNER_EXPERIMENT+++class LaunchExperimentAction(EnableFeatureFlagAction):+ """Gate starting an experiment, whichever route starts it."""++ key = "experiment.launch"+ version = 1+ description = "Launch an experiment"+ owner_scope = FLAG_OWNER_EXPERIMENT++ # An experiment owns its flag only once the experiment row exists, so a create mints an+ # unowned flag that this family never governs. Opting out only makes `detect` return before it+ # reads the organization's rollout state.+ gate_on_create = False++ @classmethod+ def get_display_data(cls, intent_data: dict[str, Any]) -> dict[str, Any]:+ return {+ **super().get_display_data(intent_data),+ "description": f"Launch the experiment on feature flag '{intent_data.get('flag_key', 'unknown')}'",+ }+++class PauseExperimentAction(DisableFeatureFlagAction):+ """Gate pausing a running experiment, which stops its flag serving."""++ key = "experiment.pause"+ version = 1+ description = "Pause an experiment"+ owner_scope = FLAG_OWNER_EXPERIMENT++ @classmethod+ def get_display_data(cls, intent_data: dict[str, Any]) -> dict[str, Any]:+ return {+ **super().get_display_data(intent_data),+ "description": f"Pause the experiment on feature flag '{intent_data.get('flag_key', 'unknown')}'",+ }+++class UpdateExperimentAction(UpdateFeatureFlagAction):+ """Gate a change to how an experiment's traffic is split, including shipping a winner.++ Shipping a winning variant is a rollout change with a different button on it, so it belongs to+ this action rather than one of its own. The description says so, because "update" alone does+ not tell an approver that a request may hand one variant every user.+ """++ key = "experiment.update"+ version = 1+ description = "Change an experiment's rollout or variant split, or ship a winning variant"+ owner_scope = FLAG_OWNER_EXPERIMENT++ @classmethod+ def _display_subject(cls, flag_key: str, changed_fields: list[str]) -> str:+ return f"Change the rollout or variant split of the experiment on feature flag '{flag_key}'"diff --git a/products/approvals/backend/actions/feature_flags.py b/products/approvals/backend/actions/feature_flags.pyindex fdd0b95a323d..a213721ed3c7 100644--- a/products/approvals/backend/actions/feature_flags.py+++ b/products/approvals/backend/actions/feature_flags.py@@ -13,7 +13,7 @@ from posthog.exceptions import Conflictfrom products.approvals.backend.actions.base import BaseActionfrom products.approvals.backend.exceptions import ApplyFailed, PreconditionFailed-from products.approvals.backend.ownership import OWNER_KIND_UNOWNED, owner_kind_changed+from products.approvals.backend.ownership import OWNER_KIND_UNOWNED, owner_in_scope, owner_kind_changedfrom products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer, flag_version_conflict_messagefrom products.feature_flags.backend.api.filters_schema import FEATURE_FLAG_OPERATOR_ALIASESfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -245,6 +245,20 @@ def _cached_owner_kind(flag: FeatureFlag) -> Optional[str]:return getattr(flag, _OWNER_KIND_ATTR)+def _in_family_scope(flag: Optional[FeatureFlag], owner_scope: Optional[str], team) -> bool:+ """Whether this action's family governs this flag, given which product owns it.++ A create has no flag yet and so no owner, which leaves it with the unowned family. That is not+ a hole: the flag a product mints is unowned for the instant it is written, because the row that+ will own it does not exist yet.+ """+ return owner_in_scope(+ owner_scope,+ team.organization if team is not None else None,+ lambda: _cached_owner_kind(flag) if flag is not None else None,+ )++def _comparable(value: Any) -> str:"""Encode a release condition value so that values flag evaluation tells apart compare unequal.@@ -376,6 +390,14 @@ class FeatureFlagActionBase(BaseAction):endpoint_serializer_class = FeatureFlagSerializerintent_fields = ["active"]+ # Which product's flags this family governs, or None for the flags no product owns.+ # `owner_in_scope` reads it; an owner-scoped subclass sets it.+ owner_scope: Optional[str] = None++ # The write this action gates, named so the same write can be recognised across families.+ # Two families name one operation with two keys, and only the operation makes them comparable.+ gated_operation: str+# Subclasses define the target statetarget_active_state: bool@@ -465,7 +487,7 @@ class FeatureFlagActionBase(BaseAction):if not team:return False- return True+ return _in_family_scope(flag, cls.owner_scope, team)@classmethoddef extract_intent(cls, request, view, *args, **kwargs) -> dict[str, Any]:@@ -570,6 +592,7 @@ class EnableFeatureFlagAction(FeatureFlagActionBase):key = "feature_flag.enable"version = 1description = "Enable a feature flag"+ gated_operation = "enable"target_active_state = Truegate_on_create = True@@ -591,6 +614,7 @@ class DisableFeatureFlagAction(FeatureFlagActionBase):key = "feature_flag.disable"version = 1description = "Disable a feature flag"+ gated_operation = "disable"target_active_state = False@classmethod@@ -619,6 +643,12 @@ class UpdateFeatureFlagAction(BaseAction):resource_type = "feature_flag"endpoint_serializer_class = FeatureFlagSerializer+ # Which product's flags this family governs, or None for the flags no product owns.+ owner_scope: Optional[str] = None++ # The write this action gates. See `FeatureFlagActionBase.gated_operation`.+ gated_operation = "update"+GATEABLE_FIELDS: dict[str, dict[str, str]] = {"rollout_percentage": {"type": "number",@@ -773,7 +803,7 @@ class UpdateFeatureFlagAction(BaseAction):if not team:return False- return True+ return _in_family_scope(flag, cls.owner_scope, team)@classmethoddef extract_intent(cls, request, view, *args, **kwargs) -> dict[str, Any]:@@ -906,6 +936,11 @@ class UpdateFeatureFlagAction(BaseAction):return f"{label} removed"return label+ @classmethod+ def _display_subject(cls, flag_key: str, changed_fields: list[str]) -> str:+ """The opening of the request description, which the list of changes follows."""+ return f"Update {' and '.join(changed_fields)} for feature flag '{flag_key}'"+@classmethoddef get_display_data(cls, intent_data: dict[str, Any]) -> dict[str, Any]:"""Generate human-readable diff showing before/after for gated fields."""@@ -935,7 +970,7 @@ class UpdateFeatureFlagAction(BaseAction):for name, changes in (("release conditions", release_changes), (rollout_display_name, rollout_changes))if changes] or [rollout_display_name]- description = f"Update {' and '.join(changed_fields)} for feature flag '{flag_key}'"+ description = cls._display_subject(flag_key, changed_fields)changes_description = [*release_changes, *rollout_changes]if changes_description:description = f"{description}: {'; '.join(changes_description)}"diff --git a/products/approvals/backend/actions/registry.py b/products/approvals/backend/actions/registry.pyindex 98ec50d4a387..0e15cb5988bf 100644--- a/products/approvals/backend/actions/registry.py+++ b/products/approvals/backend/actions/registry.py@@ -10,6 +10,11 @@ def register_actions():DeleteExperimentHoldoutAction,UpdateExperimentHoldoutAction,)+ from products.approvals.backend.actions.experiments import (+ LaunchExperimentAction,+ PauseExperimentAction,+ UpdateExperimentAction,+ )from products.approvals.backend.actions.feature_flags import (DisableFeatureFlagAction,EnableFeatureFlagAction,@@ -19,6 +24,9 @@ def register_actions():ACTION_REGISTRY[EnableFeatureFlagAction.key] = EnableFeatureFlagActionACTION_REGISTRY[DisableFeatureFlagAction.key] = DisableFeatureFlagActionACTION_REGISTRY[UpdateFeatureFlagAction.key] = UpdateFeatureFlagAction+ ACTION_REGISTRY[LaunchExperimentAction.key] = LaunchExperimentAction+ ACTION_REGISTRY[PauseExperimentAction.key] = PauseExperimentAction+ ACTION_REGISTRY[UpdateExperimentAction.key] = UpdateExperimentActionACTION_REGISTRY[UpdateExperimentHoldoutAction.key] = UpdateExperimentHoldoutActionACTION_REGISTRY[DeleteExperimentHoldoutAction.key] = DeleteExperimentHoldoutActiondiff --git a/products/approvals/backend/api.py b/products/approvals/backend/api.pyindex 60d408d33efc..b58727c89c03 100644--- a/products/approvals/backend/api.py+++ b/products/approvals/backend/api.py@@ -24,6 +24,7 @@ from posthog.permissions import (from products.approvals.backend.exceptions import AlreadyVotedError, InvalidStateError, ReasonRequiredErrorfrom products.approvals.backend.experiment_policy_sync import SYNCED_ACTION_KEYSfrom products.approvals.backend.models import ApprovalPolicy, ChangeRequest+from products.approvals.backend.ownership import scope_by_owner_enabledfrom products.approvals.backend.permissions import CanApprove, CanCancelfrom products.approvals.backend.serializers import (ApprovalPolicySerializer,@@ -184,9 +185,11 @@ class ApprovalPolicyViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):premium_feature_on_cloud = AvailableFeature.APPROVALSdef safely_get_queryset(self, queryset: QuerySet) -> QuerySet:- # TODO(experiment-approval-policies): temporary. Experiment policies are hidden mirrors of flag policies- # until they are enforced. See experiment_policy_sync.py.- queryset = queryset.exclude(action_key__in=SYNCED_ACTION_KEYS)+ # TODO(experiment-approval-policies): temporary. Until an organization evaluates policies by+ # flag owner, its experiment policies are hidden mirrors of its flag policies, and showing+ # them would offer an edit that the next sync run overwrites. See experiment_policy_sync.py.+ if not scope_by_owner_enabled(self.organization):+ queryset = queryset.exclude(action_key__in=SYNCED_ACTION_KEYS)filters = self.request.query_paramsif "action_key" in filters:@@ -215,8 +218,10 @@ class ApprovalPolicyViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):organization=self.organization,team=self.team,)- # TODO(experiment-approval-policies): ignore hidden mirrors so this error cannot reveal them.- .exclude(action_key__in=SYNCED_ACTION_KEYS)+ # TODO(experiment-approval-policies): ignore hidden mirrors so this error cannot reveal+ # them. Once the organization evaluates policies by flag owner its mirrors are its own+ # policies, and a second one for the same action is the duplicate this check refuses.+ .exclude(action_key__in=() if scope_by_owner_enabled(self.organization) else SYNCED_ACTION_KEYS).exists()):raise exceptions.ValidationError(diff --git a/products/approvals/backend/coverage.py b/products/approvals/backend/coverage.pynew file mode 100644index 000000000000..165ffe8aeab1--- /dev/null+++ b/products/approvals/backend/coverage.py@@ -0,0 +1,168 @@+"""Which approval families cover a flag, and whether a change of owner would drop that cover.++Scoping policies by flag owner means a flag's cover follows its owner. Pointing a product at a+flag therefore changes which policies govern it, and for a product with no family of its own it+removes every one of them. That makes adoption a way around a policy rather than a routine edit,+so the paths that adopt a flag ask here first.+"""++from typing import Any, Optional, cast++from posthog.dataclasses import frozen++from products.approvals.backend import decorators+from products.approvals.backend.ownership import scope_by_owner_enabled+from products.approvals.backend.policies import PolicyEngine+++@frozen+class FlagWriteAction:+ """One registered action that gates a flag write."""++ # The product whose flags this action governs, or None for the flags no product owns.+ owner_scope: Optional[str]+ # The write it gates. Two families name the same write with different keys.+ operation: str+ key: str+++def _flag_write_actions() -> list[FlagWriteAction]:+ """Every action that gates a flag write.++ Read off the actions the flag write gate offers rather than the registry, so a policy counts as+ cover only when the gate evaluates it.+ """+ # Deferred: the flag API module reaches this module through the adoption guard, so an eager+ # import would be circular.+ from products.feature_flags.backend.api.feature_flag import FLAG_WRITE_APPROVAL_ACTIONS # noqa: PLC0415++ actions: list[FlagWriteAction] = []+ for action in decorators._resolve_actions(list(FLAG_WRITE_APPROVAL_ACTIONS)):+ if not hasattr(action, "owner_scope") or not hasattr(action, "gated_operation"):+ continue+ actions.append(+ FlagWriteAction(+ owner_scope=cast(Optional[str], action.owner_scope),+ operation=cast(str, action.gated_operation),+ key=cast(str, action.key),+ )+ )+ return actions+++@frozen+class WriteGate:+ """What an enabled policy asks of one flag write."""++ # The changes it gates. Empty gates every change.+ conditions: dict[str, Any]+ # Who skips it: organization membership levels, and role ids.+ bypass_levels: frozenset[int]+ bypass_role_ids: frozenset[str]++ def stops_everything_stopped_by(self, other: "WriteGate") -> bool:+ """Whether this gate stops every write that `other` stops, for every member."""+ if self.conditions and self.conditions != other.conditions:+ return False+ return self.bypass_levels <= other.bypass_levels and self.bypass_role_ids <= other.bypass_role_ids+++def governing_gates(owner_kind: Optional[str], team, organization) -> dict[str, WriteGate]:+ """For each write an enabled policy governs on this product's flags, what that policy asks."""+ engine = PolicyEngine()+ governed: dict[str, WriteGate] = {}+ for action in _flag_write_actions():+ if action.owner_scope != owner_kind:+ continue+ policy = engine.get_policy(action.key, team, organization)+ if policy is not None:+ governed[action.operation] = WriteGate(+ conditions=policy.conditions or {},+ bypass_levels=frozenset(int(level) for level in policy.bypass_org_membership_levels or []),+ bypass_role_ids=frozenset(str(role_id) for role_id in policy.bypass_roles.values_list("id", flat=True)),+ )+ return governed+++def write_needs_approval(owner_kind: Optional[str], operation: str, team, organization) -> bool:+ """Whether an enabled policy governs this write on a flag that `owner_kind` owns.++ For a caller that must refuse a write up front, because it runs where a change request+ cannot survive.+ """+ family = owner_kind if scope_by_owner_enabled(organization) else None+ return operation in governing_gates(family, team, organization)+++def cover_dropped(governed_now: dict[str, WriteGate], governed_after: dict[str, WriteGate]) -> bool:+ """Whether some write governed now is not stopped as fully afterwards."""+ return any(+ operation not in governed_after or not governed_after[operation].stops_everything_stopped_by(gate)+ for operation, gate in governed_now.items()+ )+++def _adoption_guard_applies(organization) -> bool:+ """Whether adoption can move a flag out of review in this organization.++ Before scoping, `feature_flag.*` covers every flag whoever owns it. Without the Approvals+ feature, the gate admits every write, so a policy row left behind protects nothing.+ """+ return scope_by_owner_enabled(organization) and decorators._is_approvals_enabled(organization)+++def adoption_drops_approval_cover(+ current_owner_kind: Optional[str],+ target_owner_kind: str,+ team,+ organization,+) -> bool:+ """Whether pointing this product at the flag would leave some write of it less governed.++ Compared write by write. For each write governed now, the target family must gate at least+ the same changes, which a policy does in two cases:++ - It has no conditions, so it gates every such write.+ - It has the same conditions, so it gates the same writes. Each experiment action subclasses+ the flag action for the same write and builds the same intent, so equal conditions evaluate+ equally. This is what keeps the synced mirrors, which copy conditions exactly, allowed.++ A target policy that merely exists is not enough. One whose conditions name a field the write+ never carries matches nothing, and the gate reads an unmatched condition as "allow", so it+ would let through the write the current policy stopped.++ The target must also let no more members skip the gate. Otherwise a member that the current+ policy stops could adopt the flag and then make the write unreviewed.++ False before the organization is scoped by flag owner: `feature_flag.*` still covers every+ flag whoever owns it, so no owner change can drop the cover.+ """+ if not _adoption_guard_applies(organization):+ return False+ return cover_dropped(+ governing_gates(current_owner_kind, team, organization),+ governing_gates(target_owner_kind, team, organization),+ )+++def adoption_skips_enable_review(+ flag_active: bool,+ current_owner_kind: Optional[str],+ target_owner_kind: str,+ team,+ organization,+) -> bool:+ """Whether adopting an enabled flag would skip the review the target gives to enabling it.++ The target family reviews the move from off to on, for an experiment its launch. A flag+ that is already on never makes that move again, so the adopting product starts live with+ nobody from the target family having reviewed it.++ A flag the target product already owns has been through that family's review, so it is+ not refused.+ """+ if not flag_active or current_owner_kind == target_owner_kind:+ return False+ if not _adoption_guard_applies(organization):+ return False+ return "enable" in governing_gates(target_owner_kind, team, organization)diff --git a/products/approvals/backend/experiment_policy_sync.py b/products/approvals/backend/experiment_policy_sync.pyindex 598b5288a501..30e2cef0bd61 100644--- a/products/approvals/backend/experiment_policy_sync.py+++ b/products/approvals/backend/experiment_policy_sync.py@@ -1,8 +1,10 @@"""TEMPORARY: mirror feature flag approval policies to experiment approval policies.This module exists only until experiment-owned flags leave `feature_flag.*` policy scope and the-`experiment.*` policies are enforced. Delete it in the PR that ships that enforcement. The last sync-run before that deploy is the final copy, so organizations keep the approvals they configured.+`experiment.*` policies are enforced. Enforcement rolls out one organization at a time, and the sync+skips an organization once it is rolled out, so the last run before that is that organization's+final copy and it keeps the approvals it configured. Delete this module once every organization+with a flag policy is rolled out.Every part of the sync carries the tag `TODO(experiment-approval-policies)`. Remove all of them:- this module and `tests/test_experiment_policy_sync.py`@@ -11,8 +13,15 @@ Every part of the sync carries the tag `TODO(experiment-approval-policies)`. Rem- the `experiment.*` exclusions in `ApprovalPolicyViewSet`- the `experiment.*` rejection in `ApprovalPolicySerializer.validate_action_key`- the tests in `test_approvals_api.py` that create `experiment.*` rows to check they stay hidden-- `fallback_policy_action_keys` on the experiment holdout actions, the fallback lookup in- `PolicyEngine.get_policy_for_action`, and `ignore_conditions` in `PolicyEngine.evaluate`+- the branch of `fallback_policy_action_keys_for` on the experiment holdout actions that serves an+ organization not rolled out++Keep the rest of the holdout fallback: the fallback lookup in `PolicyEngine.get_policy_for_action`+and `ignore_conditions` in `PolicyEngine.evaluate`. A holdout has no policy of its own, and once+every organization is rolled out it borrows `experiment.update` through them.++A self-hosted instance cannot evaluate the rollout flag, so it never rolls out. Decide how those+instances move to the experiment policies before deleting this module.No column marks a row as a mirror. This is on purpose, because the sync is short-lived. So the synctreats every `experiment.*` row as a mirror. It overwrites or deletes any `experiment.*` row that a@@ -26,6 +35,7 @@ from django.db import connection, transactionfrom structlog import get_loggerfrom products.approvals.backend.models import ApprovalPolicy+from products.approvals.backend.ownership import scope_by_owner_statelogger = get_logger(__name__)@@ -62,6 +72,12 @@ def sync_experiment_policies() -> None:Deleting orphans is safe because every row with a synced action key is a mirror: the APIrejects those keys, so no person can create one.+ An organization that evaluates policies by flag owner is skipped entirely. Its experiment+ policies are enforced and it can edit them, so mirroring would overwrite a person's edit with+ the flag policy, and the orphan sweep would delete an experiment policy they created. Skipping+ makes the last run before that organization was rolled out its final copy, which is the+ handover this sync exists to produce.+One run at a time holds a lock, and an overlapping run skips. The unique constraint cannotstop two runs from each inserting an organization-level mirror, because `team_id` is NULL there."""@@ -72,9 +88,16 @@ def sync_experiment_policies() -> None:created = updated = 0live: set[tuple[UUID, int | None, str]] = set()+ handed_over: dict[UUID, bool] = {}- sources = ApprovalPolicy.objects.filter(action_key__in=ACTION_MAP).prefetch_related("bypass_roles")+ sources = (+ ApprovalPolicy.objects.filter(action_key__in=ACTION_MAP)+ .select_related("organization")+ .prefetch_related("bypass_roles")+ )for source in sources:+ if _is_handed_over(source.organization, handed_over):+ continuetarget_action = ACTION_MAP[source.action_key]live.add((source.organization_id, source.team_id, target_action))fields = {field: getattr(source, field) for field in MIRRORED_FIELDS}@@ -105,8 +128,11 @@ def sync_experiment_policies() -> None:orphans = [mirror- for mirror in ApprovalPolicy.objects.filter(action_key__in=SYNCED_ACTION_KEYS)+ for mirror in ApprovalPolicy.objects.filter(action_key__in=SYNCED_ACTION_KEYS).select_related(+ "organization"+ )if (mirror.organization_id, mirror.team_id, mirror.action_key) not in live+ and not _is_handed_over(mirror.organization, handed_over)]for orphan in orphans:orphan.delete()@@ -118,3 +144,18 @@ def _try_sync_lock() -> bool:with connection.cursor() as cursor:cursor.execute("SELECT pg_try_advisory_xact_lock(hashtextextended(%s, 0))", [_SYNC_LOCK_KEY])return cursor.fetchone()[0]+++def _is_handed_over(organization, handed_over: dict[UUID, bool]) -> bool:+ """Whether this organization may own its experiment policies, so the sync leaves them alone.++ Only an organization known to be on the old scope is synced. When the rollout flag cannot+ answer, skipping costs one run of freshness, while syncing could overwrite or delete the+ policies of an organization that is rolled out.++ Memoized per run: one organization holds several policies, and the answer cannot change+ while the run holds the lock.+ """+ if organization.id not in handed_over:+ handed_over[organization.id] = scope_by_owner_state(organization) is not False+ return handed_over[organization.id]diff --git a/products/approvals/backend/management/__init__.py b/products/approvals/backend/management/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/approvals/backend/management/commands/__init__.py b/products/approvals/backend/management/commands/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/approvals/backend/management/commands/approval_coverage.py b/products/approvals/backend/management/commands/approval_coverage.pynew file mode 100644index 000000000000..bec8d133aaaa--- /dev/null+++ b/products/approvals/backend/management/commands/approval_coverage.py@@ -0,0 +1,91 @@+"""Report which approval family covers an organization's flags, before and after narrowing.++Scoping policies by flag owner removes coverage from the flags a product owns, so the rollout is+one organization at a time and each step needs the size of the change in front of it first.+"""++from collections import Counter+from typing import Any, Optional++from django.core.management.base import BaseCommand++from posthog.models import Organization, Team++from products.approvals.backend.coverage import cover_dropped, governing_gates+from products.approvals.backend.models import ApprovalPolicy+from products.approvals.backend.ownership import scope_by_owner_state+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.ownership import owner_kind_counts++UNOWNED_LABEL = "(unowned)"+NO_FAMILY = "(none)"+# The sync skips an organization whose state is unknown, so the report must not show it as "no".+ROLLOUT_LABELS = {True: "yes", False: "no", None: "unknown, so the policy sync skips it"}+++class Command(BaseCommand):+ help = "Show the approval coverage an organization has now and would have scoped by flag owner"++ def add_arguments(self, parser: Any) -> None:+ parser.add_argument(+ "--organization",+ dest="organization_id",+ help="Report one organization by id. Omit to report every organization that has a policy.",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ organization_ids = (+ [options["organization_id"]]+ if options.get("organization_id")+ else sorted(+ {str(row) for row in ApprovalPolicy.objects.values_list("organization_id", flat=True).distinct()}+ )+ )++ for organization_id in organization_ids:+ organization = Organization.objects.filter(id=organization_id).first()+ if organization is None:+ self.stderr.write(f"No organization {organization_id}")+ continue+ self._report(organization)++ def _report(self, organization: Organization) -> None:+ organization_keys = sorted(+ set(+ ApprovalPolicy.objects.enabled()+ .filter(organization=organization, team__isnull=True)+ .values_list("action_key", flat=True)+ )+ )++ rolled_out = ROLLOUT_LABELS[scope_by_owner_state(organization)]+ self.stdout.write(f"\n{organization.name} ({organization.id}) rolled out: {rolled_out}")+ self.stdout.write(f" organization policies: {', '.join(organization_keys) or '(none)'}")+ self.stdout.write(+ f" {'owner kind':<22}{'flags':>10} {'not scoped':<28}{'scoped by owner':<28}{'loses cover':<12}"+ )++ # Compared write by write with the adoption guard's rule, so a family whose policies gate+ # fewer writes, other changes or more bypass counts as a loss, not a move.+ rows: Counter[tuple[Optional[str], tuple[str, ...], tuple[str, ...], bool]] = Counter()+ moved = lost = 0+ for team in Team.objects.filter(organization=organization):+ # Before scoping, the unowned family's policies govern every flag, whoever owns it.+ governed_now = governing_gates(None, team, organization)+ counts = owner_kind_counts(FeatureFlag.objects.filter(team_id=team.id, deleted=False))+ for owner_kind, total in counts.items():+ governed_after = governing_gates(owner_kind, team, organization)+ drops = cover_dropped(governed_now, governed_after)+ rows[(owner_kind, tuple(sorted(governed_now)), tuple(sorted(governed_after)), drops)] += total+ if drops:+ lost += total+ elif governed_now and owner_kind is not None:+ moved += total++ for (owner_kind, now, after, drops), total in sorted(rows.items(), key=lambda row: -row[1]):+ self.stdout.write(+ f" {owner_kind or UNOWNED_LABEL:<22}{total:>10,} "+ f"{', '.join(now) or NO_FAMILY:<28}{', '.join(after) or NO_FAMILY:<28}{'yes' if drops else 'no':<12}"+ )++ self.stdout.write(f" {moved:,} flags move family, {lost:,} flags lose coverage")diff --git a/products/approvals/backend/ownership.py b/products/approvals/backend/ownership.pyindex b03c3548d9f6..24604e7e75c9 100644--- a/products/approvals/backend/ownership.py+++ b/products/approvals/backend/ownership.py@@ -1,5 +1,12 @@+from collections.abc import Callablefrom typing import Optional+from django.core.cache import cache++import posthoganalytics++from posthog.exceptions_capture import capture_exception+# A recorded classification meaning "nothing owned this resource". It is distinct from NULL,# which means no classification was recorded at all: a request created before the column# existed, or an action that does not classify ownership. Those must still apply.@@ -16,3 +23,74 @@ def owner_kind_changed(recorded: Optional[str], current: Optional[str]) -> bool:if recorded is None or current is None:return Falsereturn recorded != current+++# Narrowing takes every product-owned flag out of `feature_flag.*` coverage, so it rolls out per+# organization rather than all at once. Off, every family behaves as it did before narrowing:+# `feature_flag.*` covers every flag and the owner-scoped families match nothing.+SCOPE_BY_OWNER_FLAG = "approvals-scope-by-flag-owner"+++def scope_by_owner_state(organization) -> Optional[bool]:+ """Whether this organization evaluates approval policies by flag owner, or None when unknown.++ The flag is evaluated locally, and local evaluation answers None while the flag definitions+ are unavailable. Reading that as off is not safe for an organization already rolled out: it+ may have deleted a flag policy and kept the experiment policy, so the old scope would match+ neither. The last answer the flag gave for the organization stands in until it answers again.+ """+ if organization is None:+ return False+ remembered_key = f"{SCOPE_BY_OWNER_FLAG}:{organization.id}"+ resolved = posthoganalytics.feature_enabled(+ SCOPE_BY_OWNER_FLAG,+ f"org-{organization.id}",+ groups={"organization": str(organization.id)},+ group_properties={"organization": {"id": str(organization.id)}},+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ if resolved is None:+ try:+ return cache.get(remembered_key)+ except Exception as e:+ capture_exception(e)+ return None+ enabled = resolved is True+ # The flag answered, so a cache failure must not fail the write that asked. The remembered+ # answer only matters to a later read that the flag cannot answer.+ try:+ if cache.get(remembered_key) != enabled:+ cache.set(remembered_key, enabled, timeout=None)+ except Exception as e:+ capture_exception(e)+ return enabled+++def scope_by_owner_enabled(organization) -> bool:+ """Whether this organization evaluates approval policies by which product owns the flag.++ Unknown reads as off. That is the scope every organization had before narrowing, so it keeps+ the coverage of every organization not rolled out.+ """+ return scope_by_owner_state(organization) is True+++def owner_in_scope(owner_scope: Optional[str], organization, derive_owner_kind: Callable[[], Optional[str]]) -> bool:+ """Whether a family scoped to `owner_scope` governs this flag.++ `owner_scope` is the product a family covers, or None for the family that covers the flags no+ product owns. `derive_owner_kind` reports which product owns this flag, None when none does.+ A reference is not ownership, so a flag a survey merely links to derives as unowned and stays+ with the unowned family.++ Before narrowing, the unowned family covers every flag and every owner-scoped family covers+ none. That is what keeps this change inert until an organization is rolled out.++ The owner arrives as a callable because deriving it reads every owning relation. An+ organization that is not rolled out must not pay for a classification that cannot change+ the answer.+ """+ if not scope_by_owner_enabled(organization):+ return owner_scope is None+ return derive_owner_kind() == owner_scopediff --git a/products/approvals/backend/policies.py b/products/approvals/backend/policies.pyindex fc9bb007bab1..b9e774756424 100644--- a/products/approvals/backend/policies.py+++ b/products/approvals/backend/policies.py@@ -88,7 +88,7 @@ class PolicyEngine:def get_policy_for_action(self, action_class, team, organization):"""Get the active policy for an action, falling back to its fallback action keys in order."""- for action_key in (action_class.key, *action_class.fallback_policy_action_keys):+ for action_key in (action_class.key, *action_class.fallback_policy_action_keys_for(organization)):policy = self.get_policy(action_key, team, organization)if policy:return policydiff --git a/products/approvals/backend/scheduled_changes.py b/products/approvals/backend/scheduled_changes.pyindex 1fa9dfee885e..e0fb842cd6aa 100644--- a/products/approvals/backend/scheduled_changes.py+++ b/products/approvals/backend/scheduled_changes.py@@ -72,12 +72,10 @@ def _detect_gated_action(flag: "FeatureFlag", payload: dict[str, Any], user) ->"""# Deferred: feature_flags' serializer/actions transitively import posthog.tasks, which imports# this module — eager imports would create a circular import at startup.- from products.approvals.backend.actions.feature_flags import ( # noqa: PLC0415- DisableFeatureFlagAction,- EnableFeatureFlagAction,- UpdateFeatureFlagAction,+ from products.feature_flags.backend.api.feature_flag import ( # noqa: PLC0415+ FLAG_WRITE_APPROVAL_ACTIONS,+ FeatureFlagSerializer,)- from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer # noqa: PLC0415team = flag.teamorganization = team.organization@@ -89,7 +87,9 @@ def _detect_gated_action(flag: "FeatureFlag", payload: dict[str, Any], user) ->if serializer_data is None:return None- feature_flag_actions = [EnableFeatureFlagAction, DisableFeatureFlagAction, UpdateFeatureFlagAction]+ # The actions the request-time gate offers. The product that owns the flag decides which family+ # evaluates, so a schedule on an experiment's flag reaches the experiment family here as well.+ feature_flag_actions = decorators._resolve_actions(list(FLAG_WRITE_APPROVAL_ACTIONS))# Build a partial-update serializer over the real flag so detect()/extract_intent() read the# change out of validated_data exactly as they do for an API-driven update.diff --git a/products/approvals/backend/serializers.py b/products/approvals/backend/serializers.pyindex 1115f681c7c7..0cd3cb114e26 100644--- a/products/approvals/backend/serializers.py+++ b/products/approvals/backend/serializers.py@@ -8,6 +8,7 @@ from posthog.api.shared import UserBasicSerializerfrom products.access_control.backend.models.role import Rolefrom products.approvals.backend.experiment_policy_sync import SYNCED_ACTION_KEYSfrom products.approvals.backend.models import Approval, ApprovalPolicy, ChangeRequest, ChangeRequestState+from products.approvals.backend.ownership import scope_by_owner_enabledfrom products.approvals.backend.policies import lock_approval_policies@@ -245,10 +246,11 @@ class ApprovalPolicySerializer(serializers.ModelSerializer):]read_only_fields = ["id", "created_by", "created_at", "updated_at"]- # TODO(experiment-approval-policies): temporary. Only the sync may write experiment policies.+ # TODO(experiment-approval-policies): temporary. Until an organization evaluates policies by+ # flag owner, its experiment policies are hidden mirrors that only the sync may write.# See experiment_policy_sync.py.def validate_action_key(self, value: str) -> str:- if value in SYNCED_ACTION_KEYS:+ if value in SYNCED_ACTION_KEYS and not scope_by_owner_enabled(self.context["view"].organization):raise serializers.ValidationError("This approval action isn't available yet.")return valuediff --git a/products/approvals/backend/tests/test_approval_coverage_command.py b/products/approvals/backend/tests/test_approval_coverage_command.pynew file mode 100644index 000000000000..b5b74afeb838--- /dev/null+++ b/products/approvals/backend/tests/test_approval_coverage_command.py@@ -0,0 +1,59 @@+from io import StringIO++from posthog.test.base import BaseTest+from unittest.mock import patch++from django.core.management import call_command++from posthog.models import Team++from products.approvals.backend.models import ApprovalPolicy+from products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlag+++class TestApprovalCoverageCommand(BaseTest):+ def _policy(self, action_key: str, team: Team | None) -> ApprovalPolicy:+ return ApprovalPolicy.objects.create(+ organization=self.organization,+ team=team,+ action_key=action_key,+ approver_config={"quorum": 1, "users": [self.user.id]},+ created_by=self.user,+ )++ def test_a_team_policy_counts_only_for_its_own_team(self) -> None:+ other_team = Team.objects.create(organization=self.organization, project=self.team.project)+ self._policy("feature_flag.enable", team=None)+ self._policy("experiment.launch", team=self.team)+ flag = FeatureFlag.objects.create(team=other_team, key="other-team-experiment", created_by=self.user)+ Experiment.objects.create(team=other_team, name="Other team experiment", feature_flag=flag)++ out = StringIO()+ call_command("approval_coverage", "--organization", str(self.organization.id), stdout=out)++ assert "0 flags move family, 1 flags lose coverage" in out.getvalue()++ def test_a_family_that_gates_fewer_writes_loses_coverage(self) -> None:+ self._policy("feature_flag.enable", team=None)+ self._policy("feature_flag.update", team=None)+ self._policy("experiment.launch", team=None)+ flag = FeatureFlag.objects.create(team=self.team, key="experiment-flag", created_by=self.user)+ Experiment.objects.create(team=self.team, name="Experiment", feature_flag=flag)++ out = StringIO()+ call_command("approval_coverage", "--organization", str(self.organization.id), stdout=out)++ assert "0 flags move family, 1 flags lose coverage" in out.getvalue()++ def test_an_unknown_rollout_state_is_not_reported_as_off(self) -> None:+ self._policy("feature_flag.enable", team=None)++ out = StringIO()+ with patch(+ "products.approvals.backend.management.commands.approval_coverage.scope_by_owner_state",+ return_value=None,+ ):+ call_command("approval_coverage", "--organization", str(self.organization.id), stdout=out)++ assert "rolled out: unknown" in out.getvalue()diff --git a/products/approvals/backend/tests/test_approvals_api.py b/products/approvals/backend/tests/test_approvals_api.pyindex 370c0a9a9fa5..d04fda7c391e 100644--- a/products/approvals/backend/tests/test_approvals_api.py+++ b/products/approvals/backend/tests/test_approvals_api.py@@ -1,4 +1,5 @@from datetime import timedelta+from typing import Optionalfrom posthog.test.base import APIBaseTestfrom unittest.mock import patch@@ -7,10 +8,12 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status+from rest_framework.exceptions import ValidationErrorfrom posthog.constants import AvailableFeaturefrom posthog.models import User+from products.access_control.backend.models.role import Rolefrom products.approvals.backend.models import (Approval,ApprovalDecision,@@ -19,6 +22,7 @@ from products.approvals.backend.models import (ChangeRequestState,ValidationStatus,)+from products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -652,6 +656,81 @@ class TestApprovalPolicyViewSet(APIBaseTest):assert "do not exist" in str(response.json())+# TODO(experiment-approval-policies): remove with the sync, once every organization is rolled out.+class TestExperimentPoliciesOnceScopedByOwner(APIBaseTest):+ """An organization that evaluates policies by flag owner owns its experiment policies.++ Until then they are hidden mirrors that the sync overwrites, so showing or accepting one+ would offer an edit that the next run reverts. The rollout flag is what separates the two,+ and it is read in both the viewset and the serializer, so both are checked here.+ """++ def setUp(self):+ super().setUp()+ self.organization.available_product_features = [+ {"key": AvailableFeature.APPROVALS, "name": "approvals"},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": "role based access"},+ ]+ self.organization.save()+ self.organization_membership.level = 8+ self.organization_membership.save()++ def _rolled_out(self):+ return (+ patch("products.approvals.backend.api.scope_by_owner_enabled", return_value=True),+ patch("products.approvals.backend.serializers.scope_by_owner_enabled", return_value=True),+ )++ def test_an_experiment_policy_is_listed(self):+ policy = ApprovalPolicy.objects.create(+ organization=self.organization,+ team=self.team,+ action_key="experiment.launch",+ approver_config={"quorum": 1, "users": [self.user.id]},+ created_by=self.user,+ )++ viewset_patch, serializer_patch = self._rolled_out()+ with viewset_patch, serializer_patch:+ response = self.client.get(f"/api/environments/{self.team.id}/approval_policies/")++ assert response.status_code == status.HTTP_200_OK+ assert [row["id"] for row in response.json()["results"]] == [str(policy.id)]++ def test_an_experiment_policy_can_be_created(self):+ viewset_patch, serializer_patch = self._rolled_out()+ with viewset_patch, serializer_patch:+ response = self.client.post(+ f"/api/environments/{self.team.id}/approval_policies/",+ {"action_key": "experiment.launch", "approver_config": {"quorum": 1, "users": [self.user.id]}},+ format="json",+ )++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ assert response.json()["action_key"] == "experiment.launch"++ def test_a_second_policy_for_the_same_experiment_action_is_refused(self):+ """The duplicate check must see the mirrors once they are the organization's own rows."""+ ApprovalPolicy.objects.create(+ organization=self.organization,+ team=self.team,+ action_key="experiment.launch",+ approver_config={"quorum": 1, "users": [self.user.id]},+ created_by=self.user,+ )++ viewset_patch, serializer_patch = self._rolled_out()+ with viewset_patch, serializer_patch:+ response = self.client.post(+ f"/api/environments/{self.team.id}/approval_policies/",+ {"action_key": "experiment.launch", "approver_config": {"quorum": 1, "users": [self.user.id]}},+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "already exists" in response.json()["detail"]++class TestFeatureFlagApprovalIntegration(APIBaseTest):"""End-to-end tests: policy exists → API call blocked → change request created@@ -817,3 +896,205 @@ class TestFeatureFlagApprovalIntegration(APIBaseTest):self.flag.refresh_from_db()assert self.flag.filters["groups"][0]["rollout_percentage"] == 75assert not ChangeRequest.objects.filter(team=self.team).exists()+++_ROLLOUT_OVER_50 = {"type": "before_after", "field": "rollout_percentage", "operator": ">", "value": 50}+++@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)+class TestAdoptingAFlagCannotDropItsApprovalCover(APIBaseTest):+ """Which policies cover a flag follows its owner, so adoption must not be a way around one.++ A member who may not enable a governed flag could otherwise attach it to a survey or an early+ access feature, which leaves it owned by a product with no family, and then enable it with no+ change request. They need flag write access either way, so what this protects is the approval.+ """++ def setUp(self):+ super().setUp()+ self.organization.available_product_features = [+ {"key": AvailableFeature.APPROVALS, "name": "approvals"},+ ]+ self.organization.save()+ self.flag = FeatureFlag.objects.create(+ team=self.team,+ key="governed",+ name="governed",+ active=False,+ filters={"groups": [{"properties": [], "rollout_percentage": 50}]},+ created_by=self.user,+ )++ def _policy(+ self, action_key: str, conditions: Optional[dict] = None, bypass_levels: Optional[list[str]] = None+ ) -> ApprovalPolicy:+ return ApprovalPolicy.objects.create(+ organization=self.organization,+ team=self.team,+ action_key=action_key,+ conditions=conditions or {},+ approver_config={"quorum": 1, "users": [self.user.id]},+ bypass_org_membership_levels=bypass_levels or [],+ created_by=self.user,+ )++ def _adopt(self, product: str):+ from products.feature_flags.backend.ownership import assert_flag_available_for++ return assert_flag_available_for(self.flag, product=product)++ # TODO(experiment-approval-policies): remove with the sync, once every organization is rolled+ # out. The guard stays, so the tests keep running with the rollout state always on.+ def _scoped_by_owner(self, enabled: bool):+ return patch(+ "products.approvals.backend.coverage.scope_by_owner_enabled",+ return_value=enabled,+ )++ @parameterized.expand([("survey",), ("product_tour",), ("early_access_feature",)])+ def test_a_product_with_no_family_cannot_adopt_a_governed_flag(self, _mock_enabled, product: str) -> None:+ self._policy("feature_flag.enable")++ with self._scoped_by_owner(True), self.assertRaises(ValidationError) as caught:+ self._adopt(product)++ assert "need approval" in str(caught.exception)++ def test_an_experiment_may_adopt_it_because_the_cover_moves(self, _mock_enabled) -> None:+ """Experiment policies mirror the flag policies, so adoption keeps the flag governed."""+ self._policy("feature_flag.enable")+ self._policy("experiment.launch")++ with self._scoped_by_owner(True):+ self._adopt("experiment")++ def test_a_family_that_governs_a_different_write_does_not_count(self, _mock_enabled) -> None:+ """The cover has to survive write by write, not merely exist.++ A flag protected against being enabled, adopted into a family that gates only pausing,+ would keep a policy and lose the only protection it had. Comparing whole families instead+ of operations let that through.+ """+ self._policy("feature_flag.enable")+ self._policy("experiment.pause")++ with self._scoped_by_owner(True), self.assertRaises(ValidationError) as caught:+ self._adopt("experiment")++ assert "need approval" in str(caught.exception)++ @parameterized.expand(+ [+ # The target policy exists but its condition names a field a launch never carries,+ # so it matches nothing and the gate allows the launch it was meant to stop.+ (+ "narrower_target",+ {},+ {"type": "before_after", "field": "rollout_percentage", "operator": ">", "value": 50},+ True,+ ),+ # The synced mirror copies conditions exactly, and both families build the same+ # intent, so the same conditions gate the same writes.+ ("mirrored_conditions", _ROLLOUT_OVER_50, _ROLLOUT_OVER_50, False),+ # A target with no conditions gates every write the conditional source gated.+ ("broader_target", _ROLLOUT_OVER_50, {}, False),+ ]+ )+ def test_a_target_policy_counts_only_if_it_gates_at_least_as_much(+ self, _mock_enabled, _name: str, source: dict, target: dict, refused: bool+ ) -> None:+ self._policy("feature_flag.enable", conditions=source)+ self._policy("experiment.launch", conditions=target)++ with self._scoped_by_owner(True):+ if refused:+ with self.assertRaises(ValidationError):+ self._adopt("experiment")+ else:+ self._adopt("experiment")++ @parameterized.expand(+ [+ # Admins and owners the flag policy stops could adopt the flag and enable it unreviewed.+ ("target_lets_more_levels_skip", [], ["8", "15"], False, True),+ ("target_lets_a_role_skip", [], [], True, True),+ ("same_bypass", ["8", "15"], ["8", "15"], False, False),+ ("target_lets_fewer_skip", ["8", "15"], ["15"], False, False),+ ]+ )+ def test_a_target_policy_must_let_no_more_members_skip_it(+ self,+ _mock_enabled,+ _name: str,+ source_levels: list[str],+ target_levels: list[str],+ target_role: bool,+ refused: bool,+ ) -> None:+ self._policy("feature_flag.enable", bypass_levels=source_levels)+ target = self._policy("experiment.launch", bypass_levels=target_levels)+ if target_role:+ target.bypass_roles.add(Role.objects.create(organization=self.organization, name="Release managers"))++ with self._scoped_by_owner(True):+ if refused:+ with self.assertRaises(ValidationError):+ self._adopt("experiment")+ else:+ self._adopt("experiment")++ @parameterized.expand(+ [+ # Launching reviews turning the flag on, which a flag already on never does again.+ ("standalone_and_on", True, False, True),+ ("standalone_and_off", False, False, False),+ # Another experiment's launch already reviewed it, and experiments may share a flag.+ ("owned_by_an_experiment_and_on", True, True, False),+ ]+ )+ def test_an_active_flag_cannot_skip_the_launch_review(+ self, _mock_enabled, _name: str, active: bool, owned_by_experiment: bool, refused: bool+ ) -> None:+ self._policy("experiment.launch")+ self.flag.active = active+ self.flag.save()+ if owned_by_experiment:+ Experiment.objects.create(team=self.team, name="Earlier", feature_flag=self.flag)++ with self._scoped_by_owner(True):+ if refused:+ with self.assertRaises(ValidationError) as caught:+ self._adopt("experiment")+ assert "already on" in str(caught.exception)+ else:+ self._adopt("experiment")++ def test_a_partial_overlap_still_refuses(self, _mock_enabled) -> None:+ """Covering some of the writes is not covering them, so one gap is enough to refuse."""+ self._policy("feature_flag.enable")+ self._policy("feature_flag.update")+ self._policy("experiment.launch")++ with self._scoped_by_owner(True), self.assertRaises(ValidationError):+ self._adopt("experiment")++ def test_an_ungoverned_flag_may_be_adopted(self, _mock_enabled) -> None:+ with self._scoped_by_owner(True):+ self._adopt("survey")++ def test_adoption_is_untouched_without_the_approvals_feature(self, _mock_enabled) -> None:+ self._policy("feature_flag.enable")++ with (+ self._scoped_by_owner(True),+ patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=False),+ ):+ self._adopt("survey")++ # TODO(experiment-approval-policies): remove with the sync, once every organization is rolled out.+ def test_adoption_is_untouched_before_the_rollout(self, _mock_enabled) -> None:+ """`feature_flag.*` still covers every flag then, so no owner change can drop the cover."""+ self._policy("feature_flag.enable")++ with self._scoped_by_owner(False):+ self._adopt("survey")diff --git a/products/approvals/backend/tests/test_experiment_policy_sync.py b/products/approvals/backend/tests/test_experiment_policy_sync.pyindex 16209b5ad44c..35b25009facf 100644--- a/products/approvals/backend/tests/test_experiment_policy_sync.py+++ b/products/approvals/backend/tests/test_experiment_policy_sync.py@@ -1,12 +1,13 @@from datetime import timedeltafrom posthog.test.base import BaseTest+from unittest.mock import patchfrom django.db import connectionfrom parameterized import parameterized-from posthog.models import Team+from posthog.models import Organization, Teamfrom products.access_control.backend.models.role import Rolefrom products.approvals.backend.experiment_policy_sync import _SYNC_LOCK_KEY, sync_experiment_policies@@ -14,6 +15,14 @@ from products.approvals.backend.models import ApprovalPolicyclass TestSyncExperimentPolicies(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ not_rolled_out = patch(+ "products.approvals.backend.experiment_policy_sync.scope_by_owner_state", return_value=False+ )+ not_rolled_out.start()+ self.addCleanup(not_rolled_out.stop)+def _flag_policy(self, action_key: str, **overrides) -> ApprovalPolicy:fields = {"organization": self.organization,@@ -113,3 +122,69 @@ class TestSyncExperimentPolicies(BaseTest):assert not ApprovalPolicy.objects.filter(action_key="experiment.launch").exists()sync_experiment_policies()assert self._mirror("experiment.launch", None)+++class TestSyncLeavesRolledOutOrganizationsAlone(BaseTest):+ """An organization that evaluates policies by flag owner owns its experiment policies.++ The sync must not touch them after that point. Overwriting one would silently revert an edit+ the organization just gained the right to make, and the orphan sweep would delete an+ experiment policy it created, both without anything failing.+ """++ def _policy(self, action_key: str, **overrides) -> ApprovalPolicy:+ fields = {+ "organization": self.organization,+ "team": self.team,+ "action_key": action_key,+ "approver_config": {"quorum": 1, "users": [self.user.id]},+ "created_by": self.user,+ **overrides,+ }+ return ApprovalPolicy.objects.create(**fields)++ def _rollout_state(self, state: bool | None):+ return patch("products.approvals.backend.experiment_policy_sync.scope_by_owner_state", return_value=state)++ @parameterized.expand([("rolled_out", True), ("rollout_unknown", None)])+ def test_does_not_overwrite_an_edited_experiment_policy(self, _name: str, state: bool | None) -> None:+ self._policy("feature_flag.update", approver_config={"quorum": 1, "users": [self.user.id]})+ edited = self._policy("experiment.update", approver_config={"quorum": 3, "users": [self.user.id]})++ with self._rollout_state(state):+ sync_experiment_policies()++ edited.refresh_from_db()+ assert edited.approver_config["quorum"] == 3++ @parameterized.expand([("rolled_out", True), ("rollout_unknown", None)])+ def test_does_not_delete_an_experiment_policy_with_no_flag_policy(self, _name: str, state: bool | None) -> None:+ own = self._policy("experiment.launch")++ with self._rollout_state(state):+ sync_experiment_policies()++ assert ApprovalPolicy.objects.filter(id=own.id).exists()++ def test_does_not_create_a_mirror(self) -> None:+ self._policy("feature_flag.enable")++ with self._rollout_state(True):+ sync_experiment_policies()++ assert not ApprovalPolicy.objects.filter(action_key="experiment.launch").exists()++ def test_still_syncs_an_organization_that_is_not_rolled_out(self) -> None:+ """The skip must be per organization, or one rollout would freeze everybody's mirrors."""+ rolled_out = Organization.objects.create(name="Rolled out")+ self._policy("feature_flag.enable")+ self._policy("feature_flag.enable", organization=rolled_out, team=None)++ with patch(+ "products.approvals.backend.experiment_policy_sync.scope_by_owner_state",+ side_effect=lambda organization: organization.id == rolled_out.id,+ ):+ sync_experiment_policies()++ assert ApprovalPolicy.objects.filter(organization=self.organization, action_key="experiment.launch").exists()+ assert not ApprovalPolicy.objects.filter(organization=rolled_out, action_key="experiment.launch").exists()diff --git a/products/approvals/backend/tests/test_owner_operation_decision_table.py b/products/approvals/backend/tests/test_owner_operation_decision_table.pyindex 61c9f08b6387..20a3496322b5 100644--- a/products/approvals/backend/tests/test_owner_operation_decision_table.py+++ b/products/approvals/backend/tests/test_owner_operation_decision_table.py@@ -7,9 +7,13 @@ checked rather than described.Phase 3 proved every entry point behaves alike, so this varies owner and operation over oneentry point (the flag API) instead of multiplying by entry point.-Read DECISION_TABLE as the current, pre-narrowing state: `feature_flag.*` covers every owner,-except that a release condition change is gated on an unowned flag only. Narrowing a family to an-owner changes cells here, and that diff is the coverage change.+There are two tables, because scoping policies by flag owner rolls out one organization at a+time. DECISION_TABLE is what an organization sees before it is rolled out, and+DECISION_TABLE_NARROWED is what it sees after. COVERAGE_CHANGE names every cell that differs,+so the coverage this change removes and the coverage it moves are asserted rather than described.++A release condition change already gates on an unowned flag only, so its column reads the same+in both tables."""from typing import Any, Optional@@ -29,7 +33,16 @@ from products.feature_flags.backend.ownership import flag_owner_kindfrom products.product_tours.backend.models import ProductTourfrom products.surveys.backend.models import Survey-GATED_ACTION_KEYS = ("feature_flag.enable", "feature_flag.disable", "feature_flag.update")+GATED_ACTION_KEYS = (+ "feature_flag.enable",+ "feature_flag.disable",+ "feature_flag.update",+ # The organization holds these as hidden mirrors of its flag policies before it is rolled+ # out, so both tables run against the same set of policies and only the scoping differs.+ "experiment.launch",+ "experiment.pause",+ "experiment.update",+)# A flag has no owner at the moment it is created, so the create column is not a function of# owner. It is covered once, under `standalone`, and marked NOT_APPLICABLE elsewhere.@@ -76,6 +89,9 @@ EXPECTED_OWNER_KIND: dict[str, Optional[str]] = {ENABLE = "feature_flag.enable"UPDATE = "feature_flag.update"DISABLE = "feature_flag.disable"+LAUNCH = "experiment.launch"+PAUSE = "experiment.pause"+EXP_UPD = "experiment.update"NA = NOT_APPLICABLE# The decision table. One row per owner, one column per operation, in the order OPERATIONS@@ -97,8 +113,49 @@ DECISION_TABLE: dict[str, dict[str, Optional[str]]] = {"early_access": _row(NA, UPDATE, UNGATED, ENABLE, DISABLE, REJECTED),"session_recording_reference": _row(NA, UPDATE, UPDATE, ENABLE, DISABLE, REJECTED),}++# The same table once the organization evaluates policies by flag owner.+#+# An experiment's flags move family: the `experiment.*` policies are one-for-one mirrors of the+# flag policies, so every cell that moves here stays gated and nobody loses an approval.+#+# A survey's, tour's or early access feature's flags become ungated. Surveys get a family of+# their own next; tours and early access are excluded by decision, not by omission.+#+# A create has no owner yet, so it does not move. A flag a product merely references is unowned,+# so it does not move either. The release condition column already gates on an unowned flag only,+# so it reads the same in both tables and contributes nothing to COVERAGE_CHANGE.+DECISION_TABLE_NARROWED: dict[str, dict[str, Optional[str]]] = {+ # create update release enable disable delete+ "standalone": _row(ENABLE, UPDATE, UPDATE, ENABLE, DISABLE, UNGATED),+ "experiment": _row(NA, EXP_UPD, UNGATED, LAUNCH, PAUSE, UNGATED),+ "survey_owned": _row(NA, UNGATED, UNGATED, UNGATED, UNGATED, UNGATED),+ "survey_linked": _row(NA, UPDATE, UPDATE, ENABLE, DISABLE, UNGATED),+ "tour_owned": _row(NA, UNGATED, UNGATED, UNGATED, UNGATED, UNGATED),+ "tour_linked": _row(NA, UPDATE, UPDATE, ENABLE, DISABLE, UNGATED),+ "early_access": _row(NA, UNGATED, UNGATED, UNGATED, UNGATED, REJECTED),+ "session_recording_reference": _row(NA, UPDATE, UPDATE, ENABLE, DISABLE, REJECTED),+}# fmt: on+# Every cell the rollout changes, as (owner, operation, before, after). A cell that moves to+# another family keeps its approval; a cell that becomes UNGATED loses it. Asserting the whole+# set means neither kind can be added or dropped without a reviewer seeing it here.+COVERAGE_CHANGE: set[tuple[str, str, Optional[str], Optional[str]]] = {+ ("experiment", "update_gated_field", UPDATE, EXP_UPD),+ ("experiment", "enable", ENABLE, LAUNCH),+ ("experiment", "disable", DISABLE, PAUSE),+ ("survey_owned", "update_gated_field", UPDATE, UNGATED),+ ("survey_owned", "enable", ENABLE, UNGATED),+ ("survey_owned", "disable", DISABLE, UNGATED),+ ("tour_owned", "update_gated_field", UPDATE, UNGATED),+ ("tour_owned", "enable", ENABLE, UNGATED),+ ("tour_owned", "disable", DISABLE, UNGATED),+ ("early_access", "update_gated_field", UPDATE, UNGATED),+ ("early_access", "enable", ENABLE, UNGATED),+ ("early_access", "disable", DISABLE, UNGATED),+}+CELLS = [(owner, operation) for owner in OWNERS for operation in OPERATIONS]@@ -170,24 +227,33 @@ class TestOwnerOperationDecisionTable(APIBaseTest):def _assert_operation_took_effect(self, operation: str, flag: Optional[FeatureFlag], expected: Optional[str]) -> None:- """An ungated cell must prove the write landed, or "no change request" means nothing."""- if operation == "update_release_condition":- assert flag is not None- properties = FeatureFlag.objects.get(id=flag.id).filters["groups"][0]["properties"]- landed = [prop["key"] for prop in properties] == [RELEASE_CONDITION["key"]]- assert landed is (expected is UNGATED), f"release edit landed={landed} but the table says {expected}"- return- if operation != "delete":+ """An ungated cell must prove the write landed, or "no change request" means nothing.++ A REJECTED cell also leaves no change request, so only the write landing tells the two apart.+ """+ if operation == "create_active":returnassert flag is not None- deleted = FeatureFlag.objects_including_soft_deleted.get(id=flag.id).deleted- # An ungated delete must land, or "no change request" would prove nothing. A REJECTED- # cell must not.- assert deleted is (expected is UNGATED), f"delete landed={deleted} but the table says {expected}"-- @parameterized.expand([(f"{owner}__{operation}", owner, operation) for owner, operation in CELLS])- def test_cell(self, _mock_enabled, _name: str, owner: str, operation: str) -> None:- expected = DECISION_TABLE[owner][operation]+ stored = FeatureFlag.objects_including_soft_deleted.get(id=flag.id)+ group = stored.filters["groups"][0]+ landed = {+ "update_gated_field": group["rollout_percentage"] == 100,+ "update_release_condition": [prop["key"] for prop in group["properties"]] == [RELEASE_CONDITION["key"]],+ "enable": stored.active is True,+ "disable": stored.active is False,+ "delete": stored.deleted,+ }[operation]+ assert landed is (expected is UNGATED), f"{operation} landed={landed} but the table says {expected}"++ @parameterized.expand(+ [+ (f"{owner}__{operation}__{'narrowed' if narrowed else 'wide'}", owner, operation, narrowed)+ for owner, operation in CELLS+ for narrowed in (False, True)+ ]+ )+ def test_cell(self, _mock_enabled, _name: str, owner: str, operation: str, narrowed: bool) -> None:+ expected = (DECISION_TABLE_NARROWED if narrowed else DECISION_TABLE)[owner][operation]if expected == NOT_APPLICABLE:self.skipTest("a flag has no owner at creation; the create column is covered under standalone")@@ -199,7 +265,8 @@ class TestOwnerOperationDecisionTable(APIBaseTest):flag.refresh_from_db()assert flag_owner_kind(flag) == EXPECTED_OWNER_KIND[owner]- self._perform(operation, flag)+ with patch("products.approvals.backend.ownership.scope_by_owner_enabled", return_value=narrowed):+ self._perform(operation, flag)self._assert_operation_took_effect(operation, flag, expected)keys = sorted(ChangeRequest.objects.filter(team=self.team).values_list("action_key", flat=True))@@ -207,3 +274,23 @@ class TestOwnerOperationDecisionTable(APIBaseTest):assert keys == [], f"{owner}/{operation} created {keys}, so it is gated after all"else:assert keys == [expected], f"{owner}/{operation} gated by {keys}, expected [{expected}]"++ def test_the_rollout_changes_exactly_the_cells_coverage_change_names(self, _mock_enabled) -> None:+ moved = {+ (owner, operation, DECISION_TABLE[owner][operation], DECISION_TABLE_NARROWED[owner][operation])+ for owner, operation in CELLS+ if DECISION_TABLE[owner][operation] != DECISION_TABLE_NARROWED[owner][operation]+ }+ assert moved == COVERAGE_CHANGE++ def test_narrowing_only_moves_an_experiment_between_families(self, _mock_enabled) -> None:+ """Every cell that keeps an approval is an experiment's, and every other one loses it.++ This is the claim the rollout rests on: the organizations being narrowed keep every+ experiment approval they have today, and what they lose is the coverage of the products+ that get a family later or none at all.+ """+ kept = {(owner, after) for owner, _, _, after in COVERAGE_CHANGE if after is not UNGATED}+ lost = {owner for owner, _, _, after in COVERAGE_CHANGE if after is UNGATED}+ assert {owner for owner, _ in kept} == {"experiment"}+ assert lost == {"survey_owned", "tour_owned", "early_access"}diff --git a/products/approvals/backend/tests/test_ownership.py b/products/approvals/backend/tests/test_ownership.pynew file mode 100644index 000000000000..390f431de033--- /dev/null+++ b/products/approvals/backend/tests/test_ownership.py@@ -0,0 +1,43 @@+from types import SimpleNamespace+from uuid import uuid4++from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase++from parameterized import parameterized++from products.approvals.backend.ownership import scope_by_owner_state+++class TestScopeByOwnerState(SimpleTestCase):+ @parameterized.expand(+ [+ ("remembers_the_rollout", [True, None], [True, True]),+ ("follows_a_rollback", [True, False, None], [True, False, False]),+ ("unknown_before_any_answer", [None], [None]),+ ]+ )+ def test_an_unanswered_read_returns_the_last_answer(+ self, _name: str, reads: list[bool | None], expected: list[bool | None]+ ) -> None:+ organization = SimpleNamespace(id=uuid4())++ with patch("products.approvals.backend.ownership.posthoganalytics.feature_enabled", side_effect=reads):+ assert [scope_by_owner_state(organization) for _ in reads] == expected++ def test_a_cache_failure_falls_back_to_the_flag_answer(self) -> None:+ organization = SimpleNamespace(id=uuid4())+ broken_cache = MagicMock()+ broken_cache.get.side_effect = ConnectionError("cache unavailable")+ broken_cache.set.side_effect = ConnectionError("cache unavailable")++ with (+ patch("products.approvals.backend.ownership.cache", broken_cache),+ patch("products.approvals.backend.ownership.capture_exception"),+ patch(+ "products.approvals.backend.ownership.posthoganalytics.feature_enabled",+ side_effect=[True, False, None],+ ),+ ):+ assert [scope_by_owner_state(organization) for _ in range(3)] == [True, False, None]diff --git a/products/approvals/backend/tests/test_policy_engine.py b/products/approvals/backend/tests/test_policy_engine.pyindex 37f426dd4307..3f94724affb8 100644--- a/products/approvals/backend/tests/test_policy_engine.py+++ b/products/approvals/backend/tests/test_policy_engine.py@@ -1,11 +1,13 @@from collections.abc import Sequencefrom posthog.test.base import APIBaseTest+from unittest.mock import patchfrom parameterized import parameterizedfrom posthog.models.organization import OrganizationMembership+from products.approvals.backend.actions.experiment_holdouts import UpdateExperimentHoldoutActionfrom products.approvals.backend.models import ApprovalPolicyfrom products.approvals.backend.policies import PolicyEngine@@ -378,3 +380,52 @@ class TestBypassRolesValidation(APIBaseTest):policy.set_bypass_roles([])assert policy.bypass_roles.count() == 0+++class TestHoldoutFallbackPolicySelection(APIBaseTest):+ """A holdout change is gated as one operation and borrows the policy that would gate its+ flag writes. Which policy that is depends on how far the organization has moved between+ families, and reading the wrong one answers from an hourly mirror instead of the live row.+ """++ def _policy(self, action_key: str) -> ApprovalPolicy:+ return ApprovalPolicy.objects.create(+ organization=self.organization,+ team=self.team,+ action_key=action_key,+ conditions={},+ approver_config={"quorum": 1, "users": [self.user.id]},+ created_by=self.user,+ )++ @parameterized.expand(+ [("before_handoff", False, "feature_flag.update"), ("after_handoff", True, "experiment.update")]+ )+ def test_the_borrowed_policy_follows_the_rollout(self, _name: str, scoped: bool, expected: str) -> None:+ self._policy("feature_flag.update")+ self._policy("experiment.update")++ with patch(+ "products.approvals.backend.actions.experiment_holdouts.scope_by_owner_enabled",+ return_value=scoped,+ ):+ policy = PolicyEngine().get_policy_for_action(UpdateExperimentHoldoutAction, self.team, self.organization)++ assert policy is not None+ assert policy.action_key == expected++ def test_the_mirror_is_not_borrowed_before_handoff(self) -> None:+ """Only the mirror exists, so the holdout change must find no policy rather than it.++ The mirror lags the flag policy by up to an hour, so honouring it here would keep a+ revoked bypass working until the next sync run.+ """+ self._policy("experiment.update")++ with patch(+ "products.approvals.backend.actions.experiment_holdouts.scope_by_owner_enabled",+ return_value=False,+ ):+ policy = PolicyEngine().get_policy_for_action(UpdateExperimentHoldoutAction, self.team, self.organization)++ assert policy is Nonediff --git a/products/approvals/backend/tests/test_scheduled_change_gating.py b/products/approvals/backend/tests/test_scheduled_change_gating.pyindex 557b7ade0474..336ad37138aa 100644--- a/products/approvals/backend/tests/test_scheduled_change_gating.py+++ b/products/approvals/backend/tests/test_scheduled_change_gating.py@@ -13,6 +13,7 @@ from posthog.tasks.process_scheduled_changes import process_scheduled_changesfrom products.approvals.backend.models import ApprovalPolicy, ChangeRequest, ChangeRequestState, ValidationStatusfrom products.approvals.backend.services import ChangeRequestService+from products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.models.scheduled_change import ScheduledChange@@ -72,21 +73,40 @@ class TestScheduledChangeGating(APIBaseTest):return gate_scheduled_change(flag, payload, self.user)- def test_scheduled_enable_under_policy_creates_pending_cr_and_does_not_apply(self, _mock_enabled):- self._enable_policy()- flag = self._disabled_flag()-- scheduled = self._schedule(- flag,- {"operation": "update_status", "value": True},- datetime.now(UTC) - timedelta(seconds=30),+ @parameterized.expand(+ [+ ("standalone_flag", False, False, "feature_flag.enable"),+ ("experiment_flag_after_rollout", True, True, "experiment.launch"),+ ]+ )+ def test_scheduled_enable_under_policy_creates_pending_cr_and_does_not_apply(+ self, _mock_enabled, _name: str, owned_by_experiment: bool, rolled_out: bool, action_key: str+ ):+ ApprovalPolicy.objects.create(+ organization=self.organization,+ team=self.team,+ action_key=action_key,+ conditions={},+ approver_config={"quorum": 1, "users": [self.user.id]},+ created_by=self.user,)+ flag = self._disabled_flag()+ if owned_by_experiment:+ Experiment.objects.create(team=self.team, name="Owner", feature_flag=flag)++ with patch("products.approvals.backend.ownership.scope_by_owner_state", return_value=rolled_out):+ scheduled = self._schedule(+ flag,+ {"operation": "update_status", "value": True},+ datetime.now(UTC) - timedelta(seconds=30),+ )- assert scheduled.change_request is not None- assert scheduled.change_request.state == ChangeRequestState.PENDING- assert ChangeRequest.objects.filter(state=ChangeRequestState.APPROVED).count() == 0+ assert scheduled.change_request is not None+ assert scheduled.change_request.action_key == action_key+ assert scheduled.change_request.state == ChangeRequestState.PENDING+ assert ChangeRequest.objects.filter(state=ChangeRequestState.APPROVED).count() == 0- process_scheduled_changes()+ process_scheduled_changes()flag.refresh_from_db()assert flag.active is Falsediff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex 9901a2196620..91709e8e8327 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -35,6 +35,7 @@ from posthog.api.cohort import ()from posthog.api.utils import ServiceRequestfrom posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.constants import AvailableFeaturefrom posthog.event_usage import EventSource, report_user_actionfrom posthog.exceptions import (ClickHouseEstimatedQueryExecutionTimeTooLong,@@ -51,6 +52,9 @@ from posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.utils import str_to_bool+from products.approvals.backend.actions.experiments import LaunchExperimentAction+from products.approvals.backend.ownership import scope_by_owner_enabled+from products.approvals.backend.policies import PolicyEnginefrom products.cohorts.backend.models.cohort import Cohortfrom products.experiments.backend.facade.contracts import ExperimentHealthFindingfrom products.experiments.backend.facade.launch_signals import experiment_launched@@ -1188,6 +1192,7 @@ class ExperimentService:)self.validate_saved_metrics_ids(saved_metrics_ids, self.team.id)is_draft = start_date is None+ self._reject_live_create_under_launch_policy(is_draft)feature_flag, used_variants = self._ensure_feature_flag(feature_flag_key=feature_flag_key,@@ -1542,6 +1547,40 @@ class ExperimentService:return feature_flag, variants or list(DEFAULT_VARIANTS)+ def _reject_live_create_under_launch_policy(self, is_draft: bool) -> None:+ """Refuse creating an already-running experiment when launching one needs approval.++ A create mints the flag before the experiment row exists, so the flag is unowned for that+ instant and `experiment.launch` cannot see it. Gating the create instead is not the+ answer: a change request replays a flag write, and there is no experiment yet for that+ write to belong to. So refuse, and point at the draft-then-launch route, where the launch+ is reviewed.++ Only reachable through the API. The experiment form sends no start date, so every+ experiment it creates is a draft.++ Existence of the policy decides, not evaluation of it, which mirrors the flag API's own+ refusal of a write it cannot send for approval. A caller who could bypass the launch+ approval is refused here too, because the create carries no intent to evaluate conditions+ or a bypass against, and refusing is the direction that cannot leak an unreviewed launch.+ """+ if is_draft:+ return+ organization = self.team.organization+ if not organization.is_feature_available(AvailableFeature.APPROVALS):+ # Without the feature the gate admits every flag write, so there is no review to protect.+ return+ if not scope_by_owner_enabled(organization):+ # The flag family still gates this create until the organization scopes policies by+ # flag owner, so there is nothing for this guard to add.+ return+ if PolicyEngine().get_policy_for_action(LaunchExperimentAction, self.team, organization) is None:+ return+ raise ValidationError(+ "Launching an experiment needs approval in this project. "+ "Create the experiment as a draft, then launch it to request approval."+ )+def _assert_flag_access(self,feature_flag: FeatureFlag | None = None,@@ -1935,7 +1974,7 @@ class ExperimentService:# A side-effect mutation can't be routed through the change-request flow (this runs# inside archive_experiment's transaction, so an ApprovalRequired would roll back the# just-created ChangeRequest) — refuse up front instead of letting the gate fire.- if flag_disable_requires_approval(self.team):+ if flag_disable_requires_approval(feature_flag.id, team=self.team):raise PermissionDenied("Disabling this feature flag requires approval. Disable it from the feature flag page ""to go through the approval flow, then archive the experiment."diff --git a/products/experiments/backend/test/test_experiment_service_approvals.py b/products/experiments/backend/test/test_experiment_service_approvals.pyindex 76d93f938ced..df972f1dca9d 100644--- a/products/experiments/backend/test/test_experiment_service_approvals.py+++ b/products/experiments/backend/test/test_experiment_service_approvals.py@@ -1,8 +1,10 @@+from datetime import UTC, datetimefrom typing import Anyfrom posthog.test.base import APIBaseTestfrom unittest.mock import patch+from parameterized import parameterizedfrom rest_framework.exceptions import ValidationErrorfrom rest_framework.test import APIRequestFactory@@ -239,3 +241,108 @@ class TestExperimentServiceApprovals(APIBaseTest):experiment.feature_flag.refresh_from_db()# The invalid payload must not have committed the flag's variant rewrite.assert experiment.feature_flag.filters["multivariate"]["variants"] == original_variants+++@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)+class TestCreatingALiveExperimentUnderALaunchPolicy(APIBaseTest):+ """A create that starts the experiment at once cannot be sent for approval.++ The flag is minted before the experiment row exists, so it is unowned at that instant and+ `experiment.launch` cannot see it. Only the API can reach this: the experiment form sends no+ start date, so everything it creates is a draft.+ """++ _METRIC = {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": "m1",+ "source": {"kind": "EventsNode", "event": "$pageview"},+ }++ def setUp(self):+ super().setUp()+ self.organization.available_product_features = [+ {"key": AvailableFeature.APPROVALS, "name": AvailableFeature.APPROVALS}+ ]+ self.organization.save()++ def _policy(self, action_key: str) -> ApprovalPolicy:+ return ApprovalPolicy.objects.create(+ organization=self.organization,+ team=self.team,+ action_key=action_key,+ conditions={},+ approver_config={"quorum": 1, "users": [self.user.id]},+ created_by=self.user,+ )++ def _create(self, key: str, start_date: Any = None) -> Experiment:+ return ExperimentService(team=self.team, user=self.user).create_experiment(+ name="Live create",+ feature_flag_key=key,+ metrics=[self._METRIC],+ primary_metrics_ordered_uuids=["m1"],+ allow_unknown_events=True,+ start_date=start_date,+ )++ def _scoped_by_owner(self, enabled: bool):+ return patch(+ "products.experiments.backend.experiment_service.scope_by_owner_enabled",+ return_value=enabled,+ )++ def test_a_live_create_is_refused(self, _mock_enabled) -> None:+ self._policy("experiment.launch")++ with self._scoped_by_owner(True), self.assertRaises(ValidationError) as caught:+ self._create("live-flag", start_date=datetime(2026, 1, 1, tzinfo=UTC))++ assert "draft" in str(caught.exception)+ assert not Experiment.objects.filter(team=self.team).exists()+ assert not ChangeRequest.objects.filter(team=self.team).exists()++ def test_a_draft_create_is_allowed(self, _mock_enabled) -> None:+ """The route the refusal points at has to work, or the message sends nobody anywhere."""+ self._policy("experiment.launch")++ with self._scoped_by_owner(True):+ experiment = self._create("draft-flag")++ assert experiment.is_draft+ assert experiment.feature_flag is not None+ assert experiment.feature_flag.active is False++ @parameterized.expand(+ [+ ("no_launch_policy", False, True),+ ("approvals_not_available", True, False),+ ]+ )+ def test_a_live_create_is_allowed_when_launching_needs_no_approval(+ self, _mock_enabled, _name: str, launch_policy: bool, approvals_available: bool+ ) -> None:+ if launch_policy:+ self._policy("experiment.launch")+ if not approvals_available:+ self.organization.available_product_features = []+ self.organization.save()++ with self._scoped_by_owner(True):+ experiment = self._create("live-ungated", start_date=datetime(2026, 1, 1, tzinfo=UTC))++ assert not experiment.is_draft+ assert experiment.feature_flag is not None+ assert experiment.feature_flag.active is True++ def test_a_live_create_still_reaches_the_flag_policy_before_rollout(self, _mock_enabled) -> None:+ """Before the organization scopes by flag owner the flag family gates the create.++ The guard must not pre-empt that, or an organization would get a refusal where it used to+ get a change request it could approve.+ """+ self._policy("experiment.launch")+ self._policy("feature_flag.enable")++ with self._scoped_by_owner(False), self.assertRaises(ApprovalRequired):+ self._create("pre-rollout-flag", start_date=datetime(2026, 1, 1, tzinfo=UTC))diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 7882ffac178b..a8d3233f3759 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -97,6 +97,7 @@ from products.access_control.backend.presentation.access_control import (from products.approvals.backend.decorators import approval_gatefrom products.approvals.backend.mixins import ApprovalHandlingMixinfrom products.approvals.backend.models import ApprovalPolicy+from products.approvals.backend.ownership import scope_by_owner_enabledfrom products.approvals.backend.policies import lock_approval_policiesfrom products.cohorts.backend.models.cohort import Cohort, CohortTypefrom products.cohorts.backend.models.util import get_all_cohort_dependencies@@ -318,6 +319,15 @@ V2_SAFETY_FIELDS = frozenset({"version", "active", "deleted"})V2_UPDATE_FIELDS = V2_SAFETY_FIELDS | {"filters", "name", "key", "tags"}V2_CREATE_FIELDS = V2_UPDATE_FIELDS - {"deleted"}V2_APPROVAL_ACTIONS = ("feature_flag.enable", "feature_flag.disable", "feature_flag.update")+# Every family that can gate a flag write. The gate offers all of them and the product that+# owns the flag decides which one evaluates, so an experiment's flag is governed wherever it is+# edited rather than only through the experiment endpoints. See approvals' `ownership` module.+FLAG_WRITE_APPROVAL_ACTIONS = (+ *V2_APPROVAL_ACTIONS,+ "experiment.launch",+ "experiment.pause",+ "experiment.update",+)_MISSING: Any = object()@@ -2006,9 +2016,11 @@ class FeatureFlagSerializer(# Deliberately broader than the gate's own detect(): any enabled flag-write policy on# this team or its organization denies the write, because a v2 change that needs# approval has nowhere to go. Existence only, so PolicyEngine's precedence is irrelevant.+ # Before rollout the experiment policies are unenforced copies, so they deny nothing.+ action_keys = FLAG_WRITE_APPROVAL_ACTIONS if scope_by_owner_enabled(team.organization) else V2_APPROVAL_ACTIONSif (ApprovalPolicy.objects.enabled()- .filter(organization_id=team.organization_id, action_key__in=V2_APPROVAL_ACTIONS)+ .filter(organization_id=team.organization_id, action_key__in=action_keys).filter(Q(team=team) | Q(team__isnull=True)).exists()):@@ -2687,7 +2699,7 @@ class FeatureFlagSerializer(return instance- @approval_gate(list(V2_APPROVAL_ACTIONS))+ @approval_gate(list(FLAG_WRITE_APPROVAL_ACTIONS))def update(self, instance: FeatureFlag, validated_data: dict, *args: Any, **kwargs: Any) -> FeatureFlag:request = self.context["request"]# Service-layer callers may carry no body, and an endpoint that declares no request schemadiff --git a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.pyindex 50330cfbe581..eb6514511807 100644--- a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py+++ b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py@@ -681,7 +681,22 @@ class TestV2AdmissionBoundary(AdmittedV2TestCase):flag.refresh_from_db()assert flag.version == 3- def test_an_enabled_approval_policy_denies_the_update(self) -> None:+ @parameterized.expand(+ [+ ("flag_policy", "feature_flag.update", False, True),+ # An organization that scopes policies by flag owner governs an experiment's flags+ # through its experiment policy. A config version 2 write has nowhere to send an+ # approval, so that policy has to deny it too, or the one family this organization+ # relies on would be the one a v2 write could walk past.+ ("experiment_policy", "experiment.update", True, True),+ # Before rollout an experiment policy is an unenforced copy of a flag policy, and it+ # outlives a deleted flag policy until the next sync.+ ("experiment_copy_before_rollout", "experiment.update", False, False),+ ]+ )+ def test_an_enabled_approval_policy_denies_the_update(+ self, _name: str, action_key: str, rolled_out: bool, denied: bool+ ) -> None:self.organization.available_product_features = [{"key": AvailableFeature.APPROVALS, "name": AvailableFeature.APPROVALS}]@@ -689,12 +704,16 @@ class TestV2AdmissionBoundary(AdmittedV2TestCase):ApprovalPolicy.objects.create(organization=self.organization,team=self.team,- action_key="feature_flag.update",+ action_key=action_key,approver_config={"quorum": 1, "users": [self.user.id]},enabled=True,)flag = self.flag()- response = self.patch_flag(flag, {"version": 3, "filters": config(targeted())})+ with patch("products.approvals.backend.ownership.scope_by_owner_state", return_value=rolled_out):+ response = self.patch_flag(flag, {"version": 3, "filters": config(targeted())})+ if not denied:+ assert response.status_code == status.HTTP_200_OK, response.json()+ returnassert response.status_code == status.HTTP_400_BAD_REQUESTassert response.json()["code"] == "unsupported_config_version"flag.refresh_from_db()diff --git a/products/feature_flags/backend/facade/api.py b/products/feature_flags/backend/facade/api.pyindex 20e9e6743911..a525f39558da 100644--- a/products/feature_flags/backend/facade/api.py+++ b/products/feature_flags/backend/facade/api.py@@ -38,7 +38,7 @@ from posthog.models.team.team import Teamfrom posthog.models.user import Userfrom products.access_control.backend.facade.user_access_control import UserAccessControl-from products.approvals.backend.policies import PolicyEngine+from products.approvals.backend.coverage import write_needs_approvalfrom products.feature_flags.backend.api.feature_flag import (FeatureFlagSerializer,validate_stored_cohort_references as _validate_stored_cohort_references,@@ -47,6 +47,7 @@ from products.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLfrom products.feature_flags.backend.facade.config import detect_config_formatfrom products.feature_flags.backend.facade.filters import set_feature_enrollmentfrom products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.ownership import flag_owner_kindfrom products.feature_flags.backend.request_usage import (FeatureFlagRequestType as FeatureFlagRequestType,FeatureFlagRequestUsage as FeatureFlagRequestUsage,@@ -388,10 +389,14 @@ def user_can_create_flags(*, team: Team, user: User) -> bool:return UserAccessControl(user=user, team=team).check_access_level_for_resource("feature_flag", "editor")-def flag_disable_requires_approval(team: Team) -> bool:- """Whether an enabled approval policy gates disabling a flag for this team/org."""- policy = PolicyEngine().get_policy(action_key="feature_flag.disable", team=team, organization=team.organization)- return policy is not None+def flag_disable_requires_approval(flag_id: int, *, team: Team) -> bool:+ """Whether an enabled approval policy gates disabling this flag.++ Reads the policy of the family that governs the flag, which follows its owner once the+ organization scopes policies by flag owner.+ """+ flag = FeatureFlag.objects_including_soft_deleted.get(pk=flag_id, team=team)+ return write_needs_approval(flag_owner_kind(flag), "disable", team, team.organization)def serialize_flags(flags: Any, *, context: dict) -> Any:diff --git a/products/feature_flags/backend/ownership.py b/products/feature_flags/backend/ownership.pyindex 021e9d893890..c7a0db8c1287 100644--- a/products/feature_flags/backend/ownership.py+++ b/products/feature_flags/backend/ownership.py@@ -1,7 +1,11 @@-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Optional, cast++from django.db.models import Case, CharField, Count, Exists, Model, OuterRef, QuerySet, Value, When+from django.db.models.fields.reverse_related import ForeignObjectRelfrom rest_framework import serializers+from products.approvals.backend.coverage import adoption_drops_approval_cover, adoption_skips_enable_reviewfrom products.feature_flags.backend.facade.config import detect_config_formatif TYPE_CHECKING:@@ -80,6 +84,11 @@ def assert_flag_available_for(flag: "FeatureFlag", *, product: str) -> None:parent that already owns the flag must not raise, so the caller compares the incoming idagainst the stored one first.+ Reject it too when the adoption would leave the flag less governed by approval policies, or+ would skip the review the product gives to turning a flag on. Which policies cover a flag+ follows its owner, so either is a way around a policy rather than a routine edit. See+ approvals' `coverage` module for when this applies.+This reads before the caller writes, so two products adopting the same free flag at the samemoment can both pass. No database constraint can span the four owning tables, so the remainingwindow is accepted rather than locked.@@ -98,3 +107,52 @@ def assert_flag_available_for(flag: "FeatureFlag", *, product: str) -> None:f"The feature flag {flag.key} already belongs to {_OWNER_LABELS[owner]}. "f"Pick a different flag, or edit this one where it is already used.")+ if adoption_drops_approval_cover(owner, product, flag.team, flag.team.organization):+ raise serializers.ValidationError(+ f"Changes to the feature flag {flag.key} need approval, and {_OWNER_LABELS[product]} "+ f"cannot keep that. Pick a different flag, or make a new one."+ )+ if adoption_skips_enable_review(flag.active, owner, product, flag.team, flag.team.organization):+ raise serializers.ValidationError(+ f"The feature flag {flag.key} is already on, and turning it on for {_OWNER_LABELS[product]} "+ f"needs approval. Turn the flag off first, or make a new one."+ )+++def _owning_conditions(model: type[Model]) -> list[tuple[str, Exists]]:+ """One EXISTS per owning relation, in the order `flag_owner_kind` checks them.++ Built from `_OWNING_ACCESSORS` rather than written out, so a relation cannot be classified in+ one place and missed in the other. The manager matters for the same reason it does there: an+ archived product tour still holds its flag.+ """+ relations = {+ relation.get_accessor_name(): relation+ for relation in model._meta.get_fields()+ if isinstance(relation, ForeignObjectRel)+ }+ conditions = []+ for accessor, kind, manager in _OWNING_ACCESSORS:+ relation = relations[accessor]+ # Every accessor in `_OWNING_ACCESSORS` names a concrete reverse relation, so the related+ # model is a model class rather than the "self" sentinel the field type allows.+ related_model = cast(type[Model], relation.related_model)+ objects = getattr(related_model, manager) if manager else related_model._default_manager+ conditions.append((kind, Exists(objects.filter(**{relation.field.name: OuterRef("pk")}))))+ return conditions+++def owner_kind_counts(flags: "QuerySet[FeatureFlag]") -> dict[Optional[str], int]:+ """Count the flags in a queryset by the product that owns each one.++ The same classification and the same precedence as `flag_owner_kind`, as one query, because+ the populations worth counting are too large to classify row by row. A flag no product owns+ counts under None, exactly as that function reports it.+ """+ whens = [When(condition, then=Value(kind)) for kind, condition in _owning_conditions(flags.model)]+ rows = (+ flags.annotate(owner_kind=Case(*whens, default=Value(None, output_field=CharField())))+ .values("owner_kind")+ .annotate(total=Count("id"))+ )+ return {row["owner_kind"]: row["total"] for row in rows}diff --git a/products/feature_flags/backend/test/test_facade.py b/products/feature_flags/backend/test/test_facade.pyindex 10754d1461f1..2833e8f0b98c 100644--- a/products/feature_flags/backend/test/test_facade.py+++ b/products/feature_flags/backend/test/test_facade.py@@ -15,6 +15,7 @@ from posthog.models.activity_logging.activity_log import ActivityLogfrom products.approvals.backend.exceptions import ApprovalRequiredfrom products.approvals.backend.models import ApprovalPolicy, ChangeRequest+from products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUE, flag_payload_codecfrom products.feature_flags.backend.facade.api import (_redact_unchanged_encrypted_payloads,@@ -79,18 +80,33 @@ class TestFeatureFlagFacadeGatedWrites(APIBaseTest):assert flag.archived is Trueassert flag.active is False- def test_flag_disable_requires_approval_reflects_policy(self):- assert flag_disable_requires_approval(self.team) is False+ @parameterized.expand(+ [+ ("no_policy", False, False, None, False),+ ("flag_policy_on_a_standalone_flag", False, False, "feature_flag.disable", True),+ ("flag_policy_on_an_experiment_flag_before_scoping", True, False, "feature_flag.disable", True),+ ("pause_policy_on_an_experiment_flag_after_scoping", True, True, "experiment.pause", True),+ ("flag_policy_on_an_experiment_flag_after_scoping", True, True, "feature_flag.disable", False),+ ]+ )+ def test_flag_disable_requires_approval_reads_the_governing_policy(+ self, _name: str, owned_by_experiment: bool, scoped_by_owner: bool, action_key: str | None, expected: bool+ ) -> None:+ flag = self._create_flag(active=True)+ if owned_by_experiment:+ Experiment.objects.create(team=self.team, name="Owner", feature_flag=flag)+ if action_key is not None:+ ApprovalPolicy.objects.create(+ organization=self.organization,+ team=self.team,+ action_key=action_key,+ conditions={},+ approver_config={"quorum": 1, "users": [self.user.id]},+ created_by=self.user,+ )- ApprovalPolicy.objects.create(- organization=self.organization,- team=self.team,- action_key="feature_flag.disable",- conditions={},- approver_config={"quorum": 1, "users": [self.user.id]},- created_by=self.user,- )- assert flag_disable_requires_approval(self.team) is True+ with patch("products.approvals.backend.coverage.scope_by_owner_enabled", return_value=scoped_by_owner):+ assert flag_disable_requires_approval(flag.id, team=self.team) is expecteddef test_archive_active_flag_without_disable_is_rejected(self):flag = self._create_flag(active=True)diff --git a/products/feature_flags/backend/test/test_ownership.py b/products/feature_flags/backend/test/test_ownership.pyindex 38ad791ce358..b4b5c91e7f9c 100644--- a/products/feature_flags/backend/test/test_ownership.py+++ b/products/feature_flags/backend/test/test_ownership.py@@ -6,7 +6,12 @@ from rest_framework import serializersfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlag-from products.feature_flags.backend.ownership import FLAG_OWNER_SURVEY, assert_flag_available_for, flag_owner_kind+from products.feature_flags.backend.ownership import (+ FLAG_OWNER_SURVEY,+ assert_flag_available_for,+ flag_owner_kind,+ owner_kind_counts,+)from products.product_tours.backend.models import ProductTourfrom products.surveys.backend.models import Survey@@ -62,6 +67,7 @@ class TestFlagOwnership(APIBaseTest):getattr(self, setup)(flag)assert flag_owner_kind(flag) == expected+ assert owner_kind_counts(FeatureFlag.objects.filter(id=flag.id)) == {expected: 1}def test_guard_rejects_a_flag_a_different_product_owns(self) -> None:flag = self._flag("taken")