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): move dataclass conventions into a writing-dataclasses skill (#83524)

Arno Hillen1716f538fa9e
diff --git a/.agents/skills/writing-dataclasses/SKILL.md b/.agents/skills/writing-dataclasses/SKILL.md
new file mode 100644
index 000000000000..43f36f682d4b
--- /dev/null
+++ b/.agents/skills/writing-dataclasses/SKILL.md
@@ -0,0 +1,78 @@
+---
+name: writing-dataclasses
+description: >
+ House rules for Python dataclasses in PostHog: when to reach for one instead of a tuple or `dict[str, Any]`, which decorator to use (`@frozen` from `posthog.dataclasses`), how to name, construct, consume and evolve them, how to keep secrets out of `repr`, and when a function should accept a dataclass instead of its unpacked fields.
+ Use when adding or changing a dataclass, returning or passing several values from a function, converting a tuple or dict payload, deciding `frozen=`/`slots=`/`kw_only=`, or passing a facade contract DTO through internal layers.
+ Not for pydantic models used as HogQL/query schema, DRF serializers, or Django models.
+---
+
+# Writing dataclasses
+
+The point of every rule here is the same: values that share a type get swapped silently, and a positional tuple or a `dict[str, Any]` lets that happen. A named, frozen dataclass makes the swap a typecheck failure instead of a runtime bug. Everything below follows from that; if a rule doesn't serve it in your case, say so in the PR and skip it.
+
+## When a dataclass, when not
+
+- **Return or pass a dataclass instead of a tuple** when two or more elements share a type (`(start, end)`, `(width, height)`, `(rows, columns)`), or when the tuple has roughly 3+ elements and positional access hurts readability. A small tuple of clearly different types (`(user, count)`) is fine as-is.
+- **Prefer a dataclass over `dict[str, Any]`** when a fixed set of values crosses a function boundary. A dict key typo fails at runtime; a dataclass field typo fails typecheck. Dicts stay for genuinely dynamic key sets.
+- **`NamedTuple` is not the answer** for the swap problem: it still unpacks positionally.
+
+## Which decorator
+
+Use `@frozen` from `posthog.dataclasses` for internal value and result objects. It is `@dataclass` with `frozen=True, kw_only=True, slots=True` as defaults, and every flag is overridable:
+
+```python
+from posthog.dataclasses import frozen
+
+@frozen
+class BillingPeriod:
+ start: datetime
+ end: datetime
+
+@frozen(slots=False) # class uses functools.cached_property
+class ParsedQuery: ...
+
+@frozen(frozen=False) # genuinely mutated after construction (a builder, an accumulator)
+class RunAccumulator: ...
+```
+
+- `kw_only=True` is what actually prevents swaps at construction: `BillingPeriod(start=a, end=b)`, never `BillingPeriod(a, b)`. Don't override it without a reason.
+- `slots=True` blocks `functools.cached_property` and ad-hoc attributes; override with `slots=False` rather than dropping `@frozen`.
+- A bare `@dataclass` with no explicit `frozen=` fails the ratchet in `posthog/test/test_dataclass_defaults.py` and is flagged by the advisory `prefer-frozen-dataclasses` semgrep rule. `@dataclass(frozen=False)` passes; the ratchet asks for a stated choice, not immutability. If you only _moved_ an existing bare `@dataclass`, regenerate the baseline with `python posthog/test/test_dataclass_defaults.py` instead of decorating it.
+- Don't add `frozen=False` to a bare `@dataclass` you didn't otherwise touch. The ratchet counts per file against a baseline; an unchanged count passes, and the edit is churn in someone else's file.
+- Facade contracts (`products/<name>/backend/facade/contracts.py`) are frozen dataclasses too, usually `pydantic.dataclasses.dataclass(frozen=True)` so they validate on construction. See [products/architecture.md](../../../products/architecture.md).
+
+## Naming
+
+Name the class after the domain concept, not the plumbing: `ClickHouseCredentials`, `BillingPeriod`, `SnapshotManifestItem`. `*Result` only when the function's outcome genuinely is the concept; never `*Info`, `*Data`, `*Tuple`, `*Response` for an internal object. Underscore-prefix classes private to one module.
+
+## Constructing and enforcing invariants
+
+- Enforce invariants in `__post_init__` (`start <= end`, exactly one auth method set, value in range) so an invalid instance fails at construction rather than deep in later logic. On a frozen class use `object.__setattr__` only if you must normalize; prefer raising.
+- Type a field holding a closed set of strings as `Literal[...]` or an enum, not bare `str`. Check call sites: narrowing an existing field can surface mypy errors where callers pass a plain `str`; fix the callers, don't widen the field back.
+- A frozen dataclass hashes, so use a small keyed class as a dict or set key instead of a tuple when the key has two or more same-typed parts.
+
+## Consuming and evolving
+
+- Read fields with dot notation (`result.start`). Never `a, b = result.a, result.b` into positional locals; that reintroduces the swap.
+- Evolve a frozen instance with `dataclasses.replace(instance, field=value)`, not by copying fields by hand.
+- Dispatch on variants with `match`/`case` (`case BinaryOp(left=left, right=right):`) when there are several; a single-type check stays a plain `isinstance` guard.
+
+## Secrets
+
+Mark secret fields with `field(repr=False)` so they cannot leak through `repr()` into tracebacks and logs, and never `asdict()` such a dataclass into log output, which reintroduces what `repr=False` hides.
+
+## Passing a dataclass through layers
+
+When a function's parameters mirror the fields of a dataclass the caller already holds, accept the dataclass instead of the unpacked fields. That stops same-typed positionals being threaded through several layers, and it is Fowler's Preserve Whole Object.
+
+Three carve-outs, in priority order:
+
+1. **Invariants win over mirroring.** Never pass a wider type into a callee that needs a narrower one. If the dataclass has `url: str | None` and the helper needs a `str`, keep the `str` parameter (or narrow the type at the boundary); do not accept the dataclass and add a runtime `ValueError`. That trades a typecheck for a guard clause, which is the opposite of the point.
+2. **Wire signatures keep their shape.** Temporal `@activity.defn`/`@workflow.run` and celery task boundaries take what they take; the helper behind them accepts the dataclass.
+3. **Facade contracts that are also request bodies are wire signatures too.** A contract in `facade/contracts.py` backed by `DataclassSerializer` and `@validated_request` is the HTTP body, the OpenAPI schema, and the shape shipped clients send. A product's `logic` may accept its own contract while the fields are one-to-one with what logic needs; do not pre-emptively build a parallel internal DTO. Split into an internal parameter object at the first real divergence: the wire carries dead or deprecated fields logic ignores, logic needs values the wire must not accept, or logic needs an invariant the wire can't promise. The split lives in `facade/api.py`, the only in-process caller.
+
+## What enforces this
+
+- `posthog/test/test_dataclass_defaults.py` (blocking ratchet): new bare `@dataclass` without `frozen=`.
+- `.semgrep/rules/devex/prefer-frozen-dataclasses.yaml` and `tuple-return-prefer-dataclass.yaml` (advisory).
+- Everything else is review.
diff --git a/AGENTS.md b/AGENTS.md
index fa845b1a902e..31e711a40a4d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -191,7 +191,7 @@ See [.agents/security.md](.agents/security.md) for security guidelines — least
- Python: Write as if mypy `--strict` is enabled — annotate all function signatures (arguments + return types), avoid `Any`, use `TYPE_CHECKING` imports for type-only references. When a change is type-risky, run mypy the way CI does — `uv run mypy --cache-fine-grained .`, repo-wide, never a file subset (it follows imports, so a subset misses reverse-dependency breakage); `hogli ci:preflight` reminds you, and CI blocks on the same command. The config isn't fully strict yet, but new code should be
- Python imports: keep imports at module level — not inside functions, methods, or conditionals. Inline imports hide dependencies from static analysis, slow hot paths with repeated lookups, and mask circular-import problems instead of fixing them; ruff's `PLC0415` enforces this. Defer an import only to (1) break a true unavoidable circular import (fix the structure first if you can), (2) reference types under `TYPE_CHECKING`, or (3) keep a heavy/optional dependency off the import path so it loads only when its code runs. For (3), add a justified `# noqa: PLC0415` on the import line (e.g. `# noqa: PLC0415 — keeps the heavy dep off the import path`) — never blanket-suppress the rule
-- Python: prefer a small dataclass over a tuple when returning or passing multiple values: always when two or more elements share a type, so callers can silently swap them (e.g. `(start, end)`, `(width, height)`), and when the tuple is big (roughly 3+ elements), where positional access hurts readability. Small tuples with unambiguous, differently typed elements are fine as-is. Use `@frozen` from `posthog.dataclasses` (frozen, `kw_only`, `slots` by default; every flag overridable, e.g. `@frozen(slots=False)` for `functools.cached_property`). A bare `@dataclass` without an explicit `frozen=` choice fails the ratchet in `posthog/test/test_dataclass_defaults.py` and is flagged by the `prefer-frozen-dataclasses` semgrep rule
+- Python dataclasses: invoke `/writing-dataclasses` before adding or changing a dataclass, returning or passing several values, or passing a dataclass through layers. House decorator is `@frozen` from `posthog.dataclasses`; a bare `@dataclass` without an explicit `frozen=` fails the ratchet in `posthog/test/test_dataclass_defaults.py`
- Frontend: for any frontend work — the main app (`frontend/src/`) **or** a product frontend (`products/*/frontend/`) — follow [frontend/src/AGENTS.md](frontend/src/AGENTS.md): reuse existing Lemon/quill components instead of hand-rolling tables/badges/labels, import generated `*Api` types instead of handwriting them, and run typecheck/typegen at the right moments. Product frontends share the same components and generated types, so the same rules apply there
- Frontend: TypeScript required, explicit return types
- Frontend: If there is a kea logic file, write all business logic there, avoid React hooks at all costs.
@@ -207,8 +207,6 @@ See [.agents/security.md](.agents/security.md) for security guidelines — least
- Comments: when refactoring or moving code, preserve existing comments unless they are explicitly made obsolete by the change
- Python tests: do not add doc comments
- Python: do not create empty `__init__.py` files
-- Python: consume dataclass results with dot notation (`result.field`), never by unpacking into positional locals (`a, b = result.a, result.b`), which reintroduces the swap hazard the dataclass exists to prevent. Mark secret fields with `field(repr=False)`
-- Python: name dataclasses after the domain concept, not the plumbing: `ClickHouseCredentials`, `BillingPeriod`, not `GetCredsResult` or `CredsTuple`. A `*Result` suffix only when the function's outcome genuinely is the concept; never `*Info`/`*Data`/`*Tuple`. Underscore-prefix classes private to one module
- jest tests: when writing jest tests, prefer a single top-level describe block in a file
- Tests: prefer parameterized tests (use the `parameterized` library in Python) — if you're writing multiple assertions for variations of the same logic, it should be parameterized
- Tests must earn their place: every new test has to catch a realistic regression no existing test already catches (if you can't name it, don't add it), assert observable behavior through the public interface rather than implementation details, and stay cheap — deterministic, isolated, and at the lowest level that catches the bug (see `/writing-tests`)
@@ -255,6 +253,7 @@ ALWAYS invoke the matching skill **before** writing or reviewing code in these a
**Invoke when in the area:**
+- `/writing-dataclasses` — adding or changing a Python dataclass, replacing a tuple or `dict[str, Any]` payload, or passing a dataclass or facade contract through internal layers
- `/merging-prs` — merging a PR, or babysitting one through the Trunk merge queue
- `/stacking-prs` — creating, restacking, adopting, or landing a stack of PRs (`gh stack`)
- `/implementing-mcp-tools` — adding/modifying endpoints or `tools.yaml`
diff --git a/products/architecture.md b/products/architecture.md
index ffa4b1889ef8..c54daf996b23 100644
--- a/products/architecture.md
+++ b/products/architecture.md
@@ -246,6 +246,15 @@ class ArtifactAPI:
return _to_artifact(instance)
```
+### Contracts inside the product
+
+A product's own `logic.py` may take its contracts as arguments, as `logic.create_artifact(params)` above does; internals importing `facade.contracts` and `facade.enums` is expected, not a layering violation.
+Keep the wire in mind: a contract that also backs a `DataclassSerializer` request body is the HTTP shape shipped clients send.
+Pass it through while its fields are one-to-one with what logic needs, and split off an internal parameter object at the first real divergence — dead or deprecated wire fields, values logic needs that the wire must not accept, invariants the wire can't promise.
+That split lives in the facade, the only in-process caller.
+Never widen a type on the way in: if logic needs a `str`, don't accept a contract with `str | None` and add a runtime guard.
+See `/writing-dataclasses` for the general rule.
+
### Why explicit mappers?
Facades convert ORM models to frozen dataclasses via mapper functions. These look repetitive when fields align 1:1: