← Back to Pull requests

[1a] Typed model construction via @dataclass_transform #83

Closed
unknown closed this pull request without merging on Sep 19, 2026 01:50 UTC
View on GitHub
unknown unknown commented on Jul 21, 2026 19:20 UTC
Author

Gives Model(field=…) a per-field typed __init__ — wrong value types, unknown field names, and missing required fields become type errors instead of runtime surprises. Django can't do this (Model(*kwargs) is Any, and django-stubs can't type it per-field), so it's a genuine improvement over the framework Plain forked.

Mechanism

PEP 681 @dataclass_transform on the ModelBase metaclass, listing the types. constructors as field_specifiers. Purely a type-checker affordance — the runtime __init__ is untouched, and the full suite passes unchanged.

The catch is that PEP 681 only sees annotated class attributes, so this reverses the current "don't annotate fields" rule:

from datetime import datetime

from plain import postgres
from plain.postgres import Field, types


@postgres.register_model
class Article(postgres.Model):
    title: Field[str] = types.TextField(max_length=100)
    views: Field[int] = types.IntegerField(default=0)
    author: Field[User] = types.ForeignKeyField(User, on_delete=postgres.CASCADE)
    published_at: Field[datetime | None] = types.DateTimeField(
        allow_null=True, default=None
    )
    created_at: Field[datetime] = types.DateTimeField(create_now=True)

Access typing is unchanged: Article.title is still Field[str] (the class-level reference the typed query API will build on), article.title is still str.

The one rule to learn

