Skip to content

ADR-0050: The annotation states a field's type, and field() states its constraints and roles

Status: Accepted

Date: December 2026

Context

A field declaration carries three facts: the kind of value (text, integer, a value object), whether it may hold None, and whether the caller must pass it. Before this decision, Protean put all three in a type-named function:

@domain.aggregate
class Customer:
    name: String(max_length=100, required=True)
    loyalty_points = Integer(default=0)
    notes = String()          # accepts None, because required=True is absent

Before this decision, this form had these problems:

  • A type checker cannot read it. String(...) in the annotation is a function call, which mypy --strict reports as an error. ADR-0038 chose name: str = String(required=True), which writes the kind and the required-ness twice. The two copies can disagree, and only mypy with Protean's plugin notices.
  • pyright, ty and pyrefly load no plugins. The typing standard for this kind of class (PEP 681, dataclass_transform) decides whether the caller must pass a field by whether the field call gives a default. A field that is optional unless it says required=True cannot be written in that standard.
  • The runtime ignored the annotation in ADR-0038's form. isbn: str = String(max_length=5) accepted None.
  • A forgotten required=True made a field optional with no error, which works against Protean's promise that a domain object is always valid.
  • The domain declaration held storage choices: Text against String, a stored name (referenced_as), the table name and raw SQL indexes on the aggregate.

Most code written against Protean is written by AI. Each error that guides the author counts: a type checker's report, an error at class creation, at domain init and at run time, and the text of each message. A strict rule costs such an author little.

The reference frameworks for each choice are Pydantic v2, attrs, dataclasses and SQLAlchemy 2.0. When three or four of them agree, Protean follows them. A two and two split is a ruling for the maintainer. The typing specification is a constraint every answer meets, and is not counted. A framework with no such concept is counted on neither side.

The decisions answer six questions:

  1. How is an association with options written, and how does a list get its empty default? (decisions 2, 3 and 8)
  2. How are the identifier role and generated identifiers written? (decision 6)
  3. How are status transitions and Decimal precision written? (decision 4)
  4. What replaces Custom fields? (decision 13)
  5. Is Annotated[...] metadata a second form? (decision 5)
  6. How much of the mypy plugin is still needed? (decision 14)

Every example uses the class form (class Order(Aggregate):), with each class inside its domain's folder. A separate ADR records that form, which replaces the element decorators.

Decision

1. The annotation states the type and whether the field accepts None

class Customer(Aggregate):
    name: str = field(max_length=100)
    loyalty_points: int = 0
    notes: str | None = None
  • name: str never holds None. notes: str | None may.
  • The legal annotation types are str, int, float, bool, Decimal, date, datetime, datetime.time, datetime.timedelta, bytes, uuid.UUID, an Enum class, a value object class, an entity class, list[T], set[T], dict[str, T], the free-form JSON forms below, and T | None of any of them apart from a list of child entities (decision 8).
  • A list or a set holds a simple type, an Enum, a shared field type (decision 5) or a value object, and a list also holds a child entity. A dict's key is str, and its value is a simple type, an Enum, a shared field type or a value object. An item of a simple type, an Enum or a value object may be | None (values: list[str | None]). A child entity item may not, because a None child has no identity and no stored row.
  • A collection inside a collection (list[list[int]]) raises at class creation, with a message that names a value object.
  • Free-form JSON is dict[str, Any] for an object, list[Any] for an array, list[dict[str, Any]] for an array of objects, and dict[str, Any] | list[Any] for either. Protean checks the content as JSON when the object is built and when the field is assigned, so {"placed": datetime.now()} raises.
  • Every other annotation raises at class creation, with a message that names what to write. This covers a bare dict, list or Any, a frozenset, a tuple, a union of two types, a Literal, a Pydantic type, and a plain Python class with no converter and serializer (decision 13).
  • A field annotated with an Enum holds the member. Protean converts a raw value to the member, and stores the member's value. to_dict() writes the value. Pydantic and SQLAlchemy hold the member, and attrs and dataclasses do no conversion. protean check reports a comparison of such a field with a text or with a member's .value, and names the member to write.
  • An Enum whose member values are not all str or all int raises at class creation, because the IR and the column need one type for the field.
  • A field annotated uuid.UUID holds a UUID object on every element kind. A string is converted, and a bad string raises.
  • Each type has one JSON form, taken from its published standard: RFC 4122 text for a UUID, ISO 8601 for a time and a timedelta, base64 for bytes, and a list for a set. to_dict() writes this form, and from_dict() reads it back.
  • to_dict() orders a set's items by each item's canonical JSON text (RFC 8785, the JSON Canonicalization Scheme). The order holds for every legal item type, including None, a mix of None and a number, and a value object written as a JSON object, so one set always gives the same list.

One legal list gives every field one IR type, one column type and one JSON form. A refused type gets a message that names the form to write, which is the error that guides an AI author.

2. A field with no default is required, and a required field is never empty

class Note(Aggregate):
    body: str                              # required: Note(body="") raises
    caption: str = field(min_length=0)     # required, and may be empty
    remark: str | None = None              # optional: "" is accepted
    nickname: str = "anon"                 # has a default: nickname="" raises
    slots: list[str]                       # required: slots=[] raises
    tags: list[str] = field(default_factory=list)  # optional: [] is accepted
  • Whether a default is present decides whether the caller must pass the field. All four reference frameworks and the typing specification use this rule.
  • A str with no | None refuses "", with a default or without one, and the IR records min_length: 1. field(min_length=0) lifts the rule. A default of "" with no min_length=0 raises at class creation. Each item of a list[str] or a set[str] refuses "" too, and names the item; a list that allows an empty item uses a shared field type with min_length=0.
  • A list, set or dict field with no default refuses an empty value, and the IR records min_length: 1. field(min_length=0) lifts the rule. A field with default_factory=list, set or dict is the optional form of a collection and accepts an empty value.
  • str has no implicit maximum length. A str that is indexed, unique or a stored identifier needs a max_length from the author, on every provider. A stored identifier is the identifier of an aggregate, an entity or a database-backed projection. Indexed means named in a portable Index(...). A command's and an event's identifier have no column and no length rule. An identifier Protean makes on the UUID strategy and stores as text has the length 36 with no max_length from the author. No domain-level setting gives a default length.

None of the four frameworks refuses "" for a required str. Protean departs from them because a required value that holds nothing is not a valid value, and an always-valid domain object refuses it.

3. A default is a value, a factory is a function, and construction takes keywords only

class Order(Aggregate):
    tags: list[str] = field(default_factory=list)
    placed_on: datetime.date = field(default_factory=datetime.date.today)
    status: OrderStatus = field(default=OrderStatus.DRAFT, init=False)
  • = [], = {}, = set() and field(default=[]) raise at class creation, with a message that names field(default_factory=...). dataclasses and SQLAlchemy raise on = [], attrs shares the list across instances, and Pydantic copies it. A type checker accepts = [], so the class creation error is the one report.
  • default holds a value and is never called. default_factory holds a function of no arguments. A field with both raises, and so does a factory that takes an argument.
  • A default that does not fit the annotated type raises at class creation, so quantity: int = "one" raises, and so does a function passed as default. A value a factory makes is checked when it is made, and one that does not fit raises ValidationError, as a caller's value does.
  • field(init=False) keeps a field out of the constructor. Passing it raises TypeError, and the class's own methods set it. A field with init=False and no default, no factory and no | None raises at class creation, because nothing could give it a value. attrs, dataclasses and SQLAlchemy offer init=False. Pydantic's BaseModel ignores it at run time, so Protean enforces it.
  • Construction is keyword-only. A positional dict of values raises TypeError, with a message that names the merge form Customer(**(template | {"name": "Ann"})).
  • A default picked from another field is set in a named factory method:
class Customer(Aggregate):
    name: str
    display_name: str

    @classmethod
    def register(cls, name: str, display_name: str | None = None) -> "Customer":
        return cls(name=name, display_name=display_name or name)

The defaults() hook is removed, and there is no post-init hook.

4. One field() call carries every constraint and role

class OrderItem(Entity, part_of="Order"):
    sku: str = field(max_length=20, unique=True, pattern=r"[A-Z]{3}-\d{3}",
                     sanitize=True, description="Stock code")
    unit_price: decimal.Decimal = field(greater_than=0, precision=10, scale=2)
    size: str = field(choices=["S", "M", "L"])
    quantity: int = field(min_value=1,
                          error_messages={"min_value": "Order at least {min_value}"})

