Skip to content

: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.

feat(devex): add django-free labeled enums for facade contract files (#108465)

Julian Beze531eb323f89
diff --git a/.agents/skills/improving-drf-endpoints/SKILL.md b/.agents/skills/improving-drf-endpoints/SKILL.md
index 7170b98430b6..57df8f3be913 100644
--- a/.agents/skills/improving-drf-endpoints/SKILL.md
+++ b/.agents/skills/improving-drf-endpoints/SKILL.md
@@ -53,7 +53,7 @@ Work through this list for every serializer and viewset you touch.
3. **No bare `JSONField()`** — create a custom field class with `@extend_schema_field(TypedSchema)`
4. **`SerializerMethodField` has `@extend_schema_field`** on its `get_*` method
5. **`ChoiceField` has explicit `choices=`** with all valid values listed
-6. **Define choices as a `models.TextChoices` class** — the OpenAPI component is named after the class (`EarlyAccessFeature.Stage` -> `EarlyAccessFeatureStageEnum`, via `ChoicesEnumNameOverrides` in `posthog/openapi/enum_names.py`), so a class-backed enum never collides on field names like `format`, `type`, `status`, `kind`. Inline `choices=[...]` lists have no class to read, collide with existing choices, and fail CI under `--fail-on-warn`; an explicit `ENUM_NAME_OVERRIDES` entry in `posthog/settings/web.py` is the fallback for choice sets no class can carry, and a product enum's entry must point at a re-export in the product's `backend/facade/enums.py`, never at an internal module (see [serializer-fields.md](references/serializer-fields.md#choicefield--explicit-choices))
+6. **Define choices as a class** — `models.TextChoices` in a product's internal modules, `LabeledStrEnum` or `LabeledIntEnum` from `posthog/enums.py` in facade contract files (`backend/facade/contracts.py`, `backend/facade/enums.py`), which must not import Django. The OpenAPI component is named after the class either way (`EarlyAccessFeature.Stage` -> `EarlyAccessFeatureStageEnum`, via `ChoicesEnumNameOverrides` in `posthog/openapi/enum_names.py`), so a class-backed enum never collides on field names like `format`, `type`, `status`, `kind`. Pass `X.choices` to `choices=`, and to name a labeled enum on a `SerializerMethodField` use `@extend_schema_field(ChoiceField(choices=X.choices))`, not a return type hint. Inline `choices=[...]` lists have no class to read, collide with existing choices, and fail CI under `--fail-on-warn`; an explicit `ENUM_NAME_OVERRIDES` entry in `posthog/settings/web.py` is the fallback for choice sets no class can carry (see [serializer-fields.md](references/serializer-fields.md#choicefield--explicit-choices))
7. **Read vs write serializers are separate** when input shape differs from output
8. **Every success response is backed by a serializer** — returning raw dicts or untyped lists means no generated types downstream
diff --git a/.agents/skills/improving-drf-endpoints/references/serializer-fields.md b/.agents/skills/improving-drf-endpoints/references/serializer-fields.md
index 85b7f772ab65..908087dbbcf3 100644
--- a/.agents/skills/improving-drf-endpoints/references/serializer-fields.md
+++ b/.agents/skills/improving-drf-endpoints/references/serializer-fields.md
@@ -131,15 +131,32 @@ status = serializers.ChoiceField(
**Collision-prone field names.** Generic names like `format`, `type`, `status`,
`kind`, `level`, `mode`, `state`, `platform`, `provider` already exist on multiple
-components with different choices. A ChoiceField built from a
-`models.TextChoices` class is safe: the component is named after the class
-(`ChoicesEnumNameOverrides` in `posthog/openapi/enum_names.py`), independent of
-the field name. An inline `choices=[...]` list on a colliding field name makes
-drf-spectacular auto-name your enum (`Format5eaEnum` and similar), which fails CI
-under `--fail-on-warn` — so define the choices as a TextChoices class, or as a
-fallback add an explicit `ENUM_NAME_OVERRIDES` entry in
-`posthog/settings/web.py`. Run `python manage.py find_enum_collisions` after the
-change — it prints the colliding fields and a suggested override entry.
+components with different choices. A ChoiceField built from a class is safe:
+the component is named after the class (`ChoicesEnumNameOverrides` in
+`posthog/openapi/enum_names.py`), independent of the field name. Use
+`models.TextChoices` in a product's internal modules. In a facade contract file
+(`backend/facade/contracts.py`, `backend/facade/enums.py`), which must not import
+Django, use `LabeledStrEnum` or `LabeledIntEnum` from `posthog/enums.py`: same
+class body, same `.choices`, same derived name.
+
+```python
+class DecisionQuestionType(LabeledStrEnum):
+ NOUL = "noul", "Yes or no"
+ SCORE = "score", "Rating scale"
+
+question_type = serializers.ChoiceField(choices=DecisionQuestionType.choices, help_text="...")
+```
+
+Pass `X.choices`, not the class. A return type hint does not carry the labels of
+a labeled enum, so name one on a `SerializerMethodField` with
+`@extend_schema_field(serializers.ChoiceField(choices=X.choices))`.
+
+An inline `choices=[...]` list on a colliding field name makes drf-spectacular
+auto-name your enum (`Format5eaEnum` and similar), which fails CI under
+`--fail-on-warn`, so define the choices as a class, or as a fallback add an
+explicit `ENUM_NAME_OVERRIDES` entry in `posthog/settings/web.py`. Run
+`python manage.py find_enum_collisions` after the change. It prints the colliding
+fields and a suggested override entry.
## DictField — typed values
diff --git a/.agents/skills/improving-drf-endpoints/references/viewset-annotations.md b/.agents/skills/improving-drf-endpoints/references/viewset-annotations.md
index f2d4215c2fe7..f9c64aa7c318 100644
--- a/.agents/skills/improving-drf-endpoints/references/viewset-annotations.md
+++ b/.agents/skills/improving-drf-endpoints/references/viewset-annotations.md
@@ -200,17 +200,19 @@ drf-spectacular's `COMPONENT_SPLIT_PATCH` setting (enabled by default) handles
the PATCH case automatically, creating separate schemas for PATCH vs POST
since PATCH doesn't require all fields.
-## Enum naming — derived from Choices classes, overrides as fallback
+## Enum naming — derived from choices classes, overrides as fallback
-Enum components are named after the `django.db.models.Choices` class that defines
-the choices: `ChoicesEnumNameOverrides` (`posthog/openapi/enum_names.py`) walks
-every Choices subclass at schema-build time and registers it under a name derived
-from its qualname. A field whose choices come from a TextChoices class therefore
-gets a stable name with no configuration.
+Enum components are named after the class that defines the choices:
+`ChoicesEnumNameOverrides` (`posthog/openapi/enum_names.py`) walks every
+`django.db.models.Choices` subclass and every `LabeledStrEnum` / `LabeledIntEnum`
+subclass (`posthog/enums.py`) at schema-build time and registers it under a name
+derived from its qualname. A field whose choices come from such a class (passed as
+`X.choices`) therefore gets a stable name with no configuration. Facade contract
+files use the labeled bases, because they must not import Django.
When choices have no class behind them (inline lists, computed lists, pydantic
literals) and multiple fields collide, drf-spectacular emits warnings. Those are
-fixed by defining a TextChoices class, or as a fallback via the explicit
+fixed by defining a choices class, or as a fallback via the explicit
`ENUM_NAME_OVERRIDES` dict in `posthog/settings/web.py`; the comment on the dict
lists the reasons an entry can be required.
diff --git a/.agents/skills/isolating-product-facade-contracts/SKILL.md b/.agents/skills/isolating-product-facade-contracts/SKILL.md
index 55702fcd5585..7ebdb076df2b 100644
--- a/.agents/skills/isolating-product-facade-contracts/SKILL.md
+++ b/.agents/skills/isolating-product-facade-contracts/SKILL.md
@@ -280,7 +280,7 @@ records the decrease. See `products/architecture.md` § Wiring couplings.
`related_name="+"` — the reverse-accessor ratchet blocks new unsealed ones.
- Do not register a signal receiver on another boundary's sender; use the moves
in "Signal coupling" above.
-- Keep contracts pure (no Django/DRF imports).
+- Keep contract files pure (no Django/DRF imports in `facade/contracts.py` or `facade/enums.py`). A choices enum there is a `LabeledStrEnum` / `LabeledIntEnum` from `posthog/enums.py`.
- Filter by `team_id` in querysets.
- Do not add product-specific fields to `Team`; use a Team Extension model.
- Add request/response schema annotations on viewset endpoints (`@validated_request` or `@extend_schema`).
diff --git a/ee/models/dashboard_privilege.py b/ee/models/dashboard_privilege.py
index 4dae7a500392..6be84501532d 100644
--- a/ee/models/dashboard_privilege.py
+++ b/ee/models/dashboard_privilege.py
@@ -19,7 +19,7 @@ class DashboardPrivilege(UUIDTModel):
related_name="explicit_dashboard_privileges",
related_query_name="explicit_dashboard_privilege",
)
- level = models.PositiveSmallIntegerField(choices=Dashboard.RestrictionLevel)
+ level = models.PositiveSmallIntegerField(choices=Dashboard.RestrictionLevel.choices)
added_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
diff --git a/posthog/api/test/test_project.py b/posthog/api/test/test_project.py
index 315b13d066c2..a487dd57dab6 100644
--- a/posthog/api/test/test_project.py
+++ b/posthog/api/test/test_project.py
@@ -27,8 +27,8 @@ from posthog.test.persons import create_person, delete_person
from products.customer_analytics.backend.facade.team_extension import TeamCustomerAnalyticsConfig
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
from products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfig
-from products.feature_flags.backend.models.team_feature_flags_config import FlagEvaluationsMode
class TestProjectAPI(team_api_test_factory()): # type: ignore
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index cf5eec19e9d8..576aed68ff69 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -49,8 +49,8 @@ from posthog.utils import get_context_for_template, get_instance_realm
from products.access_control.backend.models.access_control import AccessControl
from products.conversations.backend.playbook import compose_support_playbook
from products.dashboards.backend.models.dashboard import Dashboard
+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
from products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfig
-from products.feature_flags.backend.models.team_feature_flags_config import FlagEvaluationsMode
from products.workflows.backend.facade.team_extension import TeamWorkflowsConfig
diff --git a/posthog/enums.py b/posthog/enums.py
new file mode 100644
index 000000000000..9c434d2327b9
--- /dev/null
+++ b/posthog/enums.py
@@ -0,0 +1,114 @@
+"""Labeled enums that work like Django's TextChoices and IntegerChoices, without Django.
+
+A product's facade contract files (``backend/facade/contracts.py`` and ``backend/facade/enums.py``)
+must not import Django, so they cannot define a ``models.TextChoices`` class. Define a choices enum
+with these bases instead. The class body uses the same syntax:
+
+ class DecisionQuestionType(LabeledStrEnum):
+ NOUL = "noul", "Yes or no"
+ SCORE = "score" # the label defaults to "Score", the same rule Django uses
+
+The class has ``choices``, ``values``, ``labels`` and ``names``, and each member has ``label``.
+``choices`` holds the same (value, label) pairs that a TextChoices class with the same body holds,
+so a conversion from TextChoices changes no migration and no OpenAPI schema.
+posthog/openapi/enum_names.py derives the OpenAPI component name from the class name, the same way
+it does for a Choices class.
+
+This module imports nothing from Django, which is what the facade contract rule checks. Importing
+it still runs posthog/__init__.py, which loads Celery and Django, the same as posthog.dataclasses.
+
+Django special-cases only its own Choices classes, so two rules differ from TextChoices:
+
+- Pass ``X.choices`` to ``choices=`` on a model field or a DRF field. Django rejects the class.
+- Pass ``X.MEMBER.value`` to ``default=`` on a model field. The migration writer serializes a
+ member as an import of the enum's module, so later migrations of the field depend on that path.
+"""
+
+import enum
+from typing import TYPE_CHECKING, Any, ClassVar, Self, cast
+
+
+def _default_label(member_name: str) -> str:
+ return member_name.replace("_", " ").title()
+
+
+class LabeledEnumType(enum.EnumType):
+ """Split each ``NAME = value, "label"`` pair before EnumType builds the members.
+
+ This follows django.db.models.enums.ChoicesType, without its Django dependencies.
+ """
+
+ def __new__(
+ metacls, classname: str, bases: tuple[type, ...], classdict: enum.EnumDict, **kwds: Any
+ ) -> "LabeledEnumType":
+ if "__empty__" in classdict:
+ raise TypeError(f"{classname} defines __empty__, which only Django's Choices classes support.")
+ labels: list[str] = []
+ for key in classdict.member_names:
+ value = classdict[key]
+ if isinstance(value, tuple) and len(value) == 2 and isinstance(value[1], str):
+ value, label = value
+ else:
+ label = _default_label(key)
+ labels.append(label)
+ # dict.__setitem__ skips the EnumDict guard against assigning a member name twice.
+ dict.__setitem__(classdict, key, value)
+ cls = super().__new__(metacls, classname, bases, classdict, **kwds)
+ for member, label in zip(cls._labeled_members(), labels):
+ member._label_ = label
+ enum.unique(cast(type[enum.Enum], cls))
+ return cls
+
+ def _labeled_members(cls) -> list[Any]:
+ return list(cls.__members__.values())
+
+ @property
+ def choices(cls) -> list[tuple[Any, str]]:
+ return [(member.value, member._label_) for member in cls._labeled_members()]
+
+ @property
+ def values(cls) -> list[Any]:
+ return [member.value for member in cls._labeled_members()]
+
+ @property
+ def labels(cls) -> list[str]:
+ return [member._label_ for member in cls._labeled_members()]
+
+ @property
+ def names(cls) -> list[str]:
+ return list(cls.__members__)
+
+
+class LabeledStrEnum(enum.StrEnum, metaclass=LabeledEnumType):
+ _value_: str
+ _label_: str
+
+ if TYPE_CHECKING:
+ # mypy reads _value_ as the type of .value only when the class declares __new__. Without
+ # it, .value is typed as the (value, label) tuple from the class body.
+ def __new__(cls, value: str) -> Self: ...
+
+ # The metaclass properties return Any values. These give mypy the value type, the same
+ # types django-stubs gives TextChoices, so `x in X.values` narrows x.
+ choices: ClassVar[list[tuple[str, str]]]
+ values: ClassVar[list[str]]
+
+ @property
+ def label(self) -> str:
+ return self._label_
+
+
+class LabeledIntEnum(enum.IntEnum, metaclass=LabeledEnumType):
+ _value_: int
+ _label_: str
+
+ if TYPE_CHECKING:
+ # See LabeledStrEnum.
+ def __new__(cls, value: int) -> Self: ...
+
+ choices: ClassVar[list[tuple[int, str]]]
+ values: ClassVar[list[int]]
+
+ @property
+ def label(self) -> str:
+ return self._label_
diff --git a/posthog/management/commands/find_enum_collisions.py b/posthog/management/commands/find_enum_collisions.py
index 4a0d88350eb8..0ccf7ba911ef 100644
--- a/posthog/management/commands/find_enum_collisions.py
+++ b/posthog/management/commands/find_enum_collisions.py
@@ -77,11 +77,15 @@ class Command(BaseCommand):
self.stdout.write(" Override entry to add to ENUM_NAME_OVERRIDES in web.py")
self.stdout.write(" (key defaults to the current auto-resolved name; rename for a nicer schema type):")
if c["has_spec_id"] and not c["inline_override_matches"]:
- self.stdout.write(f' "{c["auto_name"]}": "products.<name>.backend.facade.enums.ChoicesClass",')
self.stdout.write(
- " # ChoiceField with custom labels (labels != values) — override must be a choices class path."
- "\n # For a product enum, point at a re-export in backend/facade/enums.py, never at an"
- "\n # internal module: internal targets go stale invisibly when the product refactors."
+ f' "{c["auto_name"]}": "products.<name>.backend.facade.enums.ChoicesClass.choices",'
+ )
+ self.stdout.write(
+ " # ChoiceField with custom labels (labels != values). Point at .choices: drf-spectacular"
+ "\n # hashes a bare Enum class as (value, name), which a field's (value, label) pairs never match."
+ "\n # A field built from a choices class (choices=X.choices) needs no entry at all, because the"
+ "\n # class name derives the component name. Define a product enum in backend/facade/enums.py"
+ "\n # as a posthog.enums.LabeledStrEnum."
)
else:
vals = c["values"]
diff --git a/posthog/models/team/team_marketing_analytics_config.py b/posthog/models/team/team_marketing_analytics_config.py
index 5e01a9b08f8a..8b670bfce67a 100644
--- a/posthog/models/team/team_marketing_analytics_config.py
+++ b/posthog/models/team/team_marketing_analytics_config.py
@@ -287,7 +287,7 @@ class TeamMarketingAnalyticsConfig(models.Model):
attribution_mode = field_access_control(
models.CharField(
max_length=20,
- default=AttributionMode.LAST_TOUCH,
+ default=AttributionMode.LAST_TOUCH.value,
choices=[(mode.value, mode.value.replace("_", " ").title()) for mode in AttributionMode],
help_text="Attribution mode: first_touch, last_touch, linear, time_decay, or position_based",
),
diff --git a/posthog/openapi/enum_names.py b/posthog/openapi/enum_names.py
index ec0bfb33dbbf..c684c08f5204 100644
--- a/posthog/openapi/enum_names.py
+++ b/posthog/openapi/enum_names.py
@@ -7,9 +7,9 @@ so it depends on which other serializers declare a field with the same name:
a new colliding field anywhere renames an unrelated enum.
ChoicesEnumNameOverrides makes the name independent of that pool. On first
-access it walks every django.db.models.Choices subclass and registers the class under a
-name derived from its qualname, so the schema name follows the definition
-site of the choices and never depends on the enum pool. The explicit dict
+access it walks every django.db.models.Choices subclass and every labeled enum from
+posthog.enums, and registers each class under a name derived from its qualname, so the
+schema name follows the definition site of the choices and never depends on the enum pool. The explicit dict
passed in wins over anything derived; it is reserved for choice sets no class
can name (see the comment on the dict in posthog/settings/web.py).
@@ -22,8 +22,11 @@ import inspect
from collections import defaultdict
from collections.abc import ItemsView, Iterable, Iterator, KeysView, Mapping, ValuesView
from enum import Enum
+from itertools import chain
from typing import Any
+from posthog.enums import LabeledEnumType, LabeledIntEnum, LabeledStrEnum
+
ENUM_SUFFIX = "Enum"
@@ -45,7 +48,7 @@ def derive_enum_name(qualname: str) -> str | None:
def build_derived_overrides(classes: Iterable[type], explicit: Mapping[str, Any]) -> dict[str, Any]:
- """Name -> Choices class for every class the explicit dict does not displace.
+ """Name -> override value for every class the explicit dict does not displace.
Two safety rules keep the result unambiguous:
- Classes with identical (value, label) pairs share one hash, so the
@@ -77,9 +80,16 @@ def build_derived_overrides(classes: Iterable[type], explicit: Mapping[str, Any]
continue
hashes_by_name[name].append(cls_hash)
class_by_name[name] = next(iter(class_set))
- # The value registered is the class itself, so drf-spectacular applies its own
- # normalization and the hash always matches the fields built from the class.
- return {name: class_by_name[name] for name, hashes in hashes_by_name.items() if len(hashes) == 1}
+ return {name: _override_value(class_by_name[name]) for name, hashes in hashes_by_name.items() if len(hashes) == 1}
+
+
+def _override_value(cls: type) -> Any:
+ # drf-spectacular hashes any Enum class as (value, name) pairs, but fields built from a
+ # labeled enum carry X.choices, which are (value, label) pairs. So a labeled enum registers
+ # its choices. A Choices class registers itself, and drf-spectacular reads its choices.
+ if isinstance(cls, LabeledEnumType):
+ return cls.choices
+ return cls
def _choices_hash(value: Any) -> str | None:
@@ -98,7 +108,7 @@ def _choices_hash(value: Any) -> str | None:
try:
if isinstance(value, str):
value = deep_import_string(value)
- if inspect.isclass(value) and issubclass(value, Choices):
+ if inspect.isclass(value) and (issubclass(value, Choices) or isinstance(value, LabeledEnumType)):
value = value.choices
if inspect.isclass(value) and issubclass(value, Enum):
value = [(member.value, member.name) for member in value]
@@ -160,5 +170,6 @@ class ChoicesEnumNameOverrides(Mapping[str, Any]):
def _load(self) -> dict[str, Any]:
from django.db.models import Choices # noqa: PLC0415 because settings import this module before Django is ready
- derived = build_derived_overrides(_all_subclasses(Choices), self._explicit)
+ classes = chain(_all_subclasses(Choices), _all_subclasses(LabeledStrEnum), _all_subclasses(LabeledIntEnum))
+ derived = build_derived_overrides(classes, self._explicit)
return {**derived, **self._explicit}
diff --git a/posthog/openapi/test/test_enum_names.py b/posthog/openapi/test/test_enum_names.py
index 189a165f6f6e..e9382744e5c2 100644
--- a/posthog/openapi/test/test_enum_names.py
+++ b/posthog/openapi/test/test_enum_names.py
@@ -3,6 +3,7 @@ from django.test import SimpleTestCase
from parameterized import parameterized
+from posthog.enums import LabeledStrEnum
from posthog.openapi.enum_names import build_derived_overrides, derive_enum_name
@@ -21,6 +22,16 @@ class Basket(models.TextChoices):
LARGE = "large", "Large"
+class LabeledFruitCopy(LabeledStrEnum):
+ APPLE = "apple", "Apple"
+ PEAR = "pear", "Pear"
+
+
+class Crate(LabeledStrEnum):
+ WOOD = "wood", "Wooden crate"
+ PLASTIC = "plastic"
+
+
class TestDeriveEnumName(SimpleTestCase):
@parameterized.expand(
[
@@ -40,8 +51,13 @@ class TestBuildDerivedOverrides(SimpleTestCase):
overrides = build_derived_overrides([Fruit, Basket], {})
assert overrides == {"FruitEnum": Fruit, "BasketEnum": Basket}
- def test_identical_choice_sets_are_left_to_the_explicit_dict(self) -> None:
- overrides = build_derived_overrides([Fruit, FruitCopy, Basket], {})
+ def test_registers_labeled_enum_by_its_choices(self) -> None:
+ overrides = build_derived_overrides([Crate], {})
+ assert overrides == {"CrateEnum": [("wood", "Wooden crate"), ("plastic", "Plastic")]}
+
+ @parameterized.expand([("two choices classes", FruitCopy), ("choices class and labeled enum", LabeledFruitCopy)])
+ def test_identical_choice_sets_are_left_to_the_explicit_dict(self, _name: str, copy: type) -> None:
+ overrides = build_derived_overrides([Fruit, copy, Basket], {})
assert overrides == {"BasketEnum": Basket}
def test_explicit_entry_displaces_derived_by_name_and_by_hash(self) -> None:
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index cedab3cd5c3d..5ba6bc6593a1 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -574,10 +574,12 @@ SPECTACULAR_SETTINGS = {
"ENUM_NAME_OVERRIDES": ChoicesEnumNameOverrides(
{
# Most enum components are named automatically: ChoicesEnumNameOverrides walks
- # every django.db.models.Choices subclass at schema-build time and names the
- # component after the class (EarlyAccessFeature.Stage -> EarlyAccessFeatureStageEnum),
- # so defining choices as a TextChoices class is all a new enum needs. See
- # posthog/openapi/enum_names.py for the derivation and its safety rules.
+ # every django.db.models.Choices subclass and every posthog.enums labeled enum at
+ # schema-build time and names the component after the class
+ # (EarlyAccessFeature.Stage -> EarlyAccessFeatureStageEnum), so defining choices as
+ # a TextChoices class, or a LabeledStrEnum in a facade contract file, is all a new
+ # enum needs. See posthog/openapi/enum_names.py for the derivation and its safety
+ # rules.
#
# An entry below is for a choice set no class can carry, and each group states
# why. drf-spectacular matches an entry to fields by a hash of the exact
@@ -617,8 +619,6 @@ SPECTACULAR_SETTINGS = {
"RoleEnum": ["primary", "supporting"],
# replay_vision alert destinations: the create body and the alert's listed destinations share this set.
"VisionAlertDestinationTypeEnum": ["slack", "webhook"],
- # visual_review facade enums are framework-free StrEnums, so no Choices class derives a name.
- "ShiftBandKindEnum": ["inserted", "deleted"],
"ExperimentStatusEnum": ["draft", "running", "paused", "exposure_frozen", "stopped"],
"ErrorTrackingIssueStatusEnum": ["archived", "active", "resolved", "pending_release", "suppressed", "all"],
# The subset a client may write. Shared by the single-issue and bulk write serializers,
@@ -654,20 +654,18 @@ SPECTACULAR_SETTINGS = {
# growth's identity-matching tier and the signals scout suggestion confidence.
"ConfidenceTierEnum": ["low", "medium", "high"],
#
- # The definition site is a deliberately Django-free module (facade contracts,
- # signals taxonomy), so it cannot define a models.Choices class.
- "WizardTaskStatusEnum": "products.wizard.backend.facade.enums.WIZARD_TASK_STATUS_CHOICES",
+ # The definition site is a Django-free module, and no field builds these choices from a
+ # posthog.enums labeled enum, so no name derives. The engineering_analytics fields go
+ # through DataclassSerializer, which pairs each value with the member name, not a label.
+ # The signals entries need a member order, or a name without the Enum suffix, that no
+ # class derives.
"SignalSourceProductEnum": "products.signals.backend.enums.signal_source_product_choices",
- "ReportLinkKindEnum": "products.signals.backend.enums.report_link_kind_choices",
"EngineeringAnalyticsPRStateEnum": "products.engineering_analytics.backend.facade.contracts.PRState",
"QuarantineModeEnum": "products.engineering_analytics.backend.facade.contracts.QuarantineMode",
"CITestRunnerEnum": "products.engineering_analytics.backend.facade.contracts.CITestRunner",
"PRTimelineSegmentKindEnum": "products.engineering_analytics.backend.facade.contracts.PRTimelineSegmentKind",
"DeliveryScopeKindEnum": "products.engineering_analytics.backend.facade.contracts.DeliveryScopeKind",
"FrictionGroupEnum": "products.engineering_analytics.backend.facade.contracts.FrictionGroup",
- "UserInterviewSearchDocumentTypeEnum": "products.user_interviews.backend.facade.enums.SEARCH_DOCUMENT_TYPES",
- "DesktopAccessReasonEnum": "products.tasks.backend.facade.contracts.DESKTOP_ACCESS_REASON_SCHEMA_VALUES",
- "LifecycleStatusEnum": "products.notebooks.backend.widget_models.WIDGET_LIFECYCLE_STATUS_CHOICES",
"SignalSourceProduct": "products.signals.backend.enums.SIGNAL_SOURCE_PRODUCT_VALUES",
"SignalSourceType": "products.signals.backend.enums.SIGNAL_SOURCE_TYPE_VALUES",
"ErrorTrackingIssueSeverityRuleEnum": ["low", "medium", "high", "critical"],
diff --git a/posthog/test/repo_invariants/test_model_enum_defaults.py b/posthog/test/repo_invariants/test_model_enum_defaults.py
new file mode 100644
index 000000000000..8b8796730757
--- /dev/null
+++ b/posthog/test/repo_invariants/test_model_enum_defaults.py
@@ -0,0 +1,28 @@
+import enum
+
+from django.apps import apps
+from django.db import models
+
+
+def _fields_with_enum_member_defaults() -> list[str]:
+ found = []
+ for model in apps.get_models():
+ for field in model._meta.get_fields():
+ for attribute in ("default", "db_default"):
+ value = getattr(field, attribute, None)
+ # Django serializes a Choices member by value, and a plain Enum member as an
+ # import of the enum's module, so only the plain member pins a module path.
+ if isinstance(value, enum.Enum) and not isinstance(value, models.Choices):
+ found.append(
+ f"{model._meta.label}.{field.name} {attribute}={type(value).__qualname__}.{value.name}"
+ )
+ return sorted(found)
+
+
+def test_model_defaults_are_not_plain_enum_members() -> None:
+ found = _fields_with_enum_member_defaults()
+ assert found == [], (
+ "These model fields use a plain Enum member as a default. A migration then imports the "
+ "enum's module, and every later migration of the field depends on that path. Pass "
+ "MEMBER.value instead (see posthog/enums.py):\n" + "\n".join(found)
+ )
diff --git a/posthog/test/test_enums.py b/posthog/test/test_enums.py
new file mode 100644
index 000000000000..736a8189614b
--- /dev/null
+++ b/posthog/test/test_enums.py
@@ -0,0 +1,56 @@
+from django.db import models
+from django.db.migrations.writer import MigrationWriter
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.enums import LabeledIntEnum, LabeledStrEnum
+
+
+class QuestionType(LabeledStrEnum):
+ NOUL = "noul", "Yes or no"
+ CONTINUED_AS_NEW = "ContinuedAsNew"
+ AI = "ai", "AI"
+
+
+class QuestionTypeChoices(models.TextChoices):
+ NOUL = "noul", "Yes or no"
+ CONTINUED_AS_NEW = "ContinuedAsNew"
+ AI = "ai", "AI"
+
+
+class Level(LabeledIntEnum):
+ CAN_VIEW = 21, "Can view dashboard"
+ CAN_EDIT = 37
+
+
+class LevelChoices(models.IntegerChoices):
+ CAN_VIEW = 21, "Can view dashboard"
+ CAN_EDIT = 37
+
+
+class TestLabeledEnums(SimpleTestCase):
+ @parameterized.expand([("str", QuestionType, QuestionTypeChoices), ("int", Level, LevelChoices)])
+ def test_matches_the_django_choices_class_with_the_same_body(
+ self,
+ _name: str,
+ labeled: type[LabeledStrEnum] | type[LabeledIntEnum],
+ django_choices: type[models.TextChoices] | type[models.IntegerChoices],
+ ) -> None:
+ assert labeled.choices == django_choices.choices
+ assert MigrationWriter.serialize(labeled.choices) == MigrationWriter.serialize(django_choices.choices)
+ assert [member.label for member in labeled] == django_choices.labels
+
+ def test_rejects_a_duplicate_value(self) -> None:
+ with self.assertRaises(ValueError):
+
+ class Broken(LabeledStrEnum):
+ A = "a", "Alpha"
+ B = "a", "Beta"
+
+ def test_rejects_an_empty_choice(self) -> None:
+ with self.assertRaises(TypeError):
+
+ class Broken(LabeledStrEnum):
+ __empty__ = "(none)"
+ A = "a"
diff --git a/products/alerts/backend/facade/contracts.py b/products/alerts/backend/facade/contracts.py
index c27077ca604d..dbc60a333df7 100644
--- a/products/alerts/backend/facade/contracts.py
+++ b/products/alerts/backend/facade/contracts.py
@@ -14,6 +14,7 @@ from typing import Any, Final, NotRequired, TypedDict
from uuid import UUID
from posthog.dataclasses import frozen
+from posthog.enums import LabeledStrEnum
class SourceKind(StrEnum):
@@ -273,29 +274,12 @@ class OrchestrateResult:
deadline_reached: bool
-class DestinationType(StrEnum):
- SLACK = "slack"
- DISCORD = "discord"
- WEBHOOK = "webhook"
- TEAMS = "teams"
-
- @property
- def label(self) -> str:
- """Name for this type in a message a person reads."""
- return _DESTINATION_TYPE_LABELS[self]
-
-
-_DESTINATION_TYPE_LABELS: Final[dict[DestinationType, str]] = {
- DestinationType.SLACK: "Slack",
- DestinationType.DISCORD: "Discord",
- DestinationType.WEBHOOK: "Webhook",
- DestinationType.TEAMS: "Microsoft Teams",
-}
-
-# A type without a label would only surface as a KeyError inside a validation message a
-# person reads, so a new member without one fails the import instead.
-if _DESTINATION_TYPE_LABELS.keys() != set(DestinationType):
- raise RuntimeError("Every DestinationType needs an entry in _DESTINATION_TYPE_LABELS.")
+class DestinationType(LabeledStrEnum):
+ # The label names the type in a message a person reads.
+ SLACK = "slack", "Slack"
+ DISCORD = "discord", "Discord"
+ WEBHOOK = "webhook", "Webhook"
+ TEAMS = "teams", "Microsoft Teams"
class AlertDestinationData(TypedDict):
diff --git a/products/alerts/backend/models/alert.py b/products/alerts/backend/models/alert.py
index d9d222446820..2e1c2d9c3282 100644
--- a/products/alerts/backend/models/alert.py
+++ b/products/alerts/backend/models/alert.py
@@ -137,7 +137,7 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
calculation_interval = models.CharField(
max_length=20,
choices=CALCULATION_INTERVAL_CHOICES,
- default=AlertCalculationInterval.DAILY,
+ default=AlertCalculationInterval.DAILY.value,
null=True,
blank=True,
)
@@ -149,7 +149,7 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
# Detector-based anomaly detection configuration (alternative to threshold)
detector_config = models.JSONField(null=True, blank=True)
- state = models.CharField(max_length=10, choices=ALERT_STATE_CHOICES, default=AlertState.NOT_FIRING)
+ state = models.CharField(max_length=10, choices=ALERT_STATE_CHOICES, default=AlertState.NOT_FIRING.value)
enabled = models.BooleanField(default=True)
last_notified_at = models.DateTimeField(null=True, blank=True)
@@ -443,7 +443,7 @@ class AlertCheck(UUIDTModel):
targets_notified = models.JSONField(default=dict)
error = models.JSONField(null=True, blank=True)
- state = models.CharField(max_length=10, choices=ALERT_STATE_CHOICES, default=AlertState.NOT_FIRING)
+ state = models.CharField(max_length=10, choices=ALERT_STATE_CHOICES, default=AlertState.NOT_FIRING.value)
# Detector-based anomaly detection results
anomaly_scores = models.JSONField(null=True, blank=True) # Scores for each data point
diff --git a/products/architecture.md b/products/architecture.md
index 48af88999cd4..576c8e2c9879 100644
--- a/products/architecture.md
+++ b/products/architecture.md
@@ -282,7 +282,7 @@ Each product defines its public interface as **frozen dataclasses** in `backend/
### Rules:
-- No Django imports
+- No Django imports, in `contracts.py` and in `enums.py`. An enum that backs model or serializer choices is a `LabeledStrEnum` or `LabeledIntEnum` from `posthog/enums.py`, not a `models.TextChoices`
- Immutable (`frozen=True`)
- Small, hashable, stable
- Facades accept them as inputs and return them as outputs
diff --git a/products/customer_analytics/backend/facade/enums.py b/products/customer_analytics/backend/facade/enums.py
index dbf775a40477..9509eacbf8bd 100644
--- a/products/customer_analytics/backend/facade/enums.py
+++ b/products/customer_analytics/backend/facade/enums.py
@@ -1,6 +1,6 @@
from enum import Enum
-from django.db import models
+from posthog.enums import LabeledStrEnum
class AccountPropertyPinKind(str, Enum):
@@ -8,19 +8,19 @@ class AccountPropertyPinKind(str, Enum):
RELATIONSHIP = "relationship"
-class AccountViewVisibility(models.TextChoices):
+class AccountViewVisibility(LabeledStrEnum):
PRIVATE = "private", "Personal"
TEAM = "team", "Team"
-class TaskDigestCadence(models.TextChoices):
+class TaskDigestCadence(LabeledStrEnum):
"""How often a user's customer task digest email is sent."""
WEEKDAYS = "weekdays", "Weekdays"
EVERY_DAY = "every_day", "Every day"
-class AccountRelationshipSource(models.TextChoices):
+class AccountRelationshipSource(LabeledStrEnum):
"""Which kind of writer created or ended a relationship row. Rows written before provenance
was recorded carry NULL."""
@@ -31,7 +31,7 @@ class AccountRelationshipSource(models.TextChoices):
MIGRATION = "migration", "Migration"
-class OwnershipRoleState(models.TextChoices):
+class OwnershipRoleState(LabeledStrEnum):
"""What a consumer may conclude about a controlled relationship on one account."""
# No control row: legacy authority holds, whatever the relationship rows say.
@@ -43,7 +43,7 @@ class OwnershipRoleState(models.TextChoices):
BLOCKED = "blocked", "Blocked"
-class OwnershipRoleDiagnostic(models.TextChoices):
+class OwnershipRoleDiagnostic(LabeledStrEnum):
HOLDER_MISSING = "holder_missing", "The active relationship has no user"
HOLDER_INACTIVE = "holder_inactive", "The holder's user account is deactivated"
HOLDER_NOT_IN_ORGANIZATION = "holder_not_in_organization", "The holder is not a member of the organization"
diff --git a/products/customer_analytics/backend/models/account_view.py b/products/customer_analytics/backend/models/account_view.py
index 0f1bdfc49f81..1208e023b371 100644
--- a/products/customer_analytics/backend/models/account_view.py
+++ b/products/customer_analytics/backend/models/account_view.py
@@ -13,7 +13,7 @@ class AccountView(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):
visibility = models.CharField(
max_length=16,
choices=AccountViewVisibility.choices,
- default=AccountViewVisibility.PRIVATE,
+ default=AccountViewVisibility.PRIVATE.value,
)
content = models.JSONField()
text_content = models.TextField(default="", db_default="")
diff --git a/products/customer_analytics/backend/models/custom_property_definition.py b/products/customer_analytics/backend/models/custom_property_definition.py
index 155aa366105a..b6f485e11f5d 100644
--- a/products/customer_analytics/backend/models/custom_property_definition.py
+++ b/products/customer_analytics/backend/models/custom_property_definition.py
@@ -60,7 +60,7 @@ class CustomPropertyDefinition(TeamScopedRootMixin, UUIDModel, CreatedMetaFields
target_type = models.CharField(
choices=[(t.value, t.value) for t in TargetType],
- default=TargetType.ACCOUNT,
+ default=TargetType.ACCOUNT.value,
max_length=20,
help_text="What entity this property is attached to: an account (default), a person, or a group.",
)
@@ -74,7 +74,7 @@ class CustomPropertyDefinition(TeamScopedRootMixin, UUIDModel, CreatedMetaFields
name = models.CharField(max_length=400)
description = models.TextField(null=True)
display_type = models.CharField(
- choices=[(t.value, t.value) for t in DisplayType], default=DisplayType.TEXT, max_length=20
+ choices=[(t.value, t.value) for t in DisplayType], default=DisplayType.TEXT.value, max_length=20
)
is_big_number = models.BooleanField(
default=False, help_text="Whether the property is a big number and should be abbreviated. E.g.: 10,000 -> 10K"
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index d9296d0804cb..2d4ed62dce95 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -1240,11 +1240,13 @@ class DashboardBasicSerializer(
"restriction_level": {"help_text": "Controls who can edit the dashboard."},
}
+ @extend_schema_field(serializers.ChoiceField(choices=RestrictionLevel.choices))
def get_effective_restriction_level(self, dashboard: Dashboard) -> RestrictionLevel:
if self.context.get("is_shared"):
return RestrictionLevel.ONLY_COLLABORATORS_CAN_EDIT
return self.user_permissions.dashboard(dashboard).effective_restriction_level
+ @extend_schema_field(serializers.ChoiceField(choices=PrivilegeLevel.choices))
def get_effective_privilege_level(self, dashboard: Dashboard) -> PrivilegeLevel:
if self.context.get("is_shared"):
return PrivilegeLevel.CAN_VIEW
diff --git a/products/dashboards/backend/facade/enums.py b/products/dashboards/backend/facade/enums.py
index e340e55fa5a9..84fa9e75e2f1 100644
--- a/products/dashboards/backend/facade/enums.py
+++ b/products/dashboards/backend/facade/enums.py
@@ -13,7 +13,7 @@ keeps ``Dashboard.RestrictionLevel`` / ``Dashboard.PrivilegeLevel`` as aliases o
from enum import StrEnum
-from django.db import models
+from posthog.enums import LabeledIntEnum
class DashboardAccessMethod(StrEnum):
@@ -23,7 +23,7 @@ class DashboardAccessMethod(StrEnum):
API = "api"
-class RestrictionLevel(models.IntegerChoices):
+class RestrictionLevel(LabeledIntEnum):
"""Collaboration restriction level (which is a dashboard setting). Sync with PrivilegeLevel."""
EVERYONE_IN_PROJECT_CAN_EDIT = 21, "Everyone in the project can edit"
@@ -33,7 +33,7 @@ class RestrictionLevel(models.IntegerChoices):
)
-class PrivilegeLevel(models.IntegerChoices):
+class PrivilegeLevel(LabeledIntEnum):
"""Collaboration privilege level (which is a user property). Sync with RestrictionLevel."""
CAN_VIEW = 21, "Can view dashboard"
diff --git a/products/dashboards/backend/models/dashboard.py b/products/dashboards/backend/models/dashboard.py
index d5707d14dbfc..41849ed7c161 100644
--- a/products/dashboards/backend/models/dashboard.py
+++ b/products/dashboards/backend/models/dashboard.py
@@ -79,8 +79,8 @@ class Dashboard(Taggable, FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin
)
creation_mode = models.CharField(max_length=16, default="default", choices=CreationMode)
restriction_level = models.PositiveSmallIntegerField(
- default=RestrictionLevel.EVERYONE_IN_PROJECT_CAN_EDIT,
- choices=RestrictionLevel,
+ default=RestrictionLevel.EVERYONE_IN_PROJECT_CAN_EDIT.value,
+ choices=RestrictionLevel.choices,
)
insights = models.ManyToManyField(
"product_analytics.Insight", related_name="dashboards", through="DashboardTile", blank=True
diff --git a/products/data_catalog/backend/models/certification.py b/products/data_catalog/backend/models/certification.py
index e5cf90b7644b..e47533b0b3e8 100644
--- a/products/data_catalog/backend/models/certification.py
+++ b/products/data_catalog/backend/models/certification.py
@@ -42,7 +42,7 @@ class TableCertification(CreatedMetaFields, UpdatedMetaFields, UUIDModel):
status = models.CharField(
max_length=32,
choices=[(s.value, s.value) for s in CertificationStatus],
- default=CertificationStatus.PROPOSED,
+ default=CertificationStatus.PROPOSED.value,
help_text="proposed, certified (prefer this source), or deprecated (avoid this source).",
)
proposed_status = models.CharField(
@@ -51,7 +51,7 @@ class TableCertification(CreatedMetaFields, UpdatedMetaFields, UUIDModel):
(CertificationStatus.CERTIFIED.value, CertificationStatus.CERTIFIED.value),
(CertificationStatus.DEPRECATED.value, CertificationStatus.DEPRECATED.value),
],
- default=CertificationStatus.CERTIFIED,
+ default=CertificationStatus.CERTIFIED.value,
help_text="The mark this proposal asks for: 'certified' (trust this source) or 'deprecated' "
"(avoid this source). Informational once the mark is settled.",
)
diff --git a/products/data_catalog/backend/models/metric.py b/products/data_catalog/backend/models/metric.py
index 9f8472b86aa4..f8e7b57f1eb2 100644
--- a/products/data_catalog/backend/models/metric.py
+++ b/products/data_catalog/backend/models/metric.py
@@ -76,7 +76,7 @@ class Metric(
status = models.CharField(
max_length=32,
choices=[(s.value, s.value) for s in MetricStatus],
- default=MetricStatus.PROPOSED,
+ default=MetricStatus.PROPOSED.value,
help_text="Persisted lifecycle state. drifted is computed at read time, not stored here.",
)
approved_by = models.ForeignKey(
@@ -108,7 +108,7 @@ class Metric(
created_source = models.CharField(
max_length=32,
choices=[(s.value, s.value) for s in CreatedSource],
- default=CreatedSource.USER,
+ default=CreatedSource.USER.value,
help_text="Whether a human or an agent authored this metric.",
)
ai_model = models.CharField(
diff --git a/products/data_catalog/backend/models/relationship_proposal.py b/products/data_catalog/backend/models/relationship_proposal.py
index 6d538e4b52d4..c80930a279cd 100644
--- a/products/data_catalog/backend/models/relationship_proposal.py
+++ b/products/data_catalog/backend/models/relationship_proposal.py
@@ -42,7 +42,7 @@ class RelationshipProposal(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFi
status = models.CharField(
max_length=32,
choices=[(s.value, s.value) for s in RelationshipStatus],
- default=RelationshipStatus.PROPOSED,
+ default=RelationshipStatus.PROPOSED.value,
help_text="proposed, accepted (promoted to a real join), or rejected (never re-proposed).",
)
reviewed_by = models.ForeignKey(
diff --git a/products/data_modeling/backend/models/datawarehouse_managed_viewset.py b/products/data_modeling/backend/models/datawarehouse_managed_viewset.py
index 5cfb3f60c3a0..2d27a48ef9fa 100644
--- a/products/data_modeling/backend/models/datawarehouse_managed_viewset.py
+++ b/products/data_modeling/backend/models/datawarehouse_managed_viewset.py
@@ -45,7 +45,7 @@ class ExpectedView:
class DataWarehouseManagedViewSet(CreatedMetaFields, UpdatedMetaFields, UUIDTModel):
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")
- kind = models.CharField(max_length=64, choices=DataWarehouseManagedViewSetKind)
+ kind = models.CharField(max_length=64, choices=DataWarehouseManagedViewSetKind.choices)
class Meta:
constraints = [
diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query_column_annotation.py b/products/data_modeling/backend/models/datawarehouse_saved_query_column_annotation.py
index d04153f0a585..584c84aa8e66 100644
--- a/products/data_modeling/backend/models/datawarehouse_saved_query_column_annotation.py
+++ b/products/data_modeling/backend/models/datawarehouse_saved_query_column_annotation.py
@@ -31,7 +31,7 @@ class DataWarehouseSavedQueryColumnAnnotation(TeamScopedRootMixin, CreatedMetaFi
# Empty string = view-level annotation; otherwise the column this describes.
column_name = models.CharField(max_length=400, blank=True, default="")
description = models.TextField()
- description_source = models.CharField(max_length=32, choices=DescriptionSource)
+ description_source = models.CharField(max_length=32, choices=DescriptionSource.choices)
ai_model = models.CharField(max_length=128, null=True, blank=True)
is_user_edited = models.BooleanField(default=False)
diff --git a/products/data_quality/backend/models/check.py b/products/data_quality/backend/models/check.py
index a611c11f5bd3..8325b5003728 100644
--- a/products/data_quality/backend/models/check.py
+++ b/products/data_quality/backend/models/check.py
@@ -162,7 +162,7 @@ class DataQualityCheck(
subject_status = models.CharField(
max_length=32,
choices=[(s.value, s.value) for s in SubjectStatus],
- default=SubjectStatus.ACTIVE,
+ default=SubjectStatus.ACTIVE.value,
help_text="orphaned once the subject stops resolving; orphaned checks are skipped, not deleted.",
)
column_name = models.CharField(
@@ -185,7 +185,7 @@ class DataQualityCheck(
severity = models.CharField(
max_length=16,
choices=[(s.value, s.value) for s in CheckSeverity],
- default=CheckSeverity.ERROR,
+ default=CheckSeverity.ERROR.value,
help_text="error failures mark the subject failing and notify; warn failures only surface.",
)
enabled = models.BooleanField(default=True, help_text="Disabled checks are never run by any trigger.")
@@ -219,7 +219,7 @@ class DataQualityCheck(
created_source = models.CharField(
max_length=32,
choices=[(s.value, s.value) for s in CreatedSource],
- default=CreatedSource.USER,
+ default=CreatedSource.USER.value,
help_text="Whether a human or an agent authored this check.",
)
ai_model = models.CharField(max_length=128, blank=True, help_text="Model that generated the check, if AI-authored.")
diff --git a/products/data_quality/backend/models/check_run.py b/products/data_quality/backend/models/check_run.py
index 585d929c21dc..9475f3b96f67 100644
--- a/products/data_quality/backend/models/check_run.py
+++ b/products/data_quality/backend/models/check_run.py
@@ -33,7 +33,7 @@ class DataQualitySuiteRun(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFie
status = models.CharField(
max_length=16,
choices=[(s.value, s.value) for s in SuiteRunStatus],
- default=SuiteRunStatus.RUNNING,
+ default=SuiteRunStatus.RUNNING.value,
help_text="empty means the trigger matched no runnable checks, which is not a failure.",
)
diff --git a/products/feature_flags/backend/api/staff_team_config.py b/products/feature_flags/backend/api/staff_team_config.py
index ef325df756d9..affb04ee1ade 100644
--- a/products/feature_flags/backend/api/staff_team_config.py
+++ b/products/feature_flags/backend/api/staff_team_config.py
@@ -19,6 +19,7 @@ from posthog.models.team.extensions import get_or_create_team_extension
from posthog.permissions import IsStaffUser
from products.feature_flags.backend.api.staff_cache import _team_ids_field
+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
from products.feature_flags.backend.facade.flags import get_organization_flag_evaluations_mode
from products.feature_flags.backend.flag_evaluations_mode import (
OrganizationModeChange,
@@ -34,7 +35,6 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfig
from products.feature_flags.backend.models.team_feature_flags_config import (
MAX_FEATURE_FLAGS_OVERRIDE_CEILING,
- FlagEvaluationsMode,
PropertyMatchingVersion,
TeamFeatureFlagsConfig,
)
diff --git a/products/feature_flags/backend/facade/enums.py b/products/feature_flags/backend/facade/enums.py
index 2ef29382844c..82d19214ae58 100644
--- a/products/feature_flags/backend/facade/enums.py
+++ b/products/feature_flags/backend/facade/enums.py
@@ -1,5 +1,22 @@
"""Exported enums for feature_flags."""
-from products.feature_flags.backend.models.team_feature_flags_config import FlagEvaluationsMode
+from posthog.enums import LabeledIntEnum
-__all__ = ["FlagEvaluationsMode"]
+
+class FlagEvaluationsMode(LabeledIntEnum):
+ """Which table the product reads an organization's $feature_flag_called data from. This field does not
+ control ingestion. The INGESTION_FLAG_EVALUATIONS_TEAMS allowlist in FlagEvaluationsService
+ decides which teams ingestion also writes to flag_evaluations. FLAG_EVALUATIONS_ONLY is
+ reserved for the ingestion change that stops the events writes.
+ """
+
+ # The Usage tab reads the events table. The flag_evaluations HogQL table stays hidden unless
+ # the flag-evaluations-hogql-table flag is on for the organization.
+ EVENTS = 0, "Events"
+ # The Usage tab reads flag_evaluations, and the HogQL table is visible.
+ READ_FLAG_EVALUATIONS = 1, "Read flag evaluations"
+ # As READ_FLAG_EVALUATIONS, and ingestion stops writing $feature_flag_called to events. Ingestion
+ # ignores this mode until the change that implements it deploys. Until then the mode acts as
+ # READ_FLAG_EVALUATIONS. An organization already on this mode stops the events writes when that
+ # change deploys.
+ FLAG_EVALUATIONS_ONLY = 2, "Flag evaluations only"
diff --git a/products/feature_flags/backend/facade/flags.py b/products/feature_flags/backend/facade/flags.py
index e748b2a50167..3641c6036a45 100644
--- a/products/feature_flags/backend/facade/flags.py
+++ b/products/feature_flags/backend/facade/flags.py
@@ -11,8 +11,8 @@ from django.conf import settings
from posthog.models.instance_setting import get_instance_setting
from posthog.ph_client import feature_enabled_or_false
+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
from products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfig
-from products.feature_flags.backend.models.team_feature_flags_config import FlagEvaluationsMode
if TYPE_CHECKING:
from posthog.models.team import Team
diff --git a/products/feature_flags/backend/flag_evaluations_mode.py b/products/feature_flags/backend/flag_evaluations_mode.py
index 474ed7ddc1db..079185cb6e68 100644
--- a/products/feature_flags/backend/flag_evaluations_mode.py
+++ b/products/feature_flags/backend/flag_evaluations_mode.py
@@ -10,9 +10,9 @@ from django.db.models import QuerySet
from posthog.dataclasses import frozen
from posthog.models import Organization, Team
+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
from products.feature_flags.backend.facade.flags import get_organization_flag_evaluations_mode
from products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfig
-from products.feature_flags.backend.models.team_feature_flags_config import FlagEvaluationsMode
@frozen
diff --git a/products/feature_flags/backend/management/commands/set_flag_evaluations_mode.py b/products/feature_flags/backend/management/commands/set_flag_evaluations_mode.py
index 400be56c1be4..e16403ee61a7 100644
--- a/products/feature_flags/backend/management/commands/set_flag_evaluations_mode.py
+++ b/products/feature_flags/backend/management/commands/set_flag_evaluations_mode.py
@@ -16,13 +16,13 @@ from uuid import UUID
from django.core.management.base import BaseCommand, CommandError, CommandParser
from django.db import transaction
+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
from products.feature_flags.backend.flag_evaluations_mode import (
UnknownIdsError,
get_organizations,
select_organizations,
set_organization_flag_evaluations_mode,
)
-from products.feature_flags.backend.models.team_feature_flags_config import FlagEvaluationsMode
def _parse_instant(value: str) -> datetime:
diff --git a/products/feature_flags/backend/management/commands/test/test_set_flag_evaluations_mode.py b/products/feature_flags/backend/management/commands/test/test_set_flag_evaluations_mode.py
index d198cdf3a3c5..b49c2ea8da1f 100644
--- a/products/feature_flags/backend/management/commands/test/test_set_flag_evaluations_mode.py
+++ b/products/feature_flags/backend/management/commands/test/test_set_flag_evaluations_mode.py
@@ -15,13 +15,13 @@ from parameterized import parameterized
from posthog.models.instance_setting import override_instance_config
from posthog.models.organization import Organization
+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
from products.feature_flags.backend.facade.flags import get_organization_flag_evaluations_mode
from products.feature_flags.backend.flag_evaluations_mode import (
OrganizationModeChange,
set_organization_flag_evaluations_mode,
)
from products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfig
-from products.feature_flags.backend.models.team_feature_flags_config import FlagEvaluationsMode
class TestSetFlagEvaluationsMode(BaseTest):
diff --git a/products/feature_flags/backend/models/organization_feature_flags_config.py b/products/feature_flags/backend/models/organization_feature_flags_config.py
index 6865ca70eb89..9aa06ff97868 100644
--- a/products/feature_flags/backend/models/organization_feature_flags_config.py
+++ b/products/feature_flags/backend/models/organization_feature_flags_config.py
@@ -6,7 +6,7 @@ from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
-from products.feature_flags.backend.models.team_feature_flags_config import FlagEvaluationsMode
+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
if TYPE_CHECKING:
from posthog.models.organization import Organization
@@ -32,9 +32,9 @@ class OrganizationFeatureFlagsConfig(models.Model):
# The database default keeps raw SQL INSERTs that omit this column valid. Django's default
# applies only to rows the ORM creates.
flag_evaluations_mode = models.SmallIntegerField(
- choices=FlagEvaluationsMode,
- default=FlagEvaluationsMode.EVENTS,
- db_default=FlagEvaluationsMode.EVENTS,
+ choices=FlagEvaluationsMode.choices,
+ default=FlagEvaluationsMode.EVENTS.value,
+ db_default=FlagEvaluationsMode.EVENTS.value,
)
class Meta:
diff --git a/products/feature_flags/backend/models/team_feature_flags_config.py b/products/feature_flags/backend/models/team_feature_flags_config.py
index 658c976665ad..30d97a40f6bc 100644
--- a/products/feature_flags/backend/models/team_feature_flags_config.py
+++ b/products/feature_flags/backend/models/team_feature_flags_config.py
@@ -5,6 +5,8 @@ from django.db import models
from posthog.models.team.extensions import register_team_extension_signal
+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
+
logger = logging.getLogger(__name__)
# Ceiling on a staff-granted max_feature_flags_override. The global default exists to bound the
@@ -24,25 +26,6 @@ class PropertyMatchingVersion(models.IntegerChoices):
EXPLICIT = 2, "Explicit"
-class FlagEvaluationsMode(models.IntegerChoices):
- """Which table the product reads an organization's $feature_flag_called data from. This field does not
- control ingestion. The INGESTION_FLAG_EVALUATIONS_TEAMS allowlist in FlagEvaluationsService
- decides which teams ingestion also writes to flag_evaluations. FLAG_EVALUATIONS_ONLY is
- reserved for the ingestion change that stops the events writes.
- """
-
- # The Usage tab reads the events table. The flag_evaluations HogQL table stays hidden unless
- # the flag-evaluations-hogql-table flag is on for the organization.
- EVENTS = 0, "Events"
- # The Usage tab reads flag_evaluations, and the HogQL table is visible.
- READ_FLAG_EVALUATIONS = 1, "Read flag evaluations"
- # As READ_FLAG_EVALUATIONS, and ingestion stops writing $feature_flag_called to events. Ingestion
- # ignores this mode until the change that implements it deploys. Until then the mode acts as
- # READ_FLAG_EVALUATIONS. An organization already on this mode stops the events writes when that
- # change deploys.
- FLAG_EVALUATIONS_ONLY = 2, "Flag evaluations only"
-
-
class TeamFeatureFlagsConfig(models.Model):
"""Internal-only team-level feature flags settings, written by staff and never by customers.
@@ -92,9 +75,9 @@ class TeamFeatureFlagsConfig(models.Model):
# the mode. The database default keeps older writers, and raw INSERTs that omit this column, valid
# during rolling deploys.
flag_evaluations_mode = models.SmallIntegerField(
- choices=FlagEvaluationsMode,
- default=FlagEvaluationsMode.EVENTS,
- db_default=FlagEvaluationsMode.EVENTS,
+ choices=FlagEvaluationsMode.choices,
+ default=FlagEvaluationsMode.EVENTS.value,
+ db_default=FlagEvaluationsMode.EVENTS.value,
)
class Meta:
diff --git a/products/feature_flags/backend/test/test_organization_feature_flags_config.py b/products/feature_flags/backend/test/test_organization_feature_flags_config.py
index 5a4006bfa12f..39c86afc65eb 100644
--- a/products/feature_flags/backend/test/test_organization_feature_flags_config.py
+++ b/products/feature_flags/backend/test/test_organization_feature_flags_config.py
@@ -6,9 +6,9 @@ from parameterized import parameterized
from posthog.models.instance_setting import override_instance_config
from posthog.models.organization import Organization
+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
from products.feature_flags.backend.facade.flags import is_flag_evaluations_table_enabled
from products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfig
-from products.feature_flags.backend.models.team_feature_flags_config import FlagEvaluationsMode
class TestOrganizationFeatureFlagsConfig(BaseTest):
diff --git a/products/feature_flags/backend/test/test_staff_team_config_api.py b/products/feature_flags/backend/test/test_staff_team_config_api.py
index c32cfe96562f..c2a1ff09c743 100644
--- a/products/feature_flags/backend/test/test_staff_team_config_api.py
+++ b/products/feature_flags/backend/test/test_staff_team_config_api.py
@@ -19,12 +19,12 @@ from products.feature_flags.backend.api.staff_team_config import (
StaffFlagEvaluationsModeMutationSerializer,
StaffTeamConfigMutationSerializer,
)
+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
from products.feature_flags.backend.facade.flags import get_organization_flag_evaluations_mode
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfig
from products.feature_flags.backend.models.team_feature_flags_config import (
MAX_FEATURE_FLAGS_OVERRIDE_CEILING,
- FlagEvaluationsMode,
PropertyMatchingVersion,
TeamFeatureFlagsConfig,
)
diff --git a/products/ml_inference/backend/facade/enums.py b/products/ml_inference/backend/facade/enums.py
index 8fa09b914d98..9eb008bad915 100644
--- a/products/ml_inference/backend/facade/enums.py
+++ b/products/ml_inference/backend/facade/enums.py
@@ -1,9 +1,9 @@
"""Exported enums for ml_inference."""
-from django.db import models
+from posthog.enums import LabeledStrEnum
-class DecisionQuestionType(models.TextChoices):
+class DecisionQuestionType(LabeledStrEnum):
NOUL = "noul", "Yes or no"
CHOICE = "choice", "Multiple choice"
SCORE = "score", "Rating scale"
diff --git a/products/notebooks/backend/facade/widgets.py b/products/notebooks/backend/facade/widgets.py
index b06c279b8d60..ff5084ce29e0 100644
--- a/products/notebooks/backend/facade/widgets.py
+++ b/products/notebooks/backend/facade/widgets.py
@@ -22,8 +22,8 @@ from products.notebooks.backend.widget_models import (
DEFAULT_WIDGET_MODEL,
MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH,
MAX_WIDGET_PROMPT_LENGTH,
- WIDGET_LIFECYCLE_STATUS_CHOICES,
WIDGET_MODEL_CHOICES,
+ LifecycleStatus,
)
from products.notebooks.backend.widgets import (
WidgetConflictError,
@@ -47,7 +47,7 @@ __all__ = [
"MAX_REUSABLE_WIDGET_DEMO_ROWS",
"MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH",
"MAX_WIDGET_PROMPT_LENGTH",
- "WIDGET_LIFECYCLE_STATUS_CHOICES",
+ "LifecycleStatus",
"WIDGET_MODEL_CHOICES",
"WidgetConflictError",
"WidgetError",
diff --git a/products/notebooks/backend/presentation/widget_serializers.py b/products/notebooks/backend/presentation/widget_serializers.py
index 0f3767ad08a7..cd8a636599ed 100644
--- a/products/notebooks/backend/presentation/widget_serializers.py
+++ b/products/notebooks/backend/presentation/widget_serializers.py
@@ -7,8 +7,8 @@ from products.notebooks.backend.facade.widgets import (
DEFAULT_WIDGET_MODEL,
MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH,
MAX_WIDGET_PROMPT_LENGTH,
- WIDGET_LIFECYCLE_STATUS_CHOICES,
WIDGET_MODEL_CHOICES,
+ LifecycleStatus,
)
@@ -132,7 +132,7 @@ class WidgetInputContractItemSerializer(serializers.Serializer):
class WidgetStatusSerializer(serializers.Serializer):
lifecycle_status = serializers.ChoiceField(
- choices=WIDGET_LIFECYCLE_STATUS_CHOICES,
+ choices=LifecycleStatus.choices,
help_text="Current widget and preview state.",
)
error_detail = serializers.CharField(required=False, allow_null=True, help_text="Actionable failure detail.")
diff --git a/products/notebooks/backend/widget_models.py b/products/notebooks/backend/widget_models.py
index c122ebf854d0..1ffbf42079ee 100644
--- a/products/notebooks/backend/widget_models.py
+++ b/products/notebooks/backend/widget_models.py
@@ -1,3 +1,5 @@
+from posthog.enums import LabeledStrEnum
+
WIDGET_MODEL_CHOICES = (
"claude-haiku-4-5",
"claude-sonnet-4-6",
@@ -7,14 +9,16 @@ WIDGET_MODEL_CHOICES = (
DEFAULT_WIDGET_MODEL = "claude-sonnet-5"
-WIDGET_LIFECYCLE_STATUS_CHOICES = (
- "awaiting_generation",
- "generating",
- "building",
- "ready",
- "failed",
- "incompatible",
-)
+
+# Each label repeats its value, because the API documents these choices as plain values.
+class LifecycleStatus(LabeledStrEnum):
+ AWAITING_GENERATION = "awaiting_generation", "awaiting_generation"
+ GENERATING = "generating", "generating"
+ BUILDING = "building", "building"
+ READY = "ready", "ready"
+ FAILED = "failed", "failed"
+ INCOMPATIBLE = "incompatible", "incompatible"
+
MAX_WIDGET_PROMPT_LENGTH = 20_000
MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH = 50_000
diff --git a/products/notifications/backend/facade/contracts.py b/products/notifications/backend/facade/contracts.py
index b665a8fe189b..8dbd302c49e3 100644
--- a/products/notifications/backend/facade/contracts.py
+++ b/products/notifications/backend/facade/contracts.py
@@ -1,7 +1,7 @@
from __future__ import annotations
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, Protocol
from uuid import UUID
from products.notifications.backend.facade.enums import (
@@ -13,7 +13,19 @@ from products.notifications.backend.facade.enums import (
)
if TYPE_CHECKING:
- from products.notifications.backend.resolvers import RecipientsResolver
+ from posthog.models import Team
+
+
+class RecipientsResolverProtocol(Protocol):
+ """What notification delivery calls on a custom resolver.
+
+ backend.resolvers.RecipientsResolver implements it, and products subclass that class to
+ change who receives a notification.
+ """
+
+ def resolve(self, target_type: TargetType, target_id: str, team_id: int | None) -> list[int]: ...
+
+ def filter_by_access_control(self, user_ids: list[int], resource_type: str, team: Team) -> list[int]: ...
@dataclass(frozen=True)
@@ -32,5 +44,5 @@ class NotificationData:
source_id: str | None = None
priority: Priority = Priority.NORMAL
metadata: dict[str, Any] | None = None
- resolver: RecipientsResolver | None = field(default=None, compare=False)
+ resolver: RecipientsResolverProtocol | None = field(default=None, compare=False)
idempotency_key: str | None = None
diff --git a/products/notifications/backend/facade/enums.py b/products/notifications/backend/facade/enums.py
index f0ab66196e82..3acf216d718b 100644
--- a/products/notifications/backend/facade/enums.py
+++ b/products/notifications/backend/facade/enums.py
@@ -3,8 +3,6 @@ from typing import Union
from posthog.scopes import APIScopeObject
-from products.access_control.backend.facade.user_access_control import ACCESS_CONTROL_RESOURCES
-
class NotificationType(str, Enum):
COMMENT_MENTION = "comment_mention"
@@ -68,5 +66,3 @@ class NotificationOnlyResourceType(str, Enum):
# Derived from APIScopeObject (used by ACCESS_CONTROL_RESOURCES) — keep in sync
# if ACCESS_CONTROL_RESOURCES changes its element type
type NotificationResourceType = Union[APIScopeObject, NotificationOnlyResourceType]
-
-AC_RESOURCE_TYPES: set[str] = set(ACCESS_CONTROL_RESOURCES)
diff --git a/products/notifications/backend/logic.py b/products/notifications/backend/logic.py
index aded51f81700..881066fa9624 100644
--- a/products/notifications/backend/logic.py
+++ b/products/notifications/backend/logic.py
@@ -7,10 +7,10 @@ from posthog.kafka_client.routing import get_producer
from posthog.kafka_client.topics import KAFKA_NOTIFICATION_EVENTS
from posthog.models import Organization, Team, User
+from products.access_control.backend.facade.user_access_control import ACCESS_CONTROL_RESOURCES
from products.notifications.backend.cache import invalidate_unread_count_for_users
from products.notifications.backend.facade.contracts import NotificationData
from products.notifications.backend.facade.enums import (
- AC_RESOURCE_TYPES,
RESOURCE_EDITED_EVENT_TYPE,
NotificationOnlyResourceType,
NotificationType,
@@ -125,7 +125,7 @@ def publish_resource_edited(
resolver = RecipientsResolver()
recipient_user_ids = resolver.resolve(TargetType.TEAM, str(team.id), team.id)
- if ac_resource_type and ac_resource_type in AC_RESOURCE_TYPES:
+ if ac_resource_type and ac_resource_type in ACCESS_CONTROL_RESOURCES:
recipient_user_ids = resolver.filter_by_access_control(recipient_user_ids, ac_resource_type, team)
if not recipient_user_ids:
@@ -184,7 +184,7 @@ def create_notification(data: NotificationData) -> NotificationEvent | None:
resolver = data.resolver or RecipientsResolver()
resolved_user_ids = resolver.resolve(data.target_type, data.target_id, data.team_id)
- if team is not None and data.resource_type and str(data.resource_type) in AC_RESOURCE_TYPES:
+ if team is not None and data.resource_type and str(data.resource_type) in ACCESS_CONTROL_RESOURCES:
resolved_user_ids = resolver.filter_by_access_control(resolved_user_ids, str(data.resource_type), team)
# Per-user pref filter must run AFTER AC — prefs cannot override access denials.
diff --git a/products/notifications/backend/models.py b/products/notifications/backend/models.py
index 3703a352c275..4e468f0bfc31 100644
--- a/products/notifications/backend/models.py
+++ b/products/notifications/backend/models.py
@@ -19,7 +19,7 @@ class NotificationEvent(UUIDModel):
organization = models.ForeignKey("posthog.Organization", on_delete=models.CASCADE, related_name="+")
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, null=True, blank=True, related_name="+")
notification_type = models.CharField(max_length=32, choices=notification_type_choices)
- priority = models.CharField(max_length=16, choices=priority_choices, default=Priority.NORMAL)
+ priority = models.CharField(max_length=16, choices=priority_choices, default=Priority.NORMAL.value)
title = models.CharField(max_length=255)
body = models.TextField(blank=True, default="")
resource_type = models.CharField(max_length=64, null=True, blank=True)
diff --git a/products/notifications/backend/presentation/views.py b/products/notifications/backend/presentation/views.py
index eb0875cd51aa..337fad5cc124 100644
--- a/products/notifications/backend/presentation/views.py
+++ b/products/notifications/backend/presentation/views.py
@@ -22,9 +22,8 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
from posthog.models import User
-from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.access_control.backend.facade.user_access_control import ACCESS_CONTROL_RESOURCES, UserAccessControl
from products.notifications.backend.cache import get_unread_count, invalidate_unread_count, set_unread_count
-from products.notifications.backend.facade.enums import AC_RESOURCE_TYPES
from products.notifications.backend.models import NotificationArchiveState, NotificationEvent, NotificationReadState
from products.notifications.backend.presentation.serializers import NotificationEventSerializer
@@ -111,7 +110,7 @@ class NotificationsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
.distinct()
)
- ac_types_to_check = resource_types_in_set & AC_RESOURCE_TYPES
+ ac_types_to_check = resource_types_in_set.intersection(ACCESS_CONTROL_RESOURCES)
if not ac_types_to_check:
return queryset
diff --git a/products/product_analytics/backend/facade/contracts.py b/products/product_analytics/backend/facade/contracts.py
index e4049c0573c3..c1a5c0051766 100644
--- a/products/product_analytics/backend/facade/contracts.py
+++ b/products/product_analytics/backend/facade/contracts.py
@@ -23,9 +23,8 @@ from pydantic.dataclasses import dataclass
class InsightVariableDefinition:
"""A saved query variable, as callers outside product analytics read it.
- ``type`` carries an ``InsightVariableType`` value; the field stays a plain ``str`` because
- that enum is a Django ``TextChoices`` and contracts hold no Django imports. Comparing it to
- ``InsightVariableType.LIST`` works either way.
+ ``type`` carries an ``InsightVariableType`` value. Comparing it to
+ ``InsightVariableType.LIST`` works because the enum is a ``StrEnum``.
"""
id: UUID
diff --git a/products/product_analytics/backend/facade/enums.py b/products/product_analytics/backend/facade/enums.py
index 021b01392644..1a7bc03251b1 100644
--- a/products/product_analytics/backend/facade/enums.py
+++ b/products/product_analytics/backend/facade/enums.py
@@ -1,15 +1,15 @@
"""Enumerations the product_analytics models use.
Consumers that only need a variable type read it from here and do not need the model class. The
-model keeps it as a class attribute (``InsightVariable.Type``) so ``choices=`` and existing call
-sites are unchanged. In an annotation the class attribute is not a valid type, so annotate with
+model keeps it as a class attribute (``InsightVariable.Type``) so existing call sites are
+unchanged. In an annotation the class attribute is not a valid type, so annotate with
``InsightVariableType`` directly.
"""
-from django.db import models
+from posthog.enums import LabeledStrEnum
-class InsightVariableType(models.TextChoices):
+class InsightVariableType(LabeledStrEnum):
STRING = "String", "String"
NUMBER = "Number", "Number"
BOOLEAN = "Boolean", "Boolean"
diff --git a/products/product_analytics/backend/models/insight_variable.py b/products/product_analytics/backend/models/insight_variable.py
index 6003bdf2b127..f27e7a14be65 100644
--- a/products/product_analytics/backend/models/insight_variable.py
+++ b/products/product_analytics/backend/models/insight_variable.py
@@ -11,7 +11,7 @@ class InsightVariable(UUIDTModel, RootTeamMixin, CreatedMetaFields, UpdatedMetaF
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")
name = models.CharField(max_length=400)
code_name = models.CharField(max_length=400, null=True, blank=True)
- type = models.CharField(max_length=128, choices=Type)
+ type = models.CharField(max_length=128, choices=Type.choices)
default_value = models.JSONField(null=True, blank=True)
values = models.JSONField(null=True, blank=True)
is_multi = models.BooleanField(default=False, db_default=False)
diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.py
index 5b882e9baa52..f61d239e30c0 100644
--- a/products/product_analytics/backend/presentation/insight.py
+++ b/products/product_analytics/backend/presentation/insight.py
@@ -1178,11 +1178,13 @@ class InsightSerializer(InsightBasicSerializer):
resolved_layers = resolve_filter_layers_by_priority(dashboard_filters, tile_filters_override)
return {key: value or None for key, value in resolved_layers.items()}
+ @extend_schema_field(serializers.ChoiceField(choices=RestrictionLevel.choices))
def get_effective_restriction_level(self, insight: Insight) -> RestrictionLevel:
if self.context.get("is_shared"):
return RestrictionLevel.ONLY_COLLABORATORS_CAN_EDIT
return self.user_permissions.insight(insight).effective_restriction_level
+ @extend_schema_field(serializers.ChoiceField(choices=PrivilegeLevel.choices))
def get_effective_privilege_level(self, insight: Insight) -> PrivilegeLevel:
if self.context.get("is_shared"):
return PrivilegeLevel.CAN_VIEW
diff --git a/products/signals/backend/enums.py b/products/signals/backend/enums.py
index 4de10374ca34..7589586f945b 100644
--- a/products/signals/backend/enums.py
+++ b/products/signals/backend/enums.py
@@ -2,6 +2,8 @@ from enum import StrEnum
from django.utils.functional import Promise
+from posthog.enums import LabeledStrEnum
+
# Source-of-truth taxonomy for signals. Django-free (plain StrEnum) so it stays cheap to import
# from contracts.py, the model layer, and the frontend-types codegen alike. StrEnum members compare
# equal to their string value, so they drop into `==` checks and ORM filters unchanged.
@@ -18,16 +20,16 @@ class ReportPriority(StrEnum):
P4 = "P4"
-class ReportLinkKind(StrEnum):
+class ReportLinkKind(LabeledStrEnum):
# How one report relates to another, written as a directed `report_link` artefact on the
# report the sentence starts from: "this report DEPENDS_ON that one". A GitHub issue that
# specs a stack of dependent pull requests needs the direction recorded, which the older
# symmetric `related_to` artefact cannot express.
- DEPENDS_ON = "depends_on"
- PART_OF = "part_of"
- FOLLOW_UP_OF = "follow_up_of"
- DUPLICATE_OF = "duplicate_of"
- RECURRENCE_OF = "recurrence_of"
+ DEPENDS_ON = "depends_on", "Depends on"
+ PART_OF = "part_of", "Part of"
+ FOLLOW_UP_OF = "follow_up_of", "Follow-up of"
+ DUPLICATE_OF = "duplicate_of", "Duplicate of"
+ RECURRENCE_OF = "recurrence_of", "Recurrence of"
class ReportLinkWritePath(StrEnum):
@@ -38,21 +40,6 @@ class ReportLinkWritePath(StrEnum):
PIPELINE = "pipeline"
-REPORT_LINK_KIND_LABELS: dict[ReportLinkKind, str] = {
- ReportLinkKind.DEPENDS_ON: "Depends on",
- ReportLinkKind.PART_OF: "Part of",
- ReportLinkKind.FOLLOW_UP_OF: "Follow-up of",
- ReportLinkKind.DUPLICATE_OF: "Duplicate of",
- ReportLinkKind.RECURRENCE_OF: "Recurrence of",
-}
-
-
-def report_link_kind_choices() -> list[tuple[str, str | Promise]]:
- # drf-spectacular matches an ENUM_NAME_OVERRIDES entry by a hash of the exact (value, label)
- # pairs, so the serializer's ChoiceField and the override must both read this one callable.
- return [(kind.value, label) for kind, label in REPORT_LINK_KIND_LABELS.items()]
-
-
class SignalSourceProduct(StrEnum):
SESSION_REPLAY = "session_replay"
LLM_ANALYTICS = "llm_analytics"
diff --git a/products/signals/backend/report_generation/research.py b/products/signals/backend/report_generation/research.py
index f7aea88a9a16..4a8a51add14e 100644
--- a/products/signals/backend/report_generation/research.py
+++ b/products/signals/backend/report_generation/research.py
@@ -24,7 +24,7 @@ from products.signals.backend.artefact_schemas import (
PriorityAssessment,
SignalFinding,
)
-from products.signals.backend.enums import REPORT_LINK_KIND_LABELS, ReportLinkKind
+from products.signals.backend.enums import ReportLinkKind
# Dependency-light on purpose (see its module docstring): safe to import here without dragging
# `posthog.schema` onto the research path.
@@ -649,7 +649,7 @@ def _render_linked_report_context(linked: list[LinkedReportContext]) -> str:
group = [entry for entry in linked if entry.kind == kind]
if not group:
continue
- heading = f"### {REPORT_LINK_KIND_LABELS[kind]}\n\n{_LINK_KIND_PROTOCOL[kind]}\n"
+ heading = f"### {kind.label}\n\n{_LINK_KIND_PROTOCOL[kind]}\n"
group_parts: list[str] = []
for entry in group:
key = (kind, entry.report_id)
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index b1edeacbecdc..a69335071b30 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -39,7 +39,7 @@ from products.signals.backend.artefact_schemas import (
ActionabilityChoice,
Priority,
)
-from products.signals.backend.enums import report_link_kind_choices
+from products.signals.backend.enums import ReportLinkKind
from products.signals.backend.models import SignalReportCheck, SignalScoutConfig, SignalScoutEmission
from products.signals.backend.report_charts import MAX_REPORT_CHARTS
from products.signals.backend.report_metrics import MAX_REPORT_METRICS
@@ -1498,7 +1498,7 @@ class ReportLinkWriteSerializer(serializers.Serializer):
"""One typed, directed link to write on the report being emitted or edited."""
kind = serializers.ChoiceField(
- choices=report_link_kind_choices(),
+ choices=ReportLinkKind.choices,
help_text=(
"How this report relates to `report_id`. `depends_on` for work that cannot land "
"until the other report's fix does, `part_of` for one piece of a larger report, "
diff --git a/products/stamphog/backend/models.py b/products/stamphog/backend/models.py
index 2c0d2bc8f66f..8bdbfdda91dd 100644
--- a/products/stamphog/backend/models.py
+++ b/products/stamphog/backend/models.py
@@ -47,7 +47,7 @@ class StamphogRepoConfig(ModelActivityMixin, ProductTeamModel):
review_mode = models.CharField(
max_length=16,
choices=[(m.value, m.value) for m in ReviewMode],
- default=ReviewMode.ALL,
+ default=ReviewMode.ALL.value,
)
trigger_label = models.CharField(max_length=100, default="stamphog")
# The PostHog user who connected this repo's installation (plain id, no FK — multi-DB product).
@@ -244,12 +244,12 @@ class ReviewRun(ProductTeamModel):
status = models.CharField(
max_length=32,
choices=[(s.value, s.value) for s in ReviewRunStatus],
- default=ReviewRunStatus.QUEUED,
+ default=ReviewRunStatus.QUEUED.value,
)
verdict = models.CharField(
max_length=32,
choices=[(v.value, v.value) for v in ReviewVerdict],
- default=ReviewVerdict.NONE,
+ default=ReviewVerdict.NONE.value,
)
gate_result = models.JSONField(null=True)
output = models.JSONField(default=dict)
@@ -304,13 +304,13 @@ class DigestRun(ProductTeamModel):
resolution_source = models.CharField(
max_length=32,
choices=[(s.value, s.value) for s in ChannelResolutionSource],
- default=ChannelResolutionSource.SLACK_NAME_MATCH,
+ default=ChannelResolutionSource.SLACK_NAME_MATCH.value,
db_default=ChannelResolutionSource.SLACK_NAME_MATCH.value,
)
status = models.CharField(
max_length=32,
choices=[(s.value, s.value) for s in DigestRunStatus],
- default=DigestRunStatus.PENDING,
+ default=DigestRunStatus.PENDING.value,
)
pr_count = models.IntegerField(default=0)
# LLM (or fallback) summary output that was rendered into the Slack message.
diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.py
index 5562e7ebccab..a0ebe20d9c23 100644
--- a/products/tasks/backend/facade/contracts.py
+++ b/products/tasks/backend/facade/contracts.py
@@ -23,17 +23,17 @@ from uuid import UUID
from pydantic import Field
from pydantic.dataclasses import dataclass
+from posthog.enums import LabeledStrEnum
+
# Re-exported: the exception is defined in an import-light module so ``storage.py`` can raise it
# without dragging this module onto the ``django.setup()`` path.
from products.tasks.backend.storage_errors import TaskRunLogAppendUnserialized as TaskRunLogAppendUnserialized
-class DesktopAccessReason(StrEnum):
- STARTUP_PLAN = "startup_plan"
- PREPAID_CREDITS = "prepaid_credits"
-
-
-DESKTOP_ACCESS_REASON_SCHEMA_VALUES = [*(reason.value for reason in DesktopAccessReason), None]
+# Each label repeats its value, because the API documents these choices as plain values.
+class DesktopAccessReason(LabeledStrEnum):
+ STARTUP_PLAN = "startup_plan", "startup_plan"
+ PREPAID_CREDITS = "prepaid_credits", "prepaid_credits"
@dataclass(frozen=True)
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index afca412e23df..98c27cbaa22c 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -1246,13 +1246,10 @@ class TaskRunSetSummaryRequestSerializer(serializers.Serializer):
)
-DESKTOP_ACCESS_REASON_CHOICES = [reason.value for reason in DesktopAccessReason]
-
-
class DesktopAccessResponseSerializer(serializers.Serializer):
allowed = serializers.BooleanField(help_text="Whether the selected project can use PostHog Desktop.")
reason = serializers.ChoiceField(
- choices=DESKTOP_ACCESS_REASON_CHOICES,
+ choices=DesktopAccessReason.choices,
allow_null=True,
help_text="Why Desktop access is blocked, or null when access is allowed.",
)
@@ -1273,7 +1270,7 @@ class TaskRunErrorResponseSerializer(serializers.Serializer):
help_text="After confirmed warm startup nondelivery, echo this token in X-PostHog-Warm-Retry to retry the same run and message within 60 seconds.",
)
reason = serializers.ChoiceField(
- choices=DESKTOP_ACCESS_REASON_CHOICES,
+ choices=DesktopAccessReason.choices,
required=False,
help_text="Why PostHog Desktop access was denied, when applicable.",
)
diff --git a/products/user_interviews/backend/facade/enums.py b/products/user_interviews/backend/facade/enums.py
index ad05298345b5..8db692ede489 100644
--- a/products/user_interviews/backend/facade/enums.py
+++ b/products/user_interviews/backend/facade/enums.py
@@ -1 +1,7 @@
-SEARCH_DOCUMENT_TYPES: tuple[str, ...] = ("transcript", "summary")
+from posthog.enums import LabeledStrEnum
+
+
+# Each label repeats its value, because the API documents these choices as plain values.
+class UserInterviewSearchDocumentType(LabeledStrEnum):
+ TRANSCRIPT = "transcript", "transcript"
+ SUMMARY = "summary", "summary"
diff --git a/products/user_interviews/backend/presentation/views.py b/products/user_interviews/backend/presentation/views.py
index 504c97fc42b0..2e614d2ab286 100644
--- a/products/user_interviews/backend/presentation/views.py
+++ b/products/user_interviews/backend/presentation/views.py
@@ -47,7 +47,7 @@ from posthog.security.spreadsheet_safety import sanitize_formula_injection
from posthog.utils import absolute_uri
from ..facade.api import SHARED_INTERVIEWEE_IDENTIFIER, derive_auto_classifications, parse_interviewee_identifier
-from ..facade.enums import SEARCH_DOCUMENT_TYPES
+from ..facade.enums import UserInterviewSearchDocumentType
from ..invite_email import (
build_invite_email_context,
resolve_invite_preview,
@@ -319,7 +319,7 @@ class UserInterviewSearchRequestSerializer(serializers.Serializer):
help_text="Natural-language query to match semantically against interview transcripts and summaries.",
)
document_types = serializers.ListField(
- child=serializers.ChoiceField(choices=list(SEARCH_DOCUMENT_TYPES)),
+ child=serializers.ChoiceField(choices=UserInterviewSearchDocumentType.choices),
required=False,
allow_empty=False,
min_length=1,
@@ -358,7 +358,7 @@ class UserInterviewSearchRequestSerializer(serializers.Serializer):
class UserInterviewSearchResultSerializer(serializers.Serializer):
interview_id = serializers.UUIDField(help_text="ID of the matched UserInterview.")
document_type = serializers.ChoiceField(
- choices=list(SEARCH_DOCUMENT_TYPES),
+ choices=UserInterviewSearchDocumentType.choices,
help_text="Which document type matched — `transcript` is the raw conversation, `summary` is the AI-generated abstract.",
)
similarity = serializers.FloatField(
@@ -441,7 +441,7 @@ class UserInterviewViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
def search(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> response.Response:
body = request.validated_data
query_str: str = body["query"]
- document_types: list[str] = body.get("document_types") or list(SEARCH_DOCUMENT_TYPES)
+ document_types: list[str] = body.get("document_types") or UserInterviewSearchDocumentType.values
topic_id = body.get("topic_id")
classifications: list[str] = body.get("classifications") or []
limit: int = body.get("limit") or SEARCH_DEFAULT_LIMIT
diff --git a/products/visual_review/backend/facade/enums.py b/products/visual_review/backend/facade/enums.py
index 75dfb0f73480..aa96c0b1a261 100644
--- a/products/visual_review/backend/facade/enums.py
+++ b/products/visual_review/backend/facade/enums.py
@@ -2,6 +2,8 @@
from enum import StrEnum
+from posthog.enums import LabeledStrEnum
+
class RunStatus(StrEnum):
"""Status of a visual review run."""
@@ -91,15 +93,16 @@ class ChangeKind(StrEnum):
LAYOUT = "layout"
-class ShiftBandKind(StrEnum):
+class ShiftBandKind(LabeledStrEnum):
"""Whether a shift band marks rows the current image gained or lost.
- Named explicitly in ENUM_NAME_OVERRIDES (ShiftBandKindEnum) so the OpenAPI
- component does not collide with the other `kind` fields across products.
+ The OpenAPI component name (ShiftBandKindEnum) derives from this class, so it
+ does not collide with the other `kind` fields across products. Each label
+ repeats its value, because the API documents these choices as plain values.
"""
- INSERTED = "inserted"
- DELETED = "deleted"
+ INSERTED = "inserted", "inserted"
+ DELETED = "deleted", "deleted"
class FlakinessState(StrEnum):
diff --git a/products/visual_review/backend/models.py b/products/visual_review/backend/models.py
index c95e01c28312..67e8318bae3b 100644
--- a/products/visual_review/backend/models.py
+++ b/products/visual_review/backend/models.py
@@ -124,8 +124,10 @@ class Run(ProductTeamModel):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
repo = models.ForeignKey(Repo, on_delete=models.CASCADE, related_name="runs")
- status = models.CharField(max_length=20, choices=[(s.value, s.value) for s in RunStatus], default=RunStatus.PENDING)
- run_type = models.CharField(max_length=64, default=RunType.OTHER)
+ status = models.CharField(
+ max_length=20, choices=[(s.value, s.value) for s in RunStatus], default=RunStatus.PENDING.value
+ )
+ run_type = models.CharField(max_length=64, default=RunType.OTHER.value)
# Git context
commit_sha = models.CharField(max_length=40)
@@ -134,10 +136,10 @@ class Run(ProductTeamModel):
# Purpose and review
purpose = models.CharField(
- max_length=20, choices=[(p.value, p.value) for p in RunPurpose], default=RunPurpose.REVIEW
+ max_length=20, choices=[(p.value, p.value) for p in RunPurpose], default=RunPurpose.REVIEW.value
)
review_decision = models.CharField(
- max_length=20, choices=[(d.value, d.value) for d in ReviewDecision], default=ReviewDecision.PENDING
+ max_length=20, choices=[(d.value, d.value) for d in ReviewDecision], default=ReviewDecision.PENDING.value
)
# Legacy — derived from review_decision, kept for backward compat during migration
approved = models.BooleanField(default=False)
@@ -227,7 +229,7 @@ class RunSnapshot(ProductTeamModel):
)
result = models.CharField(
- max_length=20, choices=[(r.value, r.value) for r in SnapshotResult], default=SnapshotResult.UNCHANGED
+ max_length=20, choices=[(r.value, r.value) for r in SnapshotResult], default=SnapshotResult.UNCHANGED.value
)
# Why this snapshot was classified as UNCHANGED (empty for CHANGED/NEW/REMOVED)
classification_reason = models.CharField(
@@ -393,7 +395,7 @@ class QuarantinedIdentifier(ProductTeamModel):
source = models.CharField(
max_length=10,
choices=[(a.value, a.value) for a in ActorType],
- default=ActorType.HUMAN,
+ default=ActorType.HUMAN.value,
)
expires_at = models.DateTimeField(null=True, blank=True)
diff --git a/products/visual_review/backend/presentation/serializers.py b/products/visual_review/backend/presentation/serializers.py
index 9a4178e8777f..8eee6fff758c 100644
--- a/products/visual_review/backend/presentation/serializers.py
+++ b/products/visual_review/backend/presentation/serializers.py
@@ -94,7 +94,7 @@ class ShiftBandSerializer(DataclassSerializer):
y = serializers.IntegerField(help_text="First row of the band, in current-image coordinates.")
rows = serializers.IntegerField(help_text="How many rows the band covers.")
kind = serializers.ChoiceField(
- choices=[(kind.value, kind.value) for kind in ShiftBandKind],
+ choices=ShiftBandKind.choices,
help_text=(
"'inserted' when the current image gained these rows, 'deleted' when it lost them. "
"A deleted band has no rows of its own in the current image, so its y is the seam "
diff --git a/products/warehouse_sources/backend/facade/types.py b/products/warehouse_sources/backend/facade/types.py
index 6bf1f0d59563..3f758988de8f 100644
--- a/products/warehouse_sources/backend/facade/types.py
+++ b/products/warehouse_sources/backend/facade/types.py
@@ -1,18 +1,16 @@
"""
Shared type surface for warehouse_sources.
-The framework-light shared enums and typed structures that cross-product consumers
-compare against or annotate with. They carry Django ``TextChoices`` / ``StrEnum``
-semantics (not framework-free), so they live here as object wiring rather than in
-``facade.contracts``. Defined in the facade so the contract-check inputs always watch
-them; ``backend.types`` re-exports them for product-internal use.
+The shared enums and typed structures that cross-product consumers compare against or annotate with.
+The choices enums use ``LabeledStrEnum`` from ``posthog.enums``, so this module does not import Django.
+The module is in the facade so that the contract-check inputs watch these types.
+``backend.types`` re-exports them for product-internal use.
"""
import typing
from enum import StrEnum
-from django.db import models
-from django.utils.functional import Promise
+from posthog.enums import LabeledStrEnum
__all__ = [
"DIRECT_ENGINE_BY_SOURCE_TYPE",
@@ -73,7 +71,7 @@ class PartitionSettings(typing.NamedTuple):
partition_size: int
-class ExternalDataSourceType(models.TextChoices):
+class ExternalDataSourceType(LabeledStrEnum):
ASHBY = "Ashby", "Ashby"
SUPABASE = "Supabase", "Supabase"
CUSTOMERIO = "CustomerIO", "CustomerIO"
@@ -1429,7 +1427,7 @@ class ExternalDataSourceType(models.TextChoices):
LETTRLABS = "LettrLabs", "LettrLabs"
-def external_data_source_type_choices() -> list[tuple[str, str | Promise]]:
+def external_data_source_type_choices() -> list[tuple[typing.Any, str]]:
# Callable so growing the enum doesn't generate a no-op migration.
return list(ExternalDataSourceType.choices)
@@ -1455,12 +1453,12 @@ class ManagedWarehouseSQLMode(StrEnum):
UNAVAILABLE = "unavailable"
-class DataWarehouseManagedViewSetKind(models.TextChoices):
+class DataWarehouseManagedViewSetKind(LabeledStrEnum):
REVENUE_ANALYTICS = "revenue_analytics", "Revenue Analytics"
ENGINEERING_ANALYTICS = "engineering_analytics", "Engineering Analytics"
-class DataWarehouseTableFormat(models.TextChoices):
+class DataWarehouseTableFormat(LabeledStrEnum):
CSV = "CSV", "CSV"
CSVWithNames = "CSVWithNames", "CSVWithNames"
Parquet = "Parquet", "Parquet"
@@ -1469,7 +1467,7 @@ class DataWarehouseTableFormat(models.TextChoices):
DeltaS3Wrapper = "DeltaS3Wrapper", "DeltaS3Wrapper"
-class DataWarehouseTableCreatedVia(models.TextChoices):
+class DataWarehouseTableCreatedVia(LabeledStrEnum):
# The first five mirror `ExternalDataSource.CreatedVia` value-for-value, so table and source
# attribution can be counted together. The last three have no source equivalent — they cover
# the tables PostHog creates itself, which a request surface would otherwise misattribute to
@@ -1484,7 +1482,7 @@ class DataWarehouseTableCreatedVia(models.TextChoices):
DEMO = "demo", "demo"
-class ExternalDataJobStatus(models.TextChoices):
+class ExternalDataJobStatus(LabeledStrEnum):
RUNNING = "Running", "Running"
FAILED = "Failed", "Failed"
COMPLETED = "Completed", "Completed"
@@ -1492,18 +1490,18 @@ class ExternalDataJobStatus(models.TextChoices):
BILLING_LIMIT_TOO_LOW = "BillingLimitTooLow", "BillingLimitTooLow"
-class ExternalDataJobPipelineVersion(models.TextChoices):
+class ExternalDataJobPipelineVersion(LabeledStrEnum):
V1 = "v1-dlt-sync", "v1-dlt-sync"
V2 = "v2-non-dlt", "v2-non-dlt"
V3 = "v3-kafka-s3", "v3-kafka-s3"
-class ExternalDataSourceAccessMethod(models.TextChoices):
+class ExternalDataSourceAccessMethod(LabeledStrEnum):
WAREHOUSE = "warehouse", "warehouse"
DIRECT = "direct", "direct"
-class ExternalDataSourceCreatedVia(models.TextChoices):
+class ExternalDataSourceCreatedVia(LabeledStrEnum):
WEB = "web", "web"
API = "api", "api"
MCP = "mcp", "mcp"
@@ -1511,7 +1509,7 @@ class ExternalDataSourceCreatedVia(models.TextChoices):
SELF_DRIVING = "self_driving", "self_driving"
-class ExternalDataSourceStatus(models.TextChoices):
+class ExternalDataSourceStatus(LabeledStrEnum):
RUNNING = "Running", "Running"
PAUSED = "Paused", "Paused"
ERROR = "Error", "Error"
@@ -1519,7 +1517,7 @@ class ExternalDataSourceStatus(models.TextChoices):
CANCELLED = "Cancelled", "Cancelled"
-class ExternalDataSchemaStatus(models.TextChoices):
+class ExternalDataSchemaStatus(LabeledStrEnum):
RUNNING = "Running", "Running"
PAUSED = "Paused", "Paused"
FAILED = "Failed", "Failed"
@@ -1528,7 +1526,7 @@ class ExternalDataSchemaStatus(models.TextChoices):
BILLING_LIMIT_TOO_LOW = "BillingLimitTooLow", "BillingLimitTooLow"
-class ExternalDataSchemaSyncType(models.TextChoices):
+class ExternalDataSchemaSyncType(LabeledStrEnum):
FULL_REFRESH = "full_refresh", "full_refresh"
INCREMENTAL = "incremental", "incremental"
APPEND = "append", "append"
@@ -1537,7 +1535,7 @@ class ExternalDataSchemaSyncType(models.TextChoices):
XMIN = "xmin", "xmin"
-class IncrementalSyncBlockedReason(models.TextChoices):
+class IncrementalSyncBlockedReason(LabeledStrEnum):
"""Why the last sync run could not merge rows on a schema's primary key.
A missing key is a configuration state and stays until someone picks one. A duplicate key is a
@@ -1549,14 +1547,14 @@ class IncrementalSyncBlockedReason(models.TextChoices):
DUPLICATE_PRIMARY_KEY = "duplicate_primary_key", "Duplicate primary key"
-class ExternalDataSchemaSyncFrequency(models.TextChoices):
+class ExternalDataSchemaSyncFrequency(LabeledStrEnum):
DAILY = "day", "Daily"
WEEKLY = "week", "Weekly"
MONTHLY = "month", "Monthly"
# TODO provide flexible schedule definition
-class WarehouseColumnAnnotationDescriptionSource(models.TextChoices):
+class WarehouseColumnAnnotationDescriptionSource(LabeledStrEnum):
CANONICAL = "canonical", "Canonical"
AI_GENERATED = "ai_generated", "AI generated"
USER_EDITED = "user_edited", "User edited"
diff --git a/products/warehouse_sources/backend/models/column_annotation.py b/products/warehouse_sources/backend/models/column_annotation.py
index 289d63c7d28a..0b18df67f123 100644
--- a/products/warehouse_sources/backend/models/column_annotation.py
+++ b/products/warehouse_sources/backend/models/column_annotation.py
@@ -16,7 +16,7 @@ class WarehouseColumnAnnotation(TeamScopedRootMixin, CreatedMetaFields, UpdatedM
marked `is_user_edited` is never overwritten by automatic enrichment.
"""
- # Kept on the model so the nested names and the `choices=` below stay unchanged.
+ # Kept on the model so the nested names stay unchanged.
DescriptionSource = WarehouseColumnAnnotationDescriptionSource
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")
@@ -26,7 +26,7 @@ class WarehouseColumnAnnotation(TeamScopedRootMixin, CreatedMetaFields, UpdatedM
# Empty string = table-level annotation; otherwise the column this describes.
column_name = models.CharField(max_length=400, blank=True, default="")
description = models.TextField()
- description_source = models.CharField(max_length=32, choices=DescriptionSource)
+ description_source = models.CharField(max_length=32, choices=DescriptionSource.choices)
ai_model = models.CharField(max_length=128, null=True, blank=True)
is_user_edited = models.BooleanField(default=False)
diff --git a/products/warehouse_sources/backend/models/external_data_job.py b/products/warehouse_sources/backend/models/external_data_job.py
index 356434373c96..c42b2bf7d59b 100644
--- a/products/warehouse_sources/backend/models/external_data_job.py
+++ b/products/warehouse_sources/backend/models/external_data_job.py
@@ -14,7 +14,7 @@ from products.warehouse_sources.backend.types import ExternalDataJobPipelineVers
class ExternalDataJob(CreatedMetaFields, UpdatedMetaFields, UUIDTModel):
- # Kept on the model so the nested names and the `choices=` below stay unchanged.
+ # Kept on the model so the nested names stay unchanged.
Status = ExternalDataJobStatus
PipelineVersion = ExternalDataJobPipelineVersion
@@ -41,7 +41,7 @@ class ExternalDataJob(CreatedMetaFields, UpdatedMetaFields, UUIDTModel):
workflow_id = models.CharField(max_length=400, null=True, blank=True)
workflow_run_id = models.CharField(max_length=400, null=True, blank=True)
- pipeline_version = models.CharField(max_length=400, choices=PipelineVersion, null=True, blank=True)
+ pipeline_version = models.CharField(max_length=400, choices=PipelineVersion.choices, null=True, blank=True)
billable = models.BooleanField(default=True, null=True, blank=True)
# The destinations this run delivers to, snapshotted when the run started so a config
# change mid-run cannot alter where an in-flight run lands or what it bills. Empty means
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 3b7ad01f04ff..07642b61db1e 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -230,7 +230,7 @@ CDC_SNAPSHOT_LANE_KEY = "cdc_snapshot_lane"
class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-django-pk -- grandfathered UUIDT primary key
ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields, UUIDTModel, DeletedMetaFields
):
- # Kept on the model so the nested names and the `choices=` below stay unchanged.
+ # Kept on the model so the nested names stay unchanged.
Status = ExternalDataSchemaStatus
SyncType = ExternalDataSchemaSyncType
SyncFrequency = ExternalDataSchemaSyncFrequency
@@ -257,7 +257,7 @@ class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-djan
)
status = models.CharField(max_length=400, null=True, blank=True)
last_synced_at = models.DateTimeField(null=True, blank=True)
- sync_type = models.CharField(max_length=128, choices=SyncType, null=True, blank=True)
+ sync_type = models.CharField(max_length=128, choices=SyncType.choices, null=True, blank=True)
# User-managed vendor API version override for this schema. NULL (the norm) means the schema
# syncs on its source's pinned version; a value here wins over the source pin. Deliberately
# ignored by version-migration tooling — only the user changes it. Not available for
@@ -278,7 +278,9 @@ class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-djan
s3_folder_name = models.CharField(max_length=400, null=True, blank=True)
# Deprecated in favour of `sync_frequency_interval`
sync_frequency = deprecate_field(
- models.CharField(max_length=128, choices=SyncFrequency, default=SyncFrequency.DAILY, blank=True, null=True)
+ models.CharField(
+ max_length=128, choices=SyncFrequency.choices, default=SyncFrequency.DAILY.value, blank=True, null=True
+ )
)
sync_frequency_interval = models.DurationField(default=timedelta(hours=6), null=True, blank=True)
sync_time_of_day = models.TimeField(null=True, blank=True, help_text="Time of day to run the sync (UTC)")
diff --git a/products/warehouse_sources/backend/models/external_data_source.py b/products/warehouse_sources/backend/models/external_data_source.py
index 692eba28f020..0a92d99a1b78 100644
--- a/products/warehouse_sources/backend/models/external_data_source.py
+++ b/products/warehouse_sources/backend/models/external_data_source.py
@@ -37,7 +37,7 @@ class ExternalDataSourceManager(models.Manager):
class ExternalDataSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields, UUIDTModel, DeletedMetaFields):
- # Kept on the model so the nested names and the `choices=` below stay unchanged.
+ # Kept on the model so the nested names stay unchanged.
AccessMethod = ExternalDataSourceAccessMethod
CreatedVia = ExternalDataSourceCreatedVia
Status = ExternalDataSourceStatus
@@ -51,7 +51,9 @@ class ExternalDataSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")
# Deprecated, use `ExternalDataSchema.sync_frequency_interval`
- sync_frequency = models.CharField(max_length=128, choices=SyncFrequency, default=SyncFrequency.DAILY, blank=True)
+ sync_frequency = models.CharField(
+ max_length=128, choices=SyncFrequency.choices, default=SyncFrequency.DAILY.value, blank=True
+ )
# `status` is deprecated in favour of external_data_schema.status
status = models.CharField(max_length=400)
@@ -68,8 +70,8 @@ class ExternalDataSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
description = models.CharField(max_length=400, null=True, blank=True)
# How this source was created — e.g. web UI, direct API call, or MCP tool. Required for new rows
# via the serializer; NULL on historical rows created before this field existed.
- created_via = models.CharField(max_length=20, choices=CreatedVia, null=True, blank=True)
- access_method = models.CharField(max_length=32, choices=AccessMethod, default=AccessMethod.WAREHOUSE)
+ created_via = models.CharField(max_length=20, choices=CreatedVia.choices, null=True, blank=True)
+ access_method = models.CharField(max_length=32, choices=AccessMethod.choices, default=AccessMethod.WAREHOUSE.value)
# Lets a synced (warehouse) source also be live-queryable via direct connection; ignored for pure direct sources.
# Off by default — a user opts a synced source in explicitly before it becomes live-queryable.
direct_query_enabled = models.BooleanField(default=False)
diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.py
index 04058b2a3a7e..1aace48bb41d 100644
--- a/products/warehouse_sources/backend/models/table.py
+++ b/products/warehouse_sources/backend/models/table.py
@@ -410,12 +410,12 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
# Use if it's certain externaldataschemas aren't needed
raw_objects = DataWarehouseTableQuerySet.as_manager()
- # Kept on the model so the nested names and the `choices=` below stay unchanged.
+ # Kept on the model so the nested names stay unchanged.
TableFormat = DataWarehouseTableFormat
CreatedVia = DataWarehouseTableCreatedVia
name = models.CharField(max_length=128)
- format = models.CharField(max_length=128, choices=TableFormat)
+ format = models.CharField(max_length=128, choices=TableFormat.choices)
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")
url_pattern = models.CharField(max_length=500)
@@ -427,7 +427,7 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
# Where this table came from — the request surface for user-created tables, or the internal
# path that built it. Derived server-side (never taken from the request body) so a client can't
# self-label. NULL on rows created before this field existed.
- created_via = models.CharField(max_length=20, choices=CreatedVia, null=True, blank=True)
+ created_via = models.CharField(max_length=20, choices=CreatedVia.choices, null=True, blank=True)
columns = models.JSONField(
default=dict,
diff --git a/products/wizard/backend/facade/enums.py b/products/wizard/backend/facade/enums.py
index e422be18b12b..8c19e1ffb3d4 100644
--- a/products/wizard/backend/facade/enums.py
+++ b/products/wizard/backend/facade/enums.py
@@ -8,6 +8,8 @@ the implementation (logic.py, models.py).
from enum import StrEnum
+from posthog.enums import LabeledStrEnum
+
class WizardSessionRunPhase(StrEnum):
IDLE = "idle"
@@ -26,14 +28,12 @@ class WizardSessionTaskStatus(StrEnum):
CANCELED = "canceled"
-class WizardTaskStatus(StrEnum):
- CREATED = "created"
- RUNNING = "running"
- COMPLETED = "completed"
- FAILED = "failed"
-
-
-WIZARD_TASK_STATUS_CHOICES = [(status.value, status.value) for status in WizardTaskStatus]
+# Each label repeats its value, because the API documents these choices as plain values.
+class WizardTaskStatus(LabeledStrEnum):
+ CREATED = "created", "created"
+ RUNNING = "running", "running"
+ COMPLETED = "completed", "completed"
+ FAILED = "failed", "failed"
class WizardRunStatus(StrEnum):
diff --git a/products/wizard/backend/presentation/runs/serializers.py b/products/wizard/backend/presentation/runs/serializers.py
index 6e1d2bd6197d..6cf9c09fc5b7 100644
--- a/products/wizard/backend/presentation/runs/serializers.py
+++ b/products/wizard/backend/presentation/runs/serializers.py
@@ -13,7 +13,6 @@ from products.wizard.backend.facade.contracts import (
WizardWorkspace,
)
from products.wizard.backend.facade.enums import (
- WIZARD_TASK_STATUS_CHOICES,
WizardRunEnvironment,
WizardRunErrorCode,
WizardRunStage,
@@ -211,7 +210,7 @@ class UpdateWizardRunTaskSerializer(serializers.Serializer):
)
status = serializers.ChoiceField(
- choices=WIZARD_TASK_STATUS_CHOICES,
+ choices=WizardTaskStatus.choices,
help_text="Current task status reported by the setup agent.",
)
@@ -244,7 +243,7 @@ class WizardRunTaskSerializer(serializers.Serializer):
status = serializers.ChoiceField(
read_only=True,
- choices=WIZARD_TASK_STATUS_CHOICES,
+ choices=WizardTaskStatus.choices,
help_text="Current task status reported by the setup agent.",
)
diff --git a/pyproject.toml b/pyproject.toml
index a4492672c9b3..80e3c514924a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -898,6 +898,22 @@ ignore_imports = [
"products.tasks.backend.facade.client_provenance -> rest_framework",
]
+# Contract files hold the data types other products read, so they stay free of Django, directly
+# and through other product modules. Define a choices enum with posthog.enums.LabeledStrEnum or
+# LabeledIntEnum instead of models.TextChoices. import-linter treats posthog as an external
+# package, so Django reached through posthog.* is not visible here. See products/architecture.md
+# § Contracts.
+[[tool.importlinter.contracts]]
+name = "facade contracts and enums must not import Django (use posthog.enums for choices)"
+type = "forbidden"
+source_modules = [
+ "products.*.backend.facade.contracts",
+ "products.*.backend.facade.enums",
+ "products.*.backend.facade.types",
+]
+forbidden_modules = ["django"]
+allow_indirect_imports = false
+
[tool.ty.rules]
# Import resolution - ty can't always find all modules/stubs
unresolved-import = "ignore"
diff --git a/tools/hogli-commands/hogli_commands/product_structure.yaml b/tools/hogli-commands/hogli_commands/product_structure.yaml
index 7fa9a07038eb..1913c2b0eeee 100644
--- a/tools/hogli-commands/hogli_commands/product_structure.yaml
+++ b/tools/hogli-commands/hogli_commands/product_structure.yaml
@@ -150,8 +150,9 @@ backend_files:
name = models.CharField(max_length=255)
status = models.CharField(
max_length=32,
- choices=[(s.value, s.value) for s in SplineStatus],
- default=SplineStatus.PENDING,
+ choices=SplineStatus.choices,
+ # A member default would make the migration import the enum's module.
+ default=SplineStatus.PENDING.value,
)
created_at = models.DateTimeField(auto_now_add=True)
@@ -287,12 +288,15 @@ backend_files:
If an enum appears in a contract dataclass field, it belongs here.
Internal-only constants (DB magic values, feature flags) stay in
the implementation (logic.py, models.py).
+
+ No Django imports: use LabeledStrEnum or LabeledIntEnum, not
+ models.TextChoices, for an enum that backs model or serializer choices.
"""
- from enum import StrEnum
+ from posthog.enums import LabeledStrEnum
- class SplineStatus(StrEnum):
+ class SplineStatus(LabeledStrEnum):
PENDING = "pending"
RETICULATED = "reticulated"