: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
refactor(visual-review): use pydantic.dataclasses for facade DTOs (#57504)
Julian Bezeb8c56a47470
diff --git a/.agents/skills/isolating-product-facade-contracts/SKILL.md b/.agents/skills/isolating-product-facade-contracts/SKILL.mdindex 7c9341a81e12..b33cfd16cffa 100644--- a/.agents/skills/isolating-product-facade-contracts/SKILL.md+++ b/.agents/skills/isolating-product-facade-contracts/SKILL.md@@ -50,7 +50,7 @@ For detailed sequencing, load [references/phased-migration-plan.md](references/p- Classify each usage by capability (read/list, detail/read, create/update/delete, async/task, webhook/event).2. Define the minimal contract surface.- Start from currently consumed fields only.- - Create frozen dataclasses in `backend/facade/contracts.py`.+ - Create frozen dataclasses in `backend/facade/contracts.py` using `pydantic.dataclasses.dataclass` — same shape as the stdlib variant but with runtime type validation on construction.3. Introduce a thin facade in `backend/facade/api.py`.- Map ORM instances to contracts with explicit mapper functions.- Keep method names capability-oriented and stable.diff --git a/.agents/skills/isolating-product-facade-contracts/references/phased-migration-plan.md b/.agents/skills/isolating-product-facade-contracts/references/phased-migration-plan.mdindex 6b7e77539c97..7bccf4b680f6 100644--- a/.agents/skills/isolating-product-facade-contracts/references/phased-migration-plan.md+++ b/.agents/skills/isolating-product-facade-contracts/references/phased-migration-plan.md@@ -28,7 +28,7 @@ rg -n "products\.<target>\.backend\.facade" .Start with read paths before write paths.-1. Add `backend/facade/contracts.py` with frozen dataclasses for existing read responses.+1. Add `backend/facade/contracts.py` with `pydantic.dataclasses.dataclass` frozen dataclasses for existing read responses. (Stdlib `dataclasses.dataclass` works too, but the Pydantic variant adds runtime type validation on construction for the same syntax.)2. Add `backend/facade/__init__.py` exports to make imports straightforward.3. Add minimal domain enums either in `contracts.py` or `facade/enums.py` if they grow.diff --git a/.semgrep/devex-rules/api-response-must-match-schema.py b/.semgrep/devex-rules/api-response-must-match-schema.pynew file mode 100644index 000000000000..83dfcd10ed27--- /dev/null+++ b/.semgrep/devex-rules/api-response-must-match-schema.py@@ -0,0 +1,68 @@+# Test cases for api-response-must-match-schema rule.+# ruff: noqa: F841, E501++from rest_framework.response import Response+++# ============================================================+# Should flag: viewset returns hand-assembled data dict+# ============================================================+++def list_things():+ # ruleid: api-response-must-match-schema+ return Response({"things": [1, 2, 3]})+++def detail_thing():+ # ruleid: api-response-must-match-schema+ return Response({"id": 1, "name": "foo"})+++def detail_with_data_kwarg():+ # ruleid: api-response-must-match-schema+ return Response(data={"id": 1, "name": "foo"})+++# ============================================================+# Should NOT flag: conventional DRF error/ack idioms+# ============================================================+++def not_found():+ # ok: api-response-must-match-schema+ return Response({"detail": "Not found"}, status=404)+++def not_found_data_kwarg():+ # ok: api-response-must-match-schema+ return Response(data={"detail": "Not found"}, status=404)+++def bad_request():+ # ok: api-response-must-match-schema+ return Response({"error": "bad input"}, status=400)+++def ack():+ # ok: api-response-must-match-schema+ return Response({"success": True})+++def paginated():+ # ok: api-response-must-match-schema+ return Response({"results": [], "count": 0, "next": None, "previous": None})+++# ============================================================+# Should NOT flag: payload constructed via serializer+# ============================================================+++class FooSerializer:+ pass+++def correct_pattern(foo):+ # ok: api-response-must-match-schema+ return Response(FooSerializer(instance=foo).data)diff --git a/.semgrep/devex-rules/api-response-must-match-schema.yaml b/.semgrep/devex-rules/api-response-must-match-schema.yamlnew file mode 100644index 000000000000..089991afd44b--- /dev/null+++ b/.semgrep/devex-rules/api-response-must-match-schema.yaml@@ -0,0 +1,56 @@+rules:+ - id: api-response-must-match-schema+ message: |+ Returning a hand-assembled dict from a product viewset is a common+ source of spec drift. The OpenAPI schema for this endpoint is built+ from its `serializer_class` or `@extend_schema(responses=...)`+ declaration — nothing checks that the dict you returned actually+ matches that schema. When they diverge, generated FE types and MCP+ tool schemas silently lie about the wire shape.++ Why this matters: spectacular trusts the declaration, not the+ runtime. A `Response({"foo": ...})` next to a `@extend_schema(+ responses=FooSerializer)` produces a wrong-but-plausible spec that+ flows downstream into `api.schemas.ts`, MCP tool definitions, and+ anything else generated from `openapi.json`.++ Instead of:+ return Response({"id": str(run.id), "status": run.status, ...})++ Use:+ return Response(FooSerializer(instance=foo).data)++ For products on the facade layout (visual_review-style), construct+ a contract dataclass and pass it through a `DataclassSerializer` —+ that gives you runtime type validation on top of spec alignment. See+ the `isolating-product-facade-contracts` skill.++ This rule is currently informational (WARNING severity). Findings+ are the backlog of viewsets still assembling responses by hand.+ Once a product's count hits zero, the path can be narrowed and+ severity flipped to ERROR for that product.+ languages: [python]+ severity: WARNING+ paths:+ include:+ - 'products/*/backend/'+ # Test fixture lives here — must be in include so `semgrep --test` exercises the rule.+ - '.semgrep/devex-rules/'+ exclude:+ - '**/tests/**'+ - '**/test_*.py'+ - '**/conftest.py'+ patterns:+ - pattern-either:+ - pattern: return Response({...}, ...)+ - pattern: return Response({...})+ - pattern: return Response(data={...}, ...)+ # Error / pagination / ack idioms are conventional DRF shapes — not+ # data payloads. Match the dict's *first key* so we don't accidentally+ # exempt larger payloads that happen to contain one of these names.+ # `(?:data=)?` covers both `Response({...})` and `Response(data={...})`.+ - pattern-not-regex: 'Response\(\s*(?:data=)?\{\s*"(detail|error|errors|message|status|success|ok|results|count|next|previous)"\s*:'+ metadata:+ category: best-practice+ subcategory:+ - auditdiff --git a/products/architecture.md b/products/architecture.mdindex e800ed09b597..100e71967c14 100644--- a/products/architecture.md+++ b/products/architecture.md@@ -123,9 +123,31 @@ Each product defines its public interface as **frozen dataclasses** in `backend/- Small, hashable, stable- Facades accept them as inputs and return them as outputs+### Choosing a dataclass flavor++Stdlib `dataclasses.dataclass` is the baseline.+`pydantic.dataclasses.dataclass` is the preferred upgrade when construction-time validation is useful:+it keeps full dataclass semantics (passes `is_dataclass()`, works with `DataclassSerializer`, identical kwargs construction, `frozen=True`, `field(default_factory=...)`)+and adds Pydantic's runtime type validation as a 1-line import swap.++Use `pydantic.BaseModel` only when a contract genuinely needs features that dataclasses don't have — field aliases (e.g., camelCase wire / snake_case Python), computed fields exposed in the schema, custom validators, discriminated unions.+Stay with one of the dataclass flavors otherwise;+switching to `BaseModel` loses `is_dataclass()`-based tooling.++DTO validation is **best-effort, not HTTP validation**.+DRF serializers (or Pydantic schemas at the HTTP boundary) own the contract for untrusted input.+Pydantic dataclass validation catches construction-site mistakes inside the backend — structural mismatches from mappers, malformed data from internal callers — close to the bug rather than at the wire.++Note that Pydantic v2 dataclasses coerce inputs where the conversion is unambiguous (string → UUID/datetime, int → str) rather than reject them.+Structural mistakes (None for a required int, dict where a list is expected, unparseable UUID) still raise `ValidationError`.+If a contract genuinely needs strict typing — e.g., to catch a string sneaking into a UUID field — opt in per-contract via `@dataclass(frozen=True, config=ConfigDict(strict=True))`.+### Example```python+from pydantic.dataclasses import dataclass++@dataclass(frozen=True)class Artifact:id: UUIDdiff --git a/products/visual_review/backend/facade/contracts.py b/products/visual_review/backend/facade/contracts.pyindex cdd6d180515f..7cc4ed8f70e2 100644--- a/products/visual_review/backend/facade/contracts.py+++ b/products/visual_review/backend/facade/contracts.py@@ -3,12 +3,23 @@ Contract types for visual_review.Stable, framework-free frozen dataclasses that define what this productexposes to the rest of the codebase. No Django imports.++These use ``pydantic.dataclasses.dataclass`` rather than the stdlib variant — same+syntax, same ``is_dataclass()`` compatibility (so ``DataclassSerializer`` keeps+working), but with runtime validation on construction. Pydantic v2 coerces where+the conversion is unambiguous (string→UUID/datetime, int→str) and raises+``ValidationError`` otherwise, so structural mistakes from mappers or internal+callers (None for a required int, a dict where a list is expected, an+unparseable UUID) surface at the facade boundary instead of producing a+malformed JSON payload twelve stack frames later."""-from dataclasses import dataclass, field+from dataclasses import fieldfrom datetime import datetimefrom uuid import UUID+from pydantic.dataclasses import dataclass+# --- Input DTOs ---diff --git a/tools/hogli-commands/hogli_commands/product_structure.yaml b/tools/hogli-commands/hogli_commands/product_structure.yamlindex 8bf629816d3c..65c2b4d5c815 100644--- a/tools/hogli-commands/hogli_commands/product_structure.yaml+++ b/tools/hogli-commands/hogli_commands/product_structure.yaml@@ -237,12 +237,18 @@ backend_files:Frozen dataclasses that define what this product exposes.No Django imports. Used by facade as inputs/outputs.++ Uses ``pydantic.dataclasses.dataclass`` rather than the stdlib+ variant — same syntax, same ``is_dataclass()`` compatibility (so+ ``DataclassSerializer`` keeps working), but with runtime type+ validation on construction."""- from dataclasses import dataclassfrom datetime import datetimefrom uuid import UUID+ from pydantic.dataclasses import dataclass+from .enums import SplineStatus