class Order(Aggregate):
    status: OrderStatus = field(
        default=OrderStatus.DRAFT,
        transitions={OrderStatus.DRAFT: [OrderStatus.PLACED]},
    )
    signup_channel: str = field(max_length=20, frozen=True)
    tags: list[Tag] = field(default_factory=list, max_length=3)
  • field() takes the constraints and roles the type cannot state: max_length, min_length, the inclusive bounds min_value and max_value, the exclusive bounds greater_than and less_than, precision and scale, pattern, choices, unique, identifier, transitions, frozen, init, sanitize, validators, error_messages, description, deprecated, renamed_from, converter, serializer, via, default and default_factory. Each one is a keyword on the field, where a reader sees it. Pydantic, attrs and dataclasses put every per-field option on the field call.
  • A constraint that does not fit the annotated type raises at class creation, such as min_value on a str or a str choice on an int.
  • A status field is an Enum field with transitions. A state in the map that is not a member of the field's Enum raises at class creation, and both type checkers report a target of another type. transitions is legal on an aggregate, its child entities, a projection and a process manager, and raises at class creation on a value object, a command, an event and a query, which never change after they are built. None of the four frameworks has transitions.
  • Decimal precision is precision and scale. SQL NUMERIC, the Avro decimal type and the IR use these names. Pydantic's max_digits and decimal_places raise TypeError.
  • pattern must match the whole value.
  • max_length and min_length on a list or a set limit the number of items, as in Pydantic. On a dict they limit the number of keys. A limit on each item goes on the item type.
  • choices takes a list of values of the annotated type. A closed vocabulary with no Enum is field(choices=[...]), and Literal[...] raises at class creation, so one vocabulary has one form.
  • frozen=True refuses assignment after construction with a ValidationError that names the field. The constructor, from_dict, a rebuild and an @apply method set it, because every change to an event-sourced aggregate arrives through an @apply method. It raises at class creation on a value object, a command, an event and a query, and with init=False and no default.
  • sanitize strips HTML from a text value. A field that leaves it unset follows the domain-level [field_defaults] sanitize setting, which is off unless the domain turns it on. A field's own sanitize= wins over the domain setting.
  • validators takes callables that take the value and raise ValueError.
  • error_messages is keyed by the name of the field() argument that declares the check. required and type are the keys of the two checks with no argument. A text may name the check's limit in braces. A key for a check the field does not have raises at class creation, and a check with no custom text keeps the default text. None of the four frameworks has this argument; Protean keeps it so that a domain expert reads the business message beside the rule.
  • Storage hints are not field() arguments. Text against string is a column choice for the adapter or the database model.

5. A shared field type is a type statement, and Annotated[...] holds a field() only there

type OrderId = Annotated[str, field(max_length=8)]
type Email = Annotated[str, field(max_length=254, validators=[has_at_sign])]

class Order(Aggregate):
    order_id: OrderId = field(identifier=True)

class Staff(Aggregate):
    work_email: Email = field(validators=[is_company_domain])
  • A shared field type carries constraints. The role, such as identifier, unique, transitions or a time role, goes on each field. A role inside the shared type raises at class creation. So do frozen, init, renamed_from and deprecated, which describe one field in one class. frozen inside a shared type would also make every event and command that uses the type raise. description is legal in a shared type. A default, a factory or an association option inside it raises at class creation, because both type checkers would read the field as required.
  • Annotated[...] holding a field() on a field, inside list[...] or in a plain assignment alias raises at class creation, with a message that names = field(...) and the type statement.
  • Options from the shared type and the field combine. The same option written in both raises, with two exceptions. validators on the field add to the shared type's, which run first. error_messages merge key by key, and the field's text wins.
  • The IR records on each field the name of the shared field type it uses, so the name says what the value is.
  • A plain alias with no field() inside (CustomerId = str) is legal, and the IR records no name for it. protean check reports one declared in the domain's own modules and used as a field type, and names the type statement.
  • Protean's floor is Python 3.12, for the type statement.

Pydantic and SQLAlchemy read Annotated metadata, and attrs and dataclasses read none. On that split the maintainer ruled for one form per thing: a constraint on one field is written in field(), and Annotated names a type that several fields reuse.

6. An identifier is field(identifier=True), and auto generates one from the domain's settings

type CustomerId = str

class Customer(Aggregate):
    customer_id: CustomerId = auto(identifier=True)   # made by the domain's settings

class Book(Aggregate):
    isbn: str = field(identifier=True, max_length=13)  # given by the caller

class Order(Aggregate):
    order_id: str = field(identifier=True, max_length=20, default_factory=next_order_id)

class CancelOrder(Command, part_of="Order"):
    order_id: str = field(identifier=True)            # required
  • An identifier always holds a value and exists at construction. T | None on an identifier raises at class creation. An identifier with no default is given by the caller, as an email or an ISBN is.
  • auto names a behaviour and no type. The domain's identity strategy makes the value when the caller gives none, and a value from the caller is kept. auto takes the options field() takes, apart from default and default_factory. The old Auto's identity arguments (identity_strategy, identity_function, identity_type) leave. An auto field with no annotation, or with | None, raises at class creation.
  • auto() on a field that is not the identifier makes a surrogate key the same way. It is unique only with unique=True.
  • auto is legal on every element kind that declares fields, a command, an event and a projection included, on the identifier and on any other field. It raises at class creation on a value object, which has no identity of its own.
  • An identifier with its own function is field(identifier=True, default_factory=...). All four reference frameworks write a role as an argument of the field call and a generated value as a default factory.
  • An identifier is annotated str, int or uuid.UUID, and its column type comes from its annotation. Any other annotation raises at class creation.
  • The domain's identity_type types the id the framework adds and every auto field. An auto field's annotation matches it (str on a string domain, int on an integer domain, uuid.UUID or str on a uuid domain), and Domain.init() raises a ConfigurationError that names the field otherwise. On a uuid domain the added id and an auto field annotated uuid.UUID hold a UUID object, an auto field annotated str holds the text form, and to_dict() writes the text.
  • Refused at class creation: a constant default on an identifier, and a field named id with no identifier role on an aggregate, an entity or a projection.
  • Protean has no database-assigned value. increment is removed, and its error names field(default_factory=..., unique=True). A number from a sequence is invoice_number: int = field(default_factory=next_invoice_number, unique=True). An aggregate has its identifier at construction, so every event it raises carries it. A projector builds each row from an event, so a projection's identifier comes from the event, and a cache-backed projection has no database to assign a number.
  • The framework adds id to a concrete aggregate, entity or projection that declares no identifier. The docs and protean new teach a declared identifier of a shared identity type, so every field that holds that identity names its target in the IR.

