:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(devex): name 20 enum overrides through classes (#113733)
Julian Bezb73f0b3662b4
diff --git a/ee/hogai/api/serializers.py b/ee/hogai/api/serializers.pyindex ee912b5c0771..64a94c0fad05 100644--- a/ee/hogai/api/serializers.py+++ b/ee/hogai/api/serializers.py@@ -158,7 +158,7 @@ class TaskRunDetailSerializer(DataclassSerializer):log_url = serializers.URLField(allow_null=True, required=False, help_text="Presigned S3 URL for log access.")artifacts = TaskRunArtifactResponseSerializer(many=True, read_only=True)runtime_adapter = serializers.ChoiceField(- choices=[adapter.value for adapter in RuntimeAdapter],+ choices=RuntimeAdapter.choices,allow_null=True,required=False,help_text="Configured runtime adapter for this run, such as 'claude' or 'codex'.",diff --git a/posthog/api/team.py b/posthog/api/team.pyindex a29c0411c252..cc845890ec08 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -130,7 +130,7 @@ from products.customer_analytics.backend.facade.account_property_pins import (validate_pinned_account_properties,)from products.customer_analytics.backend.facade.contracts import PinnedAccountProperty-from products.customer_analytics.backend.facade.enums import ACCOUNT_PROPERTY_PIN_KIND_CHOICES+from products.customer_analytics.backend.facade.enums import AccountPropertyPinKindfrom products.customer_analytics.backend.facade.team_extension import TeamCustomerAnalyticsConfigfrom products.dashboards.backend.models import Dashboardfrom products.feature_flags.backend.facade.enums import FlagEvaluationsMode@@ -1060,7 +1060,7 @@ class TeamFeatureFlagPolicyConfigSerializer(serializers.ModelSerializer, UserAccclass TeamCustomerAnalyticsPinnedAccountPropertySerializer(serializers.Serializer):kind = serializers.ChoiceField(- choices=ACCOUNT_PROPERTY_PIN_KIND_CHOICES,+ choices=AccountPropertyPinKind.choices,help_text="Definition type for this default pinned account property.",)id = serializers.UUIDField(help_text="Project-scoped custom property or relationship definition UUID.")diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 5bd4dbb03773..550c8963e7b6 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -647,8 +647,6 @@ SPECTACULAR_SETTINGS = {],# replay_vision alert destinations: the create body and the alert's listed destinations share this set."VisionAlertDestinationTypeEnum": ["slack", "webhook"],- # The API-only pin kind uses StrEnum; name its component without a Django Choices class.- "AccountPropertyPinKindEnum": "products.customer_analytics.backend.facade.enums.ACCOUNT_PROPERTY_PIN_KIND_CHOICES","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,@@ -672,7 +670,6 @@ SPECTACULAR_SETTINGS = {# warehouse's own SyncStatus, but that class carries different labels, so the two are# distinct choice sets and this one needs its own name."SignalSourceSyncStatusEnum": ["running", "completed", "failed"],- "RunSourceEnum": ["manual", "signal_report", "agent"],"TaskBootstrapRunSourceEnum": ["manual", "signal_report"],# Completion providers are a subset of LLMProvider that excludes evaluation-only models."LLMCompletionProviderEnum": "products.ai_observability.backend.models.provider_keys.llm_completion_provider_choices",@@ -771,12 +768,9 @@ SPECTACULAR_SETTINGS = {# The choices are computed: a subset or union of another definition, a plain# Python enum's values, or a per-widget constant. Converting each producer to# a TextChoices class would delete its entry here.- "TaskChannelWriteTypeEnum": "products.tasks.backend.facade.enums.CHANNEL_WRITE_TYPE_CHOICES","ChannelTypeEnum": "products.error_tracking.backend.facade.alerts.ALERT_CHANNEL_TYPES","TicketChannelFilterEnum": "products.conversations.backend.api.ticket_filters.TICKET_CHANNEL_FILTER_CHOICES","TicketSlaFilterEnum": "products.conversations.backend.api.ticket_filters.TICKET_SLA_FILTER_CHOICES",- "TicketSortOrderEnum": "products.conversations.backend.api.ticket_filters.TICKET_SORT_ORDER_CHOICES",- "UtmIssueKindEnum": "products.marketing_analytics.backend.services.types.UTM_ISSUE_KIND_CHOICES","ConversionGoalKindEnum": "products.marketing_analytics.backend.hogql_queries.constants.CONVERSION_GOAL_KIND_CHOICES","ReasoningEffortEnum": ["low", "medium", "high", "xhigh", "max", "ultracode", None],"TaskRunReasoningEffortEnum": [@@ -792,39 +786,13 @@ SPECTACULAR_SETTINGS = {],"TileSpacingEnum": ["tight", "condensed", "standard", "relaxed", "wide"],"DataQualityCheckSeverityEnum": ["error", "warn"],- "DataQualityScheduleIntervalEnum": "products.data_quality.backend.facade.enums.schedule_interval_choices",- "CanvasStateScopeEnum": ["user", "shared"],- "CanvasKindEnum": ["freeform", "grid", "component"],- "CanvasPlacementStatusEnum": ["pending", "generating", "live", "failed"],"CanvasGridColumnsEnum": [(4, 4), (6, 6), (8, 8), (10, 10), (12, 12)],"CanvasLayoutSchemaVersionEnum": [(1, 1)],- "ExperimentSessionBucketEnum": ["fired_any", "no_metric_activity", "funnel_dropoff"],- "ExperimentWatchCardKindEnum": ["behavior", "friction", "variant_only", "metric"],- "ExperimentWatchCardStrengthEnum": ["only", "far_more", "more", "slightly_more"],"ExperimentWatchMultipleVariantHandlingEnum": ["exclude", "first_seen"],- "ExperimentWatchEmptyReasonEnum": [- "too_early",- "no_separation",- "no_recordings",- "no_session_linked_exposures",- ],"ReviewIssuePriorityEnum": ["must_fix", "should_fix", "consider"],"OtelMetricTypeEnum": ["gauge", "sum", "histogram", "exponential_histogram", "summary"],- "VerdictEnum": ["yes", "no", "inconclusive"],"AIObservabilityInstrumentationCheckEnum": ["sessions", "tool_calls", "user_identity", "trace_structure"],"LoopTriggerTypeEnum": ["schedule", "github", "api"],- "CustomPropertyOptionColorEnum": [f"preset-{i}" for i in range(1, 11)],- "SavedQuerySyncFrequencyEnum": [- "never",- "15min",- "30min",- "1hour",- "6hour",- "12hour",- "24hour",- "7day",- "30day",- ],"MaterializeSyncFrequencyEnum": ["15min","30min",@@ -835,17 +803,6 @@ SPECTACULAR_SETTINGS = {"7day","30day",],- "AssigneeTypeEnum": ["user", "role"],- "TaskRunArtifactTypeEnum": [- "plan",- "context",- "reference",- "output",- "artifact",- "tree_snapshot",- "user_attachment",- "skill_bundle",- ],"ArtifactType2f0Enum": ["slack_message","slack_canvas",@@ -858,10 +815,8 @@ SPECTACULAR_SETTINGS = {"AdapterEnum": ["slack_message", "slack_canvas", "slack_file", "document_connector", "github_pr"],"ActionStepMatchingEnum": ["contains", "regex", "exact"],"DetailModeValueEnum": ["minimal", "detailed"],- "RuntimeAdapterEnum": ["claude", "codex"],"ClaudeRuntimeAdapterEnum": ["claude"],"CodexRuntimeAdapterEnum": ["codex"],- "StaffCacheKindEnum": ["evaluation", "definitions"],"TrialEvidenceSourceKindEnum": ["instructions", "context", "summary", "report", "memory", "trace"],## One single-value discriminator enum per dashboard widget.diff --git a/products/canvas/backend/facade/enums.py b/products/canvas/backend/facade/enums.pyindex 10596aaff975..85b4df37b9d5 100644--- a/products/canvas/backend/facade/enums.py+++ b/products/canvas/backend/facade/enums.py@@ -34,14 +34,33 @@ class CanvasAccess(LabeledStrEnum):DELETE = "delete"-CANVAS_KIND_FREEFORM = "freeform"-CANVAS_KIND_GRID = "grid"-CANVAS_KIND_COMPONENT = "component"-CANVAS_KINDS = [CANVAS_KIND_FREEFORM, CANVAS_KIND_GRID, CANVAS_KIND_COMPONENT]--CANVAS_STATE_SCOPE_USER = "user"-CANVAS_STATE_SCOPE_SHARED = "shared"-CANVAS_STATE_SCOPES = [CANVAS_STATE_SCOPE_USER, CANVAS_STATE_SCOPE_SHARED]+# The labels repeat the values because the published OpenAPI enums list these exact pairs.+class CanvasKind(LabeledStrEnum):+ FREEFORM = "freeform", "freeform"+ GRID = "grid", "grid"+ COMPONENT = "component", "component"+++class CanvasStateScope(LabeledStrEnum):+ USER = "user", "user"+ SHARED = "shared", "shared"+++class CanvasPlacementStatus(LabeledStrEnum):+ PENDING = "pending", "pending"+ GENERATING = "generating", "generating"+ LIVE = "live", "live"+ FAILED = "failed", "failed"+++CANVAS_KIND_FREEFORM = CanvasKind.FREEFORM.value+CANVAS_KIND_GRID = CanvasKind.GRID.value+CANVAS_KIND_COMPONENT = CanvasKind.COMPONENT.value+CANVAS_KINDS = CanvasKind.values++CANVAS_STATE_SCOPE_USER = CanvasStateScope.USER.value+CANVAS_STATE_SCOPE_SHARED = CanvasStateScope.SHARED.value+CANVAS_STATE_SCOPES = CanvasStateScope.valuesCANVAS_BUILD_STATUS_READY = "ready"CANVAS_BUILD_STATUS_FAILED = "failed"diff --git a/products/canvas/backend/layout.py b/products/canvas/backend/layout.pyindex 45a2a2d9e39d..96bf182d6996 100644--- a/products/canvas/backend/layout.py+++ b/products/canvas/backend/layout.py@@ -22,6 +22,7 @@ from posthog.dataclasses import frozenfrom posthog.models.scoping import team_scopefrom products.canvas.backend.contract import GRID_COLUMN_CHOICES, MAX_COMPONENT_HEIGHT, contract_limits+from products.canvas.backend.facade.enums import CanvasPlacementStatusfrom products.canvas.backend.source import diagnosticif TYPE_CHECKING:@@ -29,7 +30,7 @@ if TYPE_CHECKING:CANVAS_LAYOUT_SCHEMA_VERSION = 1-PLACEMENT_STATUSES = ("pending", "generating", "live", "failed")+PLACEMENT_STATUSES = tuple(CanvasPlacementStatus.values)PLACEMENT_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")MIN_ROW_HEIGHT = 24diff --git a/products/canvas/backend/presentation/serializers.py b/products/canvas/backend/presentation/serializers.pyindex c7566a2121f0..4a28b7a966cb 100644--- a/products/canvas/backend/presentation/serializers.py+++ b/products/canvas/backend/presentation/serializers.py@@ -15,7 +15,6 @@ from products.canvas.backend.facade.api import (MAX_COMPONENT_WIDTH,MAX_LAYOUT_PATCH_OPERATIONS,PLACEMENT_ID_RE,- PLACEMENT_STATUSES,RESERVED_TEMPLATE_IDS,ConnectorCallStatus,ConnectorKind,@@ -23,7 +22,12 @@ from products.canvas.backend.facade.api import (contract_limits,)from products.canvas.backend.facade.contracts import CanvasBuildRecord, CanvasRecord-from products.canvas.backend.facade.enums import CANVAS_KIND_FREEFORM, CANVAS_KINDS, CANVAS_STATE_SCOPES+from products.canvas.backend.facade.enums import (+ CANVAS_KIND_FREEFORM,+ CanvasKind,+ CanvasPlacementStatus,+ CanvasStateScope,+)# Base64 expands 3 source bytes into 4 characters (padded); size the asset field# from the contract's total-source cap rather than restating the number.@@ -89,7 +93,7 @@ class CanvasSerializer(serializers.Serializer):id = serializers.UUIDField(read_only=True)name = serializers.CharField(read_only=True)kind = serializers.ChoiceField(- choices=CANVAS_KINDS,+ choices=CanvasKind.choices,read_only=True,help_text=("What the canvas is: 'freeform' (a standalone app), 'component' (a reusable widget grids place), "@@ -149,7 +153,7 @@ class CanvasCreateSerializer(serializers.Serializer):)channel_id = serializers.UUIDField(help_text="Id of the channel the canvas belongs to.")kind = serializers.ChoiceField(- choices=CANVAS_KINDS,+ choices=CanvasKind.choices,required=False,default=CANVAS_KIND_FREEFORM,help_text=(@@ -228,7 +232,7 @@ class CanvasPostHogCapabilitiesSerializer(serializers.Serializer):captureEvents = serializers.ListField(child=serializers.CharField(max_length=200), max_length=100)# Optional so projects published before the state store exist unchanged.state = serializers.ListField(- child=serializers.ChoiceField(choices=CANVAS_STATE_SCOPES),+ child=serializers.ChoiceField(choices=CanvasStateScope.choices),required=False,default=list,max_length=2,@@ -368,7 +372,7 @@ class CanvasPlacementSerializer(serializers.Serializer):help_text="Stable placement id, unique within the layout. 1-64 characters of letters, digits, '_', or '-'.",)status = serializers.ChoiceField(- choices=list(PLACEMENT_STATUSES),+ choices=CanvasPlacementStatus.choices,help_text=("Placement lifecycle: 'pending' (box drawn, no prompt yet), 'generating' (an agent task is filling it), ""'live' (renders its component), 'failed' (generation failed; re-prompt or remove)."@@ -555,7 +559,9 @@ class CanvasSummarySerializer(serializers.Serializer):id = serializers.UUIDField(help_text="The canvas's id.")name = serializers.CharField(help_text="Display name of the canvas.")- kind = serializers.ChoiceField(choices=CANVAS_KINDS, help_text="The canvas's kind (freeform, component, or grid).")+ kind = serializers.ChoiceField(+ choices=CanvasKind.choices, help_text="The canvas's kind (freeform, component, or grid)."+ )channel_id = serializers.UUIDField(help_text="Id of the channel the canvas belongs to.")current_version_id = serializers.CharField(allow_null=True,@@ -1246,7 +1252,7 @@ class CanvasConnectorCallResultSerializer(serializers.Serializer):class CanvasStateQuerySerializer(serializers.Serializer):- scope = serializers.ChoiceField(choices=CANVAS_STATE_SCOPES, required=False, help_text="Only read this scope.")+ scope = serializers.ChoiceField(choices=CanvasStateScope.choices, required=False, help_text="Only read this scope.")key = serializers.CharField(required=False, max_length=200, help_text="Only read this exact key.")key_prefix = serializers.CharField(required=False,@@ -1273,7 +1279,7 @@ class CanvasStateQuerySerializer(serializers.Serializer):class CanvasStateValueQuerySerializer(serializers.Serializer):- scope = serializers.ChoiceField(choices=CANVAS_STATE_SCOPES, help_text="Scope of the value to read.")+ scope = serializers.ChoiceField(choices=CanvasStateScope.choices, help_text="Scope of the value to read.")key = serializers.CharField(max_length=200, help_text="Exact key to read.")offset = serializers.IntegerField(required=False, default=0, min_value=0, help_text="Character offset from next_offset."@@ -1298,7 +1304,7 @@ class CanvasStateValueQuerySerializer(serializers.Serializer):class CanvasStateValueResponseSerializer(serializers.Serializer):- scope = serializers.ChoiceField(choices=CANVAS_STATE_SCOPES, help_text="Scope of this value.")+ scope = serializers.ChoiceField(choices=CanvasStateScope.choices, help_text="Scope of this value.")key = serializers.CharField(help_text="Key of this value.")value_json = serializers.CharField(allow_blank=True, help_text="A chunk of JSON text. Join all chunks in order, then parse the complete JSON."@@ -1318,7 +1324,7 @@ class CanvasStateEntrySerializer(serializers.Serializer):"""One key of a canvas's runtime key-value state (the ph.state store)."""scope = serializers.ChoiceField(- choices=CANVAS_STATE_SCOPES,+ choices=CanvasStateScope.choices,help_text="user: private to the viewer who wrote it. shared: one value per canvas, visible to every viewer.",)key = serializers.CharField(max_length=200, help_text="The entry's key, unique within its scope.")@@ -1341,7 +1347,7 @@ class CanvasStateSetSerializer(serializers.Serializer):"""Payload for writing (or deleting) one key of a canvas's runtime state."""scope = serializers.ChoiceField(- choices=CANVAS_STATE_SCOPES,+ choices=CanvasStateScope.choices,help_text="Scope to write into; the canvas must declare it in capabilities.posthog.state.",)key = serializers.CharField(max_length=200, help_text="Key to write, unique within its scope.")diff --git a/products/conversations/backend/api/ticket_filters.py b/products/conversations/backend/api/ticket_filters.pyindex c25ea224c73a..785f927555a8 100644--- a/products/conversations/backend/api/ticket_filters.py+++ b/products/conversations/backend/api/ticket_filters.py@@ -60,7 +60,7 @@ VALID_CHANNEL_VALUES = frozenset(c.value for c in Channel)# Named choice sets for ChoiceFields below, registered in ENUM_NAME_OVERRIDES# (posthog/settings/web.py) so drf-spectacular doesn't mint generic globals like-# ChannelEnum/SlaEnum/OrderEnum in the shared OpenAPI namespace.+# ChannelEnum/SlaEnum in the shared OpenAPI namespace.TICKET_CHANNEL_FILTER_CHOICES = [*(c.value for c in Channel), "all"]TICKET_SLA_FILTER_CHOICES = [*SLA_FILTER_VALUES, "all"]@@ -71,9 +71,11 @@ class TicketTagsMatch(models.TextChoices):TICKET_TAGS_MATCH_CHOICES = list(TicketTagsMatch.values)-# Tuple pairs, not bare ints: drf-spectacular's override loader only accepts strings-# in plain value lists and crashes on anything else.-TICKET_SORT_ORDER_CHOICES = [(1, 1), (-1, -1)]+++class TicketSortOrder(models.IntegerChoices):+ ASCENDING = 1, "1"+ DESCENDING = -1, "-1"def _is_assignee_entry(value: Any) -> bool:@@ -155,7 +157,7 @@ class TicketViewSortingSerializer(serializers.Serializer):help_text=f"Ticket column to sort by ({', '.join(ALLOWED_ORDER_COLUMNS)}). ""Unknown columns fall back to updated_at.")- order = serializers.ChoiceField(choices=TICKET_SORT_ORDER_CHOICES, help_text="1 for ascending, -1 for descending.")+ order = serializers.ChoiceField(choices=TicketSortOrder.choices, help_text="1 for ascending, -1 for descending.")class TicketViewFiltersSerializer(serializers.Serializer):diff --git a/products/customer_analytics/backend/constants.py b/products/customer_analytics/backend/constants.pyindex 1943431af268..4a63c396cbb4 100644--- a/products/customer_analytics/backend/constants.py+++ b/products/customer_analytics/backend/constants.py@@ -1,5 +1,7 @@from django.db import models+from products.customer_analytics.backend.facade.enums import CustomPropertyOptionColor+DEFAULT_ACTIVITY_EVENT = {"kind": "EventsNode", "event": "$pageview", "name": "$pageview"}# Mirrors frontend `SLACK_ARCHIVES_ORIGIN` in accountLinksLogic.ts. PostHog-internal: hardcodes our@@ -41,8 +43,8 @@ class CustomPropertyDisplayType(models.TextChoices):CUSTOM_PROPERTY_DISPLAY_TYPE_CHOICES = list(CustomPropertyDisplayType.values)-# Mirrors OPTION_COLOR_TOKENS in the frontend's customPropertyTypes.ts (DataColorToken presets).-CUSTOM_PROPERTY_OPTION_COLORS = [f"preset-{i}" for i in range(1, 11)]++CUSTOM_PROPERTY_OPTION_COLORS = CustomPropertyOptionColor.values# Bounds the fan-out so one create can't enqueue an unbounded Slack send loop.MAX_ANNOUNCEMENT_CHANNELS = 200diff --git a/products/customer_analytics/backend/facade/enums.py b/products/customer_analytics/backend/facade/enums.pyindex 33768e04ff49..4e60727b1c3b 100644--- a/products/customer_analytics/backend/facade/enums.py+++ b/products/customer_analytics/backend/facade/enums.py@@ -1,17 +1,24 @@-from enum import StrEnum-from posthog.enums import LabeledStrEnum-class AccountPropertyPinKind(StrEnum):- CUSTOM_PROPERTY = "custom_property"- RELATIONSHIP = "relationship"+class AccountPropertyPinKind(LabeledStrEnum):+ CUSTOM_PROPERTY = "custom_property", "Custom property"+ RELATIONSHIP = "relationship", "Relationship"-ACCOUNT_PROPERTY_PIN_KIND_CHOICES: tuple[tuple[str, str], ...] = (- (AccountPropertyPinKind.CUSTOM_PROPERTY.value, "Custom property"),- (AccountPropertyPinKind.RELATIONSHIP.value, "Relationship"),-)+# Mirrors OPTION_COLOR_TOKENS in the frontend's customPropertyTypes.ts (DataColorToken presets).+# The labels repeat the values because the published OpenAPI enum lists these exact pairs.+class CustomPropertyOptionColor(LabeledStrEnum):+ PRESET_1 = "preset-1", "preset-1"+ PRESET_2 = "preset-2", "preset-2"+ PRESET_3 = "preset-3", "preset-3"+ PRESET_4 = "preset-4", "preset-4"+ PRESET_5 = "preset-5", "preset-5"+ PRESET_6 = "preset-6", "preset-6"+ PRESET_7 = "preset-7", "preset-7"+ PRESET_8 = "preset-8", "preset-8"+ PRESET_9 = "preset-9", "preset-9"+ PRESET_10 = "preset-10", "preset-10"class AccountViewVisibility(LabeledStrEnum):@@ -59,9 +66,9 @@ class OwnershipRoleDiagnostic(LabeledStrEnum):__all__ = ["AccountPropertyPinKind","AccountViewVisibility",+ "CustomPropertyOptionColor","AccountRelationshipSource","OwnershipRoleDiagnostic","OwnershipRoleState","TaskDigestCadence",- "ACCOUNT_PROPERTY_PIN_KIND_CHOICES",]diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex 7762b694ab6e..81b956263e0d 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -43,7 +43,6 @@ from products.customer_analytics.backend.facade.api import ()from products.customer_analytics.backend.facade.constants import (CUSTOM_PROPERTY_DISPLAY_TYPE_CHOICES,- CUSTOM_PROPERTY_OPTION_COLORS,SLACK_SUMMARY_CADENCE_CHOICES,)from products.customer_analytics.backend.facade.contracts import (@@ -83,9 +82,10 @@ from products.customer_analytics.backend.facade.contracts import (MeetingView,)from products.customer_analytics.backend.facade.enums import (- ACCOUNT_PROPERTY_PIN_KIND_CHOICES,+ AccountPropertyPinKind,AccountRelationshipSource,AccountViewVisibility,+ CustomPropertyOptionColor,TaskDigestCadence,)@@ -2017,7 +2017,7 @@ class CustomPropertyOptionSerializer(DataclassSerializer):help_text="Display label of the option. Stored as the account's value when picked.",)color = serializers.ChoiceField(- choices=CUSTOM_PROPERTY_OPTION_COLORS,+ choices=CustomPropertyOptionColor.choices,help_text="Preset color token used to render the option ('preset-1' through 'preset-10').",)@@ -2244,7 +2244,7 @@ class CustomPropertyValueSuggestionsResponseSerializer(serializers.Serializer):class PinnedAccountPropertySerializer(serializers.Serializer):kind = serializers.ChoiceField(- choices=ACCOUNT_PROPERTY_PIN_KIND_CHOICES,+ choices=AccountPropertyPinKind.choices,help_text="Definition type for this pinned account property.",)id = serializers.UUIDField(diff --git a/products/data_quality/backend/facade/enums.py b/products/data_quality/backend/facade/enums.pyindex 0c448bd27f29..c7e81d2f04f7 100644--- a/products/data_quality/backend/facade/enums.py+++ b/products/data_quality/backend/facade/enums.py@@ -7,6 +7,8 @@ share. Internal-only constants stay in the implementation.from enum import StrEnum+from posthog.enums import LabeledStrEnum+class CreatedSource(StrEnum):"""Who authored a check, for review context."""@@ -86,16 +88,13 @@ class SubjectType(StrEnum):POSTHOG_TABLE = "posthog_table"-class ScheduleInterval(StrEnum):- ONE_HOUR = "1hour"- SIX_HOURS = "6hour"- TWELVE_HOURS = "12hour"- DAILY = "24hour"- WEEKLY = "7day"---def schedule_interval_choices() -> list[str]:- return [interval.value for interval in ScheduleInterval]+# The labels repeat the values because the published OpenAPI enum lists these exact pairs.+class DataQualityScheduleInterval(LabeledStrEnum):+ ONE_HOUR = "1hour", "1hour"+ SIX_HOURS = "6hour", "6hour"+ TWELVE_HOURS = "12hour", "12hour"+ DAILY = "24hour", "24hour"+ WEEKLY = "7day", "7day"def subject_type_choices() -> dict[str, str]:diff --git a/products/data_quality/backend/logic/schedules.py b/products/data_quality/backend/logic/schedules.pyindex 6bdf5030652c..cbfe7e203566 100644--- a/products/data_quality/backend/logic/schedules.py+++ b/products/data_quality/backend/logic/schedules.py@@ -11,7 +11,7 @@ from posthog.dataclasses import frozenfrom posthog.models.scoping.manager import resolve_effective_team_idfrom posthog.temporal.common.client import async_connect-from ..facade.enums import ScheduleInterval, SubjectType+from ..facade.enums import DataQualityScheduleInterval, SubjectTypefrom .subject_schedules import SCHEDULE_TYPES, SubjectScheduleKey, SubjectSchedules, label_from_intervallogger = structlog.get_logger(__name__)@@ -25,7 +25,7 @@ class ScheduleUnavailableError(Exception):@frozenclass CheckSchedule:id: UUID- interval: ScheduleInterval+ interval: DataQualityScheduleIntervalenabled: boolnext_run_at: datetime | Nonelast_run_at: datetime | None = Nonediff --git a/products/data_quality/backend/logic/subject_schedules.py b/products/data_quality/backend/logic/subject_schedules.pyindex 0c130032c166..937306ff96c9 100644--- a/products/data_quality/backend/logic/subject_schedules.py+++ b/products/data_quality/backend/logic/subject_schedules.py@@ -25,7 +25,7 @@ from posthog.temporal.common.schedule import a_create_schedule, a_describe_schedfrom posthog.temporal.common.search_attributes import POSTHOG_SCHEDULE_TYPE_KEY, POSTHOG_TEAM_ID_KEYfrom ..facade.contracts import CHECK_SUITE_WORKFLOW_NAME, RunCheckSuiteInputs-from ..facade.enums import ScheduleInterval, SubjectType, SuiteRunTrigger+from ..facade.enums import DataQualityScheduleInterval, SubjectType, SuiteRunTriggerSCHEDULE_TYPES: dict[SubjectType, str] = {SubjectType.METRIC: "data-quality-metric",@@ -40,11 +40,11 @@ def runs_on_a_schedule(subject_type: SubjectType) -> bool:CATCHUP_WINDOW = timedelta(minutes=15)INTERVALS = {- ScheduleInterval.ONE_HOUR: timedelta(hours=1),- ScheduleInterval.SIX_HOURS: timedelta(hours=6),- ScheduleInterval.TWELVE_HOURS: timedelta(hours=12),- ScheduleInterval.DAILY: timedelta(days=1),- ScheduleInterval.WEEKLY: timedelta(days=7),+ DataQualityScheduleInterval.ONE_HOUR: timedelta(hours=1),+ DataQualityScheduleInterval.SIX_HOURS: timedelta(hours=6),+ DataQualityScheduleInterval.TWELVE_HOURS: timedelta(hours=12),+ DataQualityScheduleInterval.DAILY: timedelta(days=1),+ DataQualityScheduleInterval.WEEKLY: timedelta(days=7),}@@ -109,10 +109,10 @@ def selected_subject_ids(inputs: RunCheckSuiteInputs, subject_type: SubjectType)def interval_from_label(label: str) -> timedelta:- return INTERVALS[ScheduleInterval(label)]+ return INTERVALS[DataQualityScheduleInterval(label)]-def label_from_interval(interval: timedelta) -> ScheduleInterval:+def label_from_interval(interval: timedelta) -> DataQualityScheduleInterval:for label, duration in INTERVALS.items():if interval == duration:return label@@ -130,7 +130,7 @@ class SubjectSchedules:return ScheduleSpec(intervals=[ScheduleIntervalSpec(every=duration, offset=offset)])@classmethod- def build(cls, key: SubjectScheduleKey, interval: str = ScheduleInterval.DAILY) -> Schedule:+ def build(cls, key: SubjectScheduleKey, interval: str = DataQualityScheduleInterval.DAILY) -> Schedule:return Schedule(action=ScheduleActionStartWorkflow(CHECK_SUITE_WORKFLOW_NAME,diff --git a/products/data_quality/backend/presentation/serializers.py b/products/data_quality/backend/presentation/serializers.pyindex eed8ecace7fa..c38c11346a42 100644--- a/products/data_quality/backend/presentation/serializers.py+++ b/products/data_quality/backend/presentation/serializers.py@@ -16,7 +16,7 @@ from rest_framework.settings import api_settingsfrom posthog.api.shared import UserBasicSerializerfrom ..facade import api-from ..facade.enums import CheckSeverity, CheckType, CreatedSource, ScheduleInterval, SubjectType+from ..facade.enums import CheckSeverity, CheckType, CreatedSource, DataQualityScheduleInterval, SubjectTypefrom ..facade.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun@@ -324,7 +324,9 @@ class DataQualityCheckScheduleUpdateSerializer(DataQualitySubjectRefSerializer):SCHEDULE_FIELDS = ("interval", "enabled")interval = serializers.ChoiceField(- choices=list(ScheduleInterval), required=False, help_text="How often all enabled checks on the subject run."+ choices=DataQualityScheduleInterval.choices,+ required=False,+ help_text="How often all enabled checks on the subject run.",)enabled = serializers.BooleanField(required=False, help_text="Whether checks run automatically on this schedule.")@@ -336,7 +338,7 @@ class DataQualityCheckScheduleUpdateSerializer(DataQualitySubjectRefSerializer):class DataQualityCheckScheduleSerializer(serializers.Serializer):id = serializers.UUIDField(read_only=True, help_text="Schedule identifier.")interval = serializers.ChoiceField(- choices=list(ScheduleInterval), read_only=True, help_text="How often the checks run."+ choices=DataQualityScheduleInterval.choices, read_only=True, help_text="How often the checks run.")enabled = serializers.BooleanField(read_only=True, help_text="Whether the schedule runs automatically.")next_run_at = serializers.DateTimeField(diff --git a/products/data_warehouse/backend/presentation/views/saved_query/sync_cadence.py b/products/data_warehouse/backend/presentation/views/saved_query/sync_cadence.pyindex 406885d00440..ed46a092af82 100644--- a/products/data_warehouse/backend/presentation/views/saved_query/sync_cadence.py+++ b/products/data_warehouse/backend/presentation/views/saved_query/sync_cadence.py@@ -16,21 +16,23 @@ from products.warehouse_sources.backend.facade.models import (from . import rendered_node_states+# Cadences offered for view materialization. 15min is the fastest — sub-15min intervals# (1min, 5min) are source-only and not meaningful for materialized views, matching the# frontend `DataModelingSyncInterval` type. All values are accepted by-# `sync_frequency_to_sync_frequency_interval`.-SYNC_FREQUENCY_CHOICES = [- ("never", "never"),- ("15min", "15min"),- ("30min", "30min"),- ("1hour", "1hour"),- ("6hour", "6hour"),- ("12hour", "12hour"),- ("24hour", "24hour"),- ("7day", "7day"),- ("30day", "30day"),-]+# `sync_frequency_to_sync_frequency_interval`. The labels repeat the values because the published+# OpenAPI enum lists these exact pairs.+class SavedQuerySyncFrequency(models.TextChoices):+ NEVER = "never", "never"+ FIFTEEN_MINUTES = "15min", "15min"+ THIRTY_MINUTES = "30min", "30min"+ ONE_HOUR = "1hour", "1hour"+ SIX_HOURS = "6hour", "6hour"+ TWELVE_HOURS = "12hour", "12hour"+ ONE_DAY = "24hour", "24hour"+ SEVEN_DAYS = "7day", "7day"+ THIRTY_DAYS = "30day", "30day"+# Deprecated sub-15min cadences clamped up to the 15min floor for backwards compatibility# with any legacy caller still sending them.@@ -42,7 +44,7 @@ DEFAULT_MATERIALIZE_SYNC_FREQUENCY = "24hour"# `never` is missing on purpose: materializing is what starts the refreshes, so asking for none# has no meaning here. Callers stop them afterwards by setting the cadence to `never`.-MATERIALIZE_SYNC_FREQUENCY_CHOICES = [choice for choice in SYNC_FREQUENCY_CHOICES if choice[0] != "never"]+MATERIALIZE_SYNC_FREQUENCY_CHOICES = [choice for choice in SavedQuerySyncFrequency.choices if choice[0] != "never"]class SyncFrequencyBlockerSerializer(serializers.Serializer):@@ -269,7 +271,7 @@ class SyncFrequencyField(serializers.ChoiceField):"""def __init__(self, **kwargs: Any) -> None:- kwargs.setdefault("choices", SYNC_FREQUENCY_CHOICES)+ kwargs.setdefault("choices", SavedQuerySyncFrequency.choices)kwargs.setdefault("required", False)kwargs.setdefault("allow_null", True)super().__init__(**kwargs)diff --git a/products/error_tracking/backend/presentation/views/assignment_rules.py b/products/error_tracking/backend/presentation/views/assignment_rules.pyindex 6ccf2a950e11..41543e64bf60 100644--- a/products/error_tracking/backend/presentation/views/assignment_rules.py+++ b/products/error_tracking/backend/presentation/views/assignment_rules.py@@ -16,6 +16,7 @@ from posthog.api.utils import actionfrom posthog.event_usage import get_request_analytics_properties, groupsfrom products.error_tracking.backend.facade import api as error_tracking_api+from products.error_tracking.backend.presentation.views.issues import AssigneeTypelogger = structlog.get_logger(__name__)@@ -55,7 +56,7 @@ class ErrorTrackingAssignmentRuleAssigneeIdField(serializers.Field):class ErrorTrackingAssignmentRuleAssigneeRequestSerializer(serializers.Serializer):type = serializers.ChoiceField(- choices=["user", "role"],+ choices=AssigneeType.choices,help_text="Assignee type. Use `user` for a user ID or `role` for a role UUID.",)id = ErrorTrackingAssignmentRuleAssigneeIdField(diff --git a/products/error_tracking/backend/presentation/views/grouping_rules.py b/products/error_tracking/backend/presentation/views/grouping_rules.pyindex c783f95db13b..29a76cc070d8 100644--- a/products/error_tracking/backend/presentation/views/grouping_rules.py+++ b/products/error_tracking/backend/presentation/views/grouping_rules.py@@ -17,6 +17,7 @@ from posthog.api.utils import actionfrom posthog.event_usage import get_request_analytics_properties, groupsfrom products.error_tracking.backend.facade import api as error_tracking_api+from products.error_tracking.backend.presentation.views.issues import AssigneeTypelogger = structlog.get_logger(__name__)@@ -58,7 +59,7 @@ class ErrorTrackingGroupingRuleAssigneeIdField(serializers.Field):class ErrorTrackingGroupingRuleAssigneeRequestSerializer(serializers.Serializer):type = serializers.ChoiceField(- choices=["user", "role"],+ choices=AssigneeType.choices,help_text="Assignee type. Use `user` for a user ID or `role` for a role UUID.",)id = ErrorTrackingGroupingRuleAssigneeIdField(diff --git a/products/error_tracking/backend/presentation/views/issues.py b/products/error_tracking/backend/presentation/views/issues.pyindex 8b7bc887dabb..762f76fc30e5 100644--- a/products/error_tracking/backend/presentation/views/issues.py+++ b/products/error_tracking/backend/presentation/views/issues.py@@ -1,6 +1,7 @@from typing import castfrom uuid import UUID+from django.db import modelsfrom django.http import JsonResponseimport structlog@@ -98,10 +99,16 @@ class ErrorTrackingIssueAssigneeIdField(serializers.Field):return value if isinstance(value, int | str) else str(value)+# The labels repeat the values because the published OpenAPI enum lists these exact pairs.+class AssigneeType(models.TextChoices):+ USER = "user", "user"+ ROLE = "role", "role"++class ErrorTrackingIssueAssigneeWriteSerializer(serializers.Serializer):id = ErrorTrackingIssueAssigneeIdField(help_text="User ID or role UUID to assign the issue to.")type = serializers.ChoiceField(- choices=["user", "role"],+ choices=AssigneeType.choices,help_text="Assignment target type: user or role.",)diff --git a/products/error_tracking/backend/presentation/views/query_serializers.py b/products/error_tracking/backend/presentation/views/query_serializers.pyindex e4aa7c2a9f5f..5b2cb92478e6 100644--- a/products/error_tracking/backend/presentation/views/query_serializers.py+++ b/products/error_tracking/backend/presentation/views/query_serializers.py@@ -9,7 +9,7 @@ from rest_framework import serializersfrom posthog.api.documentation import PropertyItemSerializer, extend_schema_fieldfrom products.error_tracking.backend.facade import contracts-from products.error_tracking.backend.presentation.views.issues import ErrorTrackingIssueSeverityField+from products.error_tracking.backend.presentation.views.issues import AssigneeType, ErrorTrackingIssueSeverityFieldSTRING_OR_STRING_LIST_SCHEMA = {"oneOf": [@@ -99,7 +99,7 @@ class VolumeResolutionField(serializers.IntegerField):class ErrorTrackingAssigneeSerializer(serializers.Serializer):id = StringOrIntegerField(help_text="User ID or role UUID to filter by.")- type = serializers.ChoiceField(choices=["user", "role"], help_text="Assignee target type: user or role.")+ type = serializers.ChoiceField(choices=AssigneeType.choices, help_text="Assignee target type: user or role.")class ErrorTrackingIssueOrderBy(models.TextChoices):diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 2f0525db917f..b9088adb2ee8 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -66,16 +66,20 @@ from products.experiments.backend.models.experiment import (experiment_has_legacy_metrics,)from products.experiments.backend.running_time_calculator import METRIC_TYPE_CHOICES-from products.experiments.backend.session_buckets import MAX_BUCKET_SCAN_DAYS, MAX_SESSION_BUCKET_LIMIT, SessionBucket+from products.experiments.backend.session_buckets import (+ MAX_BUCKET_SCAN_DAYS,+ MAX_SESSION_BUCKET_LIMIT,+ ExperimentSessionBucket,+)from products.experiments.backend.session_context import MAX_SESSION_CONTEXT_BATCHfrom products.experiments.backend.session_event_deltas import (FIRST_SESSION_HORIZON_HOURS,MAX_CARD_HIGHLIGHTS,MAX_CARD_RECORDINGS,MAX_DELTA_SCAN_DAYS,- DeltaStrength,- WatchCardKind,- WatchEmptyReason,+ ExperimentWatchCardKind,+ ExperimentWatchCardStrength,+ ExperimentWatchEmptyReason,)from products.experiments.backend.setup_context import (DEFAULT_LIST_LIMIT,@@ -2057,7 +2061,7 @@ class ExperimentSessionBucketRequestSerializer(serializers.Serializer):"""Request body for the session-bucket endpoint."""bucket = serializers.ChoiceField(- choices=[bucket.value for bucket in SessionBucket],+ choices=ExperimentSessionBucket.choices,help_text=("Which question the returned session set answers. 'fired_any': the session fired at least one event ""of any listed metric (an OR the recordings query itself can't express). 'no_metric_activity': the "@@ -2097,7 +2101,7 @@ class ExperimentSessionBucketRequestSerializer(serializers.Serializer):)def validate(self, attrs: dict) -> dict:- if attrs["bucket"] == SessionBucket.FUNNEL_DROPOFF and len(attrs.get("metric_uuids") or []) != 1:+ if attrs["bucket"] == ExperimentSessionBucket.FUNNEL_DROPOFF and len(attrs.get("metric_uuids") or []) != 1:raise serializers.ValidationError({"metric_uuids": ["The drop-off bucket takes exactly one funnel metric."]})@@ -2218,7 +2222,7 @@ class ExperimentWatchCardSerializer(serializers.Serializer):"""kind = serializers.ChoiceField(- choices=[kind.value for kind in WatchCardKind],+ choices=ExperimentWatchCardKind.choices,help_text=("What the card is: 'behavior' for an event this variant did clearly more than the other variants ""together, 'friction' for the same finding on an error or rage signal, 'variant_only' for an event "@@ -2234,7 +2238,7 @@ class ExperimentWatchCardSerializer(serializers.Serializer):help_text="The variant whose recordings these are: for comparison cards, the one that did the event more.")strength = serializers.ChoiceField(- choices=[strength.value for strength in DeltaStrength],+ choices=ExperimentWatchCardStrength.choices,allow_null=True,help_text=("How far apart this variant and the rest are, as a band rather than a number: 'only' when nobody in "@@ -2434,7 +2438,7 @@ class ExperimentSessionEventDeltaResponseSerializer(serializers.Serializer):))empty_reason = serializers.ChoiceField(- choices=[reason.value for reason in WatchEmptyReason],+ choices=ExperimentWatchEmptyReason.choices,allow_null=True,help_text=("Why cards is empty, and null whenever cards is not empty. Report which of the four happened "diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex 1670e72a4e68..d150867ce4fb 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -134,7 +134,7 @@ from products.experiments.backend.running_time_calculator import (calculate_variance_from_stats,)from products.experiments.backend.session_buckets import (- SessionBucket,+ ExperimentSessionBucket,SessionBucketUnavailable,finalize_session_bucket,get_experiment_session_bucket,@@ -1770,7 +1770,7 @@ class EnterpriseExperimentsViewSet(# property-level access control.user=cast(User, request.user),experiment=experiment,- bucket=SessionBucket(request.validated_data["bucket"]),+ bucket=ExperimentSessionBucket(request.validated_data["bucket"]),metric_uuids=request.validated_data["metric_uuids"],variant=request.validated_data["variant"],limit=request.validated_data["limit"],diff --git a/products/experiments/backend/session_buckets.py b/products/experiments/backend/session_buckets.pyindex b4e1e58f960a..8d8e73a20c0d 100644--- a/products/experiments/backend/session_buckets.py+++ b/products/experiments/backend/session_buckets.py@@ -46,7 +46,6 @@ import hashlibimport loggingfrom dataclasses import dataclassfrom datetime import datetime, timedelta-from enum import StrEnumfrom typing import Optionalfrom django.utils import timezone@@ -59,6 +58,7 @@ from posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.enums import LabeledStrEnumfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.session_recordings.data_retention import retention_period_in_days@@ -152,12 +152,13 @@ FUNNEL_DATA_WAREHOUSE_COMPLETION_REASON = ()-class SessionBucket(StrEnum):+# The labels repeat the values because the published OpenAPI enum lists these exact pairs.+class ExperimentSessionBucket(LabeledStrEnum):"""Which question the returned session set answers."""- FIRED_ANY = "fired_any"- NO_METRIC_ACTIVITY = "no_metric_activity"- FUNNEL_DROPOFF = "funnel_dropoff"+ FIRED_ANY = "fired_any", "fired_any"+ NO_METRIC_ACTIVITY = "no_metric_activity", "no_metric_activity"+ FUNNEL_DROPOFF = "funnel_dropoff", "funnel_dropoff"class SessionBucketUnavailable(Exception):@@ -234,7 +235,7 @@ def get_experiment_session_bucket(user: User,experiment: Experiment,*,- bucket: SessionBucket,+ bucket: ExperimentSessionBucket,metric_uuids: list[str],variant: Optional[str],limit: int,@@ -393,7 +394,7 @@ def _cache_key(team: Team,user: User,experiment: Experiment,- bucket: SessionBucket,+ bucket: ExperimentSessionBucket,considered: list[MetricEventSource],variant: Optional[str],run_start: datetime,@@ -599,7 +600,7 @@ def _resolve_requested_metrics(experiment: Experiment, metric_uuids: list[str])def _partition_metrics(- requested: list[MetricEventSource], bucket: SessionBucket, never_linked: frozenset[str]+ requested: list[MetricEventSource], bucket: ExperimentSessionBucket, never_linked: frozenset[str]) -> tuple[list[MetricEventSource], list[ExcludedBucketMetric]]:"""Split the requested metrics into the ones the bucket is computed over and the ones thatcan't be matched to a recording at all, with the reason.@@ -635,7 +636,7 @@ def _partition_metrics(f"These metrics count {source_count} events between them, more than the {MAX_BUCKET_SOURCES} ""one scan can cover. Ask for fewer metrics.")- if bucket == SessionBucket.FUNNEL_DROPOFF:+ if bucket == ExperimentSessionBucket.FUNNEL_DROPOFF:if len(considered) != 1:raise SessionBucketUnavailable("The drop-off bucket takes exactly one funnel metric.")completion_reason = _funnel_completion_reason(considered[0], never_linked)@@ -741,7 +742,7 @@ def _query_bucket_sessions(user: User,experiment: Experiment,*,- bucket: SessionBucket,+ bucket: ExperimentSessionBucket,considered: list[MetricEventSource],variant_keys: list[str],window_start: datetime,@@ -763,11 +764,11 @@ def _query_bucket_sessions(def count_if(condition: ast.Expr) -> ast.Expr:return ast.Call(name="countIf", args=[condition])- if bucket == SessionBucket.FIRED_ANY:+ if bucket == ExperimentSessionBucket.FIRED_ANY:bucket_predicate: ast.Expr = ast.CompareOperation(op=ast.CompareOperationOp.Gt, left=count_if(any_metric_condition()), right=ast.Constant(value=0))- elif bucket == SessionBucket.NO_METRIC_ACTIVITY:+ elif bucket == ExperimentSessionBucket.NO_METRIC_ACTIVITY:bucket_predicate = ast.CompareOperation(op=ast.CompareOperationOp.Eq, left=count_if(any_metric_condition()), right=ast.Constant(value=0))diff --git a/products/experiments/backend/session_event_deltas.py b/products/experiments/backend/session_event_deltas.pyindex c6f305dd19c8..da3c960102ae 100644--- a/products/experiments/backend/session_event_deltas.py+++ b/products/experiments/backend/session_event_deltas.py@@ -110,7 +110,6 @@ import mathimport hashlibfrom dataclasses import dataclass, replacefrom datetime import datetime, timedelta-from enum import StrEnumfrom typing import Optionalfrom django.utils import timezone@@ -127,6 +126,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.dataclasses import frozen+from posthog.enums import LabeledStrEnumfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.session_recordings.queries.session_replay_events import SessionReplayEvents@@ -314,31 +314,34 @@ class SessionEventDeltasUnavailable(Exception):"the variants behaved identically"."""-class DeltaStrength(StrEnum):+# The labels repeat the values because the published OpenAPI enum lists these exact pairs.+class ExperimentWatchCardStrength(LabeledStrEnum):"""How far apart a variant and the rest are, conservatively, in bands rather than as a number."""# Nobody in the other variants did it, among the people compared. A fact about the compared set# rather than a ratio, and the one band that is exact.- ONLY = "only"- FAR_MORE = "far_more"- MORE = "more"- SLIGHTLY_MORE = "slightly_more"+ ONLY = "only", "only"+ FAR_MORE = "far_more", "far_more"+ MORE = "more", "more"+ SLIGHTLY_MORE = "slightly_more", "slightly_more"-class WatchCardKind(StrEnum):+# The labels repeat the values because the published OpenAPI enum lists these exact pairs.+class ExperimentWatchCardKind(LabeledStrEnum):# An event this variant did clearly more than the other variants together.- BEHAVIOR = "behavior"+ BEHAVIOR = "behavior", "behavior"# Same evidence, but the event is an error/rage signal, so it reads as a defect lead.- FRICTION = "friction"+ FRICTION = "friction", "friction"# An event only this variant can fire, because the variant is what renders it. Confirms the change is# live rather than saying anything about what people did with it.- VARIANT_ONLY = "variant_only"+ VARIANT_ONLY = "variant_only", "variant_only"# A shortcut to recordings around one of the experiment's own metric events. No comparison# claim: what happened to the metric is the results tab's answer.- METRIC = "metric"+ METRIC = "metric", "metric"-class WatchEmptyReason(StrEnum):+# The labels repeat the values because the published OpenAPI enum lists these exact pairs.+class ExperimentWatchEmptyReason(LabeledStrEnum):"""Why a shelf carries no cards. Set exactly when the shelf is empty.Each reason asks something different of the reader, so the frontend and the MCP tool report@@ -347,11 +350,11 @@ class WatchEmptyReason(StrEnum):# Fewer than two variants cleared MIN_VARIANT_PERSONS. A rollout split that changed during the# run lands here too, undiagnosed, because the exposure chart already shows it.- TOO_EARLY = "too_early"+ TOO_EARLY = "too_early", "too_early"# The variants were compared and no event told them apart.- NO_SEPARATION = "no_separation"+ NO_SEPARATION = "no_separation", "no_separation"# Events told the variants apart, but no recording behind them can be opened.- NO_RECORDINGS = "no_recordings"+ NO_RECORDINGS = "no_recordings", "no_recordings"# The experiment has exposed people and none of them has a session the scan can see in the# window. Only the sessions are read over the window; who counts as exposed is read over the# whole run, so the exposures can predate the window, which is why the copy must date the claim@@ -359,7 +362,7 @@ class WatchEmptyReason(StrEnum):# captured the same way produces more exposed people without sessions. The read stops at the# request, though, so people exposed less than a horizon ago can still return, and the copy# must not claim the day has passed.- NO_SESSION_LINKED_EXPOSURES = "no_session_linked_exposures"+ NO_SESSION_LINKED_EXPOSURES = "no_session_linked_exposures", "no_session_linked_exposures"@dataclass(frozen=True)@@ -415,12 +418,12 @@ class ExperimentWatchCard:recordings the card can actually show."""- kind: WatchCardKind+ kind: ExperimentWatchCardKindevent: str# The variant whose recordings these are — for comparison cards, the variant that did the event more.variant: str# None on metric cards: they are shortcuts, not comparisons.- strength: Optional[DeltaStrength]+ strength: Optional[ExperimentWatchCardStrength]# The metric this card's event belongs to, on a shortcut card and on a comparison card alike.# Set means the results tab measures this event, so the card must be read as pointing there# rather than as a second answer.@@ -473,13 +476,13 @@ class ExperimentWatchResult:too_early: bool# Settled per viewer in `finalize_watch_cards`: the recording access cut can empty a shelf the# scan built with findings on it.- empty_reason: Optional[WatchEmptyReason]+ empty_reason: Optional[ExperimentWatchEmptyReason]@dataclass(frozen=True)class _Shelf:cards: list[ExperimentWatchCard]- empty_reason: Optional[WatchEmptyReason]+ empty_reason: Optional[ExperimentWatchEmptyReason]def all_card_session_ids(result: ExperimentWatchResult) -> list[str]:@@ -533,10 +536,12 @@ def finalize_watch_cards(result: ExperimentWatchResult, accessible_session_ids:def _has_finding(cards: list[ExperimentWatchCard]) -> bool:"""A metric shortcut claims nothing about the variants, so it cannot hold a shelf up alone."""- return any(card.kind != WatchCardKind.METRIC for card in cards)+ return any(card.kind != ExperimentWatchCardKind.METRIC for card in cards)-def _findings_or_nothing(cards: list[ExperimentWatchCard], empty_reason: Optional[WatchEmptyReason]) -> _Shelf:+def _findings_or_nothing(+ cards: list[ExperimentWatchCard], empty_reason: Optional[ExperimentWatchEmptyReason]+) -> _Shelf:"""The shelf, or nothing when only metric shortcuts are left on it.Shortcuts alone restate what the results tab already answers while reading as a finding.@@ -546,7 +551,7 @@ def _findings_or_nothing(cards: list[ExperimentWatchCard], empty_reason: Optiona# No reason is set yet when the viewer's own recording access removed the findings. That case# must not be named: it would tell the viewer that recordings denied to them ran through this# experiment. "No recordings" is what they have either way.- return _Shelf(cards=[], empty_reason=empty_reason or WatchEmptyReason.NO_RECORDINGS)+ return _Shelf(cards=[], empty_reason=empty_reason or ExperimentWatchEmptyReason.NO_RECORDINGS)def get_experiment_session_event_deltas(team: Team, user: User, experiment: Experiment) -> ExperimentWatchResult:@@ -644,9 +649,9 @@ def get_experiment_session_event_deltas(team: Team, user: User, experiment: Expe# Empty variants read as too early, unless the people exposed have no sessions at all.no_comparison_reason = (- WatchEmptyReason.NO_SESSION_LINKED_EXPOSURES+ ExperimentWatchEmptyReason.NO_SESSION_LINKED_EXPOSURESif scan.exposed_persons_without_session- else WatchEmptyReason.TOO_EARLY+ else ExperimentWatchEmptyReason.TOO_EARLY)shelf = (_Shelf(cards=[], empty_reason=no_comparison_reason)@@ -1291,7 +1296,7 @@ def _build_shelf(metric_names_by_event={named.event: named.metric_name for named in named_metric_events},)if not comparison_candidates:- return _Shelf(cards=[], empty_reason=WatchEmptyReason.NO_SEPARATION)+ return _Shelf(cards=[], empty_reason=ExperimentWatchEmptyReason.NO_SEPARATION)metric_cards = _metric_card_candidates(named_metric_events,@@ -1311,12 +1316,14 @@ def _build_shelf(metric_nodes=_shortcut_nodes(metric_cards, nodes_by_metric_event),enrollment=scan.enrollment,)- comparison_cards = [card for card in resolved if card.kind != WatchCardKind.METRIC]+ comparison_cards = [card for card in resolved if card.kind != ExperimentWatchCardKind.METRIC]if not _has_finding(resolved):# Every finding died on the replay existence check; the surviving shortcuts alone are not# shown, so the shortcut recovery below has nothing to fill.- return _Shelf(cards=[], empty_reason=WatchEmptyReason.NO_RECORDINGS)- shortcut_by_pair = {(card.event, card.variant): card for card in resolved if card.kind == WatchCardKind.METRIC}+ return _Shelf(cards=[], empty_reason=ExperimentWatchEmptyReason.NO_RECORDINGS)+ shortcut_by_pair = {+ (card.event, card.variant): card for card in resolved if card.kind == ExperimentWatchCardKind.METRIC+ }# The shortcut selection is decided again now that survival is known: a comparison candidate# that died on the replay existence check must not keep suppressing its event's shortcuts, or@@ -1383,22 +1390,22 @@ def _separation(return ratio, max(abs(math.log(ratio)) - CONFIDENCE_Z * standard_error, 0.0)-def _strength(*, separation: float, baseline_count: int, target_count: int) -> DeltaStrength:+def _strength(*, separation: float, baseline_count: int, target_count: int) -> ExperimentWatchCardStrength:"""Which band the difference falls in, read off the conservative end of it rather than the rawone. A card that is only past the floor because the sample is large says "slightly", howeverbig the point estimate looks."""if not baseline_count or not target_count:- return DeltaStrength.ONLY+ return ExperimentWatchCardStrength.ONLYif separation >= FAR_MORE_LOG_RATIO:- return DeltaStrength.FAR_MORE+ return ExperimentWatchCardStrength.FAR_MOREif separation >= MORE_LOG_RATIO:- return DeltaStrength.MORE- return DeltaStrength.SLIGHTLY_MORE+ return ExperimentWatchCardStrength.MORE+ return ExperimentWatchCardStrength.SLIGHTLY_MOREdef _card_kind(*, event_name: str, target_count: int, target_persons: int, baseline_count: int, baseline_persons: int-) -> WatchCardKind:+) -> ExperimentWatchCardKind:"""Which shelf a comparison card belongs on.Friction is decided first and beats everything: an error only the new variant throws is the@@ -1412,14 +1419,14 @@ def _card_kind(and it needs the prediction to be large before an absence means anything at all."""if event_name in FRICTION_EVENTS:- return WatchCardKind.FRICTION+ return ExperimentWatchCardKind.FRICTIONexpected_baseline = target_count / target_persons * baseline_personsif (expected_baseline >= VARIANT_ONLY_MIN_EXPECTEDand baseline_count <= expected_baseline * VARIANT_ONLY_MAX_LEAKAGE):- return WatchCardKind.VARIANT_ONLY- return WatchCardKind.BEHAVIOR+ return ExperimentWatchCardKind.VARIANT_ONLY+ return ExperimentWatchCardKind.BEHAVIORdef _pick_behavior_cards(@@ -1486,13 +1493,13 @@ def _pick_behavior_cards(# capped low because it always sorts above everything else and is never the reason to open a# recording. Sharing one budget would let either of them push the whole behavior shelf out of# the response, which is the failure mode both splits exist to prevent.- by_kind: dict[WatchCardKind, list[ExperimentWatchCard]] = {}+ by_kind: dict[ExperimentWatchCardKind, list[ExperimentWatchCard]] = {}for _separation_value, card in picked:by_kind.setdefault(card.kind, []).append(card)return (- by_kind.get(WatchCardKind.BEHAVIOR, [])[:MAX_BEHAVIOR_CARDS]- + by_kind.get(WatchCardKind.FRICTION, [])- + by_kind.get(WatchCardKind.VARIANT_ONLY, [])[:MAX_VARIANT_ONLY_CARDS]+ by_kind.get(ExperimentWatchCardKind.BEHAVIOR, [])[:MAX_BEHAVIOR_CARDS]+ + by_kind.get(ExperimentWatchCardKind.FRICTION, [])+ + by_kind.get(ExperimentWatchCardKind.VARIANT_ONLY, [])[:MAX_VARIANT_ONLY_CARDS])@@ -1523,7 +1530,7 @@ def _drop_duplicate_recording_sets(cards: list[ExperimentWatchCard]) -> list[Expbe backed by a recording at all."""kept: list[ExperimentWatchCard] = []- seen_by_kind: dict[WatchCardKind, list[set[str]]] = {}+ seen_by_kind: dict[ExperimentWatchCardKind, list[set[str]]] = {}for card in cards:session_ids = set(card.session_ids)shelf = seen_by_kind.setdefault(card.kind, [])@@ -1615,7 +1622,7 @@ def _metric_card_candidates(][:MAX_METRIC_CARD_EVENTS]return [ExperimentWatchCard(- kind=WatchCardKind.METRIC,+ kind=ExperimentWatchCardKind.METRIC,event=named.event,variant=variant_key,strength=None,diff --git a/products/feature_flags/backend/api/staff_cache.py b/products/feature_flags/backend/api/staff_cache.pyindex a795a1bd2f99..d3ef5d230548 100644--- a/products/feature_flags/backend/api/staff_cache.py+++ b/products/feature_flags/backend/api/staff_cache.py@@ -38,10 +38,17 @@ logger = structlog.get_logger(__name__)# much work a single staff request can trigger; adjust if it proves too tight.MAX_TEAMS_PER_MUTATION = 50-EVALUATION = "evaluation"-DEFINITIONS = "definitions"-CACHE_CHOICES = [EVALUATION, DEFINITIONS]+# The labels repeat the values because the published OpenAPI enum lists these exact pairs.+class StaffCacheKind(models.TextChoices):+ EVALUATION = "evaluation", "evaluation"+ DEFINITIONS = "definitions", "definitions"+++EVALUATION = StaffCacheKind.EVALUATION.value+DEFINITIONS = StaffCacheKind.DEFINITIONS.value++CACHE_CHOICES = StaffCacheKind.values# The readable caches, enumerated once here rather than hardcoded in list/entry._READABLE_HYPERCACHES = {@@ -125,7 +132,7 @@ class StaffCacheStatusResponseSerializer(serializers.Serializer):class StaffCacheMutationSerializer(serializers.Serializer):team_ids = _team_ids_field(f"Team ids to act on (max {MAX_TEAMS_PER_MUTATION} per request).")caches = serializers.ListField(- child=serializers.ChoiceField(choices=CACHE_CHOICES),+ child=serializers.ChoiceField(choices=StaffCacheKind.choices),required=False,default=CACHE_CHOICES,help_text=(@@ -149,7 +156,7 @@ class StaffCacheMutationResponseSerializer(serializers.Serializer):class StaffCacheEntryQuerySerializer(serializers.Serializer):team_id = serializers.IntegerField(help_text="Team id to fetch the cache entry for.")cache = serializers.ChoiceField(- choices=READABLE_CACHE_CHOICES,+ choices=StaffCacheKind.choices,help_text=("Which cache to fetch: 'evaluation' (the /flags cache) or 'definitions' ""(the /flags/definitions local-eval cache)."@@ -164,7 +171,7 @@ class StaffCacheEntryDataField(serializers.JSONField):class StaffCacheEntryResponseSerializer(serializers.Serializer):team_id = serializers.IntegerField(help_text="Team id.")- cache = serializers.ChoiceField(choices=READABLE_CACHE_CHOICES, help_text="Which cache this entry is for.")+ cache = serializers.ChoiceField(choices=StaffCacheKind.choices, help_text="Which cache this entry is for.")source = _cache_source_field() # type: ignore[assignment]data = StaffCacheEntryDataField( # type: ignore[assignment]allow_null=True,diff --git a/products/marketing_analytics/backend/api.py b/products/marketing_analytics/backend/api.pyindex d4f542d8ffd0..c28303ac8fff 100644--- a/products/marketing_analytics/backend/api.py+++ b/products/marketing_analytics/backend/api.py@@ -90,7 +90,7 @@ from products.marketing_analytics.backend.services.setup_types import (SetCampaignFieldPreference,UpdateConversionGoal,)-from products.marketing_analytics.backend.services.types import SUGGESTED_ACTION_CHOICES, UTM_ISSUE_KIND_CHOICES+from products.marketing_analytics.backend.services.types import SUGGESTED_ACTION_CHOICES, UtmIssueKindfrom products.marketing_analytics.backend.services.utm_audit import run_utm_auditfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable@@ -162,11 +162,10 @@ class UtmAlternativeSourceSerializer(serializers.Serializer):class UtmIssueSerializer(serializers.Serializer):field = serializers.CharField(help_text="The UTM field with the issue (e.g. utm_campaign, utm_source)")severity = serializers.ChoiceField(choices=["error", "warning"], help_text="Issue severity level")- # `kind` collides with other enums in drf-spectacular, so it carries a stable name via- # ENUM_NAME_OVERRIDES ("UtmIssueKindEnum") rather than being flattened to a plain string —- # consumers get the five values as a union instead of having to restate them.+ # `kind` collides with other enums in drf-spectacular. The UtmIssueKind class gives the enum a+ # stable name (UtmIssueKindEnum), so consumers get the five values as a union.kind = serializers.ChoiceField(- choices=UTM_ISSUE_KIND_CHOICES,+ choices=UtmIssueKind.choices,help_text="Which kind of UTM problem this campaign has",)message = serializers.CharField(diff --git a/products/marketing_analytics/backend/services/types.py b/products/marketing_analytics/backend/services/types.pyindex afb67e2ebbc7..6bd951beb6f1 100644--- a/products/marketing_analytics/backend/services/types.py+++ b/products/marketing_analytics/backend/services/types.py@@ -4,32 +4,29 @@ from dataclasses import ()from enum import StrEnum+from posthog.enums import LabeledStrEnum+class UtmIssueSeverity(StrEnum):ERROR = "error"WARNING = "warning"-class UtmIssueKind(StrEnum):+# The labels repeat the values because the published OpenAPI enum lists these exact pairs.+class UtmIssueKind(LabeledStrEnum):# Campaign name matches zero events. Safest fix: update platform URLs.- NOT_LINKED = "not_linked"+ NOT_LINKED = "not_linked", "not_linked"# Campaign name matches events on another integration but not this one.- NAME_COLLISION = "name_collision"+ NAME_COLLISION = "name_collision", "name_collision"# Campaign name matches events, but with a utm_source that belongs to another integration.# Mapping would break the other integration's attribution.- NO_TAGGED_EVENTS = "no_tagged_events"+ NO_TAGGED_EVENTS = "no_tagged_events", "no_tagged_events"# Campaign name matches events with a utm_source unknown to every integration.# Safe to suggest a custom source mapping as an alternative to fixing the URLs.- UNKNOWN_SOURCE = "unknown_source"+ UNKNOWN_SOURCE = "unknown_source", "unknown_source"# Campaign name matches events, but they carry no utm_source at all (empty/missing).# Common for auto-tagged campaigns (e.g. Performance Max) that set utm_campaign only.- MISSING_SOURCE = "missing_source"---# Choice list for the API serializer. Derived from the enum so the two can't drift, and referenced-# by name from SPECTACULAR_SETTINGS["ENUM_NAME_OVERRIDES"] so the generated schema keeps a stable-# enum name instead of a hash-suffixed one.-UTM_ISSUE_KIND_CHOICES = [kind.value for kind in UtmIssueKind]+ MISSING_SOURCE = "missing_source", "missing_source"class SuggestedAction(StrEnum):@@ -47,7 +44,7 @@ class SuggestedAction(StrEnum):ADD_CAMPAIGN_NAME_MAPPING = "add_campaign_name_mapping"-# Same reason as UTM_ISSUE_KIND_CHOICES above: a stable enum name in the generated schema.+# Choice list for the API serializer. Derived from the enum so the two can't drift.SUGGESTED_ACTION_CHOICES = [action.value for action in SuggestedAction]diff --git a/products/tasks/backend/facade/enums.py b/products/tasks/backend/facade/enums.pyindex 1fe634edbb2d..4fdfbb02b41a 100644--- a/products/tasks/backend/facade/enums.py+++ b/products/tasks/backend/facade/enums.py@@ -1 +1,7 @@-CHANNEL_WRITE_TYPE_CHOICES: list[str] = ["public", "private"]+from posthog.enums import LabeledStrEnum+++# The labels repeat the values because the published OpenAPI enum lists these exact pairs.+class TaskChannelWriteType(LabeledStrEnum):+ PUBLIC = "public", "public"+ PRIVATE = "private", "private"diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 15ba6abb358a..2efa097a60b1 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -55,7 +55,7 @@ from products.tasks.backend.facade.contracts import (TaskUserBasicInfo,WizardCloudRunDTO,)-from products.tasks.backend.facade.enums import CHANNEL_WRITE_TYPE_CHOICES+from products.tasks.backend.facade.enums import TaskChannelWriteTypefrom products.tasks.backend.facade.model_catalogue import TASK_RUN_GATEWAY_PRODUCT, ModelChoice, available_model_choicesfrom products.tasks.backend.facade.run_config import (ALL_INITIAL_PERMISSION_MODE_CHOICES,@@ -230,16 +230,20 @@ TASK_RUN_PDF_ARTIFACT_MAX_SIZE_BYTES = 10 * 1024 * 1024# thirds, so only three quarters of that ceiling is reachable, less room for the surrounding# JSON. Larger artifacts go through prepare_upload, which presigns straight to object storage.TASK_RUN_ARTIFACT_INLINE_MAX_SIZE_BYTES = (settings.DATA_UPLOAD_MAX_MEMORY_SIZE * 3) // 4 - 1024 * 1024-TASK_RUN_ARTIFACT_TYPE_CHOICES = [- "plan",- "context",- "reference",- "output",- "artifact",- "tree_snapshot",- "user_attachment",- "skill_bundle",-]+++# The labels repeat the values because the published OpenAPI enum lists these exact pairs.+class TaskRunArtifactType(models.TextChoices):+ PLAN = "plan", "plan"+ CONTEXT = "context", "context"+ REFERENCE = "reference", "reference"+ OUTPUT = "output", "output"+ ARTIFACT = "artifact", "artifact"+ TREE_SNAPSHOT = "tree_snapshot", "tree_snapshot"+ USER_ATTACHMENT = "user_attachment", "user_attachment"+ SKILL_BUNDLE = "skill_bundle", "skill_bundle"++TASK_RUN_ARTIFACT_CONTENT_ENCODING_CHOICES = ["utf-8", "base64"]TASK_RUN_SKILL_BUNDLE_FORMAT_CHOICES = ["zip"]TASK_RUN_SKILL_SOURCE_CHOICES = ["user", "repo", "marketplace", "codex"]@@ -499,7 +503,7 @@ class TaskRunDetailSerializer(DataclassSerializer):)artifacts = TaskRunArtifactResponseSerializer(many=True, read_only=True)runtime_adapter = serializers.ChoiceField(- choices=[adapter.value for adapter in RuntimeAdapter],+ choices=RuntimeAdapter.choices,allow_null=True,required=False,help_text="Configured runtime adapter for this run, such as 'claude' or 'codex'.",@@ -834,7 +838,7 @@ class TaskWriteSerializer(serializers.Serializer):# null and "" are not interchangeable: model keeps allow_blank=False so an# empty string, which is never a valid model id, is still rejected.runtime_adapter = serializers.ChoiceField(- choices=[adapter.value for adapter in RuntimeAdapter],+ choices=RuntimeAdapter.choices,required=False,default=None,allow_null=True,@@ -1379,7 +1383,7 @@ class TaskRunRelayMessageRequestSerializer(serializers.Serializer):class TaskRunArtifactUploadSerializer(serializers.Serializer):name = serializers.CharField(max_length=255, help_text="File name to associate with the artifact")- type = serializers.ChoiceField(choices=TASK_RUN_ARTIFACT_TYPE_CHOICES, help_text="Classification for the artifact")+ type = serializers.ChoiceField(choices=TaskRunArtifactType.choices, help_text="Classification for the artifact")source = serializers.CharField( # type: ignore[assignment]max_length=64,required=False,@@ -1704,7 +1708,7 @@ class TaskRunLivingArtifactEditRequestSerializer(serializers.Serializer):class TaskRunArtifactPrepareUploadSerializer(serializers.Serializer):name = serializers.CharField(max_length=255, help_text="File name to associate with the artifact")- type = serializers.ChoiceField(choices=TASK_RUN_ARTIFACT_TYPE_CHOICES, help_text="Classification for the artifact")+ type = serializers.ChoiceField(choices=TaskRunArtifactType.choices, help_text="Classification for the artifact")source = serializers.CharField( # type: ignore[assignment]max_length=64,required=False,@@ -1788,7 +1792,7 @@ class TaskRunArtifactsPrepareUploadResponseSerializer(serializers.Serializer):class TaskRunArtifactFinalizeUploadSerializer(serializers.Serializer):id = serializers.CharField(help_text="Stable identifier returned by the prepare upload endpoint")name = serializers.CharField(max_length=255, help_text="File name associated with the artifact")- type = serializers.ChoiceField(choices=TASK_RUN_ARTIFACT_TYPE_CHOICES, help_text="Classification for the artifact")+ type = serializers.ChoiceField(choices=TaskRunArtifactType.choices, help_text="Classification for the artifact")source = serializers.CharField( # type: ignore[assignment]max_length=64,required=False,@@ -1827,7 +1831,7 @@ class TaskRunArtifactsFinalizeUploadResponseSerializer(serializers.Serializer):class TaskStagedArtifactPrepareUploadSerializer(serializers.Serializer):name = serializers.CharField(max_length=255, help_text="File name to associate with the staged artifact")- type = serializers.ChoiceField(choices=TASK_RUN_ARTIFACT_TYPE_CHOICES, help_text="Classification for the artifact")+ type = serializers.ChoiceField(choices=TaskRunArtifactType.choices, help_text="Classification for the artifact")source = serializers.CharField( # type: ignore[assignment]max_length=64,required=False,@@ -1911,7 +1915,7 @@ class TaskStagedArtifactsPrepareUploadResponseSerializer(serializers.Serializer)class TaskStagedArtifactFinalizeUploadSerializer(serializers.Serializer):id = serializers.CharField(help_text="Stable identifier returned by the staged prepare upload endpoint")name = serializers.CharField(max_length=255, help_text="File name associated with the staged artifact")- type = serializers.ChoiceField(choices=TASK_RUN_ARTIFACT_TYPE_CHOICES, help_text="Classification for the artifact")+ type = serializers.ChoiceField(choices=TaskRunArtifactType.choices, help_text="Classification for the artifact")source = serializers.CharField( # type: ignore[assignment]max_length=64,required=False,@@ -2557,7 +2561,7 @@ class ChannelWriteSerializer(serializers.Serializer):max_length=128, help_text="Channel name, shown as #<name>. Uses lowercase letters and hyphens.")channel_type = serializers.ChoiceField(- choices=CHANNEL_WRITE_TYPE_CHOICES,+ choices=TaskChannelWriteType.choices,default="public",help_text=("Use 'public' for access by all project members. Use 'private' for access by channel members only. "@@ -2625,7 +2629,7 @@ class ChannelUpdateSerializer(serializers.Serializer):help_text="Days of inactivity before tasks in this channel are archived. Accepts 1 through 365. Null disables automatic archiving.",)channel_type = serializers.ChoiceField(- choices=CHANNEL_WRITE_TYPE_CHOICES,+ choices=TaskChannelWriteType.choices,required=False,help_text=("Switch a shared space between 'public' and 'private'. Making a space private keeps only the creator "@@ -3256,7 +3260,7 @@ class ModelChoiceSerializer(DataclassSerializer):"""runtime_adapter = serializers.ChoiceField(- choices=[adapter.value for adapter in RuntimeAdapter],+ choices=RuntimeAdapter.choices,help_text="Runtime that drives this model, such as 'claude' or 'codex'.",)display_name = serializers.CharField(@@ -3558,8 +3562,6 @@ class TaskRunCreateRequestSerializer("""Request body for creating a new task run"""PR_AUTHORSHIP_MODE_CHOICES = [mode.value for mode in PrAuthorshipMode]- RUN_SOURCE_CHOICES = [source.value for source in RunSource]- RUNTIME_ADAPTER_CHOICES = [adapter.value for adapter in RuntimeAdapter]REASONING_EFFORT_CHOICES = list(REASONING_EFFORTS)mode = serializers.ChoiceField(@@ -3619,7 +3621,7 @@ class TaskRunCreateRequestSerializer(),)run_source = serializers.ChoiceField(- choices=RUN_SOURCE_CHOICES,+ choices=RunSource.choices,required=False,default=None,help_text="High-level source that triggered this run, used to distinguish manual and signal-based cloud runs.",@@ -3631,7 +3633,7 @@ class TaskRunCreateRequestSerializer(help_text="Optional signal report identifier when this run was started from Inbox.",)runtime_adapter = serializers.ChoiceField(- choices=RUNTIME_ADAPTER_CHOICES,+ choices=RuntimeAdapter.choices,required=False,default=None,help_text="Agent runtime adapter to launch for this run. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime.",@@ -3775,7 +3777,6 @@ class TaskRunBootstrapCreateRequestSerializer(PR_AUTHORSHIP_MODE_CHOICES = [mode.value for mode in PrAuthorshipMode]RUN_SOURCE_CHOICES = [source.value for source in RunSource if source != RunSource.AGENT]- RUNTIME_ADAPTER_CHOICES = [adapter.value for adapter in RuntimeAdapter]REASONING_EFFORT_CHOICES = TASK_RUN_REASONING_EFFORT_CHOICESenvironment = serializers.ChoiceField(@@ -3836,7 +3837,7 @@ class TaskRunBootstrapCreateRequestSerializer(help_text="Optional signal report identifier when this run was started from Inbox.",)runtime_adapter = serializers.ChoiceField(- choices=RUNTIME_ADAPTER_CHOICES,+ choices=RuntimeAdapter.choices,required=False,default=None,help_text="Agent runtime adapter to launch for this run. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime.",@@ -3994,7 +3995,7 @@ class WarmTaskRequestSerializer(serializers.Serializer):help_text="Branch to check out in the warm sandbox. Defaults to the repository's default branch when omitted.",)runtime_adapter = serializers.ChoiceField(- choices=[adapter.value for adapter in RuntimeAdapter],+ choices=RuntimeAdapter.choices,required=False,default=None,allow_null=True,@@ -4133,7 +4134,7 @@ class WarmTaskResumeRequestSerializer(serializers.Serializer):help_text="ID of the task's latest terminal run whose snapshot and conversation should be resumed.",)runtime_adapter = serializers.ChoiceField(- choices=[adapter.value for adapter in RuntimeAdapter],+ choices=RuntimeAdapter.choices,required=False,default=None,help_text="Agent runtime adapter to start before the next message is submitted.",@@ -4341,7 +4342,7 @@ class TaskRunResumeRequestSchemaSerializer(TaskRunScheduleSerializer):help_text="Whether pull requests for this run should be authored by the user or the bot.",)run_source = serializers.ChoiceField(- choices=TaskRunCreateRequestSerializer.RUN_SOURCE_CHOICES,+ choices=RunSource.choices,required=False,default=None,help_text="High-level source that triggered this run, used to distinguish manual and signal-based cloud runs.",@@ -5078,7 +5079,6 @@ class TasksAIRunPreferencesSerializer(serializers.Serializer):every field as null to clear a stored preference."""- RUNTIME_ADAPTER_CHOICES = [adapter.value for adapter in RuntimeAdapter]REASONING_EFFORT_CHOICES = TASK_RUN_REASONING_EFFORT_CHOICESruntime = serializers.ChoiceField(@@ -5092,7 +5092,7 @@ class TasksAIRunPreferencesSerializer(serializers.Serializer):),)runtime_adapter = serializers.ChoiceField(- choices=RUNTIME_ADAPTER_CHOICES,+ choices=RuntimeAdapter.choices,required=False,allow_null=True,default=None,diff --git a/products/tasks/backend/presentation/serializers_loops.py b/products/tasks/backend/presentation/serializers_loops.pyindex c8eb628c930b..e8740ee58e61 100644--- a/products/tasks/backend/presentation/serializers_loops.py+++ b/products/tasks/backend/presentation/serializers_loops.py@@ -440,7 +440,7 @@ class LoopWriteSerializer(serializers.Serializer):)instructions = serializers.CharField(help_text="The prompt delivered to the agent on every run.")runtime_adapter = serializers.ChoiceField(- choices=[adapter.value for adapter in RuntimeAdapter], help_text="Runtime adapter: 'claude' or 'codex'."+ choices=RuntimeAdapter.choices, help_text="Runtime adapter: 'claude' or 'codex'.")model = serializers.CharField(required=False,diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex e1b4a4365756..b85cbbd56d91 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -13,6 +13,7 @@ from django.db import transactionfrom pydantic import BaseModel+from posthog.enums import LabeledStrEnumfrom posthog.llm.gateway_client import GatewayNotConfiguredError, ensure_scout_trial_capture_readyfrom posthog.models.integration import GitHubIntegration, Integrationfrom posthog.models.user import User@@ -96,10 +97,11 @@ class GitHubCredentialSource(StrEnum):SERVER_INTEGRATION = "server_integration"-class RunSource(StrEnum):- MANUAL = "manual"- SIGNAL_REPORT = "signal_report"- AGENT = "agent"+# The labels repeat the values because the published OpenAPI enum lists these exact pairs.+class RunSource(LabeledStrEnum):+ MANUAL = "manual", "manual"+ SIGNAL_REPORT = "signal_report", "signal_report"+ AGENT = "agent", "agent"def mcp_scopes_for_run_source(run_source: RunSource | None) -> Literal["read_only", "full"]:@@ -110,9 +112,10 @@ def mcp_scopes_for_run_source(run_source: RunSource | None) -> Literal["read_onlUSER_AUTHORABLE_ORIGIN_PRODUCTS: tuple[str, ...] = ("user_created", "slack", "posthog_ai")-class RuntimeAdapter(StrEnum):- CLAUDE = "claude"- CODEX = "codex"+# The labels repeat the values because the published OpenAPI enum lists these exact pairs.+class RuntimeAdapter(LabeledStrEnum):+ CLAUDE = "claude", "claude"+ CODEX = "codex", "codex"class LLMProvider(StrEnum):