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.

chore(devex): flag new choices lists that bypass a class (#113727)

Julian Bezd23dd01580e1
diff --git a/.semgrep/rules/devex/choices-need-a-class.py b/.semgrep/rules/devex/choices-need-a-class.py
new file mode 100644
index 000000000000..ba66234dd48f
--- /dev/null
+++ b/.semgrep/rules/devex/choices-need-a-class.py
@@ -0,0 +1,99 @@
+# Test cases for choices-need-a-class.
+# ruff: noqa
+import typing
+from typing import Literal, get_args
+
+from django.db import models
+
+from rest_framework import fields, serializers
+from rest_framework.fields import ChoiceField
+
+from posthog.enums import LabeledStrEnum
+
+ConflictCode = Literal["dataset_archived", "stale_version"]
+CADENCE_CHOICES = [("daily", "Daily"), ("weekly", "Weekly")]
+
+
+class Stage(models.TextChoices):
+ DRAFT = "draft"
+ LIVE = "live"
+
+
+class PinKind(LabeledStrEnum):
+ PINNED = "pinned"
+
+
+class ExampleSerializer(serializers.Serializer):
+ # ruleid: choices-need-a-class
+ code = serializers.ChoiceField(choices=["dataset_archived", "stale_version"])
+
+ # ruleid: choices-need-a-class
+ status = serializers.ChoiceField(["active", "resolved"], required=False)
+
+ # ruleid: choices-need-a-class
+ tags = serializers.MultipleChoiceField(choices=[("a", "A"), ("b", "B")])
+
+ # ruleid: choices-need-a-class
+ level = serializers.ChoiceField(choices=[stage.value for stage in Stage])
+
+ # ruleid: choices-need-a-class
+ reason = serializers.ChoiceField(choices=get_args(ConflictCode))
+
+ # ruleid: choices-need-a-class
+ other_reason = serializers.ChoiceField(choices=typing.get_args(ConflictCode))
+
+ # ruleid: choices-need-a-class
+ kind = ChoiceField(choices=["freeform", "grid"])
+
+ # ruleid: choices-need-a-class
+ mode = fields.ChoiceField(choices=["fast", "slow"])
+
+ # ruleid: choices-need-a-class
+ sources = serializers.ListField(child=serializers.ChoiceField(choices=["manual", "agent"]))
+
+ # ruleid: choices-need-a-class
+ wrapped = serializers.ChoiceField(choices=list(get_args(ConflictCode)))
+
+ # ruleid: choices-need-a-class
+ positional_literal = serializers.ChoiceField(get_args(ConflictCode))
+
+ # ruleid: choices-need-a-class
+ as_tuple = serializers.ChoiceField(choices=("low", "high"))
+
+ # ruleid: choices-need-a-class
+ from_constant = serializers.ChoiceField(choices=CADENCE_CHOICES)
+
+ # ruleid: choices-need-a-class
+ sorted_values = serializers.ChoiceField(choices=sorted({"b", "a"}))
+
+ # ruleid: choices-need-a-class
+ bare_class = serializers.ChoiceField(choices=PinKind)
+
+ # ok: choices-need-a-class
+ stage = serializers.ChoiceField(choices=Stage.choices)
+
+ # ok: choices-need-a-class
+ stage_copy = serializers.ChoiceField(choices=list(Stage.choices))
+
+ # ok: choices-need-a-class
+ pin_kind = serializers.ChoiceField(choices=PinKind.choices)
+
+ # ok: choices-need-a-class
+ exempt = serializers.ChoiceField(choices=["x", "y"]) # nosemgrep: choices-need-a-class -- test exemption
+
+
+class ExampleModel(models.Model):
+ # ruleid: choices-need-a-class
+ cadence = models.CharField(max_length=10, choices=[("daily", "Daily"), ("weekly", "Weekly")])
+
+ # ruleid: choices-need-a-class
+ level = models.CharField(max_length=10, choices=(("low", "Low"), ("high", "High")))
+
+ # ok: choices-need-a-class
+ stage = models.CharField(max_length=10, choices=Stage.choices)
+
+ # ok: choices-need-a-class
+ bare_stage = models.CharField(max_length=10, choices=Stage)
+
+ # ok: choices-need-a-class
+ name = models.CharField(max_length=10)
diff --git a/.semgrep/rules/devex/choices-need-a-class.yaml b/.semgrep/rules/devex/choices-need-a-class.yaml
new file mode 100644
index 000000000000..243781ac2221
--- /dev/null
+++ b/.semgrep/rules/devex/choices-need-a-class.yaml
@@ -0,0 +1,95 @@
+rules:
+ - id: choices-need-a-class
+ message: |
+ These `choices=` do not come from a class.
+
+ drf-spectacular names an enum after its class. A list, a tuple or a Literal has no
+ class, so the enum gets the field name (`code` -> `CodeEnum`). When a second field with that
+ name and other values comes into the API, the first enum gets a new name and
+ the frontend imports of its generated type break. The usual patch is an
+ ENUM_NAME_OVERRIDES entry in posthog/settings/web.py.
+
+ Define the values as a class and pass its `.choices`:
+
+ class DatasetConflictCode(models.TextChoices):
+ DATASET_ARCHIVED = "dataset_archived"
+ ...
+
+ code = serializers.ChoiceField(choices=DatasetConflictCode.choices)
+
+ In a facade contract file (`backend/facade/contracts.py`, `backend/facade/enums.py`)
+ use `LabeledStrEnum` or `LabeledIntEnum` from `posthog/enums.py`, because those
+ files must not import Django. For a subset of an existing class, define a second
+ class. The component name comes from the class (`DatasetConflictCodeEnum`),
+ see `/improving-drf-endpoints`.
+
+ Add an ENUM_NAME_OVERRIDES entry only when no class can give the name, for
+ example when two classes have identical (value, label) pairs. The comments in
+ that dict list these cases.
+
+ Lists that already exist are not blocked. For a genuine exception, add
+ `# nosemgrep: choices-need-a-class -- <reason>` on the line.
+ severity: WARNING
+ languages: [python]
+ paths:
+ include:
+ - 'common/**/*.py'
+ - 'ee/**/*.py'
+ - 'posthog/**/*.py'
+ - 'products/**/*.py'
+ exclude:
+ - '**/migrations/**'
+ - '**/test/**'
+ - '**/tests/**'
+ - '**/test_*.py'
+ - '**/.semgrep/**'
+ pattern-either:
+ - patterns:
+ - pattern-either: &field_calls
+ - pattern: rest_framework.serializers.ChoiceField(..., choices=$CHOICES, ...)
+ - pattern: rest_framework.serializers.ChoiceField($CHOICES, ...)
+ - pattern: rest_framework.serializers.MultipleChoiceField(..., choices=$CHOICES, ...)
+ - pattern: rest_framework.serializers.MultipleChoiceField($CHOICES, ...)
+ - pattern: rest_framework.fields.ChoiceField(..., choices=$CHOICES, ...)
+ - pattern: rest_framework.fields.ChoiceField($CHOICES, ...)
+ - pattern: rest_framework.fields.MultipleChoiceField(..., choices=$CHOICES, ...)
+ - pattern: rest_framework.fields.MultipleChoiceField($CHOICES, ...)
+ # A ModelSerializer builds its ChoiceField from the model field.
+ - pattern: django.db.models.$FIELD(..., choices=$CHOICES, ...)
+ - metavariable-pattern:
+ metavariable: $CHOICES
+ patterns: &no_class
+ - pattern-either:
+ # List and tuple literals, and list comprehensions.
+ - pattern: '[...]'
+ - pattern: '($FIRST, ...)'
+ - pattern: list(...)
+ - pattern: tuple(...)
+ - pattern: sorted(...)
+ # The values of a typing.Literal.
+ - pattern: typing.get_args(...)
+ - pattern-not: list($CLASS.choices)
+ - pattern-not: tuple($CLASS.choices)
+ # A class passed bare to a DRF field: DRF reads its members without the labels, so no name derives.
+ - patterns:
+ - pattern-either:
+ - pattern: rest_framework.serializers.ChoiceField(..., choices=$CHOICES, ...)
+ - pattern: rest_framework.serializers.MultipleChoiceField(..., choices=$CHOICES, ...)
+ - pattern: rest_framework.fields.ChoiceField(..., choices=$CHOICES, ...)
+ - pattern: rest_framework.fields.MultipleChoiceField(..., choices=$CHOICES, ...)
+ - metavariable-regex:
+ metavariable: $CHOICES
+ regex: ^[A-Z][a-z][A-Za-z0-9]*$
+ # A name that the same file binds to one of the forms above.
+ - patterns:
+ - pattern-inside: |
+ $CHOICES = $VALUE
+ ...
+ - pattern-either: *field_calls
+ - metavariable-pattern:
+ metavariable: $VALUE
+ patterns: *no_class
+ metadata:
+ category: best-practice
+ subcategory:
+ - audit