7. A time role is timestamp(on="create") or timestamp(on="save")

class Order(Aggregate):
    placed_at: datetime.datetime = timestamp(on="create")
    updated_at: datetime.datetime = timestamp(on="save")
    entered_at: datetime.datetime = timestamp(on="create", init=False)
  • timestamp is a function beside field() and auto, and takes the options field() takes apart from default and default_factory, which raise. datetime | None with either role raises at class creation. auto is kept for identifiers and surrogate keys.
  • timestamp is legal only on a datetime.datetime field. On any other annotation, datetime.date included, it raises at class creation. The date of an instant depends on a time zone, and the author chooses the zone. For on="create" the message names a field(default_factory=...) whose function reads the domain clock and converts it in a named zone. For on="save" it names a datetime field, from which a reader derives the date in the zone it needs.
  • Outside an event-sourced aggregate, Protean fills both roles from the domain clock when the object is constructed and the caller gives no value. The caller may pass either value, in the constructor and by assignment. on="save" is refreshed just before each save. A load keeps both as stored. timestamp(on="save", frozen=True) raises at class creation, because a frozen field never changes after construction.
  • On an event-sourced aggregate and its child entities, Protean sets both roles from the events and never from the clock, on the live write and on a rebuild alike. Each applied event sets on="save" to the event's headers.time. on="create" takes the headers.time of the event that creates the object: the first event for the aggregate, and for a child the event whose @apply method adds it. An @apply method may set either from its event, and Protean keeps that value. A time value passed to the constructor, or assigned outside an @apply method, raises with a message that names @apply. Before the first event, a time field holds no value, and reading it raises.
  • on="create" is legal on every element kind. on="save" raises at class creation on a value object, a command, an event and a query, which are never saved again after construction, and the message names on="create". On a projection the author chooses whether a field holds the event's time, as a plain field the projector sets, or a new time, as a time role.
  • A business time beyond these two roles, such as a delivery date, is a plain datetime field.

Outside an event-sourced aggregate, a time filled at construction exists before the first save, so an invariant and an event can read it.

8. A value object or an entity named in the annotation is embedded or associated

class Order(Aggregate):
    shipping_address: Address | None = None
    items: list[OrderItem] = field(default_factory=list)
    shipment: Shipment | None = None

class OrderItem(Entity, part_of=Order):
    sku: str = field(max_length=20)
  • A value object class in an annotation is always embedded, and a child entity class becomes a child list or a single child, with no opt-out. Pydantic reads a nested model from the annotation. SQLAlchemy reads the target and the collection from it and still needs a relationship() call.
  • An association option goes on the same field() call. Pydantic, attrs and dataclasses have no association options, and SQLAlchemy has a separate relationship() function.
  • list[OrderItem] | None raises at class creation, with a message that names field(default_factory=list). A child list with no default is required.
  • An aggregate named in an annotation raises. An entity or an aggregate named in a field of a command, an event, a value object, a projection or a query raises at class creation, with a message that names a value object. Such an element holds another aggregate's identity (decision 9).
  • A class defined later is named in quotes (list["OrderItem"]) and resolved at domain init. A quoted name that resolves to no registered class raises at domain init and names the field.
  • A child declares no link to its parent. The framework adds <parent>_id whatever the parent's identifier is called, and the parent object (item.order), which is the live aggregate on every path. via on the parent's child field names the link otherwise (field(default_factory=list, via="book_isbn")). A child that declares a field with the link's name raises at class creation, naming via.
  • A child has no valid state outside its aggregate. Its field checks run when it is built, and its invariants run once it is attached and after each later change, so a child invariant may read self.order.
  • The child list records its own changes:
order.items.append(OrderItem(sku="A-1"))
order.items.remove(item)

The stored rows keep no order. The list records each operation that adds or removes a child: append, extend, +=, remove, pop, clear and del items[i]. An operation that places a child at a position or reorders the list raises: insert, sort, reverse and items[i] = x. The message names append, or sorted(order.items, key=...) for reading in order. A business order is a field on the child, such as line_no: int. The generated add_, remove_, get_one_from_ and filter_ methods are removed. Each change made through the list runs the aggregate's invariants before and after and undoes itself when one fails, with the check deferred to the end of an open atomic_change block. Assigning a whole list replaces it and records the adds and removes. A new object that holds an existing child's identity raises, and the message names changing that child in place, where the transition check runs. During replay, a change to a child list that the aggregate's reserved option names is dropped. - A value object is passed as an object: Order(shipping_address=Address(street="1 Main St", city="Pune")). The flattened keyword and attribute (shipping_address_city) are removed. - A dict passed where a value object, a child entity or a list of either is expected raises in the constructor and on assignment, on every element kind, and the error names from_dict (decision 11). - A command or an event carries a value object class that the author writes:

