: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
"""Feature flag facade: gated flag writes and read helpers for other products.
Every write routes through ``FeatureFlagSerializer`` — the only path that honors
``@approval_gate``, validation, and activity logging. Consumers (currently experiments)
call these functions instead of driving the serializer and its DRF context by hand.
``clear_feature_enrollment`` falls back to a raw model write when the serializer rejects
a flag's stored config version 1 filters, because enrollment cleanup must never fail.
The read helpers (``user_can_edit_flag``, ``user_can_create_flags``, ``flag_disable_requires_approval``,
``serialize_flags``, ``get_feature_flag_request_usage``) expose the flag API's
access-control, approval-policy, representation, and request-usage logic behind
the same boundary.
Writes do not enforce access control — that lives at the viewset layer. A caller
acting on behalf of an end user must pre-check ``user_can_edit_flag`` before writing an
existing flag, and ``user_can_create_flags`` before creating one.
Approval-gate ordering constraint for callers: a gated write can raise ``ApprovalRequired``
(surfacing as a 409 + change_request_id), which conflicts with ``transaction.atomic`` — the
exception propagating out of an atomic block would roll back the just-created pending
ChangeRequest. Run gated writes before/outside any transaction wrapping your own state.
System writes: callers with no acting user (beat tasks, service code reacting to
lifecycle events) pass ``user=None``. The write still routes through the serializer
(validation, caches, activity logging — attributed as ``is_system``), but the approval
gate does not engage: the request shim explicitly declares ``is_system=True``, the only
signal the gate skips on (its policies target human-driven changes, and a request-less
caller cannot surface a 409/change request), so ``ApprovalRequired`` is never raised.
"""
from datetime import datetime
from typing import Any, Literal
import structlog
from rest_framework.exceptions import ValidationError
from posthog.api.utils import ServiceRequest
from posthog.models.team.team import Team
from posthog.models.user import User
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.approvals.backend.coverage import write_needs_approval
from products.feature_flags.backend.api.feature_flag import (
FeatureFlagSerializer,
validate_stored_cohort_references as _validate_stored_cohort_references,
)
from products.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUE
from products.feature_flags.backend.facade.config import detect_config_format
from products.feature_flags.backend.facade.filters import set_feature_enrollment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.feature_flags.backend.ownership import MINTED_OWNER_CONTEXT_KEY, flag_owner_kind
from products.feature_flags.backend.request_usage import (
FeatureFlagRequestType as FeatureFlagRequestType,
FeatureFlagRequestUsage as FeatureFlagRequestUsage,
query_feature_flag_request_usage,
)
logger = structlog.get_logger(__name__)
def _serializer_context(team: Team, user: Any, request: Any | None, *, method: str = "POST") -> dict:
"""Build the DRF serializer context for a gated flag write.
Callers without a real request (internal service paths) fall back to a minimal
request shim carrying the acting user — FeatureFlagSerializer needs request.user.
``user=None`` makes this a system write (see module docstring); the shim declares
it explicitly via ``is_system``, the only signal the approval gate skips on.
``method`` is the HTTP method the shim reports — the serializer branches on it
(create-only validation runs on "POST"), so updates must pass "PATCH". Supplied
``ServiceRequest`` shims are rebuilt with it; real HTTP requests pass through
untouched.
Pass BOTH get_team and get_organization so the approval gate resolves the policy
from context rather than falling back to instance derivation.
"""
request_has_user = getattr(request, "user", None) is not None
# A user-bearing request would silently override user=None (gate engages, attribution
# goes to request.user) — reject the contradiction instead.
if user is None and request_has_user:
raise ValueError("user=None is a system write; do not pass a user-bearing request with it")
if isinstance(request, ServiceRequest):
# Caller-built shims default to POST — align the method with this write.
request.method = method
flag_request = request if request_has_user else ServiceRequest(user, is_system=user is None, method=method)
return {
"request": flag_request,
"team_id": team.id,
"project_id": team.project_id,
"get_team": lambda: team,
"get_organization": lambda: team.organization,
}
def create_flag(
data: dict,
*,
team: Team,
user: Any,
request: Any | None = None,
serializer_context: dict | None = None,
owner: Literal["survey"] | None = None,
) -> FeatureFlag:
"""Gated create: routes through FeatureFlagSerializer so @approval_gate, validation,
and activity logging apply. ``data`` is the flag's own write shape (key, name, filters,
active, ...) and is applied as-is — nothing is silently dropped. Raises ApprovalRequired
when a policy requires approval. ``user=None`` is a system write (see module docstring):
``created_by`` stays null, activity is logged as system, the approval gate is skipped.
``serializer_context`` is extra serializer context (an HTTP caller passes its viewset
context); the facade's own ``request``, ``team_id``, ``project_id``, ``get_team`` and
``get_organization`` entries win over the caller's. ``owner`` names the product that will own
the new flag, so the approval gate applies that product's policies to the create instead of the
policies for flags no product owns. Pass it only when the caller links the flag to its own row
in the same transaction."""
context = {**(serializer_context or {}), **_serializer_context(team, user, request)}
context[MINTED_OWNER_CONTEXT_KEY] = owner
serializer = FeatureFlagSerializer(data=data, context=context)
serializer.is_valid(raise_exception=True)
return serializer.save()
def _redact_unchanged_encrypted_payloads(flag: FeatureFlag, data: dict) -> dict:
"""Facade callers derive update filters from ``flag.get_filters()``, which stores
encrypted payload values as ciphertext. Ciphertext echoed back through the serializer
fails its JSON payload validation (and must never be re-encrypted), so values
byte-identical to the stored ones are swapped for the redacted placeholder, which the
serializer preserves. Genuinely new payload values pass through and are encrypted."""
if not isinstance(data, dict) or detect_config_format(flag.filters).kind != "v1":
return data
filters = data.get("filters")
if not flag.has_encrypted_payloads or not isinstance(filters, dict):
return data
stored = (flag.filters or {}).get("payloads") or {}
incoming = filters.get("payloads")
if not isinstance(incoming, dict):
return data
redacted = {k: REDACTED_PAYLOAD_VALUE if k in stored and v == stored[k] else v for k, v in incoming.items()}
if redacted == incoming:
return data
return {**data, "filters": {**filters, "payloads": redacted}}
def update_flag(
flag: FeatureFlag,
data: dict,
*,
team: Team,
user: Any,
request: Any | None = None,
partial: bool = True,
serializer_context: dict | None = None,
) -> FeatureFlag:
"""Gated update: routes through FeatureFlagSerializer so @approval_gate,
validation, and activity logging apply. ``data`` is a flag write payload applied
as-is — nothing is silently dropped. Raises ApprovalRequired when a policy requires
approval; the flag is left untouched. ``user=None`` is a system write (see module
docstring): ``last_modified_by`` is cleared, activity is logged as system, the
approval gate is skipped.
``partial=True`` (the default) leaves omitted fields untouched; ``partial=False`` is
the PUT shape, where the serializer enforces its required fields. ``serializer_context``
is extra serializer context (an HTTP caller passes its viewset context); the facade's own
``request``, ``team_id``, ``project_id``, ``get_team`` and ``get_organization`` entries
win over the caller's.
Encrypted payload values carried over unchanged from ``flag.get_filters()`` are
preserved as-is, never re-validated or re-encrypted."""
data = _redact_unchanged_encrypted_payloads(flag, data)
context = {**(serializer_context or {}), **_serializer_context(team, user, request, method="PATCH")}
serializer = FeatureFlagSerializer(flag, data=data, partial=partial, context=context)
serializer.is_valid(raise_exception=True)
saved = serializer.save()
if saved.has_encrypted_payloads:
# The serializer swaps the saved ciphertext for its response form (redacted or
# decrypted) on the in-memory instance; reload so a subsequent write of this
# instance cannot persist the placeholder over the stored ciphertext.
saved.refresh_from_db(fields=["filters"])
return saved
def set_flag_active(
flag: FeatureFlag, active: bool, *, team: Team, user: Any, request: Any | None = None
) -> FeatureFlag:
"""Flip a flag's active state THROUGH the approval gate.
Routing the flip through FeatureFlagSerializer.update() honours the
@approval_gate so the feature_flag.enable/disable policies apply. Raises
ApprovalRequired (which surfaces as a 409 + change_request_id) when a
policy requires approval; in that case the flag is left untouched.
The gate's detect()/extract_intent() read the serializer's validated_data
(the actual change being saved), so an incoming HTTP request that triggered
the flip is passed straight through — no synthetic PATCH request is needed.
"""
return update_flag(flag, {"active": active}, team=team, user=user, request=request)
def archive_flag(
flag: FeatureFlag,
*,
team: Team,
user: Any,
request: Any | None = None,
disable_if_active: bool = False,
) -> FeatureFlag:
"""Archive a flag through the gated serializer path.
An archived flag must be disabled (the serializer enforces it); pass
``disable_if_active`` to disable an active flag in the same write. Disabling
applies the dependents guard (``raise_if_flag_has_dependents``) inside the
serializer, and trips the feature_flag.disable approval policy if one is
enabled — check ``flag_disable_requires_approval`` first when the caller
cannot surface a change request.
"""
data: dict[str, Any] = {"archived": True}
if disable_if_active and flag.active:
data["active"] = False
return update_flag(flag, data, team=team, user=user, request=request)
def unarchive_flag(flag: FeatureFlag, *, team: Team, user: Any, request: Any | None = None) -> FeatureFlag:
"""Unarchive a flag through the gated serializer path.
The flag stays disabled; re-enabling it is a separate, explicit write
(``set_flag_active``). Raises ``ValidationError`` when a release condition targets a
deleted cohort.
"""
return update_flag(flag, {"archived": False}, team=team, user=user, request=request)
def validate_flag_restorable(flag_id: int, *, team_id: int) -> None:
"""Raise ``ValidationError`` when a release condition targets a missing or deleted cohort.
A restored flag with such a condition fails every evaluation that reaches it. ``update_flag`` runs this
check on a restore. A caller that restores a flag another way must run it first. A
hard-deleted id or another team's flag has nothing to check.
"""
flag = FeatureFlag.objects_including_soft_deleted.filter(pk=flag_id, team_id=team_id).first()
if flag is not None:
_validate_stored_cohort_references(flag)
def clear_feature_enrollment(flag_id: int, *, team: Team) -> None:
"""Clear the enrollment marker on an early access feature's linked flag (feature demoted or deleted).
Cleanup must never fail: a linked flag can hold stored filter shapes the current
FeatureFlagSerializer rejects or crashes on (group-aggregated conditions, malformed
legacy properties, ...), and a rejection here would make the feature undeletable.
Prefer the gated facade write (validation, activity logging); fall back to a raw
model write when it raises. This is a system write (user=None): an enabled approval
policy must never block cleanup with a 409, and activity is logged as system.
Another config format raises ``ConfigFormatError`` from ``set_feature_enrollment`` before
either write. No caller reaches it: an early access feature only links config version 1 flags.
The early return covers a hard-deleted id or another team's flag, so nothing is left to
clear. A soft-deleted flag still gets cleared, through ``objects_including_soft_deleted``:
the default manager hides it, and skipping it would leave the marker to come back with the
flag on a restore.
"""
flag = FeatureFlag.objects_including_soft_deleted.filter(pk=flag_id, team=team).first()
if flag is None:
return
cleared_filters = set_feature_enrollment(flag.get_filters() or {}, None)
# Without "groups", the serializer's partial-PATCH shortcut discards the incoming
# filters and returns the stored ones — silently skipping the cleanup entirely.
if "groups" in cleared_filters:
try:
update_flag(flag, {"filters": cleared_filters}, team=team, user=None)
return
except Exception as exc:
# Stored legacy JSON can raise arbitrary exception types through the flag
# validator (ValidationError, TypeError, KeyError, ...), so catch broadly.
logger.warning(
"early_access_feature_enrollment_cleanup_fell_back_to_raw_write",
feature_flag_id=flag.id,
error=str(exc),
)
flag.filters = cleared_filters # nosemgrep: feature-flags-no-raw-filters-access -- deliberate never-fail cleanup fallback when the gated write can't validate stored legacy filter shapes
flag.save(update_fields=["filters"])
def _roll_out_variant(
current_filters: dict,
variant_key: str,
*,
release_to_everyone: bool = False,
release_condition_description: str | None = None,
) -> dict:
"""Rewrite flag filters so the selected variant gets 100% of the variant distribution.
When ``release_to_everyone`` is False (default), existing release conditions on
the flag are preserved untouched: the variant is served only to users who
already match them, and any per-user variant overrides keep applying.
When ``release_to_everyone`` is True, a catch-all release condition is prepended
that rolls the variant out to 100% of users — note that under top-down
first-match evaluation this overrides any existing release conditions and
per-user variant overrides below it. ``release_condition_description`` is set as
the description of that catch-all condition, so callers can say why it was added;
it has no effect unless ``release_to_everyone`` is True.
"""
groups = list(current_filters.get("groups", []))
if release_to_everyone:
catch_all: dict[str, Any] = {"properties": [], "rollout_percentage": 100}
if release_condition_description is not None:
catch_all["description"] = release_condition_description
groups = [catch_all, *groups]
new_filters = {
"aggregation_group_type_index": current_filters.get("aggregation_group_type_index"),
"payloads": current_filters.get("payloads", {}),
"multivariate": {
"variants": [
{
"key": v["key"],
"rollout_percentage": 100 if v["key"] == variant_key else 0,
**({"name": v["name"]} if v.get("name") else {}),
}
for v in current_filters.get("multivariate", {}).get("variants", [])
],
},
"groups": groups,
}
# A holdout must keep excluding its users after the winner ships — that is its
# entire purpose (measuring shipped features against an unexposed baseline).
if current_filters.get("holdout"):
new_filters["holdout"] = current_filters["holdout"]
return new_filters
def ship_variant(
flag: FeatureFlag,
variant_key: str,
*,
team: Team,
user: Any,
request: Any | None = None,
release_to_everyone: bool = False,
release_condition_description: str | None = None,
base_filters: dict | None = None,
) -> FeatureFlag:
"""Roll ``variant_key`` out at 100% of the flag's variant distribution, through the gated write.
By default (``release_to_everyone=False``) existing release conditions on the flag
are preserved untouched — the variant is served only to users who already match
them. Pass ``release_to_everyone=True`` to also prepend a catch-all release
condition that rolls the variant out to 100% of users (overrides any existing
release conditions and per-user variant overrides), with
``release_condition_description`` as its description — that parameter has no
effect unless ``release_to_everyone`` is True.
``base_filters`` lets a caller fold companion adjustments it already computed from
the flag's current filters into the same gated write; defaults to the flag's
current filters. ``variant_key`` is validated against ``base_filters`` (not
``flag.filters``), so its ``multivariate.variants`` must match the flag's own.
The parameter is transitional: it exists so the experiments-side freeze-strip
folds into a single gated write, and goes away once that strip moves flag-side.
Raises ValidationError when the variant doesn't exist on the flag, and
ApprovalRequired when a policy gates the write — the flag is left untouched
in both cases.
"""
filters = base_filters if base_filters is not None else (flag.filters or {})
# Validate variant_key exists on the flag
variants = filters.get("multivariate", {}).get("variants", [])
if not any(v["key"] == variant_key for v in variants):
raise ValidationError(f"Variant '{variant_key}' not found on feature flag.")
new_filters = _roll_out_variant(
filters,
variant_key,
release_to_everyone=release_to_everyone,
release_condition_description=release_condition_description,
)
return update_flag(flag, {"filters": new_filters}, team=team, user=user, request=request)
def user_can_edit_flag(flag: FeatureFlag, *, team: Team, user: Any) -> bool:
"""Whether ``user`` has editor access to this flag — the same check the feature flag API enforces."""
if not isinstance(user, User) or user.is_anonymous:
return False
return UserAccessControl(user=user, team=team).check_access_level_for_object(flag, "editor")
def user_can_create_flags(*, team: Team, user: User) -> bool:
"""Whether ``user`` may create a flag in this team — the resource-level counterpart of
``user_can_edit_flag``, and the same check the feature flag API enforces on create.
A product that creates a flag as a side effect of its own write needs this, because the
write goes through ``create_flag``, which enforces no access control. Without it, editor
access to that product substitutes for flag access. Unlike ``user_can_edit_flag`` this takes
a real ``User``, so a caller holding an unknown principal narrows it before asking."""
return UserAccessControl(user=user, team=team).check_access_level_for_resource("feature_flag", "editor")
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:
"""The flag API's full list representation for the given flags.
``context`` is the caller's DRF serializer context (a viewset's
``get_serializer_context()``): the representation includes request- and
access-control-derived fields, so it can only be built for a real request.
"""
return FeatureFlagSerializer(flags, many=True, context=context).data
def get_feature_flag_request_usage(
*, team_id: int, date_from: datetime, date_to: datetime, time_interval: Literal["hour", "day"]
) -> list[FeatureFlagRequestUsage]:
return query_feature_flag_request_usage(
team_id=team_id, date_from=date_from, date_to=date_to, time_interval=time_interval
)
def flag_is_active(key: str, *, team_id: int | None = None) -> bool:
"""Whether an active flag with this key exists, optionally narrowed to one team.
A direct row read, not an evaluation: it ignores rollout percentages and release
conditions. Callers use it as a local-development fallback for when the analytics SDK
is disabled and ``posthoganalytics.feature_enabled`` cannot answer.
"""
qs = FeatureFlag.objects.filter(key=key, active=True)
if team_id is not None:
qs = qs.filter(team_id=team_id)
return qs.exists()