: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): type closed-set dataclass fields as Literal (#83532)
Arno Hillen574af1c3085e
diff --git a/posthog/test/dataclass_frozen_baseline.txt b/posthog/test/dataclass_frozen_baseline.txtindex f3b805adfed3..fdba583f98f7 100644--- a/posthog/test/dataclass_frozen_baseline.txt+++ b/posthog/test/dataclass_frozen_baseline.txt@@ -89,7 +89,6 @@1 products/apm/backend/logic/anomaly_detection/types.py1 products/apm/backend/logic/anomaly_detection/validation/simulation.py1 products/approvals/backend/decorators.py-1 products/approvals/backend/policies.py1 products/batch_exports/backend/api/batch_export.py1 products/batch_exports/backend/api/destination_tests/base.py1 products/batch_exports/backend/debug/debugger.py@@ -130,7 +129,6 @@1 products/error_tracking/backend/temporal/weekly_digest/test/test_weekly_digest_temporal.py1 products/experiments/backend/hogql_queries/metric_source.py1 products/experiments/backend/running_time_calculator.py-1 products/experiments/backend/temporal/canary_logic.py1 products/experiments/stats/bayesian/method.py1 products/experiments/stats/bayesian/priors.py1 products/experiments/stats/bayesian/tests.py@@ -157,7 +155,6 @@1 products/mcp_analytics/backend/management/commands/classify_mcp_failures.py1 products/mcp_store/backend/catalog_sync.py1 products/mcp_store/backend/probe.py-1 products/notebooks/backend/python_analysis.py1 products/notebooks/backend/sql_v2_state.py1 products/notebooks/backend/temporal/frame_materialize.py1 products/notebooks/backend/temporal/sql_v2.py@@ -1366,7 +1363,6 @@10 posthog/temporal/ai_observability/trace_summarization/models.py10 posthog/temporal/data_modeling/run_workflow.py10 posthog/temporal/sync_person_distinct_ids/activities.py-10 products/experiments/backend/temporal/models.py10 products/signals/backend/temporal/summary.py10 products/tasks/backend/temporal/process_task/activities/provision_sandbox.py104 posthog/hogql/ast.py@@ -1632,4 +1628,5 @@8 products/signals/backend/temporal/signal_queries.py9 posthog/clickhouse/cluster.py9 posthog/temporal/backfill_materialized_property/activities.py+9 products/experiments/backend/temporal/models.py9 products/signals/backend/temporal/reingestion.pydiff --git a/products/approvals/backend/policies.py b/products/approvals/backend/policies.pyindex 3cd3440c8c6b..28f17573c87c 100644--- a/products/approvals/backend/policies.py+++ b/products/approvals/backend/policies.py@@ -1,12 +1,13 @@-from dataclasses import dataclass-from typing import Any+from typing import Any, Literal+from posthog.dataclasses import frozen-@dataclass++@frozenclass PolicyDecision:"""Result of policy evaluation"""- result: str+ result: Literal["ALLOW", "DENY", "REQUIRE_APPROVAL"]reason: strmessage: strapprovers: dictdiff --git a/products/cohorts/backend/parity/eligibility.py b/products/cohorts/backend/parity/eligibility.pyindex db176dd4f76b..dd0e0991a757 100644--- a/products/cohorts/backend/parity/eligibility.py+++ b/products/cohorts/backend/parity/eligibility.py@@ -21,7 +21,7 @@ import mathfrom collections.abc import Mappingfrom dataclasses import dataclass, fieldfrom datetime import datetime-from typing import Any, Optional, Union+from typing import Any, Literal, Optional, UnionSINGLE_LEAF = "single_leaf"STAGE2_COMPOSABLE = "stage2_composable"@@ -60,7 +60,7 @@ class ScreenedCohort:@dataclass(frozen=True)class _Leaf:- kind: str # "person" | "behavioral" | "cohort_ref"+ kind: Literal["person", "behavioral", "cohort_ref"]negated: bool = Falsewindow_days: Optional[float] = Noneref_id: Optional[int] = None@@ -118,7 +118,7 @@ def _is_absolute_datetime(raw: str) -> bool:# window length in days for the soundness check (fractional for "seconds", inf for "explicit").@dataclass(frozen=True)class _Window:- kind: str+ kind: Literal["days", "seconds", "explicit"]days: floatdiff --git a/products/experiments/backend/temporal/canary_logic.py b/products/experiments/backend/temporal/canary_logic.pyindex 6169247ce0a9..500371ca624b 100644--- a/products/experiments/backend/temporal/canary_logic.py+++ b/products/experiments/backend/temporal/canary_logic.py@@ -70,6 +70,7 @@ from products.experiments.backend.temporal.models import (OUTCOME_SKIPPED,CanaryMetricResult,CanaryMetricTarget,+ CanaryOutcome,CanaryReportInputs,CanaryRunSnapshot,CanaryVariantStats,@@ -224,9 +225,9 @@ def sample_canary_targets_sync(inputs: ExperimentPrecomputeCanaryInputs) -> list# ---------------------------------------------------------------------------[email protected](frozen=False)class CanaryVerdict:- outcome: str+ outcome: CanaryOutcomestability_deviation: float | None = Nonecorrectness_deviation: float | None = Nonedetail: str | None = None@@ -476,7 +477,7 @@ def _send_slack_alert(divergent: list[CanaryMetricResult], counts: dict[str, intdef report_canary_results_sync(report: CanaryReportInputs) -> None:- counts = dict.fromkeys(ALL_OUTCOMES, 0)+ counts: dict[str, int] = dict.fromkeys(ALL_OUTCOMES, 0)for result in report.results:counts[result.outcome] = counts.get(result.outcome, 0) + 1diff --git a/products/experiments/backend/temporal/models.py b/products/experiments/backend/temporal/models.pyindex 9931858a7e24..c2ac8dedcfa4 100644--- a/products/experiments/backend/temporal/models.py+++ b/products/experiments/backend/temporal/models.py@@ -1,14 +1,23 @@import dataclasses+from typing import Final, Literal# Shared by the workflow definition, the schedule, and the management command.CANARY_WORKFLOW_NAME = "experiment-precompute-canary"-OUTCOME_PASS = "pass"-OUTCOME_DIVERGENCE = "divergence"-OUTCOME_PATH_FLIP = "path_flip"-OUTCOME_ERROR = "error"-OUTCOME_SKIPPED = "skipped"-ALL_OUTCOMES = (OUTCOME_PASS, OUTCOME_DIVERGENCE, OUTCOME_PATH_FLIP, OUTCOME_ERROR, OUTCOME_SKIPPED)+CanaryOutcome = Literal["pass", "divergence", "path_flip", "error", "skipped"]++OUTCOME_PASS: Final = "pass"+OUTCOME_DIVERGENCE: Final = "divergence"+OUTCOME_PATH_FLIP: Final = "path_flip"+OUTCOME_ERROR: Final = "error"+OUTCOME_SKIPPED: Final = "skipped"+ALL_OUTCOMES: tuple[CanaryOutcome, ...] = (+ OUTCOME_PASS,+ OUTCOME_DIVERGENCE,+ OUTCOME_PATH_FLIP,+ OUTCOME_ERROR,+ OUTCOME_SKIPPED,+)# Cap CanaryMetricResult.detail so a pathological error message can't bloat the Temporal payload.MAX_CANARY_DETAIL_LENGTH = 1000@@ -139,12 +148,12 @@ class CanaryRunSnapshot:variants: dict[str, CanaryVariantStats][email protected](frozen=False)class CanaryMetricResult:"""Verdict for one metric: outcome plus everything needed to investigate without re-running."""target: CanaryMetricTarget- outcome: str # "pass" | "divergence" | "path_flip" | "error" | "skipped"+ outcome: CanaryOutcomestability_deviation: float | None = None # max relative deviation, run a vs bcorrectness_deviation: float | None = None # max relative deviation, run b vs cruns: list[CanaryRunSnapshot] = dataclasses.field(default_factory=list)diff --git a/products/experiments/backend/temporal/test_canary_logic.py b/products/experiments/backend/temporal/test_canary_logic.pyindex 2b18dc20d695..f2d151c60ff9 100644--- a/products/experiments/backend/temporal/test_canary_logic.py+++ b/products/experiments/backend/temporal/test_canary_logic.py@@ -28,6 +28,7 @@ from products.experiments.backend.temporal.models import (OUTCOME_SKIPPED,CanaryMetricResult,CanaryMetricTarget,+ CanaryOutcome,CanaryReportInputs,CanaryRunSnapshot,CanaryVariantStats,@@ -402,7 +403,7 @@ class TestRunMetricCanary(BaseTest):run_metric_canary_sync(self._target(experiment, metric["uuid"]))-def _result(outcome: str, **kwargs) -> CanaryMetricResult:+def _result(outcome: CanaryOutcome, **kwargs) -> CanaryMetricResult:target = CanaryMetricTarget(team_id=1, experiment_id=2, metric_uuid="m-uuid", metric_type="funnel")return CanaryMetricResult(target=target, outcome=outcome, runs=[_snapshot("a", _BASE)], **kwargs)diff --git a/products/logs/backend/alert_signal_emitter.py b/products/logs/backend/alert_signal_emitter.pyindex 3638fdbdf448..cd54499d3614 100644--- a/products/logs/backend/alert_signal_emitter.py+++ b/products/logs/backend/alert_signal_emitter.py@@ -1,6 +1,7 @@from __future__ import annotationsimport dataclasses+from typing import Literalfrom django.conf import settings@@ -16,11 +17,13 @@ logger = structlog.get_logger(__name__)SOURCE_PRODUCT = "logs"SOURCE_TYPE = "alert_state_change"+AlertSignalAction = Literal["firing", "broken"]+# Notification -> (action label, weight). Only FIRE and BROKEN are signalled —# both are investigate-now (weight 1.0). RESOLVE (rarely worth investigating) and# ERROR (transient — the real signal is the eventual BROKEN auto-disable) are# intentionally absent, so signal_action_and_weight returns None for them.-_ACTION_WEIGHT: dict[NotificationAction, tuple[str, float]] = {+_ACTION_WEIGHT: dict[NotificationAction, tuple[AlertSignalAction, float]] = {NotificationAction.FIRE: ("firing", 1.0),NotificationAction.BROKEN: ("broken", 1.0),}@@ -36,7 +39,7 @@ class NotifiedAlert:alert_id: strteam_id: intalert_name: str- action: str # firing | broken+ action: AlertSignalActionweight: floatthreshold_count: intthreshold_operator: str@@ -46,7 +49,7 @@ class NotifiedAlert:filters: dict-def signal_action_and_weight(notification: NotificationAction) -> tuple[str, float] | None:+def signal_action_and_weight(notification: NotificationAction) -> tuple[AlertSignalAction, float] | None:"""Map a NotificationAction to (action label, weight), or None if not signalable."""return _ACTION_WEIGHT.get(notification)diff --git a/products/logs/backend/test/test_alert_signal_emitter.py b/products/logs/backend/test/test_alert_signal_emitter.pyindex 0bc404a9ccac..fc040582cc7c 100644--- a/products/logs/backend/test/test_alert_signal_emitter.py+++ b/products/logs/backend/test/test_alert_signal_emitter.py@@ -6,6 +6,7 @@ from parameterized import parameterizedfrom posthog.models import Teamfrom products.logs.backend.alert_signal_emitter import (+ AlertSignalAction,NotifiedAlert,build_signal_description,build_signal_extra,@@ -16,7 +17,7 @@ from products.logs.backend.alert_state_machine import NotificationActionfrom products.signals.backend.contracts import LogsAlertStateChangeSignalExtra-def _notified(action: str = "firing") -> NotifiedAlert:+def _notified(action: AlertSignalAction = "firing") -> NotifiedAlert:return NotifiedAlert(alert_id="11111111-1111-1111-1111-111111111111",team_id=7,diff --git a/products/logs/backend/test/test_logs_alerting_activities.py b/products/logs/backend/test/test_logs_alerting_activities.pyindex 95386801c01f..cea7b738c876 100644--- a/products/logs/backend/test/test_logs_alerting_activities.py+++ b/products/logs/backend/test/test_logs_alerting_activities.py@@ -23,7 +23,7 @@ from posthog.errors import QueryErrorCategoryfrom posthog.slo.types import SloOperation, SloOutcomefrom products.logs.backend.alert_check_query import AlertCheckQuery, BatchedBucketedResult, BucketedCount-from products.logs.backend.alert_signal_emitter import NotifiedAlert+from products.logs.backend.alert_signal_emitter import AlertSignalAction, NotifiedAlertfrom products.logs.backend.alert_state_machine import AlertCheckOutcome, AlertState, CheckResult, NotificationActionfrom products.logs.backend.models import LogsAlertConfiguration, LogsAlertEventfrom products.logs.backend.temporal.activities import (@@ -157,7 +157,7 @@ class TestNotifiedAlertCollection(APIBaseTest):class TestEmitAlertSignalsActivity(NonAtomicBaseTest):def _notified(- self, alert_id: str, action: str, result_count: int | None, consecutive_failures: int+ self, alert_id: str, action: AlertSignalAction, result_count: int | None, consecutive_failures: int) -> NotifiedAlert:return NotifiedAlert(alert_id=alert_id,diff --git a/products/notebooks/backend/python_analysis.py b/products/notebooks/backend/python_analysis.pyindex 94c304269c00..6f2105c5748e 100644--- a/products/notebooks/backend/python_analysis.py+++ b/products/notebooks/backend/python_analysis.py@@ -2,7 +2,9 @@ import astimport hashlibimport builtinsfrom dataclasses import dataclass-from typing import Any+from typing import Any, Literal++from posthog.dataclasses import frozen@dataclass(frozen=True)@@ -81,9 +83,12 @@ def collect_arg_names(arguments: ast.arguments) -> set[str]:return names-@dataclass+ScopeKind = Literal["module", "function", "class", "lambda", "comprehension"]+++@frozenclass Scope:- kind: str+ kind: ScopeKindlocals: set[str]@@ -204,7 +209,7 @@ class GlobalAnalyzer(ast.NodeVisitor):def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:self._visit_function_like(node, "function")- def _visit_function_like(self, node: ast.AST, kind: str) -> None:+ def _visit_function_like(self, node: ast.AST, kind: ScopeKind) -> None:if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):for decorator in node.decorator_list:self.visit(decorator)@@ -268,7 +273,7 @@ class GlobalAnalyzer(ast.NodeVisitor):def visit_GeneratorExp(self, node: ast.GeneratorExp) -> None:self._visit_comprehension(node, "comprehension")- def _visit_comprehension(self, node: ast.AST, kind: str) -> None:+ def _visit_comprehension(self, node: ast.AST, kind: ScopeKind) -> None:generators = getattr(node, "generators", [])locals_set: set[str] = set()for generator in generators:diff --git a/products/notebooks/backend/sql_v2_references.py b/products/notebooks/backend/sql_v2_references.pyindex afea476784ee..b386dee11cd6 100644--- a/products/notebooks/backend/sql_v2_references.py+++ b/products/notebooks/backend/sql_v2_references.py@@ -20,7 +20,7 @@ whatever HogQL refs it also reads — the same input shape Python nodes use.import refrom dataclasses import dataclass-from typing import Any+from typing import Any, Literalfrom posthog.hogql import astfrom posthog.hogql.context import HogQLContext@@ -56,7 +56,7 @@ class SQLV2Ref:message, and only surfaces when the query actually reads the name."""- kind: str # "hogql" | "local"+ kind: Literal["hogql", "local"]node_id: str | None = Nonerun_id: str | None = Nonelast_run_code: str | None = None