class OrderItemPayload(ValueObject):
    sku: str = field(max_length=20)
    quantity: int

class PlaceOrder(Command, part_of=Order):
    items: list[OrderItemPayload] = field(default_factory=list)

ValueObjectFromEntity and value_object_from_entity() are removed, and Entity.from_value_object() stays. protean check reports a value object that lacks a field of the entity it is converted to, or declares a different type or limit.

9. A field that holds another aggregate's identity is a plain field of its shared identifier type

type CustomerId = str
type OrderId = str

class Order(Aggregate):
    order_id: OrderId = auto(identifier=True)
    customer_id: CustomerId | None = None

class OrderPlaced(Event, part_of="Order"):
    order_id: OrderId = field(identifier=True)
    customer_id: CustomerId
  • field() has no references argument, and the form is the same on every element kind. The IR records the shared type's name, which names the target.
  • A shared type's targets are the aggregates whose declared identifier uses it. Two aggregates may share one identity, such as an Order and an OrderPayment keyed by one OrderId, and the IR records both targets.
  • A field annotated with a bare str or int is legal and names no target. Protean cannot tell it from any other str, so no check reports it. The docs teach the shared type.
  • Code that needs the other aggregate loads it through its repository.

Aggregates refer to each other only by identity, and a command or an event carries identifiers and never references.

10. Stored names, the table name and raw SQL indexes live on the database model

class CustomerModel(DatabaseModel, part_of=Customer, schema_name="crm_customers"):
    name = sa.Column("full_name")               # SQLAlchemy's form

class OrderModel(DatabaseModel, part_of=Order,
                 indexes=[Index.from_sql("postgresql",
                          "CREATE INDEX ix_tags ON orders USING gin (tags)")]):
    shipping_address_city = sa.Column("town")
  • A domain class carries no stored name. Protean derives every stored name from the domain names, and the database model is the one place that overrides one. referenced_as is removed. A child's link column is renamed on the child's database model (order_id = sa.Column("order_ref")). A database model names a value object's attribute by its derived name (shipping_address_city), because a class attribute cannot hold a dotted path.
  • schema_name and Index.from_sql are database model options, and the aggregate, entity and projection classes take neither. A portable Index(...) stays on the aggregate.
  • A database model declares only what it overrides, and every adapter derives the rest: a renamed SQLAlchemy column takes the derived type, length, NOT NULL and UNIQUE when it gives none.
  • Each adapter publishes the rename form native to its model, reports the map from domain names to stored names through one adapter method, and passes one shared rename test suite. The method is a class method of the database model, so the IR reads the map with no configured database. Protean ships no portable rename function.
  • One translation layer carries every save, load, query, filter, sort and index for every adapter. A query names a field, a link and a value object's attribute by its domain name. A value object's attribute is named by its path with double underscores (filter(shipping_address__city="Pune")), and a stored name is never a query key. filter(shipping_address_city="Pune") raises, with a message that names the path.
  • The IR's database model entry records stored_names, the renamed names only.

Storage choices belong to the adapter, and the domain declaration stays the same on every database.

11. from_dict builds an object from values, and every path that builds one runs every check

PlaceOrder.from_dict(body)                # create mode
Order.from_dict(stored, rebuild=True)     # rebuild mode
  • from_dict is a class method on every element kind that declares fields. It takes one dict and builds the whole tree, nested value objects and child entities included. It serves a request body, a message, a test, an import and a load. In rebuild mode it is the inverse of to_dict().
  • Create mode, the default, behaves as the constructor does. It refuses an init=False key and a @computed key. It fills auto fields when they are absent, and time fields too outside an event-sourced aggregate.
  • Rebuild mode (rebuild=True) takes every stored value: init=False fields, both time fields as stored, the identifier with no auto call, and a @computed key, which it accepts and ignores. A load by the repository uses rebuild mode.
  • A load by the repository or the event store, an event-sourced rebuild and from_dict run every field check and every post invariant, as the constructor does. A pre invariant guards a change, so it runs before each change and on none of these paths. Stored data that breaks a stricter rule is fixed in storage by a data migration.
  • An event-sourced rebuild starts a blank object with each constant default and an empty list, set or dict where the factory is list, set or dict. It calls no other factory and no auto, applies the events, and then runs every field check and every post invariant once, on the state after the last event. A field a factory fills is carried by the creation event, and a field that does not accept None and still holds None after the events raises with a message that says so.
  • protean ir diff judges a stricter field check, a new invariant, or a changed invariant or validator, on an aggregate, an entity or a projection as breaking, and names the field and the data migration it needs. A looser field check is safe. The IR records each invariant and validator by a hash of its source code, and a hash shows only that the code changed. So ir diff judges every change to an invariant or a validator as breaking.

