[1a] Typed model construction via @dataclass_transform #83
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
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
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
davegaeddert
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)isAny, and django-stubs can't type it per-field), so it's a genuine improvement over the framework Plain forked.Mechanism
PEP 681
@dataclass_transformon theModelBasemetaclass, listing thetypes.constructors asfield_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:
Access typing is unchanged:
Article.titleis stillField[str](the class-level reference the typed query API will build on),article.titleis stillstr.The one rule to learn
A constructor param is required unless the field has a
default=or is DB-owned.default=id,create_now/update_now,generate=True,RandomStringField— via signature-levelinit=Falseoverloads in the stubsNullability 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 declaresdefault="".default=Noneon a field that has no expressible columnDEFAULT(UUIDField,DateTimeField,ForeignKeyField,EncryptedJSONField) is validated and then discarded — one sharedvalidate_none_only_default()infields/base.py. Nothing is stored,has_persistent_literal_default()stays False, and no migration or DBDEFAULTfollows. It exists purely so a stock type checker sees the field as omittable.What's in here
@dataclass_transformonModelBase,Fieldexposed publicly asfrom plain.postgres import Fieldinit=Falseoverloads for DB-owned fields;DateTimeField, nullableForeignKeyField,UUIDFieldandEncryptedJSONFieldacceptdefault=None_ForeignKeyDescriptorsubclassesField[V]so FK annotations check on a stock structural checker, not just on tyModel.queryis aClassVar— default-queryset models declare nothing and inherit it; only custom-queryset models (cache, jobs) writequery: ClassVar[CustomQuerySet]queryredeclarations removedCheckTypedConstructioninpostgres/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 raisesTypeErrorat runtime. Run from an internal test rather than registered as a preflight — detecting leaks from raw annotations (aliasedClassVarimports, 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 indefault=""on the non-nullablerequired=Falsetext 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 nodefault=. The earlier workaround (addingdefault=""purely to satisfy the checker, dragging in a redundant 20-column migration) is no longer needed — those call sites carry a realdefault=""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 takesdefault=Noneon a nullable field. A non-Noneliteral 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-upgradecan apply it; see Upgrade instructions below.The merge from master is a useful preview of that all-or-nothing property:
plain-oauthserverlanded on master afterward, was never annotated, and produced 31 errors on its own until migrated. Two of its call sites needed real adaptation:views.pypasseduser=self.userinto a non-null FK, butAuthView.userisUser | Noneandlogin_required = Truedoesn't narrow it — a latent hole the untyped constructor hid entirely. Asserted locally; typinglogin_requiredviews properly is its own change.AuthorizationCodeinstances 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.Modelsubclass 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. Changefrom plain.postgres import typestofrom plain.postgres import Field, types. Addfrom __future__ import annotationsat 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 andallow_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 isField[<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 passesdefault=.required=Falsealone does not do it.required=Falseon a text field (TextField,EmailField,URLField,EncryptedTextField) → adddefault="".required=Falseon aBinaryField→ adddefault=b"".allow_null=Trueon anything → adddefault=None.Neither
default=""nordefault=Nonechanges the schema on a field that already exists:defaultis innon_migration_attrs, andNoneis 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
queryredeclarations. Deletequery: postgres.QuerySet[Thing] = postgres.QuerySet()entirely —Model.queryis nowClassVar[QuerySet[Self]]and types itself. Keep it only for a custom QuerySet, and then asquery: ClassVar[ThingQuerySet] = ThingQuerySet().2. Reverse relations get
ClassVar:children: ClassVar[types.ReverseForeignKey[Child]] = types.ReverseForeignKey(...). Without it the accessor leaks into the synthesized constructor andModel(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_nowdatetimes,generate=TrueUUIDs andRandomStringFieldstill takeField[T]annotations; the stubs'init=Falseoverloads keep them out of the constructor. Don't adddefault=to these.Step 6 — run the checker.
uv run ty checkwill 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 anX | Noneis 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 skippedplain-postgres/tests/public/test_databases.py::test_template_requires_idle_sourceis deselected in the counts above. It is flaky onmastertoo (fixed-name scratch databases collide across concurrent runs on one cluster) and this branch does not touchdatabases.pyor its test. The fix is on thetest-fixtures-per-checkoutbranch, independent of this PR.