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, whichmypy --strictreports as an error. ADR-0038 chosename: str = String(required=True), which writes the kind and the required-ness twice. The two copies can disagree, and onlymypywith 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 saysrequired=Truecannot be written in that standard. - The runtime ignored the annotation in ADR-0038's form.
isbn: str = String(max_length=5)acceptedNone. - A forgotten
required=Truemade 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:
TextagainstString, 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:
- How is an association with options written, and how does a list get its empty default? (decisions 2, 3 and 8)
- How are the identifier role and generated identifiers written? (decision 6)
- How are status transitions and
Decimalprecision written? (decision 4) - What replaces
Customfields? (decision 13) - Is
Annotated[...]metadata a second form? (decision 5) - 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: strnever holdsNone.notes: str | Nonemay.- 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, andT | Noneof 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 aNonechild 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, anddict[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,listorAny, afrozenset, a tuple, a union of two types, aLiteral, a Pydantic type, and a plain Python class with noconverterandserializer(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 checkreports 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
stror allintraises at class creation, because the IR and the column need one type for the field. - A field annotated
uuid.UUIDholds aUUIDobject 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 atimeand atimedelta, base64 forbytes, and a list for aset.to_dict()writes this form, andfrom_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, includingNone, a mix ofNoneand 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
strwith no| Nonerefuses"", with a default or without one, and the IR recordsmin_length: 1.field(min_length=0)lifts the rule. A default of""with nomin_length=0raises at class creation. Each item of alist[str]or aset[str]refuses""too, and names the item; a list that allows an empty item uses a shared field type withmin_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 withdefault_factory=list,setordictis the optional form of a collection and accepts an empty value. strhas no implicit maximum length. Astrthat is indexed, unique or a stored identifier needs amax_lengthfrom 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 portableIndex(...). 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 nomax_lengthfrom 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()andfield(default=[])raise at class creation, with a message that namesfield(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.defaultholds a value and is never called.default_factoryholds 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 asdefault. A value a factory makes is checked when it is made, and one that does not fit raisesValidationError, as a caller's value does. field(init=False)keeps a field out of the constructor. Passing it raisesTypeError, and the class's own methods set it. A field withinit=Falseand no default, no factory and no| Noneraises at class creation, because nothing could give it a value. attrs, dataclasses and SQLAlchemy offerinit=False. Pydantic'sBaseModelignores 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 formCustomer(**(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 boundsmin_valueandmax_value, the exclusive boundsgreater_thanandless_than,precisionandscale,pattern,choices,unique,identifier,transitions,frozen,init,sanitize,validators,error_messages,description,deprecated,renamed_from,converter,serializer,via,defaultanddefault_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_valueon astror astrchoice on anint. - 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.transitionsis 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. Decimalprecision isprecisionandscale. SQLNUMERIC, the Avro decimal type and the IR use these names. Pydantic'smax_digitsanddecimal_placesraiseTypeError.patternmust match the whole value.max_lengthandmin_lengthon 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.choicestakes a list of values of the annotated type. A closed vocabulary with no Enum isfield(choices=[...]), andLiteral[...]raises at class creation, so one vocabulary has one form.frozen=Truerefuses assignment after construction with aValidationErrorthat names the field. The constructor,from_dict, a rebuild and an@applymethod set it, because every change to an event-sourced aggregate arrives through an@applymethod. It raises at class creation on a value object, a command, an event and a query, and withinit=Falseand no default.sanitizestrips HTML from a text value. A field that leaves it unset follows the domain-level[field_defaults] sanitizesetting, which is off unless the domain turns it on. A field's ownsanitize=wins over the domain setting.validatorstakes callables that take the value and raiseValueError.error_messagesis keyed by the name of thefield()argument that declares the check.requiredandtypeare 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,transitionsor a time role, goes on each field. A role inside the shared type raises at class creation. So dofrozen,init,renamed_fromanddeprecated, which describe one field in one class.frozeninside a shared type would also make every event and command that uses the type raise.descriptionis 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 afield()on a field, insidelist[...]or in a plain assignment alias raises at class creation, with a message that names= field(...)and thetypestatement.- Options from the shared type and the field combine. The same option written
in both raises, with two exceptions.
validatorson the field add to the shared type's, which run first.error_messagesmerge 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 checkreports one declared in the domain's own modules and used as a field type, and names thetypestatement. - Protean's floor is Python 3.12, for the
typestatement.
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 | Noneon an identifier raises at class creation. An identifier with no default is given by the caller, as an email or an ISBN is. autonames 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.autotakes the optionsfield()takes, apart fromdefaultanddefault_factory. The oldAuto's identity arguments (identity_strategy,identity_function,identity_type) leave. Anautofield 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 withunique=True.autois 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,intoruuid.UUID, and its column type comes from its annotation. Any other annotation raises at class creation. - The domain's
identity_typetypes theidthe framework adds and everyautofield. Anautofield's annotation matches it (stron astringdomain,inton anintegerdomain,uuid.UUIDorstron auuiddomain), andDomain.init()raises aConfigurationErrorthat names the field otherwise. On auuiddomain the addedidand anautofield annotateduuid.UUIDhold aUUIDobject, anautofield annotatedstrholds the text form, andto_dict()writes the text. - Refused at class creation: a constant
defaulton an identifier, and a field namedidwith no identifier role on an aggregate, an entity or a projection. - Protean has no database-assigned value.
incrementis removed, and its error namesfield(default_factory=..., unique=True). A number from a sequence isinvoice_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
idto a concrete aggregate, entity or projection that declares no identifier. The docs andprotean newteach 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)
timestampis a function besidefield()andauto, and takes the optionsfield()takes apart fromdefaultanddefault_factory, which raise.datetime | Nonewith either role raises at class creation.autois kept for identifiers and surrogate keys.timestampis legal only on adatetime.datetimefield. On any other annotation,datetime.dateincluded, it raises at class creation. The date of an instant depends on a time zone, and the author chooses the zone. Foron="create"the message names afield(default_factory=...)whose function reads the domain clock and converts it in a named zone. Foron="save"it names adatetimefield, 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'sheaders.time.on="create"takes theheaders.timeof the event that creates the object: the first event for the aggregate, and for a child the event whose@applymethod adds it. An@applymethod may set either from its event, and Protean keeps that value. A time value passed to the constructor, or assigned outside an@applymethod, 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 nameson="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
datetimefield.
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 separaterelationship()function. list[OrderItem] | Noneraises at class creation, with a message that namesfield(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>_idwhatever the parent's identifier is called, and the parent object (item.order), which is the live aggregate on every path.viaon 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, namingvia. - 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 noreferencesargument, 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
Orderand anOrderPaymentkeyed by oneOrderId, and the IR records both targets. - A field annotated with a bare
strorintis legal and names no target. Protean cannot tell it from any otherstr, 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_asis 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_nameandIndex.from_sqlare database model options, and the aggregate, entity and projection classes take neither. A portableIndex(...)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_dictis 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 ofto_dict().- Create mode, the default, behaves as the constructor does. It refuses an
init=Falsekey and a@computedkey. It fillsautofields when they are absent, and time fields too outside an event-sourced aggregate. - Rebuild mode (
rebuild=True) takes every stored value:init=Falsefields, both time fields as stored, the identifier with noautocall, and a@computedkey, 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_dictrun every field check and everypostinvariant, as the constructor does. Apreinvariant 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,setordict. It calls no other factory and noauto, applies the events, and then runs every field check and everypostinvariant 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 acceptNoneand still holdsNoneafter the events raises with a message that says so. protean ir diffjudges 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. Soir diffjudges 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)andorder.total = 5raise. - The method's return annotation is one of decision 1's types. A method with no
return annotation, or with
@computedstacked on@property, raises at class creation. @computedis 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@propertystays 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
converterand aserializer. 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.
converterandserializerraise 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, sofield(converter=str.lower)on astrdoes nothing. The message says so and namesvalidators=[...], 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.
choiceswith aconverterraises. - A shared field type reuses a custom type.
Customleaves the public surface.FieldandFieldBaseleave it too and become the internal_Fieldand_FieldBase, sofrom protean.fields import FieldraisesImportError.- 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,| Nonelets the field holdNone, and a default makes the constructor argument optional. A field with no default is one the caller must pass. field()'s type stub types theerror_messageskeys and thechoicesvalues, so both checkers report a misspelled key and a choice of the wrong type.autoandtimestampare typed as returningAnyand 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 addedidfrom the domain's identity type, types the child's link to its parent, and gives a field whosechoiceslist is written in place the typeLiteral[...]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_manyandreference, and addsvalue_object_setandvalue_object_dictfor a set of value objects and a dict whose values are value objects. On each of the three collection kinds,content_typenames the value object. The kindstext,identifier,list,dict,statusandcustomleave. A list, a dict, a status and a custom type arestandardfields whosetype,transitions,converterorserializerkey says so. Kindreferenceis the link the framework adds to a child. - The IR adds the types
UUID,Time,Duration,BytesandSet, records nullability as"nullable": trueonly when true, and records the shared field type's name as"shared_type". - A top-level
shared_typessection 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": truebesidecontent_type. An Enum field records its values aschoicesand the Enum's name. Each invariant and each entry invalidatorsis recorded by name, with a hash of its source code that a formatting change leaves the same. protean ir diffreports a rename on stored data. It comparesnullable, and it treats a kind change across IR versions that keeps the stored form as safe. The IR states thatpatternmatches the whole value.- The event-model grammar's
textandidentifiertypes leave,stringis its one text type, andkeymarks the identifier.textandidentifierraise a parse error that namesstring.
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,HasManyand the rest),AutoandIdentifierare removed, marked breaking, with no warning release first. So arereferenced_as,increment,defaults(), the generated child methods,ValueObjectFromEntity,Custom, the publicFieldandFieldBase, andschema_nameandIndex.from_sqlon 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 anincrementcolumn 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 upgradecommand, rewrites each old form into the new form. It reads source and imports nothing. It writesvia="<parent>_<identifier>"where a parent's identifier is not namedid, and the annotation of anautofield from the domain's identity type. On a command or an event it rewritesIdentifier(identifier=True)andAuto(identifier=True)tofield(identifier=True), and reports eachAutosite, because the field no longer generates a value. It rewritesDate(auto_now_add=True)andDate(auto_now=True)totimestamp(on=...)on adatetime.dateannotation, 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 astridentifier 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, becauseviais 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 requiredListorDictthat now refuses an empty value, or aString()with no length, which losesmain's limit of 255. The field's stored column keeps its 255 limit until a migration widens it. On an indexed, unique or stored identifierstr, the class raises and namesmax_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 --checklists 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
Customfactory leaves the public surface (decision 13). - It replaces in part: ADR-0000's field examples and
Textas a domain declaration; ADR-0013's note on theadd_andremove_methods; ADR-0021's rule that a UUID identity is a string in Python; and ADR-0041'stextandidentifiergrammar 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_nameorreferenced_asto 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
uuiddomain, code that compares the addedidwith a text getsFalseafter 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 fromto_dict(). The round trip goes throughfrom_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_factoryor a time role on a value object can make two equal values compare unequal. - A
frozen=Truefield can be set from any@applymethod, 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
choiceslist, which aLiteralannotation 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
converterkeyword 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 raisesTypeErrorwhen 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 --strictasks for an annotation on a database model's rename column.protean ir diffjudges 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 checkreports nothing for it. The codemod rewritesIdentifier()to a bare annotation, which records no target either. - A declared identifier costs one line per aggregate that states no business rule.
protean checkdoes not report an Enum field compared with a text through a variable of unknown type.protean ir diffcannot 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_'sObjectNotFoundError. The docs writenext((...), 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, aset, atimedeltaorbytes, and not the text formto_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 --strictreports 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, andfield(default_factory=list)is one form that every checker reads. - Name
Decimalprecisionmax_digitsanddecimal_places, as Pydantic does. Rejected: SQLNUMERIC, the Avro decimal type and the IR useprecisionandscale. - Put association options on a separate function, as SQLAlchemy's
relationship()does. Rejected: the three other frameworks have no association options, and onefield()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:choicesholds the same list, so two forms would state one vocabulary. All four frameworks acceptLiteral, and the cost is in the Negative list. - Give
stra 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_dictis 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=...)orfield(auto_now=True). Rejected:autois kept for identifiers and surrogate keys, and a separatetimestampfunction 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
typestatement. - 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 checkrules 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 diffsupport for judging a stricter check on stored data as breaking.