A path that skips a check would let invalid data into the domain, even if only in memory.

12. A computed value is a method decorated with @computed

class Order(Aggregate):
    items: list[OrderItem] = field(default_factory=list)

    @computed
    def total(self) -> decimal.Decimal:
        return sum((i.unit_price * i.quantity for i in self.items), decimal.Decimal(0))
  • Protean stores the value and writes it in to_dict(). It computes the value from the live object on each read. Order(total=5) and order.total = 5 raise.
  • The method's return annotation is one of decision 1's types. A method with no return annotation, or with @computed stacked on @property, raises at class creation.
  • @computed is legal on a command. It raises at class creation on an event, because a changed formula would change what a recorded fact reports. A plain @property stays legal there. A fact event carries the aggregate's computed field as a plain field, with the value at the change.

13. A custom type is field(converter=..., serializer=...)

def dump_coupon(c: CouponCode) -> str:
    return c.value

class Order(Aggregate):
    coupon: CouponCode | None = field(default=None, converter=CouponCode,
                                      serializer=dump_coupon)
  • A field annotated with a class outside decision 1's list needs both a converter and a serializer. With either one missing, the class raises at class creation, and the message names the missing option.
  • The converter turns a raw value into the annotated type. Protean calls it only on a value that is not of that type.
  • converter and serializer raise at class creation on a field annotated with a type from decision 1's list. A converter there would never run on a value of that type, so field(converter=str.lower) on a str does nothing. The message says so and names validators=[...], which checks every value.
  • The IR takes the field's type from the serializer's return annotation. A serializer with no return annotation, such as a lambda, raises at class creation, and so does one whose return annotation is outside decision 1's scalar types and JSON forms. choices with a converter raises.
  • A shared field type reuses a custom type.
  • Custom leaves the public surface. Field and FieldBase leave it too and become the internal _Field and _FieldBase, so from protean.fields import Field raises ImportError.
  • No Pydantic name is legal on a domain field.

attrs attaches a converter to the field. Pydantic and SQLAlchemy attach the behaviour to the type. dataclasses has nothing. The field form keeps every option in field().

14. Type checkers read field declarations through the dataclass standard, with no plugin

  • Protean marks its base classes with the typing standard for dataclass-like classes (PEP 681, dataclass_transform). pyright and mypy, with no plugin, read a Protean class as they read a dataclass: the annotation gives the type, | None lets the field hold None, and a default makes the constructor argument optional. A field with no default is one the caller must pass.
  • field()'s type stub types the error_messages keys and the choices values, so both checkers report a misspelled key and a choice of the wrong type. auto and timestamp are typed as returning Any and kept out of the checkers' list of field functions, the form both checkers read as optional in the constructor.
  • A CI job runs pyright and mypy with no plugin over every example of the new form in the docs. Every error this ADR adds names the fix, and a test checks each one.
  • Protean's mypy plugin is an optional aid. It reports a different shared type passed at a call or assigned to a field, types auto, types the added id from the domain's identity type, types the child's link to its parent, and gives a field whose choices list is written in place the type Literal[...] of the list's values.

SQLAlchemy removed its mypy plugin in 2.1, because its 2.0 class body is valid typing on its own. Pydantic's plugin is optional. attrs needs mypy's built-in plugin and gives pyright PEP 681 alone.

15. The IR derives every field's kind and records each option by the argument's name

  • The IR keeps the field kinds standard, auto, value_object, value_object_list, has_one, has_many and reference, and adds value_object_set and value_object_dict for a set of value objects and a dict whose values are value objects. On each of the three collection kinds, content_type names the value object. The kinds text, identifier, list, dict, status and custom leave. A list, a dict, a status and a custom type are standard fields whose type, transitions, converter or serializer key says so. Kind reference is the link the framework adds to a child.
  • The IR adds the types UUID, Time, Duration, Bytes and Set, records nullability as "nullable": true only when true, and records the shared field type's name as "shared_type".
  • A top-level shared_types section lists each shared field type once, with its type, its options and "targets", the aggregates whose declared identifier uses it. A field names its shared type and repeats none of this.
  • The IR records each field option under the name of the argument the author writes, and only when the field sets it: "timestamp": "create", "computed": true, "init": false, "frozen": true, "error_messages", and "converter" and "serializer" by function name. A nullable list item is "content_nullable": true beside content_type. An Enum field records its values as choices and the Enum's name. Each invariant and each entry in validators is recorded by name, with a hash of its source code that a formatting change leaves the same.
  • protean ir diff reports a rename on stored data. It compares nullable, and it treats a kind change across IR versions that keeps the stored form as safe. The IR states that pattern matches the whole value.
  • The event-model grammar's text and identifier types leave, string is its one text type, and key marks the identifier. text and identifier raise a parse error that names string.

