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): semgrep rule and docs for the frozen dataclass convention (#76156)

Arno Hillen641d714363c8
diff --git a/.claude/commands/conventions.md b/.claude/commands/conventions.md
index 053ba4e76a3a..ebe1ecb9d174 100644
--- a/.claude/commands/conventions.md
+++ b/.claude/commands/conventions.md
@@ -81,6 +81,15 @@ Hence the explicit separation between the data and view layers.
- Always place imports at the top of the file (module level), never inside functions or methods (local imports)
+### Dataclasses
+
+- Prefer a small dataclass over a tuple when returning or passing multiple values: always when two or more elements share a type (callers can silently swap them, e.g. `(start, end)`), and when there are roughly 3+ elements, where positional access hurts readability
+- Use `@frozen` from `posthog.dataclasses` (applies `frozen=True`, `kw_only=True`, `slots=True`; every flag overridable, e.g. `@frozen(slots=False)` for `functools.cached_property`)
+- Consume results with dot notation (`result.field`), never by unpacking into positional locals
+- Name dataclasses after the domain concept (`BillingPeriod`), never `*Info`/`*Data`/`*Tuple`
+- Mark secret fields with `field(repr=False)`
+- A bare `@dataclass` without an explicit `frozen=` choice fails the `posthog/test/test_dataclass_defaults.py` ratchet and is flagged by the `prefer-frozen-dataclasses` semgrep rule
+
### Logging
As a general rule, we should have logs for every expected and unexpected actions of the application, using the appropriate _log level_.
diff --git a/.cursor/rules/django-python.mdc b/.cursor/rules/django-python.mdc
index ea434a5d4f0e..5bbe86aca0a1 100644
--- a/.cursor/rules/django-python.mdc
+++ b/.cursor/rules/django-python.mdc
@@ -102,6 +102,13 @@ Unit tests
Integration tests
- Integration tests should ensure that the feature works end-to-end. They must cover all the important use cases of the feature.
+Dataclasses
+ - Prefer a small dataclass over a tuple when returning or passing multiple values: always when two or more elements share a type (silently swappable, e.g. (start, end)), and when there are roughly 3+ elements.
+ - Use @frozen from posthog.dataclasses (frozen=True, kw_only=True, slots=True by default; every flag overridable, e.g. @frozen(slots=False) for functools.cached_property).
+ - Consume results with dot notation (result.field), never by unpacking into positional locals (a, b = result.a, result.b).
+ - Name dataclasses after the domain concept (BillingPeriod), never *Info/*Data/*Tuple; mark secret fields with field(repr=False).
+ - A bare @dataclass without an explicit frozen= choice fails the posthog/test/test_dataclass_defaults.py ratchet and is flagged by the prefer-frozen-dataclasses semgrep rule.
+
Running commands
- Use `uv sync` instead of `pip install -r ...`, and `uv add PACKAGE` instead of `pip install PACKAGE`. If there is an import error, first activate the venv at `.flox/cache/venv/` or alternatively `.venv/`.
Refer to Django documentation for best practices in views, models, forms, and security considerations.
diff --git a/.semgrep/rules/devex/prefer-frozen-dataclasses.py b/.semgrep/rules/devex/prefer-frozen-dataclasses.py
new file mode 100644
index 000000000000..e71b668c0efb
--- /dev/null
+++ b/.semgrep/rules/devex/prefer-frozen-dataclasses.py
@@ -0,0 +1,84 @@
+# Test cases for prefer-frozen-dataclasses.
+# ruff: noqa
+import dataclasses
+from dataclasses import dataclass
+
+from posthog.dataclasses import frozen
+
+
+# ruleid: prefer-frozen-dataclasses
+@dataclass
+class BareDecorator:
+ value: int
+
+
+# ruleid: prefer-frozen-dataclasses
+@dataclass()
+class EmptyCall:
+ value: int
+
+
+# ruleid: prefer-frozen-dataclasses
+@dataclass(slots=True, kw_only=True)
+class FlagsButNoFrozenChoice:
+ value: int
+
+
+# ruleid: prefer-frozen-dataclasses
+class BareModuleAttribute:
+ value: int
+
+
+# ruleid: prefer-frozen-dataclasses
[email protected](kw_only=True)
+class ModuleAttributeNoFrozenChoice:
+ value: int
+
+
+# ok: prefer-frozen-dataclasses
+@frozen
+class HouseDefault:
+ value: int
+
+
+# ok: prefer-frozen-dataclasses
+@frozen(slots=False)
+class HouseDefaultWithOverride:
+ value: int
+
+
+# ok: prefer-frozen-dataclasses
+@dataclass(frozen=True, kw_only=True, slots=True)
+class ExplicitFrozen:
+ value: int
+
+
+# ok: prefer-frozen-dataclasses
+@dataclass(frozen=False)
+class ExplicitlyMutable:
+ value: int
+
+
+# ok: prefer-frozen-dataclasses
[email protected](frozen=True)
+class ExplicitFrozenModuleAttribute:
+ value: int
+
+
+# The pydantic import below excludes everything after it, mirroring real files
+# where pydantic's dataclass is imported at the top.
+from pydantic.dataclasses import dataclass # noqa: E402
+
+
+# ok: prefer-frozen-dataclasses
+@dataclass
+class PydanticDataclass:
+ value: int
+
+
+# The module-attribute form is stdlib even in a pydantic-importing file.
+# ruleid: prefer-frozen-dataclasses
+class StdlibAfterPydanticImport:
+ value: int
diff --git a/.semgrep/rules/devex/prefer-frozen-dataclasses.yaml b/.semgrep/rules/devex/prefer-frozen-dataclasses.yaml
new file mode 100644
index 000000000000..38699992b23d
--- /dev/null
+++ b/.semgrep/rules/devex/prefer-frozen-dataclasses.yaml
@@ -0,0 +1,65 @@
+rules:
+ - id: prefer-frozen-dataclasses
+ message: |
+ Bare `@dataclass` without an explicit `frozen=` choice.
+
+ House default for value/result objects is `@frozen` from `posthog.dataclasses`
+ (frozen, kw_only, slots; every flag overridable, e.g. `@frozen(slots=False)`
+ for `functools.cached_property`):
+
+ from posthog.dataclasses import frozen
+
+ @frozen
+ class BillingPeriod:
+ start: datetime
+ end: datetime
+
+ If mutability is intentional, say so explicitly with `@dataclass(frozen=False, ...)`.
+ The `posthog/test/test_dataclass_defaults.py` ratchet blocks new undeclared uses;
+ existing ones are grandfathered in its baseline and migrated over time.
+ Informational, not blocking. For a genuine exception, add
+ `# nosemgrep: prefer-frozen-dataclasses -- <reason>` on the class line.
+ severity: WARNING
+ languages: [python]
+ paths:
+ include:
+ - 'common/**/*.py'
+ - 'dags/**/*.py'
+ - 'ee/**/*.py'
+ - 'posthog/**/*.py'
+ - 'products/**/*.py'
+ exclude:
+ - '**/migrations/**'
+ - '**/.semgrep/**'
+ patterns:
+ - pattern-either:
+ # Bare @dataclass is ambiguous: skip it when pydantic's decorator
+ # (with its own validation semantics) is imported under that name.
+ - patterns:
+ - pattern-either:
+ - pattern: |
+ @dataclass
+ class $C: ...
+ - pattern: |
+ @dataclass(...)
+ class $C: ...
+ - pattern-not-inside: |
+ from pydantic.dataclasses import dataclass
+ ...
+ # The module-attribute form is always the stdlib decorator.
+ - pattern: |
+ @dataclasses.dataclass
+ class $C: ...
+ - pattern: |
+ @dataclasses.dataclass(...)
+ class $C: ...
+ - pattern-not: |
+ @dataclass(..., frozen=$V, ...)
+ class $C: ...
+ - pattern-not: |
+ @dataclasses.dataclass(..., frozen=$V, ...)
+ class $C: ...
+ metadata:
+ category: best-practice
+ subcategory:
+ - audit
diff --git a/docs/published/handbook/engineering/conventions/backend-coding.md b/docs/published/handbook/engineering/conventions/backend-coding.md
index 168913ac164d..7ec77647b77f 100644
--- a/docs/published/handbook/engineering/conventions/backend-coding.md
+++ b/docs/published/handbook/engineering/conventions/backend-coding.md
@@ -133,6 +133,35 @@ A good test should:
- They give greater confidence (because you avoid the mistake of just testing a mock) but they're slower
- They are generally less brittle in response to changes because they test at a higher level than developer tests (e.g. they test a Django API not a class used inside it)
+### Dataclasses
+
+Prefer a small dataclass over a tuple when returning or passing multiple values:
+always when two or more elements share a type (callers can silently swap them, e.g. `(start, end)` timestamps or `(username, password)` credentials),
+and when there are roughly 3+ elements, where positional access hurts readability.
+
+Use the house-default decorator:
+
+```python
+from posthog.dataclasses import frozen
+
+
+@frozen
+class BillingPeriod:
+ start: datetime
+ end: datetime
+```
+
+`@frozen` applies `frozen=True` (immutable, hashable), `kw_only=True` (keyword-only construction, so same-typed fields can't be transposed), and `slots=True` (less memory, typo-safe attribute access).
+Every flag is overridable per class: `@frozen(slots=False)` when a class needs `functools.cached_property`, or an explicit `@dataclass(frozen=False, ...)` for a deliberately mutable builder.
+
+Consume results with dot notation (`result.field`).
+Don't unpack them back into positional locals (`a, b = result.a, result.b`), which recreates the swap hazard the dataclass exists to prevent.
+
+Name dataclasses after the domain concept (`ClickHouseCredentials`, `BillingPeriod`), never `*Info`/`*Data`/`*Tuple`; use a `*Result` suffix only when the function's outcome genuinely is the concept.
+Mark secret fields with `field(repr=False)` so they stay out of logs and tracebacks.
+
+Enforcement: a new bare `@dataclass` without an explicit `frozen=` choice fails the ratchet in `posthog/test/test_dataclass_defaults.py` (existing uses are grandfathered in its baseline) and is flagged inline by the `prefer-frozen-dataclasses` semgrep rule.
+
### Querying ClickHouse
**Always use HogQL instead of raw ClickHouse queries in product code.**