A constructor param is required unless the field has a default= or is DB-owned.

  • optional ⟺ the definition passes a call-site default=

  • excluded ⟺ DB-owned — id, create_now/update_now, generate=True, RandomStringField — via signature-level init=False overloads in the stubs

  • required otherwise
  • Nullability folds into this with no special case: a nullable field is optional iff it declares default=None, exactly as a string is optional iff it declares default="".

    default=None on a field that has no expressible column DEFAULT (UUIDField, DateTimeField, ForeignKeyField, EncryptedJSONField) is validated and then discarded — one shared validate_none_only_default() in fields/base.py. Nothing is stored, has_persistent_literal_default() stays False, and no migration or DB DEFAULT follows. It exists purely so a stock type checker sees the field as omittable.

    What's in here

  • @dataclass_transform on ModelBase, Field exposed publicly as from plain.postgres import Field

  • Stub rework: init=False overloads for DB-owned fields; DateTimeField, nullable ForeignKeyField, UUIDField and EncryptedJSONField accept default=None

  • _ForeignKeyDescriptor subclasses Field[V] so FK annotations check on a stock structural checker, not just on ty

  • Model.query is a ClassVar — default-queryset models declare nothing and inherit it; only custom-queryset models (cache, jobs) write query: ClassVar[CustomQuerySet]

  • Every shipped + example + test-fixture model migrated: 33 model files, 227 annotations, 51 query redeclarations removed

  • A conformance check (CheckTypedConstruction in postgres/preflight/models.py) that re-derives the synthesized field set and asserts each entry is a real field — it caught four leak classes during review (model_options/_model_meta, M2M, reverse FK/M2M accessors), two of which a human reviewer missed. This is the gate for the failure mode a type checker can't see: an annotation that isn't a field type-checks fine and then raises TypeError at runtime. Run from an internal test rather than registered as a preflight — detecting leaks from raw annotations (aliased ClassVar imports, annotated properties, string forward refs) is too fragile to run in every user app's startup.
  • Every field is now optional in the constructor iff it's optional in the database

    This branch was cut in June. In July master independently built out the default= taxonomy this design needs — DefaultableField, only_empty_default, accepts_default — and filled in default="" on the non-nullable required=False text and binary fields across the repo. That closed what was previously this PR's one known imprecision: ~20 fields that the runtime would have filled with "" but that typed as required, because the declaration passed no default=. The earlier workaround (adding default="" purely to satisfy the checker, dragging in a redundant 20-column migration) is no longer needed — those call sites carry a real default="" on master, and the annotation just reads it.

    The one field that still had no way to be optional, EncryptedJSONField, is fixed here: it now takes default=None on a nullable field. A non-None literal is still rejected (Fernet ciphertext is non-deterministic, so there is no literal to put in the column).

    So there is no longer any field that is required in the constructor without being required in the database. That's the invariant the design is worth having.

    Migration

    All-or-nothing by construction — an unannotated model synthesizes an empty __init__, so a half-migrated model silently gets a wrong constructor. The rewrite is mechanical, so /plain-upgrade can apply it; see Upgrade instructions below.

    The merge from master is a useful preview of that all-or-nothing property: plain-oauthserver landed on master afterward, was never annotated, and produced 31 errors on its own until migrated. Two of its call sites needed real adaptation:

  • views.py passed user=self.user into a non-null FK, but AuthView.user is User | None and login_required = True doesn't narrow it — a latent hole the untyped constructor hid entirely. Asserted locally; typing login_required views properly is its own change.

  • A unit test built partial AuthorizationCode instances to exercise pure methods, which the typed constructor rejects. Needed a helper supplying four required-but-irrelevant values. This is the deliberate tradeoff — the type models the persistence contract while the runtime stays permissive for construct-then-fill — but it's the friction users will feel most.
  • Upgrade instructions

    Applies to every postgres.Model subclass in an app. All models in a file must be converted together — a model with no annotated fields gets an empty synthesized __init__, so a partial conversion is worse than none.

    Step 1 — import Field. Change from plain.postgres import types to from plain.postgres import Field, types. Add from __future__ import annotations at the top of the file if it isn't there, plus whatever value types the annotations name (from datetime import datetime, from uuid import UUID, …).

    Step 2 — annotate every field. For <name> = types.<X>Field(<args>), write <name>: Field[<T>] = types.<X>Field(<args>), where <T> comes from the field type and allow_null:

    | Field | <T> |
    | --- | --- |
    | TextField, EmailField, URLField, RandomStringField, EncryptedTextField, GenericIPAddressField | str |
    | IntegerField, SmallIntegerField, BigIntegerField | int |
    | FloatField | float |
    | DecimalField | Decimal |
    | BooleanField | bool |
    | DateTimeField | datetime |
    | DateField | date |
    | TimeField | time |
    | DurationField | timedelta |
    | UUIDField | UUID |
    | BinaryField | bytes \| memoryview |
    | TimeZoneField | ZoneInfo |
    | JSONField, EncryptedJSONField | dict, or the precise shape (dict[str, Any]) |
    | ForeignKeyField(SomeModel, …) | SomeModel |

    If the call passes allow_null=True, the annotation is Field[<T> | None].

    Step 3 — add default= to anything that should stay optional. This is the step that is easy to miss, because it changes the call, not just the annotation. A type checker treats a field as omittable only when its definition passes default=. required=False alone does not do it.

  • required=False on a text field (TextField, EmailField, URLField, EncryptedTextField) → add default="".

  • required=False on a BinaryField → add default=b"".

  • allow_null=True on anything → add default=None.
  • # before
    name = types.TextField(max_length=255, required=False)
    expires_at = types.DateTimeField(required=False, allow_null=True)
    config = types.EncryptedJSONField(required=False, allow_null=True)
    
    # after
    name: Field[str] = types.TextField(max_length=255, required=False, default="")
    expires_at: Field[datetime | None] = types.DateTimeField(
        required=False, allow_null=True, default=None
    )
    config: Field[dict | None] = types.EncryptedJSONField(
        required=False, allow_null=True, default=None
    )
    

    Neither default="" nor default=None changes the schema on a field that already exists: default is in non_migration_attrs, and None is never a persistent literal. Skipping this step doesn't break anything at runtime — the field just becomes a required constructor argument.

    Step 4 — special-case four kinds of attribute.

    1. Drop query redeclarations. Delete query: postgres.QuerySet[Thing] = postgres.QuerySet() entirely — Model.query is now ClassVar[QuerySet[Self]] and types itself. Keep it only for a custom QuerySet, and then as query: ClassVar[ThingQuerySet] = ThingQuerySet().
    2. Reverse relations get ClassVar: children: ClassVar[types.ReverseForeignKey[Child]] = types.ReverseForeignKey(...). Without it the accessor leaks into the synthesized constructor and Model(children=...) type-checks while the runtime rejects it.
    3. String forward-ref FKs keep a value-type annotation, not Field[...] — the checker can't resolve the string to a model: parent: Foo | None = types.ForeignKeyField("self", on_delete=postgres.CASCADE, allow_null=True, default=None).
    4. M2M keeps tags: types.ManyToManyManager[Tag] = types.ManyToManyField(Tag, through=TaskTag).

    Step 5 — DB-owned fields are annotated but excluded automatically. id, create_now/update_now datetimes, generate=True UUIDs and RandomStringField still take Field[T] annotations; the stubs' init=False overloads keep them out of the constructor. Don't add default= to these.

    Step 6 — run the checker. uv run ty check will flag every model you half-converted, every construction site that now needs a value, and every construction site passing a value the field doesn't accept. Expect real bugs here: a non-null FK being passed an X | None is the most common.

    Review shape

    Tiered: the engine (base.py, types.pyi, fields/base.py, fields/related.py, the conformance check) carefully; the ~227 mechanical annotations sampled.

    Verification

  • uv run ty check (ty 0.0.80) — clean across the whole repo

  • ./scripts/fix --check — clean (ruff 0.16.7)

  • ./scripts/test — 27 packages + the example app, 2444 passed, 1 skipped
  • plain-postgres/tests/public/test_databases.py::test_template_requires_idle_source is deselected in the counts above. It is flaky on master too (fixed-name scratch databases collide across concurrent runs on one cluster) and this branch does not touch databases.py or its test. The fix is on the test-fixtures-per-checkout branch, independent of this PR.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: davegaeddert Review duration: 85350m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #83"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%
    Repository