The IR may change where long-term correctness needs it, and these changes ship under a new IR schema version.

16. Every replaced form is removed in the release that ships the new form, and a codemod rewrites it

  • The type-named field functions (String, Integer, HasMany and the rest), Auto and Identifier are removed, marked breaking, with no warning release first. So are referenced_as, increment, defaults(), the generated child methods, ValueObjectFromEntity, Custom, the public Field and FieldBase, and schema_name and Index.from_sql on an aggregate, an entity and a projection. The flattened value object keyword and attribute, a positional dict and a stored name as a query key raise. Each has a changelog fragment and a migration guide entry. The guide gives the DDL step for an increment column on each database.
  • The new field form ships in one release, with the Python 3.12 floor, the codemod and every change in this ADR.
  • This departs from ADR-0004's warn-first rule for this change. Before this decision, no code base ran Protean in production. An old form that still runs keeps teaching an AI author to write it. ADR-0004 stays unchanged for every other change.
  • A codemod, the protean upgrade command, rewrites each old form into the new form. It reads source and imports nothing. It writes via="<parent>_<identifier>" where a parent's identifier is not named id, and the annotation of an auto field from the domain's identity type. On a command or an event it rewrites Identifier(identifier=True) and Auto(identifier=True) to field(identifier=True), and reports each Auto site, because the field no longer generates a value. It rewrites Date(auto_now_add=True) and Date(auto_now=True) to timestamp(on=...) on a datetime.date annotation, so the class raises and names the form that states a time zone (decision 7). It reports by module and line each site it cannot rewrite, such as a str identifier with an identity function, whose length the author gives.
  • The codemod writes the new form as a new author would, and keeps no old behaviour that a decision here changes. The one exception is via, which keeps an existing link column's name, because via is a current form and the new name would load every existing child list empty with no error. It reports by module and line each site whose behaviour changes, such as a required List or Dict that now refuses an empty value, or a String() with no length, which loses main's limit of 255. The field's stored column keeps its 255 limit until a migration widens it. On an indexed, unique or stored identifier str, the class raises and names max_length. Stored data that breaks the new rule is fixed by a data migration (decision 11).
  • No stub keeps a removed name. The skills and agent context that Protean ships teach only the new form. Both checkers report a removed name before the code runs. protean upgrade --check lists each old form by module and line, with its fix.

17. This ADR supersedes ADR-0038 and ADR-0044, and parts of other ADRs

  • ADR-0038's reasons, real types and a form users know, hold, and this form meets them with no plugin.
  • ADR-0044's Custom factory leaves the public surface (decision 13).
  • It replaces in part: ADR-0000's field examples and Text as a domain declaration; ADR-0013's note on the add_ and remove_ methods; ADR-0021's rule that a UUID identity is a string in Python; and ADR-0041's text and identifier grammar types.

Consequences

Positive:

  • pyright and mypy with no plugin read every field declaration, so each reports a wrong assignment or a missing argument.
  • The annotation and the runtime agree. Each fact is written once.
  • A field is optional only when the author writes a default, so a forgotten flag cannot make a field optional.
  • Each thing has one form. A refused declaration raises at class creation or domain init, with a message that names the form to write.
  • The domain declaration holds no storage choice, and every adapter reads the same declaration.
  • An identifier exists at construction, so every event carries it.
  • On an event-sourced aggregate, the live object and the rebuilt object hold the same times, because both take them from the events.
  • Every path that builds an object runs every check, so no object is built invalid.
  • The IR derives each kind from the declaration and records the target of each field that holds another aggregate's identity.

Negative:

  • Every existing Protean app changes in one release, with no warning release.
  • These old forms fail only when one code path runs: a positional dict, a stored name as a query key, the flattened value object keyword, a dict where a value object is expected, a value that is not JSON in an old Dict() field, and a default factory's value of the wrong type. An app that holds one passes start-up and fails in production.
  • An author who deletes schema_name or referenced_as to clear its error reads an empty table, and no later error reports it. The errors name the move to make, and the migration guide repeats it.
  • On a uuid domain, code that compares the added id with a text gets False after the upgrade, with no error.
  • Stored data that breaks a stricter rule fails to load until a data migration fixes it, such as a stored list that holds "".
  • type(obj)(**obj.to_dict()) raises, and the merge form fails when the template comes from to_dict(). The round trip goes through from_dict(..., rebuild=True).
  • A change made in place to a list, set or dict field, a child list apart, skips the item checks and the invariants. A list or set field on a value object can change in place.
  • A default_factory or a time role on a value object can make two equal values compare unequal.
  • A frozen=True field can be set from any @apply method, so an event applied later can change it.
  • A stored computed value is out of date after a release changes the method's code, until the row is saved again. The same holds for rows saved before the field existed, during a rolling deploy, and for a child whose parent alone changed. A command queued or retried across such a release reaches its handler with the new formula's value.
  • A serializer whose return type changes changes the stored form with no version.
  • No type checker reports a class-creation refusal, so an author meets them one import at a time.
  • pyright with no plugin does not report a value outside a choices list, which a Literal annotation would have reported. mypy reports one only with Protean's plugin and only for a list written in place. An author who wants the report in every checker uses an Enum.
  • Three of the four reference frameworks accept a tuple annotation, which Protean refuses.
  • pyright tells no shared type from another of the same base type. With the mypy aid, a plain value is still reported for a local variable and a return annotated with a shared type, and the aid depends on mypy internals.
  • With no plugin, pyright and mypy report the added id, the child's link and the parent object as unknown.
  • pyright types a converter keyword by the converter's input type.
  • timestamp(on="create", init=False) reads as a default to both checkers, so they accept a caller's value, which raises TypeError when run. The same holds for a time value passed to an event-sourced aggregate's constructor.
  • On an event-sourced aggregate, a time field holds no value between construction and the first event, so an invariant that reads it at construction raises.
  • mypy --strict asks for an annotation on a database model's rename column.
  • protean ir diff judges every edit to an invariant or a validator as breaking, an edit that loosens it included.
  • A field that needs a looser check than its shared field type needs a shared type of its own.
  • A plain alias from another package (AccountId = str) gives the IR no name and no target. protean check reports nothing for it. The codemod rewrites Identifier() to a bare annotation, which records no target either.
  • A declared identifier costs one line per aggregate that states no business rule.
  • protean check does not report an Enum field compared with a text through a variable of unknown type.
  • protean ir diff cannot see the database, so it reports a rename even after the column has moved.
  • A class statement does not show a default picked from another field, which lives in a factory method.
  • Plain list code loses get_one_from_'s ObjectNotFoundError. The docs write next((...), None) with an explicit raise.
  • A test that builds a child alone to check its invariant moves to its aggregate.
  • The domain clock's time has a time zone, and datetime.now() has none, so comparing the two raises.
  • A third-party adapter receives each field value as its Python object, such as an Enum member, a UUID, a set, a timedelta or bytes, and not the text form to_dict() writes.
  • Protean's floor rises to Python 3.12.

Alternatives Considered

  • Keep ADR-0038's name: str = String(...) form. Rejected: with no plugin, pyright accepts a call that leaves out a required field. mypy --strict reports every field line as an assignment error. The form also writes the type twice, and the runtime ignores the annotation.
  • Keep fields optional unless they say required=True. Rejected: PEP 681 reads whether the caller must pass a field from its default, and a forgotten flag makes a field optional with no error.
  • Accept Annotated[...] metadata on any field as a second form. Rejected: two forms for one constraint, and a default inside it is invisible to type checkers. The reference frameworks split two and two, and the maintainer ruled.
  • Copy = [] per instance, as Pydantic does. Rejected: dataclasses and SQLAlchemy raise, attrs shares the list, and field(default_factory=list) is one form that every checker reads.
  • Name Decimal precision max_digits and decimal_places, as Pydantic does. Rejected: SQL NUMERIC, the Avro decimal type and the IR use precision and scale.
  • Put association options on a separate function, as SQLAlchemy's relationship() does. Rejected: the three other frameworks have no association options, and one field() call keeps every option in one place.
  • Write an identity function as auto(function=...). Rejected: all four frameworks write a generated value as a default factory.
  • Keep a database-assigned identifier or number (increment). Rejected: an identifier that does not exist at construction gives the first event no stream, and a cache-backed projection has no database to assign it.
  • Accept Literal[...] for a closed vocabulary. Rejected: choices holds the same list, so two forms would state one vocabulary. All four frameworks accept Literal, and the cost is in the Negative list.
  • Give str a default maximum length from a domain setting. Rejected: the limit would be hidden from the reader of the class.
  • Accept a dict where a value object or a child entity is expected. Rejected: a constructor that takes only the annotated types is checked by both type checkers at every call, and from_dict is the one place that converts a nested dict, with every check.
  • Keep the defaults() hook, or add a post-init hook. Rejected: a value that is always a function of other fields is a computed field, and a starting value picked from the inputs is set in a named factory method, which the reader sees on the class.
  • Write the time roles as auto(on=...) or field(auto_now=True). Rejected: auto is kept for identifiers and surrogate keys, and a separate timestamp function gives both checkers a field that is optional in the constructor.
  • Deprecate each old form for a release first, as ADR-0004 asks. Rejected: before this decision, no code base ran Protean in production. An old form that still runs keeps teaching an AI author to write it.

Dependencies

  • The class form for domain elements, with a base class for each element kind.
  • Python 3.12, for the type statement.
  • A codemod that rewrites the old forms and reports what it cannot rewrite.
  • An adapter method that reports the map from domain names to stored names, and a shared rename test suite that every adapter passes.
  • protean check rules for an Enum field compared with a text, a plain alias used as a field type, and a value object that does not match the entity it is converted to.
  • protean ir diff support for judging a stricter check on stored data as breaking.